From f8fbd1168708cdb6ac1107b8cd46e994cab28ff2 Mon Sep 17 00:00:00 2001 From: Justin McCandless Date: Mon, 11 May 2026 13:30:09 -0700 Subject: [PATCH 1/4] Updated analysis_options from flutter/flutter --- analysis_options.yaml | 42 ++++++++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 5a160d9d8582..d82a7a37bcf6 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,7 +1,7 @@ # Specify analysis options. # # This file is a copy of analysis_options.yaml from flutter repo -# as of 2023-12-18, but with some modifications marked with +# as of 2026-05-11, but with some modifications marked with # "DIFFERENT FROM FLUTTER/FLUTTER" below. The file is expected to # be kept in sync with the master file from the flutter repo. @@ -22,20 +22,24 @@ analyzer: - '**/*.g.dart' - '**/*.mocks.dart' # Mockito @GenerateMocks +formatter: + page_width: 100 + linter: rules: # This list is derived from the list of all available lints located at - # https://github.com/dart-lang/linter/blob/main/example/all.yaml + # https://github.com/dart-lang/sdk/blob/main/pkg/linter/example/all.yaml - always_declare_return_types - always_put_control_body_on_new_line # - always_put_required_named_parameters_first # we prefer having parameters in the same order as fields https://github.com/flutter/flutter/issues/10219 # - always_specify_types # conflicts with omit_obvious_local_variable_types # - always_use_package_imports # we do this commonly - annotate_overrides - # - avoid_annotating_with_dynamic # conflicts with always_specify_types + - annotate_redeclares + # - avoid_annotating_with_dynamic # conflicts with type_annotate_public_apis - avoid_bool_literals_in_conditional_expressions # - avoid_catches_without_on_clauses # blocked on https://github.com/dart-lang/linter/issues/3023 - # - avoid_catching_errors # blocked on https://github.com/dart-lang/linter/issues/3023 + # - avoid_catching_errors # blocked on https://github.com/dart-lang/linter/issues/4998 # - avoid_classes_with_only_static_members # we do this commonly for `abstract final class`es - avoid_double_and_int_checks - avoid_dynamic_calls @@ -43,12 +47,15 @@ linter: - avoid_equals_and_hash_code_on_mutable_classes - avoid_escaping_inner_quotes - avoid_field_initializers_in_const_classes - # - avoid_final_parameters # incompatible with prefer_final_parameters + # TODO(kallentu): Remove this lint once the Dart SDK in Flutter is on version 3.13. + - avoid_final_parameters - avoid_function_literals_in_foreach_calls + # - avoid_futureor_void # not yet tested # - avoid_implementing_value_types # see https://github.com/dart-lang/linter/issues/4558 - avoid_init_to_null - avoid_js_rounded_ints # - avoid_multiple_declarations_per_line # seems to be a stylistic choice we don't subscribe to + - avoid_null_checks_in_equality_operators # - avoid_positional_boolean_parameters # would have been nice to enable this but by now there's too many places that break it - avoid_print # - avoid_private_typedef_functions # we prefer having typedef (discussion in https://github.com/flutter/flutter/pull/16356) @@ -64,7 +71,7 @@ linter: - avoid_slow_async_io - avoid_type_to_string - avoid_types_as_parameter_names - # - avoid_types_on_closure_parameters # conflicts with always_specify_types + # - avoid_types_on_closure_parameters # not yet tested - avoid_unnecessary_containers - avoid_unused_constructor_parameters - avoid_void_async @@ -91,6 +98,7 @@ linter: - directives_ordering # - discarded_futures # too many false positives, similar to unawaited_futures # - do_not_use_environment # there are appropriate times to use the environment, especially in our tests and build logic + # - document_ignores # not yet tested - empty_catches - empty_constructor_bodies - empty_statements @@ -103,6 +111,7 @@ linter: - implicit_call_tearoffs - implicit_reopen - invalid_case_patterns + - invalid_runtime_check_with_js_interop_types # - join_return_with_assignment # not required by flutter style - leading_newlines_in_multiline_strings - library_annotations @@ -114,7 +123,7 @@ linter: # - matching_super_parameters # blocked on https://github.com/dart-lang/language/issues/2509 - missing_code_block_language_in_doc_comment - missing_whitespace_between_adjacent_strings - # - no_adjacent_strings_in_list # conflicts with prefer_adjacent_string_concatenation + - no_adjacent_strings_in_list - no_default_cases - no_duplicate_case_values - no_leading_underscores_for_library_prefixes @@ -128,12 +137,12 @@ linter: - noop_primitive_operations - null_check_on_nullable_type_parameter - null_closures - # - omit_local_variable_types # conflicts with specify_nonobvious_local_variable_types - - omit_obvious_local_variable_types + # - omit_local_variable_types # superset of omit_obvious_local_variable_types + - omit_obvious_local_variable_types # not yet tested + # - omit_obvious_property_types # conflicts with type_annotate_public_apis # - one_member_abstracts # too many false positives - only_throw_errors # this does get disabled in a few places where we have legacy code that uses strings et al - overridden_fields - # - package_api_docs # Deprecated (https://github.com/dart-lang/linter/issues/5107) - package_names - package_prefixed_library_names # - parameter_assignments # we do this commonly @@ -149,7 +158,7 @@ linter: # - prefer_constructors_over_static_methods # far too many false positives - prefer_contains # - prefer_double_quotes # opposite of prefer_single_quotes - # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#consider-using--for-short-functions-and-methods + # - prefer_expression_function_bodies # conflicts with ./docs/contributing/Style-guide-for-Flutter-repo.md#consider-using--for-short-functions-and-methods - prefer_final_fields - prefer_final_in_for_each - prefer_final_locals @@ -162,7 +171,7 @@ linter: - prefer_if_null_operators - prefer_initializing_formals - prefer_inlined_adds - # - prefer_int_literals # conflicts with https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#use-double-literals-for-double-constants + # - prefer_int_literals # conflicts with ./docs/contributing/Style-guide-for-Flutter-repo.md#use-double-literals-for-double-constants - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty @@ -190,12 +199,14 @@ linter: - sort_unnamed_constructors_first - specify_nonobvious_local_variable_types - specify_nonobvious_property_types + - strict_top_level_inference - test_types_in_equals - throw_in_finally - tighten_type_of_initializing_formals - type_annotate_public_apis - type_init_formals - type_literal_in_constant_pattern + # - unawaited_futures # too many false positives, especially with the way AnimationController works - unintended_html_in_doc_comment # DIFFERENT FROM FLUTTER/FLUTTER: Disabled due to an issue that has been fixed, so just hasn't been adopted there yet. - unawaited_futures # DIFFERENT FROM FLUTTER/FLUTTER: It's disabled there for "too many false positives"; that's not an issue here, and missing awaits have caused production issues in plugins. - unnecessary_await_in_return @@ -205,9 +216,11 @@ linter: - unnecessary_constructor_name # - unnecessary_final # conflicts with prefer_final_locals - unnecessary_getters_setters + # - unnecessary_ignore # Disabled by default to simplify migrations; should be periodically enabled locally to clean up offenders # - unnecessary_lambdas # has false positives: https://github.com/dart-lang/linter/issues/498 - unnecessary_late - unnecessary_library_directive + # - unnecessary_library_name # blocked on https://github.com/dart-lang/dartdoc/issues/3882 - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_null_aware_operator_on_extension_on_nullable @@ -222,8 +235,10 @@ linter: - unnecessary_string_interpolations - unnecessary_this - unnecessary_to_list_in_spreads + - unnecessary_underscores - unreachable_from_main - unrelated_type_equality_checks + # - unsafe_variance # not yet tested - use_build_context_synchronously - use_colored_box # - use_decorated_box # leads to bugs: DecoratedBox and Container are not equivalent (Container inserts extra padding) @@ -243,5 +258,8 @@ linter: - use_super_parameters - use_test_throws_matchers # - use_to_and_as_if_applicable # has false positives, so we prefer to catch this by code-review + - use_truncating_division - valid_regexps + # TODO(kallentu): Remove this lint once the Dart SDK in Flutter is on version 3.13. + - var_with_no_type_annotation - void_checks From ea315a23ddd35a24e119dbf8bcbf8178a3f8c2d5 Mon Sep 17 00:00:00 2001 From: Justin McCandless Date: Mon, 11 May 2026 13:42:45 -0700 Subject: [PATCH 2/4] Fixed some absolute URLs I missed. --- analysis_options.yaml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index d82a7a37bcf6..6376e49ea825 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -158,8 +158,7 @@ linter: # - prefer_constructors_over_static_methods # far too many false positives - prefer_contains # - prefer_double_quotes # opposite of prefer_single_quotes - # - prefer_expression_function_bodies # conflicts with ./docs/contributing/Style-guide-for-Flutter-repo.md#consider-using--for-short-functions-and-methods - - prefer_final_fields + # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#consider-using--for-short-functions-and-methods - prefer_final_fields - prefer_final_in_for_each - prefer_final_locals # - prefer_final_parameters # adds too much verbosity @@ -171,7 +170,7 @@ linter: - prefer_if_null_operators - prefer_initializing_formals - prefer_inlined_adds - # - prefer_int_literals # conflicts with ./docs/contributing/Style-guide-for-Flutter-repo.md#use-double-literals-for-double-constants + # - prefer_int_literals # conflicts with https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#use-double-literals-for-double-constants - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty From baccf03fc082c7a56f05b6a40680e93a8f8b1a7b Mon Sep 17 00:00:00 2001 From: Justin McCandless Date: Tue, 12 May 2026 12:45:48 -0700 Subject: [PATCH 3/4] Stuart's review --- analysis_options.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 6376e49ea825..87149dd5fa8a 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -138,7 +138,7 @@ linter: - null_check_on_nullable_type_parameter - null_closures # - omit_local_variable_types # superset of omit_obvious_local_variable_types - - omit_obvious_local_variable_types # not yet tested + - omit_obvious_local_variable_types # - omit_obvious_property_types # conflicts with type_annotate_public_apis # - one_member_abstracts # too many false positives - only_throw_errors # this does get disabled in a few places where we have legacy code that uses strings et al @@ -158,7 +158,8 @@ linter: # - prefer_constructors_over_static_methods # far too many false positives - prefer_contains # - prefer_double_quotes # opposite of prefer_single_quotes - # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#consider-using--for-short-functions-and-methods - prefer_final_fields + - prefer_final_fields + # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#consider-using--for-short-functions-and-methods - prefer_final_in_for_each - prefer_final_locals # - prefer_final_parameters # adds too much verbosity @@ -205,7 +206,6 @@ linter: - type_annotate_public_apis - type_init_formals - type_literal_in_constant_pattern - # - unawaited_futures # too many false positives, especially with the way AnimationController works - unintended_html_in_doc_comment # DIFFERENT FROM FLUTTER/FLUTTER: Disabled due to an issue that has been fixed, so just hasn't been adopted there yet. - unawaited_futures # DIFFERENT FROM FLUTTER/FLUTTER: It's disabled there for "too many false positives"; that's not an issue here, and missing awaits have caused production issues in plugins. - unnecessary_await_in_return From 4210b407a98fa4aa9425365e80e4fe311db116df Mon Sep 17 00:00:00 2001 From: Justin McCandless Date: Tue, 12 May 2026 12:48:27 -0700 Subject: [PATCH 4/4] dart format --- .../example/lib/container_transition.dart | 17 +- .../example/lib/fade_scale_transition.dart | 26 +- .../example/lib/fade_through_transition.dart | 26 +- .../example/lib/shared_axis_transition.dart | 28 +- .../lib/src/fade_scale_transition.dart | 32 +- .../lib/src/fade_through_transition.dart | 71 +- packages/animations/lib/src/modal.dart | 19 +- .../animations/lib/src/open_container.dart | 126 +- .../lib/src/page_transition_switcher.dart | 21 +- .../lib/src/shared_axis_transition.dart | 74 +- .../test/dual_transition_builder_test.dart | 168 +- packages/animations/test/modal_test.dart | 23 +- .../animations/test/open_container_test.dart | 103 +- .../example/integration_test/camera_test.dart | 59 +- packages/camera/camera/example/lib/main.dart | 100 +- .../camera/camera/example/test/main_test.dart | 4 +- .../example/test_driver/integration_test.dart | 5 +- .../camera/lib/src/camera_controller.dart | 94 +- .../camera/camera/lib/src/camera_image.dart | 7 +- .../camera/test/camera_image_stream_test.dart | 168 +- .../camera/camera/test/camera_image_test.dart | 10 +- .../camera/test/camera_preview_test.dart | 180 +- packages/camera/camera/test/camera_test.dart | 2419 ++++----- .../camera/camera/test/camera_value_test.dart | 9 +- .../example/integration_test/camera_test.dart | 40 +- .../example/lib/camera_controller.dart | 74 +- .../example/lib/camera_preview.dart | 7 +- .../camera_android/example/lib/main.dart | 118 +- .../example/test_driver/integration_test.dart | 5 +- .../lib/src/android_camera.dart | 75 +- .../camera_android/lib/src/messages.g.dart | 499 +- .../lib/src/type_conversion.dart | 5 +- .../camera/camera_android/lib/src/utils.dart | 84 +- .../camera_android/pigeons/messages.dart | 7 +- .../test/android_camera_test.dart | 409 +- .../test/android_camera_test.mocks.dart | 391 +- .../test/method_channel_mock.dart | 13 +- .../test/type_conversion_test.dart | 108 +- .../camera_android/test/utils_test.dart | 10 +- .../integration_test/integration_test.dart | 47 +- .../example/lib/camera_controller.dart | 69 +- .../example/lib/camera_image.dart | 7 +- .../example/lib/main.dart | 122 +- .../lib/src/android_camera_camerax.dart | 353 +- .../lib/src/camerax_library.dart | 10 +- .../lib/src/camerax_library.g.dart | 3107 +++++------ .../lib/src/image_reader_rotated_preview.dart | 35 +- .../lib/src/rotated_preview_utils.dart | 4 +- .../src/surface_texture_rotated_preview.dart | 34 +- .../pigeons/camerax_library.dart | 213 +- .../test/android_camera_camerax_test.dart | 4666 +++++++---------- .../android_camera_camerax_test.mocks.dart | 3231 +++++------- .../test/preview_rotation_test.dart | 775 +-- .../example/integration_test/camera_test.dart | 97 +- .../example/lib/camera_controller.dart | 79 +- .../example/lib/camera_preview.dart | 7 +- .../camera_avfoundation/example/lib/main.dart | 114 +- .../lib/src/avfoundation_camera.dart | 72 +- .../lib/src/messages.g.dart | 164 +- .../lib/src/type_conversion.dart | 12 +- .../camera_avfoundation/lib/src/utils.dart | 19 +- .../camera_avfoundation/pigeons/messages.dart | 17 +- .../test/avfoundation_camera_test.dart | 582 +- .../test/avfoundation_camera_test.mocks.dart | 459 +- .../lib/src/events/camera_event.dart | 20 +- .../lib/src/events/device_event.dart | 4 +- .../method_channel/method_channel_camera.dart | 158 +- .../src/method_channel/type_conversion.dart | 5 +- .../platform_interface/camera_platform.dart | 31 +- .../lib/src/types/media_settings.dart | 8 +- .../lib/src/types/video_capture_options.dart | 14 +- .../test/camera_platform_interface_test.dart | 610 +-- .../test/events/camera_event_test.dart | 68 +- .../test/events/device_event_test.dart | 22 +- .../method_channel_camera_test.dart | 654 +-- .../method_channel/type_conversion_test.dart | 108 +- .../test/types/camera_description_test.dart | 33 +- .../test/types/media_settings_test.dart | 81 +- .../test/utils/method_channel_mock.dart | 13 +- .../test/utils/utils_test.dart | 50 +- .../integration_test/camera_bitrate_test.dart | 10 +- .../camera_error_code_test.dart | 68 +- .../camera_metadata_test.dart | 4 +- .../integration_test/camera_options_test.dart | 76 +- .../integration_test/camera_service_test.dart | 396 +- .../example/integration_test/camera_test.dart | 630 +-- .../camera_web_exception_test.dart | 9 +- .../integration_test/camera_web_test.dart | 1124 ++-- .../integration_test/helpers/mocks.dart | 59 +- .../integration_test/helpers/mocks.mocks.dart | 845 ++- .../zoom_level_capability_test.dart | 20 +- .../camera/camera_web/lib/src/camera.dart | 125 +- .../camera_web/lib/src/camera_service.dart | 15 +- .../camera/camera_web/lib/src/camera_web.dart | 92 +- .../camera_web/lib/src/pkg_web_tweaks.dart | 12 +- .../lib/src/types/camera_error_code.dart | 36 +- .../lib/src/types/camera_metadata.dart | 4 +- .../lib/src/types/camera_options.dart | 21 +- .../example/integration_test/camera_test.dart | 69 +- .../camera_windows/example/lib/main.dart | 46 +- .../camera_windows/lib/camera_windows.dart | 50 +- .../camera_windows/lib/src/messages.g.dart | 190 +- .../test/camera_windows_test.dart | 391 +- .../test/camera_windows_test.mocks.dart | 202 +- packages/cross_file/lib/src/types/html.dart | 13 +- .../cross_file/lib/src/types/interface.dart | 8 +- packages/cross_file/lib/src/types/io.dart | 4 +- .../lib/src/web_helpers/web_helpers.dart | 18 +- .../cross_file/test/x_file_html_test.dart | 23 +- packages/cross_file/test/x_file_io_test.dart | 4 +- .../test/flutter_test_config.dart | 4 +- .../test/goldens/goldens_test.dart | 4 +- packages/cupertino_ui/test/goldens_web.dart | 6 +- .../example/lib/main.dart | 43 +- ...oogle_sign_in_as_googleapis_auth_test.dart | 23 +- .../example/lib/get_directory_page.dart | 13 +- .../lib/get_multiple_directories_page.dart | 13 +- .../file_selector/example/lib/home_page.dart | 3 +- .../file_selector/example/lib/main.dart | 6 +- .../example/lib/open_image_page.dart | 4 +- .../lib/open_multiple_images_page.dart | 7 +- .../example/lib/open_text_page.dart | 9 +- .../lib/readme_standalone_excerpts.dart | 10 +- .../example/lib/save_text_page.dart | 14 +- .../test/file_selector_test.dart | 58 +- .../example/lib/main.dart | 3 +- .../lib/open_multiple_images_page.dart | 5 +- .../example/lib/open_text_page.dart | 9 +- .../lib/src/file_selector_android.dart | 25 +- .../lib/src/file_selector_api.g.dart | 76 +- .../pigeons/file_selector_api.dart | 9 +- .../test/file_selector_android_test.dart | 67 +- .../file_selector_android_test.mocks.dart | 47 +- .../file_selector_ios/example/lib/main.dart | 3 +- .../example/lib/open_any_page.dart | 5 +- .../lib/open_multiple_images_page.dart | 7 +- .../example/lib/open_text_page.dart | 9 +- .../lib/file_selector_ios.dart | 7 +- .../file_selector_ios/lib/src/messages.g.dart | 37 +- .../file_selector_ios/pigeons/messages.dart | 8 +- .../test/file_selector_ios_test.dart | 56 +- .../example/lib/get_directory_page.dart | 16 +- .../lib/get_multiple_directories_page.dart | 16 +- .../example/lib/home_page.dart | 3 +- .../file_selector_linux/example/lib/main.dart | 6 +- .../example/lib/open_image_page.dart | 5 +- .../lib/open_multiple_images_page.dart | 12 +- .../example/lib/open_text_page.dart | 14 +- .../example/lib/save_text_page.dart | 19 +- .../lib/file_selector_linux.dart | 42 +- .../lib/src/messages.g.dart | 42 +- .../test/file_selector_linux_test.dart | 138 +- .../example/lib/get_directory_page.dart | 19 +- .../lib/get_multiple_directories_page.dart | 21 +- .../example/lib/home_page.dart | 3 +- .../file_selector_macos/example/lib/main.dart | 6 +- .../example/lib/open_image_page.dart | 5 +- .../lib/open_multiple_images_page.dart | 12 +- .../example/lib/open_text_page.dart | 14 +- .../example/lib/save_text_page.dart | 19 +- .../lib/file_selector_macos.dart | 19 +- .../lib/src/messages.g.dart | 55 +- .../file_selector_macos/pigeons/messages.dart | 3 +- .../test/file_selector_macos_test.dart | 130 +- .../method_channel_file_selector.dart | 13 +- .../file_selector_interface.dart | 10 +- .../lib/src/types/x_type_group.dart | 5 +- ...file_selector_platform_interface_test.dart | 23 +- .../method_channel_file_selector_test.dart | 51 +- .../test/x_type_group_test.dart | 48 +- .../integration_test/dom_helper_test.dart | 20 +- .../file_selector_web_test.dart | 25 +- .../lib/file_selector_web.dart | 10 +- .../file_selector_web/lib/src/dom_helper.dart | 5 +- .../file_selector_web/test/utils_test.dart | 10 +- .../example/lib/get_directory_page.dart | 16 +- .../lib/get_multiple_directories_page.dart | 16 +- .../example/lib/home_page.dart | 3 +- .../example/lib/main.dart | 6 +- .../example/lib/open_image_page.dart | 5 +- .../lib/open_multiple_images_page.dart | 12 +- .../example/lib/open_text_page.dart | 14 +- .../example/lib/save_text_page.dart | 23 +- .../lib/file_selector_windows.dart | 28 +- .../lib/src/messages.g.dart | 57 +- .../test/file_selector_windows_test.dart | 66 +- .../example/lib/main.dart | 4 +- .../example/lib/async_redirection.dart | 33 +- .../go_router/example/lib/books/main.dart | 51 +- .../go_router/example/lib/books/src/auth.dart | 5 +- .../example/lib/books/src/data/library.dart | 54 +- .../lib/books/src/screens/book_details.dart | 21 +- .../example/lib/books/src/screens/books.dart | 3 +- .../lib/books/src/screens/scaffold.dart | 6 +- .../lib/books/src/screens/settings.dart | 49 +- .../lib/books/src/screens/sign_in.dart | 10 +- .../lib/books/src/widgets/author_list.dart | 11 +- .../lib/books/src/widgets/book_list.dart | 11 +- .../go_router/example/lib/extra_codec.dart | 10 +- .../go_router/example/lib/named_routes.dart | 46 +- .../others/custom_stateful_shell_route.dart | 257 +- .../example/lib/others/error_screen.dart | 27 +- .../example/lib/others/extra_param.dart | 28 +- .../example/lib/others/init_loc.dart | 27 +- .../example/lib/others/nav_observer.dart | 39 +- .../go_router/example/lib/others/push.dart | 20 +- .../example/lib/others/router_neglect.dart | 22 +- .../example/lib/others/transitions.dart | 62 +- .../lib/path_and_query_parameters.dart | 39 +- .../example/lib/push_with_shell_route.dart | 15 +- .../go_router/example/lib/redirection.dart | 23 +- .../go_router/example/lib/routing_config.dart | 55 +- .../go_router/example/lib/shell_route.dart | 18 +- .../example/lib/shell_route_top_route.dart | 34 +- .../go_route_state_restoration.dart | 5 +- .../shell_route_state_restoration.dart | 18 +- ...tateful_shell_route_state_restoration.dart | 31 +- .../example/lib/stateful_shell_route.dart | 83 +- .../example/lib/top_level_on_enter.dart | 230 +- .../example/lib/transition_animations.dart | 58 +- .../custom_stateful_shell_route_test.dart | 38 +- .../example/test/exception_handling_test.dart | 5 +- .../example/test/extra_codec_test.dart | 10 +- .../test/path_and_query_params_test.dart | 20 +- .../go_route_state_restoration_test.dart | 4 +- .../shell_route_state_restoration_test.dart | 4 +- ...ul_shell_route_state_restoration_test.dart | 4 +- packages/go_router/lib/go_router.dart | 6 +- packages/go_router/lib/src/builder.dart | 126 +- packages/go_router/lib/src/configuration.dart | 251 +- packages/go_router/lib/src/delegate.dart | 46 +- .../lib/src/information_provider.dart | 84 +- packages/go_router/lib/src/logging.dart | 3 +- packages/go_router/lib/src/match.dart | 200 +- .../go_router/lib/src/misc/error_screen.dart | 20 +- .../go_router/lib/src/misc/extensions.dart | 3 +- .../lib/src/misc/inherited_router.dart | 6 +- .../go_router/lib/src/pages/cupertino.dart | 8 +- .../lib/src/pages/custom_transition_page.dart | 12 +- .../go_router/lib/src/pages/material.dart | 8 +- packages/go_router/lib/src/parser.dart | 184 +- packages/go_router/lib/src/path_utils.dart | 60 +- packages/go_router/lib/src/route.dart | 236 +- packages/go_router/lib/src/route_data.dart | 122 +- packages/go_router/lib/src/router.dart | 80 +- packages/go_router/lib/src/state.dart | 36 +- packages/go_router/test/builder_test.dart | 75 +- .../go_router/test/configuration_test.dart | 750 ++- packages/go_router/test/cupertino_test.dart | 16 +- .../test/custom_transition_page_test.dart | 89 +- packages/go_router/test/delegate_test.dart | 746 ++- packages/go_router/test/error_page_test.dart | 4 +- .../test/exception_handling_test.dart | 85 +- packages/go_router/test/extension_test.dart | 32 +- packages/go_router/test/extra_codec_test.dart | 4 +- packages/go_router/test/go_route_test.dart | 147 +- .../go_router/test/go_router_state_test.dart | 153 +- packages/go_router/test/go_router_test.dart | 4069 ++++++-------- .../go_router/test/imperative_api_test.dart | 160 +- .../test/information_provider_test.dart | 53 +- packages/go_router/test/inherited_test.dart | 44 +- packages/go_router/test/logging_test.dart | 41 +- packages/go_router/test/match_test.dart | 78 +- packages/go_router/test/matching_test.dart | 34 +- packages/go_router/test/material_test.dart | 16 +- packages/go_router/test/name_case_test.dart | 10 +- packages/go_router/test/on_enter_test.dart | 1956 ++++--- packages/go_router/test/on_exit_test.dart | 482 +- packages/go_router/test/parser_test.dart | 606 +-- packages/go_router/test/path_utils_test.dart | 47 +- packages/go_router/test/rebuild_test.dart | 9 +- .../go_router/test/redirect_chain_test.dart | 536 +- packages/go_router/test/request_focus.dart | 6 +- packages/go_router/test/route_data_test.dart | 437 +- .../go_router/test/routing_config_test.dart | 79 +- .../test/shell_route_observers_test.dart | 74 +- .../test/shell_route_system_back_test.dart | 4 +- ...stateful_shell_route_system_back_test.dart | 19 +- packages/go_router/test/test_helpers.dart | 85 +- packages/go_router/tool/run_tests.dart | 18 +- .../example/lib/all_extension_types.dart | 91 +- .../example/lib/all_extension_types.g.dart | 271 +- .../example/lib/all_types.dart | 98 +- .../example/lib/all_types.g.dart | 464 +- .../example/lib/case_sensitive_example.dart | 21 +- .../example/lib/case_sensitive_example.g.dart | 18 +- .../example/lib/custom_encoder_example.dart | 14 +- .../example/lib/custom_encoder_example.g.dart | 16 +- .../example/lib/extra_example.dart | 17 +- .../example/lib/extra_example.g.dart | 36 +- .../example/lib/go_relative.dart | 35 +- .../example/lib/go_relative.g.dart | 39 +- .../example/lib/json_example.dart | 11 +- .../example/lib/json_example.g.dart | 12 +- .../example/lib/json_nested_example.dart | 10 +- .../example/lib/json_nested_example.g.dart | 21 +- .../go_router_builder/example/lib/main.dart | 48 +- .../go_router_builder/example/lib/main.g.dart | 64 +- .../example/lib/on_exit_example.dart | 7 +- .../example/lib/on_exit_example.g.dart | 10 +- .../example/lib/readme_excerpts.dart | 39 +- .../example/lib/readme_excerpts.g.dart | 130 +- .../example/lib/shared/data.dart | 9 +- .../example/lib/shell_route_example.dart | 14 +- .../example/lib/shell_route_example.g.dart | 15 +- .../lib/shell_route_with_keys_example.dart | 17 +- .../lib/shell_route_with_keys_example.g.dart | 20 +- .../shell_route_with_observers_example.dart | 26 +- .../shell_route_with_observers_example.g.dart | 24 +- .../example/lib/simple_example.dart | 16 +- .../example/lib/simple_example.g.dart | 16 +- .../lib/stateful_shell_route_example.dart | 57 +- .../lib/stateful_shell_route_example.g.dart | 29 +- ..._shell_route_initial_location_example.dart | 29 +- ...hell_route_initial_location_example.g.dart | 35 +- .../lib/typed_query_parameter_example.dart | 29 +- .../lib/typed_query_parameter_example.g.dart | 36 +- .../example/test/all_types_test.dart | 340 +- .../test/case_sensitivity_example_test.dart | 6 +- .../example/test/location_test.dart | 13 +- .../example/test/on_exit_example_test.dart | 14 +- .../example/test/simple_example_test.dart | 4 +- ...ful_shell_route_initial_location_test.dart | 19 +- .../test/stateful_shell_route_test.dart | 4 +- .../test/typed_query_parameter_test.dart | 6 +- .../lib/src/go_router_generator.dart | 33 +- .../go_router_builder/lib/src/path_utils.dart | 3 +- .../lib/src/route_config.dart | 146 +- .../lib/src/type_helpers.dart | 194 +- .../test/path_utils_test.dart | 14 +- .../test_inputs/case_sensitivity.dart | 6 +- .../test_inputs/custom_encoder.dart | 7 +- .../test_inputs/extension_type_parameter.dart | 41 +- .../test_inputs/go_relative.dart | 28 +- .../iterable_with_default_value.dart | 3 +- .../go_router_builder/test_inputs/list.dart | 6 +- .../test_inputs/nullable_default_value.dart | 3 +- ..._route_with_direct_absolute_sub_route.dart | 18 +- ...oute_with_indirect_absolute_sub_route.dart | 17 +- .../test_inputs/required_extra_value.dart | 3 +- ...d_nullable_type_arguments_extra_value.dart | 4 +- ...ed_parameters_in_path_cannnot_be_null.dart | 3 +- ...ed_parameters_not_in_path_can_be_null.dart | 3 +- .../go_router_builder/test_inputs/set.dart | 6 +- .../test_inputs/typed_query_parameter.dart | 8 +- .../go_router_builder/tool/run_tests.dart | 8 +- .../example/integration_test/core_test.dart | 23 +- .../experimental_ad_unit_widget_test.dart | 74 +- .../example/integration_test/h5_test.dart | 13 +- .../js_interop_mocks/h5_test_js_interop.dart | 5 +- .../integration_test/script_tag_test.dart | 3 +- .../example/lib/ad_unit_widget.dart | 5 +- packages/google_adsense/example/lib/h5.dart | 23 +- packages/google_adsense/example/lib/main.dart | 1 + .../src/adsense/ad_unit_configuration.dart | 9 +- .../lib/src/adsense/ad_unit_widget.dart | 27 +- .../lib/src/core/adsense_code_parameters.dart | 6 +- .../lib/src/core/js_interop/js_loader.dart | 12 +- packages/google_adsense/lib/src/h5/h5.dart | 3 +- .../lib/src/h5/h5_js_interop.dart | 13 +- .../example/lib/example_font_selection.dart | 45 +- .../example/lib/example_simple.dart | 5 +- packages/google_fonts/example/lib/main.dart | 4 +- .../example/lib/readme_excerpts.dart | 19 +- .../example/test/widget_test.dart | 8 +- packages/google_fonts/generator/fonts.pb.dart | 71 +- .../google_fonts/generator/generator.dart | 59 +- packages/google_fonts/lib/src/file_io.dart | 5 +- .../lib/src/google_fonts_all_parts.dart | 378 +- .../lib/src/google_fonts_base.dart | 31 +- .../lib/src/google_fonts_descriptor.dart | 5 +- .../src/google_fonts_family_with_variant.dart | 5 +- .../lib/src/google_fonts_parts/part_a.dart | 52 +- .../lib/src/google_fonts_parts/part_b.dart | 16 +- .../lib/src/google_fonts_parts/part_c.dart | 4 +- .../lib/src/google_fonts_parts/part_f.dart | 4 +- .../lib/src/google_fonts_parts/part_i.dart | 8 +- .../lib/src/google_fonts_parts/part_j.dart | 28 +- .../lib/src/google_fonts_parts/part_l.dart | 45 +- .../lib/src/google_fonts_parts/part_n.dart | 413 +- .../lib/src/google_fonts_parts/part_p.dart | 132 +- .../lib/src/google_fonts_parts/part_s.dart | 60 +- .../lib/src/google_fonts_parts/part_t.dart | 8 +- .../lib/src/google_fonts_parts/part_y.dart | 4 +- .../lib/src/google_fonts_parts/part_z.dart | 16 +- .../lib/src/google_fonts_variant.dart | 34 +- ...mily_with_variant_asset_path_web_test.dart | 131 +- .../test/generated_font_methods_test.dart | 546 +- ...google_fonts_family_with_variant_test.dart | 8 +- .../test/google_fonts_text_style_test.dart | 20 +- .../test/google_fonts_variant_test.dart | 207 +- .../test/load_font_if_necessary_test.dart | 142 +- ...nt_if_necessary_with_local_fonts_test.dart | 27 +- .../integration_test/js_interop_id_test.dart | 63 +- .../js_interop_oauth_test.dart | 21 +- .../example/integration_test/utils.dart | 34 +- .../example/lib/main.dart | 1 + .../example/lib/main_oauth.dart | 8 +- .../example/lib/src/jwt.dart | 3 +- .../lib/oauth2.dart | 3 +- .../src/js_interop/google_accounts_id.dart | 33 +- .../js_interop/google_accounts_oauth2.dart | 21 +- .../lib/src/js_loader.dart | 15 +- .../test/js_loader_test.dart | 6 +- .../integration_test/src/maps_controller.dart | 77 +- .../integration_test/src/maps_inspector.dart | 193 +- .../example/integration_test/src/shared.dart | 3 +- .../integration_test/src/tiles_inspector.dart | 220 +- .../example/lib/advanced_marker_icons.dart | 47 +- .../lib/advanced_markers_clustering.dart | 42 +- .../example/lib/animate_camera.dart | 16 +- .../example/lib/clustering.dart | 35 +- .../example/lib/collision_behavior.dart | 16 +- .../example/lib/custom_marker_icon.dart | 4 +- .../example/lib/ground_overlay.dart | 55 +- .../example/lib/heatmap.dart | 13 +- .../example/lib/lite_mode.dart | 5 +- .../google_maps_flutter/example/lib/main.dart | 9 +- .../example/lib/map_click.dart | 29 +- .../example/lib/map_coordinates.dart | 10 +- .../example/lib/map_map_id.dart | 21 +- .../example/lib/map_ui.dart | 52 +- .../example/lib/marker_icons.dart | 79 +- .../example/lib/move_camera.dart | 24 +- .../example/lib/padding.dart | 17 +- .../example/lib/place_advanced_marker.dart | 97 +- .../example/lib/place_circle.dart | 22 +- .../example/lib/place_marker.dart | 79 +- .../example/lib/place_polygon.dart | 26 +- .../example/lib/place_polyline.dart | 52 +- .../example/lib/readme_sample.dart | 8 +- .../lib/readme_sample_advanced_markers.dart | 5 +- .../example/lib/scrolling_map.dart | 30 +- .../example/lib/snapshot.dart | 8 +- .../example/lib/tile_overlay.dart | 32 +- .../lib/src/controller.dart | 114 +- .../lib/src/google_map.dart | 73 +- .../google_maps_flutter/test/camera_test.dart | 13 +- .../test/clustermanager_updates_test.dart | 62 +- .../test/controller_test.dart | 8 +- .../fake_google_maps_flutter_platform.dart | 129 +- .../test/google_map_controller_test.dart | 13 +- .../test/google_map_test.dart | 192 +- .../test/google_maps_flutter_export_test.dart | 113 +- .../test/groundoverlay_updates_test.dart | 71 +- .../test/heatmap_updates_test.dart | 13 +- .../test/map_creation_test.dart | 20 +- .../test/marker_updates_test.dart | 6 +- .../test/polygon_updates_test.dart | 68 +- .../test/polyline_updates_test.dart | 25 +- .../test/tile_overlay_updates_test.dart | 5 +- .../integration_test/google_maps_test.dart | 607 +-- .../example/lib/advanced_marker_icons.dart | 47 +- .../lib/advanced_markers_clustering.dart | 29 +- .../example/lib/animate_camera.dart | 16 +- .../example/lib/clustering.dart | 25 +- .../example/lib/collision_behavior.dart | 16 +- .../example/lib/custom_marker_icon.dart | 4 +- .../example/lib/example_google_map.dart | 154 +- .../example/lib/ground_overlay.dart | 47 +- .../example/lib/main.dart | 8 +- .../example/lib/map_click.dart | 29 +- .../example/lib/map_coordinates.dart | 10 +- .../example/lib/map_map_id.dart | 17 +- .../example/lib/map_ui.dart | 36 +- .../example/lib/marker_icons.dart | 79 +- .../example/lib/move_camera.dart | 24 +- .../example/lib/padding.dart | 17 +- .../example/lib/place_advanced_marker.dart | 123 +- .../example/lib/place_circle.dart | 22 +- .../example/lib/place_marker.dart | 79 +- .../example/lib/place_polygon.dart | 26 +- .../example/lib/place_polyline.dart | 52 +- .../example/lib/readme_excerpts.dart | 11 +- .../example/lib/scrolling_map.dart | 30 +- .../example/lib/snapshot.dart | 3 +- .../example/lib/tile_overlay.dart | 32 +- .../example/test/example_google_map_test.dart | 17 +- .../fake_google_maps_flutter_platform.dart | 97 +- .../lib/src/google_map_inspector_android.dart | 38 +- .../lib/src/google_maps_flutter_android.dart | 455 +- .../lib/src/messages.g.dart | 416 +- .../pigeons/messages.dart | 29 +- .../google_maps_flutter_android_test.dart | 608 +-- ...oogle_maps_flutter_android_test.mocks.dart | 429 +- .../integration_test/google_maps_test.dart | 630 +-- .../example/lib/advanced_marker_icons.dart | 47 +- .../lib/advanced_markers_clustering.dart | 29 +- .../example/lib/animate_camera.dart | 16 +- .../example/lib/clustering.dart | 35 +- .../example/lib/collision_behavior.dart | 16 +- .../example/lib/custom_marker_icon.dart | 4 +- .../example/lib/example_google_map.dart | 158 +- .../example/lib/ground_overlay.dart | 43 +- .../example/lib/map_click.dart | 29 +- .../example/lib/map_coordinates.dart | 14 +- .../example/lib/map_map_id.dart | 17 +- .../example/lib/map_ui.dart | 36 +- .../example/lib/marker_icons.dart | 79 +- .../example/lib/move_camera.dart | 24 +- .../example/lib/padding.dart | 17 +- .../example/lib/place_advanced_marker.dart | 113 +- .../example/lib/place_circle.dart | 22 +- .../example/lib/place_marker.dart | 109 +- .../example/lib/place_polygon.dart | 26 +- .../example/lib/place_polyline.dart | 52 +- .../example/lib/scrolling_map.dart | 30 +- .../example/lib/snapshot.dart | 3 +- .../example/lib/tile_overlay.dart | 32 +- .../example/test/example_google_map_test.dart | 17 +- .../fake_google_maps_flutter_platform.dart | 97 +- .../lib/src/google_map_inspector_ios.dart | 68 +- .../lib/src/google_maps_flutter_ios.dart | 422 +- .../lib/src/messages.g.dart | 306 +- .../pigeons/messages.dart | 29 +- .../test/google_maps_flutter_ios_test.dart | 612 +-- .../google_maps_flutter_ios_test.mocks.dart | 372 +- .../tool/run_tests.dart | 13 +- .../tool/sync_shared_files.dart | 49 +- .../google_maps_flutter_ios/tool/utils.dart | 20 +- .../integration_test/google_maps_test.dart | 630 +-- .../example/lib/advanced_marker_icons.dart | 47 +- .../lib/advanced_markers_clustering.dart | 29 +- .../example/lib/animate_camera.dart | 16 +- .../example/lib/clustering.dart | 35 +- .../example/lib/collision_behavior.dart | 16 +- .../example/lib/custom_marker_icon.dart | 4 +- .../example/lib/example_google_map.dart | 158 +- .../example/lib/ground_overlay.dart | 43 +- .../example/lib/map_click.dart | 29 +- .../example/lib/map_coordinates.dart | 14 +- .../example/lib/map_map_id.dart | 17 +- .../example/lib/map_ui.dart | 36 +- .../example/lib/marker_icons.dart | 79 +- .../example/lib/move_camera.dart | 24 +- .../example/lib/padding.dart | 17 +- .../example/lib/place_advanced_marker.dart | 113 +- .../example/lib/place_circle.dart | 22 +- .../example/lib/place_marker.dart | 109 +- .../example/lib/place_polygon.dart | 26 +- .../example/lib/place_polyline.dart | 52 +- .../example/lib/scrolling_map.dart | 30 +- .../example/lib/snapshot.dart | 3 +- .../example/lib/tile_overlay.dart | 32 +- .../example/test/example_google_map_test.dart | 17 +- .../fake_google_maps_flutter_platform.dart | 97 +- .../lib/src/google_map_inspector_ios.dart | 68 +- .../lib/src/google_maps_flutter_ios.dart | 422 +- .../lib/src/messages.g.dart | 306 +- .../pigeons/messages.dart | 29 +- .../test/google_maps_flutter_ios_test.dart | 612 +-- .../google_maps_flutter_ios_test.mocks.dart | 372 +- .../tool/run_tests.dart | 13 +- .../tool/sync_shared_files.dart | 49 +- .../tool/utils.dart | 20 +- .../integration_test/google_maps_test.dart | 630 +-- .../example/lib/advanced_marker_icons.dart | 47 +- .../lib/advanced_markers_clustering.dart | 29 +- .../example/lib/animate_camera.dart | 16 +- .../example/lib/clustering.dart | 35 +- .../example/lib/collision_behavior.dart | 16 +- .../example/lib/custom_marker_icon.dart | 4 +- .../example/lib/example_google_map.dart | 158 +- .../example/lib/ground_overlay.dart | 43 +- .../example/lib/map_click.dart | 29 +- .../example/lib/map_coordinates.dart | 14 +- .../example/lib/map_map_id.dart | 17 +- .../example/lib/map_ui.dart | 36 +- .../example/lib/marker_icons.dart | 79 +- .../example/lib/move_camera.dart | 24 +- .../example/lib/padding.dart | 17 +- .../example/lib/place_advanced_marker.dart | 113 +- .../example/lib/place_circle.dart | 22 +- .../example/lib/place_marker.dart | 109 +- .../example/lib/place_polygon.dart | 26 +- .../example/lib/place_polyline.dart | 52 +- .../example/lib/scrolling_map.dart | 30 +- .../example/lib/snapshot.dart | 3 +- .../example/lib/tile_overlay.dart | 32 +- .../example/test/example_google_map_test.dart | 17 +- .../fake_google_maps_flutter_platform.dart | 97 +- .../lib/src/google_map_inspector_ios.dart | 68 +- .../lib/src/google_maps_flutter_ios.dart | 422 +- .../lib/src/messages.g.dart | 306 +- .../pigeons/messages.dart | 29 +- .../test/google_maps_flutter_ios_test.dart | 612 +-- .../google_maps_flutter_ios_test.mocks.dart | 372 +- .../tool/run_tests.dart | 13 +- .../tool/sync_shared_files.dart | 49 +- .../tool/utils.dart | 20 +- .../integration_test/google_maps_test.dart | 630 +-- .../example/lib/advanced_marker_icons.dart | 47 +- .../lib/advanced_markers_clustering.dart | 29 +- .../example/lib/animate_camera.dart | 16 +- .../example/lib/clustering.dart | 35 +- .../example/lib/collision_behavior.dart | 16 +- .../example/lib/custom_marker_icon.dart | 4 +- .../example/lib/example_google_map.dart | 158 +- .../example/lib/ground_overlay.dart | 43 +- .../example/lib/map_click.dart | 29 +- .../example/lib/map_coordinates.dart | 14 +- .../example/lib/map_map_id.dart | 17 +- .../example/lib/map_ui.dart | 36 +- .../example/lib/marker_icons.dart | 79 +- .../example/lib/move_camera.dart | 24 +- .../example/lib/padding.dart | 17 +- .../example/lib/place_advanced_marker.dart | 113 +- .../example/lib/place_circle.dart | 22 +- .../example/lib/place_marker.dart | 109 +- .../example/lib/place_polygon.dart | 26 +- .../example/lib/place_polyline.dart | 52 +- .../example/lib/scrolling_map.dart | 30 +- .../example/lib/snapshot.dart | 3 +- .../example/lib/tile_overlay.dart | 32 +- .../example/test/example_google_map_test.dart | 17 +- .../fake_google_maps_flutter_platform.dart | 97 +- .../lib/src/google_map_inspector_ios.dart | 68 +- .../lib/src/google_maps_flutter_ios.dart | 422 +- .../lib/src/messages.g.dart | 306 +- .../pigeons/messages.dart | 29 +- .../test/google_maps_flutter_ios_test.dart | 612 +-- .../google_maps_flutter_ios_test.mocks.dart | 372 +- .../tool/run_tests.dart | 13 +- .../tool/sync_shared_files.dart | 49 +- .../tool/utils.dart | 20 +- .../method_channel_google_maps_flutter.dart | 218 +- .../lib/src/method_channel/serialization.dart | 39 +- .../google_maps_flutter_platform.dart | 85 +- .../google_maps_inspector_platform.dart | 33 +- .../lib/src/types/advanced_marker.dart | 3 +- .../lib/src/types/bitmap.dart | 98 +- .../lib/src/types/camera.dart | 12 +- .../lib/src/types/cap.dart | 14 +- .../lib/src/types/circle_updates.dart | 3 +- .../lib/src/types/cluster.dart | 6 +- .../lib/src/types/cluster_manager.dart | 3 +- .../src/types/cluster_manager_updates.dart | 3 +- .../lib/src/types/ground_overlay.dart | 5 +- .../lib/src/types/ground_overlay_updates.dart | 3 +- .../lib/src/types/heatmap.dart | 45 +- .../lib/src/types/heatmap_updates.dart | 3 +- .../lib/src/types/location.dart | 22 +- .../lib/src/types/map_configuration.dart | 61 +- .../lib/src/types/maps_object_updates.dart | 19 +- .../lib/src/types/marker.dart | 15 +- .../lib/src/types/marker_updates.dart | 3 +- .../lib/src/types/pattern_item.dart | 10 +- .../lib/src/types/polygon.dart | 3 +- .../lib/src/types/polygon_updates.dart | 3 +- .../lib/src/types/polyline.dart | 3 +- .../lib/src/types/polyline_updates.dart | 6 +- .../lib/src/types/tile_overlay.dart | 11 +- .../lib/src/types/tile_overlay_updates.dart | 6 +- .../lib/src/types/ui.dart | 9 +- .../lib/src/types/utils/ground_overlay.dart | 8 +- .../map_configuration_serialization.dart | 34 +- .../lib/src/types/utils/maps_object.dart | 8 +- .../lib/src/types/utils/tile_overlay.dart | 8 +- ...thod_channel_google_maps_flutter_test.dart | 55 +- .../google_maps_flutter_platform_test.dart | 78 +- .../google_maps_inspector_platform_test.dart | 9 +- .../test/types/advanced_marker_test.dart | 28 +- .../test/types/bitmap_test.dart | 282 +- .../test/types/camera_test.dart | 14 +- .../test/types/cap_test.dart | 5 +- .../test/types/cluster_manager_test.dart | 16 +- .../test/types/cluster_test.dart | 5 +- .../test/types/heatmap_test.dart | 43 +- .../test/types/map_configuration_test.dart | 24 +- .../test/types/maps_object_test.dart | 6 +- .../test/types/maps_object_updates_test.dart | 32 +- .../test/types/marker_test.dart | 16 +- .../test/types/test_maps_object.dart | 7 +- .../test/types/tile_overlay_test.dart | 10 +- .../test/types/tile_overlay_updates_test.dart | 29 +- .../test/utils/cluster_manager_test.dart | 3 +- .../map_configuration_serialization_test.dart | 15 +- .../advanced_marker_test.dart | 60 +- .../advanced_markers_test.dart | 203 +- .../cloud_map_styles_test.dart | 21 +- .../google_maps_controller_test.dart | 318 +- .../google_maps_controller_test.mocks.dart | 500 +- .../google_maps_plugin_test.dart | 235 +- .../google_maps_plugin_test.mocks.dart | 286 +- .../marker_clustering_test.dart | 47 +- .../example/integration_test/marker_test.dart | 49 +- .../integration_test/markers_test.dart | 190 +- .../integration_test/overlay_test.dart | 45 +- .../integration_test/overlays_test.dart | 36 +- .../integration_test/overlays_test.mocks.dart | 26 +- .../integration_test/projection_test.dart | 154 +- .../example/integration_test/shape_test.dart | 22 +- .../example/integration_test/shapes_test.dart | 124 +- .../lib/src/circles.dart | 3 +- .../lib/src/convert.dart | 217 +- .../lib/src/google_maps_controller.dart | 154 +- .../lib/src/google_maps_flutter_web.dart | 84 +- .../lib/src/google_maps_inspector_web.dart | 32 +- .../lib/src/ground_overlay.dart | 6 +- .../lib/src/ground_overlays.dart | 25 +- .../lib/src/heatmap.dart | 3 +- .../lib/src/heatmaps.dart | 12 +- .../lib/src/marker.dart | 25 +- .../lib/src/marker_clustering.dart | 51 +- .../lib/src/marker_clustering_js_interop.dart | 36 +- .../lib/src/markers.dart | 141 +- .../lib/src/overlay.dart | 6 +- .../lib/src/overlays.dart | 10 +- .../lib/src/polygons.dart | 11 +- .../lib/src/polyline.dart | 5 +- .../lib/src/polylines.dart | 15 +- .../to_screen_location.dart | 15 +- .../google_sign_in/example/lib/main.dart | 62 +- .../example/lib/src/web_wrapper.dart | 3 +- .../google_sign_in/lib/google_sign_in.dart | 98 +- .../google_sign_in/lib/src/event_types.dart | 6 +- .../google_sign_in/lib/testing.dart | 5 +- .../google_sign_in/lib/widgets.dart | 13 +- .../google_sign_in/test/fife_test.dart | 13 +- .../test/google_sign_in_test.dart | 375 +- .../test/google_sign_in_test.mocks.dart | 121 +- .../google_sign_in/test/widgets_test.dart | 11 +- .../example/lib/main.dart | 60 +- .../lib/google_sign_in_android.dart | 49 +- .../lib/src/messages.g.dart | 179 +- .../pigeons/messages.dart | 8 +- .../test/google_sign_in_android_test.dart | 560 +- .../google_sign_in_android_test.mocks.dart | 140 +- .../google_sign_in_ios/example/lib/main.dart | 61 +- .../lib/google_sign_in_ios.dart | 58 +- .../lib/src/messages.g.dart | 139 +- .../google_sign_in_ios/pigeons/messages.dart | 9 +- .../test/google_sign_in_ios_test.dart | 967 ++-- .../test/google_sign_in_ios_test.mocks.dart | 120 +- .../google_sign_in_platform_interface.dart | 4 +- .../lib/src/types.dart | 35 +- ...oogle_sign_in_platform_interface_test.dart | 42 +- .../flexible_size_html_element_view_test.dart | 58 +- .../google_sign_in_web_test.dart | 117 +- .../google_sign_in_web_test.mocks.dart | 83 +- .../integration_test/src/jwt_examples.dart | 27 +- .../example/integration_test/utils_test.dart | 47 +- .../integration_test/web_only_test.dart | 19 +- .../integration_test/web_only_test.mocks.dart | 83 +- .../example/lib/button_tester.dart | 22 +- .../lib/src/button_configuration_column.dart | 67 +- .../lib/google_sign_in_web.dart | 41 +- .../lib/src/button_configuration.dart | 57 +- .../src/flexible_size_html_element_view.dart | 13 +- .../lib/src/gis_client.dart | 39 +- .../google_sign_in_web/lib/src/utils.dart | 12 +- .../image_picker/example/lib/main.dart | 89 +- .../example/lib/readme_excerpts.dart | 14 +- .../example/test/readme_excerpts_test.dart | 5 +- .../image_picker/lib/image_picker.dart | 10 +- .../image_picker/test/image_picker_test.dart | 283 +- .../test/image_picker_test.mocks.dart | 208 +- .../example/lib/main.dart | 102 +- .../lib/image_picker_android.dart | 66 +- .../lib/src/messages.g.dart | 65 +- .../pigeons/messages.dart | 9 +- .../test/image_picker_android_test.dart | 143 +- .../image_picker_for_web_test.dart | 121 +- .../integration_test/image_resizer_test.dart | 98 +- .../readme_excerpts_test.dart | 8 +- .../lib/image_picker_for_web.dart | 62 +- .../lib/src/image_resizer.dart | 32 +- .../lib/src/image_resizer_utils.dart | 10 +- .../lib/src/pkg_web_tweaks.dart | 4 +- .../test/image_resizer_utils_test.dart | 26 +- .../image_picker_ios/example/lib/main.dart | 97 +- .../lib/image_picker_ios.dart | 39 +- .../image_picker_ios/lib/src/messages.g.dart | 141 +- .../test/image_picker_ios_test.dart | 176 +- .../image_picker_linux/example/lib/main.dart | 94 +- .../lib/image_picker_linux.dart | 28 +- .../test/image_picker_linux_test.dart | 111 +- .../test/image_picker_linux_test.mocks.dart | 112 +- .../image_picker_macos/example/lib/main.dart | 94 +- .../lib/image_picker_macos.dart | 24 +- .../test/image_picker_macos_test.dart | 137 +- .../test/image_picker_macos_test.mocks.dart | 112 +- .../method_channel_image_picker.dart | 43 +- .../image_picker_platform.dart | 10 +- .../lib/src/types/camera_delegate.dart | 6 +- .../src/types/multi_image_picker_options.dart | 5 +- .../lib/src/types/picked_file/html.dart | 4 +- .../lib/src/types/picked_file/io.dart | 4 +- .../src/types/picked_file/picked_file.dart | 4 +- .../src/types/picked_file/unsupported.dart | 4 +- .../test/image_picker_platform_test.dart | 86 +- .../test/media_options_test.dart | 36 +- .../method_channel_image_picker_test.dart | 787 ++- .../test/multi_image_picker_options_test.dart | 26 +- .../test/picked_file_html_test.dart | 10 +- .../test/picked_file_io_test.dart | 9 +- .../example/lib/main.dart | 94 +- .../lib/image_picker_windows.dart | 8 +- .../test/image_picker_windows_test.dart | 119 +- .../test/image_picker_windows_test.mocks.dart | 112 +- .../example/lib/consumable_store.dart | 3 +- .../in_app_purchase/example/lib/main.dart | 80 +- .../in_app_purchase/lib/in_app_purchase.dart | 23 +- .../test/in_app_purchase_test.dart | 55 +- .../in_app_purchase_test.dart | 43 +- .../example/lib/consumable_store.dart | 3 +- .../example/lib/main.dart | 131 +- .../example/lib/migration_guide_examples.dart | 8 +- ...illing_only_reporting_details_wrapper.dart | 6 +- .../billing_client_manager.dart | 34 +- .../billing_client_wrapper.dart | 63 +- .../billing_config_wrapper.dart | 3 +- .../billing_response_wrapper.dart | 3 +- .../pending_purchases_params_wrapper.dart | 3 +- .../purchase_wrapper.dart | 5 +- .../subscription_offer_details_wrapper.dart | 3 +- .../user_choice_details_wrapper.dart | 7 +- .../src/in_app_purchase_android_platform.dart | 154 +- ...pp_purchase_android_platform_addition.dart | 68 +- .../lib/src/messages.g.dart | 240 +- .../lib/src/pigeon_converters.dart | 150 +- .../src/types/change_subscription_param.dart | 5 +- .../types/google_play_product_details.dart | 26 +- .../types/google_play_purchase_details.dart | 10 +- .../google_play_user_choice_details.dart | 7 +- .../lib/src/types/translator.dart | 8 +- .../pigeons/messages.dart | 51 +- .../billing_client_manager_test.dart | 213 +- .../billing_client_wrapper_test.dart | 314 +- .../billing_client_wrapper_test.mocks.dart | 458 +- .../product_details_wrapper_test.dart | 17 +- .../purchase_wrapper_test.dart | 32 +- ...rchase_android_platform_addition_test.dart | 77 +- ...in_app_purchase_android_platform_test.dart | 913 ++-- .../test/test_conversion_utils.dart | 22 +- .../test/types/translator_test.dart | 18 +- .../lib/src/errors/in_app_purchase_error.dart | 7 +- .../src/errors/in_app_purchase_exception.dart | 6 +- .../lib/src/in_app_purchase_platform.dart | 13 +- .../src/types/product_details_response.dart | 6 +- .../test/in_app_purchase_platform_test.dart | 182 +- .../in_app_purchase_exception_test.dart | 5 +- .../test/src/types/product_details_test.dart | 37 +- .../in_app_purchase_test.dart | 7 +- .../example/lib/consumable_store.dart | 3 +- .../example/lib/main.dart | 96 +- .../lib/src/channel.dart | 4 +- .../lib/src/in_app_purchase_apis.dart | 5 +- .../in_app_purchase_storekit_platform.dart | 113 +- ...p_purchase_storekit_platform_addition.dart | 6 +- .../lib/src/messages.g.dart | 307 +- .../lib/src/sk2_pigeon.g.dart | 133 +- .../sk2_product_wrapper.dart | 36 +- .../sk2_transaction_wrapper.dart | 7 +- .../store_kit_wrappers/enum_converters.dart | 29 +- .../store_kit_wrappers/enum_converters.g.dart | 10 +- .../sk_payment_queue_wrapper.dart | 80 +- .../sk_payment_queue_wrapper.g.dart | 55 +- .../sk_payment_transaction_wrappers.dart | 20 +- .../sk_payment_transaction_wrappers.g.dart | 25 +- .../sk_product_wrapper.dart | 86 +- .../sk_product_wrapper.g.dart | 91 +- .../store_kit_wrappers/sk_request_maker.dart | 13 +- .../sk_storefront_wrapper.dart | 5 +- .../sk_storefront_wrapper.g.dart | 13 +- .../lib/src/types/sk2_purchase_param.dart | 10 +- .../pigeons/messages.dart | 20 +- .../pigeons/sk2_pigeon.dart | 29 +- .../test/fakes/fake_storekit_platform.dart | 114 +- ...app_purchase_storekit_2_platform_test.dart | 690 +-- ...rchase_storekit_platform_addtion_test.dart | 10 +- ...n_app_purchase_storekit_platform_test.dart | 333 +- .../pigeon_converter_test.dart | 26 +- .../sk_methodchannel_apis_test.dart | 95 +- .../sk_payment_queue_delegate_api_test.dart | 21 +- .../store_kit_wrappers/sk_product_test.dart | 185 +- .../sk_test_stub_objects.dart | 133 +- .../example/lib/main.dart | 18 +- .../example/lib/readme_example.dart | 59 +- .../example/lib/video_ad_example_screen.dart | 77 +- .../lib/interactive_media_ads.dart | 3 +- .../interactive_media_ads/lib/src/ad.dart | 10 +- .../lib/src/ad_display_container.dart | 20 +- .../lib/src/ads_loader.dart | 3 +- .../lib/src/ads_manager_delegate.dart | 11 +- .../lib/src/ads_request.dart | 6 +- .../android/android_ad_display_container.dart | 103 +- .../lib/src/android/android_ads_loader.dart | 32 +- .../lib/src/android/android_ads_manager.dart | 42 +- .../android_ads_rendering_settings.dart | 10 +- .../android/android_companion_ad_slot.dart | 21 +- .../android_content_progress_provider.dart | 11 +- .../lib/src/android/android_ima_settings.dart | 3 +- .../android_interactive_media_ads.dart | 8 +- .../lib/src/android/android_view_widget.dart | 23 +- .../lib/src/android/enum_converter_utils.dart | 30 +- .../src/android/interactive_media_ads.g.dart | 2468 ++++----- .../lib/src/companion_ad_slot.dart | 13 +- .../lib/src/content_progress_provider.dart | 9 +- .../lib/src/ima_settings.dart | 12 +- .../lib/src/ios/enum_converter_utils.dart | 21 +- .../lib/src/ios/interactive_media_ads.g.dart | 1787 +++---- .../lib/src/ios/ios_ad_display_container.dart | 14 +- .../lib/src/ios/ios_ads_loader.dart | 26 +- .../lib/src/ios/ios_ads_manager.dart | 7 +- .../lib/src/ios/ios_ads_manager_delegate.dart | 39 +- .../src/ios/ios_ads_rendering_settings.dart | 6 +- .../lib/src/ios/ios_companion_ad_slot.dart | 15 +- .../ios/ios_content_progress_provider.dart | 5 +- .../src/ios/ios_interactive_media_ads.dart | 8 +- .../companion_ad_slot_size.dart | 3 +- .../interactive_media_ads_platform.dart | 8 +- .../platform_ad_display_container.dart | 10 +- .../platform_interface/platform_ad_event.dart | 6 +- .../platform_ads_loader.dart | 3 +- .../platform_ads_manager_delegate.dart | 15 +- .../platform_ads_rendering_settings.dart | 9 +- .../platform_companion_ad_slot.dart | 12 +- .../platform_content_progress_provider.dart | 14 +- .../platform_ima_settings.dart | 3 +- .../interactive_media_ads_android.dart | 79 +- .../pigeons/interactive_media_ads_ios.dart | 33 +- .../test/ad_display_container_test.dart | 61 +- .../test/ads_loader_test.dart | 8 +- .../test/ads_manager_delegate_test.dart | 17 +- .../test/ads_manager_test.dart | 42 +- .../android/ad_display_container_test.dart | 466 +- .../ad_display_container_test.mocks.dart | 1715 +++--- .../test/android/ad_test.dart | 48 +- .../test/android/ad_test.mocks.dart | 401 +- .../test/android/ads_loader_test.dart | 138 +- .../test/android/ads_loader_test.mocks.dart | 2234 +++----- .../test/android/ads_manager_test.dart | 36 +- .../test/android/ads_manager_test.mocks.dart | 1003 ++-- .../test/android/companion_ad_slot_test.dart | 23 +- .../android/companion_ad_slot_test.mocks.dart | 400 +- .../content_progress_provider_test.dart | 6 +- .../content_progress_provider_test.mocks.dart | 66 +- .../test/android/ima_settings_test.dart | 39 +- .../test/android/ima_settings_test.mocks.dart | 352 +- .../test/content_progress_provider_test.dart | 9 +- .../test/ios/ad_display_container_test.dart | 36 +- .../ios/ad_display_container_test.mocks.dart | 339 +- .../test/ios/ad_test.dart | 63 +- .../test/ios/ads_loader_test.dart | 69 +- .../test/ios/ads_loader_test.mocks.dart | 1027 ++-- .../test/ios/ads_manager_delegate_test.dart | 63 +- .../test/ios/ads_manager_test.dart | 22 +- .../test/ios/ads_manager_test.mocks.dart | 287 +- .../test/ios/companion_ad_slot_test.dart | 6 +- .../ios/companion_ad_slot_test.mocks.dart | 105 +- .../content_progress_provider_test.mocks.dart | 63 +- .../test/ios/ima_settings_test.dart | 36 +- .../test/ios/ima_settings_test.mocks.dart | 192 +- .../test/test_stubs.dart | 71 +- .../test/version_test.dart | 22 +- .../local_auth/example/lib/main.dart | 27 +- .../example/lib/readme_excerpts.dart | 7 +- .../local_auth/lib/src/local_auth.dart | 6 +- .../local_auth/test/local_auth_test.dart | 78 +- .../local_auth_android/example/lib/main.dart | 42 +- .../lib/local_auth_android.dart | 35 +- .../lib/src/auth_messages_android.dart | 9 +- .../lib/src/messages.g.dart | 33 +- .../local_auth_android/pigeons/messages.dart | 3 +- .../test/local_auth_test.dart | 527 +- .../test/local_auth_test.mocks.dart | 75 +- .../local_auth_darwin/example/lib/main.dart | 38 +- .../lib/local_auth_darwin.dart | 5 +- .../local_auth_darwin/lib/src/messages.g.dart | 99 +- .../lib/types/auth_messages_ios.dart | 6 +- .../lib/types/auth_messages_macos.dart | 6 +- .../local_auth_darwin/pigeons/messages.dart | 9 +- .../test/local_auth_darwin_test.dart | 1119 ++-- .../test/local_auth_darwin_test.mocks.dart | 65 +- .../lib/default_method_channel_platform.dart | 6 +- .../lib/local_auth_platform_interface.dart | 4 +- .../lib/types/auth_exception.dart | 6 +- .../lib/types/auth_options.dart | 7 +- .../default_method_channel_platform_test.dart | 113 +- .../local_auth_windows/example/lib/main.dart | 23 +- .../lib/local_auth_windows.dart | 7 +- .../lib/src/messages.g.dart | 42 +- .../test/local_auth_test.dart | 20 +- .../material_ui/test/flutter_test_config.dart | 4 +- .../test/goldens/goldens_test.dart | 4 +- packages/material_ui/test/goldens_web.dart | 6 +- packages/metrics_center/lib/src/common.dart | 9 +- packages/metrics_center/lib/src/flutter.dart | 22 +- packages/metrics_center/lib/src/gcs_lock.dart | 5 +- .../lib/src/google_benchmark.dart | 21 +- packages/metrics_center/lib/src/skiaperf.dart | 67 +- .../metrics_center/test/flutter_test.dart | 33 +- .../metrics_center/test/gcs_lock_test.dart | 121 +- .../test/gcs_lock_test.mocks.dart | 2202 ++++---- .../test/google_benchmark_test.dart | 17 +- .../metrics_center/test/skiaperf_test.dart | 303 +- .../test/skiaperf_test.mocks.dart | 342 +- packages/multicast_dns/example/main.dart | 3 +- .../multicast_dns/example/mdns_resolve.dart | 14 +- packages/multicast_dns/example/mdns_sd.dart | 14 +- packages/multicast_dns/lib/multicast_dns.dart | 46 +- .../lib/src/lookup_resolver.dart | 9 +- .../lib/src/native_protocol_client.dart | 20 +- packages/multicast_dns/lib/src/packet.dart | 51 +- .../lib/src/resource_record.dart | 34 +- packages/multicast_dns/test/client_test.dart | 29 +- packages/multicast_dns/test/decode_test.dart | 54 +- .../test/lookup_resolver_test.dart | 30 +- .../test/resource_record_cache_test.dart | 15 +- .../integration_test/path_provider_test.dart | 12 +- .../path_provider/example/lib/main.dart | 60 +- .../path_provider/lib/path_provider.dart | 20 +- .../test/path_provider_test.dart | 28 +- .../integration_test/path_provider_test.dart | 18 +- .../example/lib/main.dart | 48 +- .../lib/src/path_provider.g.dart | 2735 +++------- .../lib/src/path_provider_android_real.dart | 33 +- .../path_provider_android/tool/jnigen.dart | 11 +- .../integration_test/path_provider_test.dart | 141 +- .../path_provider_test.mocks.dart | 84 +- .../example/lib/main.dart | 3 +- .../lib/src/ffi_bindings.g.dart | 144 +- .../src/path_provider_foundation_real.dart | 51 +- .../test/path_provider_foundation_test.dart | 10 +- .../path_provider_foundation/tool/ffigen.dart | 9 +- .../lib/src/get_application_id.dart | 3 +- .../lib/src/get_application_id_real.dart | 7 +- .../lib/src/path_provider_linux.dart | 8 +- .../test/path_provider_linux_test.dart | 26 +- .../lib/path_provider_platform_interface.dart | 24 +- .../lib/src/method_channel_path_provider.dart | 16 +- .../method_channel_path_provider_test.dart | 121 +- ...path_provider_platform_interface_test.dart | 5 +- .../lib/src/folders.dart | 21 +- .../path_provider_windows/lib/src/guid.dart | 5 +- .../lib/src/path_provider_windows_real.dart | 46 +- .../lib/src/win32_wrappers.dart | 59 +- .../path_provider_windows/test/guid_test.dart | 9 +- .../test/path_provider_windows_test.dart | 136 +- packages/pigeon/example/app/lib/main.dart | 18 +- .../app/lib/src/event_channel_messages.g.dart | 8 +- .../example/app/lib/src/messages.g.dart | 41 +- .../app/pigeons/event_channel_messages.dart | 1 + .../pigeon/example/app/pigeons/messages.dart | 4 +- packages/pigeon/lib/src/ast.dart | 89 +- .../src/dart/proxy_api_generator_helper.dart | 228 +- packages/pigeon/lib/src/dart/templates.dart | 12 +- packages/pigeon/lib/src/functional.dart | 11 +- packages/pigeon/lib/src/generator.dart | 143 +- packages/pigeon/lib/src/generator_tools.dart | 65 +- .../lib/src/gobject/gobject_generator.dart | 1107 ++-- packages/pigeon/lib/src/kotlin/templates.dart | 3 +- packages/pigeon/lib/src/pigeon_cl.dart | 6 +- packages/pigeon/lib/src/pigeon_lib.dart | 122 +- .../pigeon/lib/src/pigeon_lib_internal.dart | 569 +- .../pigeons/configure_pigeon_dart_out.dart | 6 +- packages/pigeon/pigeons/core_tests.dart | 169 +- packages/pigeon/pigeons/message.dart | 5 +- packages/pigeon/pigeons/non_null_fields.dart | 8 +- packages/pigeon/pigeons/null_fields.dart | 8 +- packages/pigeon/pigeons/proxy_api_tests.dart | 54 +- .../lib/integration_tests.dart | 2048 +++----- .../background_platform_channels.gen.dart | 20 +- .../lib/src/generated/core_tests.gen.dart | 1230 ++--- .../lib/src/generated/enum.gen.dart | 30 +- .../generated/event_channel_tests.gen.dart | 27 +- ...ent_channel_without_classes_tests.gen.dart | 4 +- .../src/generated/flutter_unittests.gen.dart | 25 +- .../lib/src/generated/message.gen.dart | 55 +- .../lib/src/generated/multiple_arity.gen.dart | 26 +- .../src/generated/non_null_fields.gen.dart | 48 +- .../lib/src/generated/null_fields.gen.dart | 49 +- .../src/generated/nullable_returns.gen.dart | 69 +- .../lib/src/generated/primitive.gen.dart | 71 +- .../src/generated/proxy_api_tests.gen.dart | 1820 +++---- .../lib/test_types.dart | 66 +- .../test/equality_test.dart | 122 +- .../test/generated_dart_test_code_test.dart | 18 +- .../test/instance_manager_test.dart | 170 +- .../test/multiple_arity_test.dart | 9 +- .../test/null_fields_test.dart | 8 +- .../test/null_safe_test.dart | 69 +- .../test/null_safe_test.mocks.dart | 9 +- .../test/primitive_test.dart | 4 +- .../test/primitive_test.mocks.dart | 12 +- .../test/proxy_api_overrides_test.dart | 6 +- .../test/test_message.gen.dart | 134 +- .../test/test_util.dart | 14 +- packages/pigeon/test/ast_generator_test.dart | 6 +- packages/pigeon/test/cpp_generator_test.dart | 732 +-- packages/pigeon/test/dart/proxy_api_test.dart | 213 +- packages/pigeon/test/dart_generator_test.dart | 236 +- packages/pigeon/test/functional_test.dart | 13 +- .../pigeon/test/generator_tools_test.dart | 151 +- .../pigeon/test/gobject_generator_test.dart | 264 +- packages/pigeon/test/java_generator_test.dart | 536 +- .../pigeon/test/kotlin/proxy_api_test.dart | 375 +- .../pigeon/test/kotlin_generator_test.dart | 580 +- packages/pigeon/test/objc_generator_test.dart | 896 +--- packages/pigeon/test/pigeon_lib_test.dart | 271 +- .../pigeon/test/swift/proxy_api_test.dart | 285 +- .../pigeon/test/swift_generator_test.dart | 505 +- packages/pigeon/test/version_test.dart | 3 +- packages/pigeon/tool/generate.dart | 23 +- packages/pigeon/tool/run_tests.dart | 6 +- .../pigeon/tool/shared/flutter_utils.dart | 7 +- .../pigeon/tool/shared/process_utils.dart | 4 +- packages/pigeon/tool/shared/test_runner.dart | 9 +- packages/pigeon/tool/shared/test_suites.dart | 45 +- packages/pigeon/tool/test.dart | 43 +- .../lib/plugin_platform_interface.dart | 7 +- .../test/plugin_platform_interface_test.dart | 26 +- .../pointer_interceptor/example/lib/main.dart | 9 +- .../example/lib/native_widget.dart | 3 +- .../lib/src/pointer_interceptor.dart | 6 +- .../example/lib/main.dart | 7 +- .../test/pointer_interceptor_ios_test.dart | 4 +- .../lib/src/pointer_interceptor_platform.dart | 4 +- .../pointer_interceptor_platform_test.dart | 26 +- .../example/integration_test/widget_test.dart | 73 +- .../example/lib/main.dart | 22 +- .../integration_test/quick_actions_test.dart | 5 +- .../quick_actions/example/lib/main.dart | 6 +- .../quick_actions/lib/quick_actions.dart | 3 +- .../test/quick_actions_test.dart | 8 +- .../example/lib/main.dart | 12 +- .../lib/quick_actions_android.dart | 4 +- .../lib/src/messages.g.dart | 48 +- .../pigeons/messages.dart | 3 +- .../test/quick_actions_android_test.dart | 24 +- .../integration_test/quick_actions_test.dart | 5 +- .../quick_actions_ios/example/lib/main.dart | 6 +- .../quick_actions_ios/lib/messages.g.dart | 59 +- .../lib/quick_actions_ios.dart | 4 +- .../quick_actions_ios/pigeons/messages.dart | 10 +- .../method_channel_quick_actions.dart | 18 +- .../method_channel_quick_actions_test.dart | 73 +- ...quick_actions_platform_interface_test.dart | 57 +- packages/rfw/example/local/lib/main.dart | 5 +- packages/rfw/example/remote/lib/main.dart | 64 +- packages/rfw/lib/src/dart/binary.dart | 51 +- packages/rfw/lib/src/dart/model.dart | 35 +- packages/rfw/lib/src/dart/text.dart | 394 +- .../lib/src/flutter/argument_decoders.dart | 176 +- packages/rfw/lib/src/flutter/content.dart | 24 +- .../rfw/lib/src/flutter/core_widgets.dart | 282 +- .../rfw/lib/src/flutter/material_widgets.dart | 253 +- .../rfw/lib/src/flutter/remote_widget.dart | 12 +- packages/rfw/lib/src/flutter/runtime.dart | 291 +- packages/rfw/test/argument_decoders_test.dart | 268 +- packages/rfw/test/binary_test.dart | 1767 ++++++- packages/rfw/test/core_widgets_test.dart | 286 +- packages/rfw/test/material_widgets_test.dart | 95 +- packages/rfw/test/model_test.dart | 39 +- packages/rfw/test/readme_test.dart | 161 +- packages/rfw/test/remote_widget_test.dart | 10 +- packages/rfw/test/runtime_test.dart | 1035 ++-- packages/rfw/test/source_locations_test.dart | 25 +- packages/rfw/test/text_test.dart | 546 +- packages/rfw/test/tolerant_comparator.dart | 22 +- .../rfw/test/tolerant_comparator_web.dart | 5 +- .../rfw/test_coverage/bin/test_coverage.dart | 24 +- ...hared_preferences_migration_util_test.dart | 59 +- .../shared_preferences_test.dart | 181 +- .../shared_preferences/example/lib/main.dart | 19 +- .../example/lib/readme_excerpts.dart | 17 +- .../example/test/example_app_test.dart | 41 +- .../lib/shared_preferences.dart | 3 +- .../lib/src/shared_preferences_async.dart | 91 +- ...d_preferences_devtools_extension_data.dart | 21 +- .../lib/src/shared_preferences_legacy.dart | 29 +- .../util/legacy_to_async_migration_util.dart | 4 +- .../test/shared_preferences_async_test.dart | 294 +- ...ferences_devtools_extension_data_test.dart | 134 +- .../test/shared_preferences_test.dart | 97 +- .../shared_preferences/tool/pre_publish.dart | 5 +- .../shared_preferences_test.dart | 468 +- .../example/lib/main.dart | 25 +- .../lib/src/messages.g.dart | 170 +- .../lib/src/messages_async.g.dart | 344 +- .../lib/src/shared_preferences_android.dart | 37 +- .../src/shared_preferences_async_android.dart | 153 +- .../pigeons/messages.dart | 3 +- .../pigeons/messages_async.dart | 41 +- .../test/shared_preferences_android_test.dart | 68 +- .../test/shared_preferences_async_test.dart | 103 +- .../shared_preferences_test.dart | 396 +- .../example/lib/main.dart | 11 +- .../lib/src/messages.g.dart | 253 +- .../shared_preferences_async_foundation.dart | 93 +- .../src/shared_preferences_foundation.dart | 16 +- .../pigeons/messages.dart | 10 +- ...red_preferences_async_foundation_test.dart | 16 +- .../shared_preferences_foundation_test.dart | 39 +- .../shared_preferences_test.dart | 170 +- .../example/lib/main.dart | 11 +- .../lib/shared_preferences_linux.dart | 132 +- .../test/fake_path_provider_linux.dart | 3 +- .../legacy_shared_preferences_linux_test.dart | 27 +- .../in_memory_shared_preferences_async.dart | 55 +- .../method_channel_shared_preferences.dart | 55 +- ..._preferences_async_platform_interface.dart | 34 +- ...shared_preferences_platform_interface.dart | 26 +- ...ethod_channel_shared_preferences_test.dart | 143 +- ...d_preferences_platform_interface_test.dart | 12 +- .../shared_preferences_tool/lib/main.dart | 13 +- .../lib/src/async_state.dart | 30 +- .../lib/src/shared_preferences_state.dart | 42 +- .../shared_preferences_state_notifier.dart | 28 +- .../shared_preferences_state_provider.dart | 86 +- .../lib/src/shared_preferences_tool_eval.dart | 19 +- .../lib/src/ui/api_switch.dart | 14 +- .../lib/src/ui/data_panel.dart | 64 +- .../lib/src/ui/error_panel.dart | 5 +- .../lib/src/ui/keys_panel.dart | 39 +- ...hared_preferences_state_notifier_test.dart | 32 +- ...preferences_state_notifier_test.mocks.dart | 274 +- .../src/shared_preferences_state_test.dart | 17 +- .../shared_preferences_tool_eval_test.dart | 75 +- .../test/src/ui/data_panel_test.dart | 124 +- .../test/src/ui/error_panel_test.dart | 4 +- .../test/src/ui/keys_panel_test.dart | 55 +- .../src/ui/shared_preferences_body_test.dart | 4 +- .../notifier_mocking_helpers.dart | 12 +- .../notifier_mocking_helpers.mocks.dart | 123 +- .../shared_preferences_web_test.dart | 169 +- .../lib/shared_preferences_web.dart | 107 +- .../shared_preferences_test.dart | 170 +- .../example/lib/main.dart | 11 +- .../lib/shared_preferences_windows.dart | 115 +- .../test/fake_path_provider_windows.dart | 3 +- ...egacy_shared_preferences_windows_test.dart | 27 +- .../example/lib/readme_excerpts.dart | 7 +- .../lib/src/serialization.dart | 44 +- .../test/standard_message_codec_test.dart | 63 +- .../lib/table_view/infinite_table.dart | 9 +- .../example/lib/table_view/merged_table.dart | 12 +- .../example/lib/table_view/simple_table.dart | 40 +- .../lib/table_view/table_explorer.dart | 5 +- .../example/lib/tree_view/custom_tree.dart | 65 +- .../example/lib/tree_view/simple_tree.dart | 46 +- .../example/lib/tree_view/tree_explorer.dart | 5 +- .../test/table_view/simple_table_test.dart | 10 +- .../test/table_view/table_explorer_test.dart | 4 +- .../test/tree_view/custom_tree_test.dart | 16 +- .../test/tree_view/simple_tree_test.dart | 12 +- .../test/tree_view/tree_explorer_test.dart | 4 +- .../lib/src/common/span.dart | 30 +- .../lib/src/table_view/table.dart | 495 +- .../lib/src/table_view/table_cell.dart | 3 +- .../lib/src/table_view/table_delegate.dart | 24 +- .../lib/src/tree_view/render_tree.dart | 134 +- .../lib/src/tree_view/tree.dart | 56 +- .../lib/src/tree_view/tree_core.dart | 7 +- .../lib/src/tree_view/tree_delegate.dart | 17 +- .../test/common/span_test.dart | 37 +- .../test/table_view/alignment_test.dart | 276 +- .../pinned_extent_warning_test.dart | 175 +- .../test/table_view/table_cell_test.dart | 871 +-- .../test/table_view/table_delegate_test.dart | 38 +- .../test/table_view/table_span_test.dart | 458 +- .../test/table_view/table_test.dart | 1411 ++--- .../test/tree_view/alignment_test.dart | 36 +- .../test/tree_view/render_tree_test.dart | 293 +- .../test/tree_view/tree_span_test.dart | 64 +- .../test/tree_view/tree_test.dart | 253 +- .../integration_test/url_launcher_test.dart | 5 +- .../url_launcher/example/lib/basic.dart | 5 +- .../url_launcher/example/lib/encoding.dart | 6 +- .../url_launcher/example/lib/main.dart | 15 +- .../url_launcher/lib/src/legacy_api.dart | 12 +- .../url_launcher/lib/src/link.dart | 15 +- .../url_launcher/lib/src/type_conversion.dart | 8 +- .../lib/src/url_launcher_string.dart | 3 +- .../lib/src/url_launcher_uri.dart | 3 +- .../url_launcher/test/link_test.dart | 4 +- .../mocks/mock_url_launcher_platform.dart | 4 +- .../test/src/legacy_api_test.dart | 76 +- .../test/src/url_launcher_string_test.dart | 34 +- .../test/src/url_launcher_uri_test.dart | 28 +- .../example/lib/main.dart | 25 +- .../lib/src/messages.g.dart | 49 +- .../lib/url_launcher_android.dart | 3 +- .../pigeons/messages.dart | 9 +- .../test/url_launcher_android_test.dart | 80 +- .../url_launcher_ios/example/lib/main.dart | 13 +- .../url_launcher_ios/lib/src/messages.g.dart | 77 +- .../lib/url_launcher_ios.dart | 26 +- .../test/url_launcher_ios_test.dart | 148 +- .../test/url_launcher_ios_test.mocks.dart | 63 +- .../url_launcher_linux/example/lib/main.dart | 5 +- .../lib/src/messages.g.dart | 44 +- .../lib/url_launcher_linux.dart | 8 +- .../test/url_launcher_linux_test.dart | 43 +- .../url_launcher_macos/example/lib/main.dart | 5 +- .../lib/src/messages.g.dart | 53 +- .../lib/url_launcher_macos.dart | 3 +- .../url_launcher_macos/pigeons/messages.dart | 3 +- .../test/url_launcher_macos_test.dart | 48 +- .../lib/link.dart | 12 +- .../lib/src/url_launcher_platform.dart | 3 +- .../test/launch_options_test.dart | 27 +- .../test/link_test.dart | 7 +- .../method_channel_url_launcher_test.dart | 24 +- .../test/url_launcher_platform_test.dart | 172 +- .../integration_test/link_widget_test.dart | 193 +- .../url_launcher_web_test.dart | 215 +- .../url_launcher_web/lib/src/link.dart | 64 +- .../lib/url_launcher_web.dart | 9 +- .../example/lib/main.dart | 5 +- .../lib/src/messages.g.dart | 44 +- .../lib/url_launcher_windows.dart | 3 +- .../test/url_launcher_windows_test.dart | 39 +- .../example/lib/svg_string.dart | 4 +- .../lib/src/html_render_vector_graphics.dart | 50 +- .../vector_graphics/lib/src/listener.dart | 119 +- packages/vector_graphics/lib/src/loader.dart | 22 +- .../lib/src/render_vector_graphic.dart | 37 +- .../lib/src/vector_graphics.dart | 63 +- .../vector_graphics/test/caching_test.dart | 193 +- .../vector_graphics/test/listener_test.dart | 21 +- .../test/render_vector_graphics_test.dart | 256 +- .../test/vector_graphics_test.dart | 319 +- .../vector_graphics_codec/lib/src/fp16.dart | 3 +- .../lib/vector_graphics_codec.dart | 209 +- .../vector_graphics_codec/test/fp16_test.dart | 6 +- .../test/vector_graphics_codec_test.dart | 155 +- .../bin/util/isolate_processor.dart | 4 +- .../bin/vector_graphics_compiler.dart | 23 +- .../lib/src/_initialize_tessellator_io.dart | 3 +- .../lib/src/debug_format.dart | 33 +- .../lib/src/draw_command_builder.dart | 34 +- .../lib/src/geometry/basic_types.dart | 3 +- .../lib/src/geometry/matrix.dart | 26 +- .../lib/src/geometry/path.dart | 59 +- .../lib/src/geometry/vertices.dart | 13 +- .../lib/src/image/image_info.dart | 20 +- .../lib/src/paint.dart | 35 +- .../lib/src/svg/_path_ops_ffi.dart | 99 +- .../lib/src/svg/_path_ops_unsupported.dart | 9 +- .../lib/src/svg/_tessellator_ffi.dart | 157 +- .../lib/src/svg/_tessellator_unsupported.dart | 5 +- .../lib/src/svg/clipping_optimizer.dart | 31 +- .../lib/src/svg/color_mapper.dart | 7 +- .../lib/src/svg/colors.dart | 39 +- .../lib/src/svg/masking_optimizer.dart | 45 +- .../lib/src/svg/node.dart | 58 +- .../lib/src/svg/overdraw_optimizer.dart | 62 +- .../lib/src/svg/parser.dart | 199 +- .../lib/src/svg/parsers.dart | 36 +- .../lib/src/svg/path_ops.dart | 22 +- .../lib/src/svg/resolver.dart | 110 +- .../lib/src/svg/tessellator.dart | 10 +- .../lib/src/svg/theme.dart | 7 +- .../lib/src/svg/visitor.dart | 24 +- .../lib/vector_graphics_compiler.dart | 36 +- .../test/basic_types_test.dart | 7 +- .../test/cli_test.dart | 12 +- .../test/clipping_optimizer_test.dart | 43 +- .../test/colors_test.dart | 147 +- .../test/end_to_end_test.dart | 115 +- .../test/masking_optimizer_test.dart | 107 +- .../test/matrix_test.dart | 43 +- .../test/overdraw_optimizer_test.dart | 654 +-- .../test/paint_test.dart | 5 +- .../test/parser_test.dart | 2020 ++----- .../test/parsers_test.dart | 229 +- .../test/path_ops_test.dart | 67 +- .../test/path_test.dart | 29 +- .../test/resolver_test.dart | 79 +- .../test/tessellator_test.dart | 5 +- .../test/test_svg_strings.dart | 198 +- .../test/theme_test.dart | 15 +- .../test/vertices_test.dart | 25 +- .../controller_swap_test.dart | 8 +- .../integration_test/video_player_test.dart | 33 +- .../example/lib/audio_tracks_demo.dart | 7 +- .../video_player/example/lib/basic.dart | 22 +- .../video_player/example/lib/main.dart | 16 +- .../lib/src/closed_caption_file.dart | 7 +- .../video_player/lib/src/sub_rip.dart | 14 +- .../video_player/lib/src/web_vtt.dart | 10 +- .../video_player/lib/video_player.dart | 101 +- .../video_player/test/sub_rip_file_test.dart | 35 +- .../video_player_initialization_test.dart | 15 +- .../video_player/test/video_player_test.dart | 694 +-- .../video_player/test/web_vtt_test.dart | 44 +- .../integration_test/video_player_test.dart | 19 +- .../example/lib/main.dart | 22 +- .../example/lib/mini_controller.dart | 60 +- .../lib/src/android_video_player.dart | 68 +- .../lib/src/messages.g.dart | 118 +- .../lib/src/platform_view_player.dart | 19 +- .../pigeons/messages.dart | 3 +- .../test/android_video_player_test.dart | 572 +- .../test/android_video_player_test.mocks.dart | 329 +- .../integration_test/video_player_test.dart | 27 +- .../example/lib/main.dart | 27 +- .../example/lib/mini_controller.dart | 56 +- .../lib/src/avfoundation_video_player.dart | 37 +- .../src/video_player_instance_messages.g.dart | 98 +- .../src/video_player_plugin_messages.g.dart | 62 +- .../video_player_instance_messages.dart | 3 +- .../test/avfoundation_video_player_test.dart | 580 +- .../avfoundation_video_player_test.mocks.dart | 321 +- .../lib/video_player_platform_interface.dart | 45 +- .../video_player_platform_interface_test.dart | 61 +- ...ideo_player_web_options_controls_test.dart | 5 +- .../test/video_player_web_options_test.dart | 15 +- .../integration_test/duration_utils_test.dart | 28 +- .../integration_test/pkg_web_tweaks.dart | 18 +- .../integration_test/video_player_test.dart | 181 +- .../video_player_web_test.dart | 85 +- .../lib/src/video_player.dart | 29 +- .../lib/video_player_web.dart | 11 +- .../example/analyze_example.dart | 16 +- packages/web_benchmarks/lib/analysis.dart | 47 +- packages/web_benchmarks/lib/client.dart | 54 +- packages/web_benchmarks/lib/src/browser.dart | 99 +- .../web_benchmarks/lib/src/computations.dart | 60 +- packages/web_benchmarks/lib/src/metrics.dart | 62 +- packages/web_benchmarks/lib/src/recorder.dart | 71 +- packages/web_benchmarks/lib/src/runner.dart | 62 +- .../test/src/analysis_test.dart | 325 +- .../test/src/benchmark_result_test.dart | 12 +- .../web_benchmarks/test/src/browser_test.dart | 24 +- .../test/src/browser_test_json_samples.dart | 36 +- .../benchmark/test_infra/automator.dart | 14 +- .../test_infra/client/app_client.dart | 9 +- .../benchmark/test_infra/recorder.dart | 3 +- .../benchmark/web_benchmarks_test.dart | 53 +- .../testing/test_app/lib/about_page.dart | 9 +- .../testing/test_app/lib/home_page.dart | 10 +- packages/web_benchmarks/tool/run_tests.dart | 16 +- .../webview_flutter_test.dart | 139 +- .../webview_flutter_test_legacy.dart | 139 +- .../webview_flutter/example/lib/main.dart | 101 +- .../example/test/main_test.dart | 24 +- .../lib/src/legacy/webview.dart | 79 +- .../lib/src/navigation_delegate.dart | 6 +- .../lib/src/webview_controller.dart | 28 +- .../lib/src/webview_cookie_manager.dart | 9 +- .../test/legacy/webview_flutter_test.dart | 334 +- .../legacy/webview_flutter_test.mocks.dart | 338 +- .../test/navigation_delegate_test.dart | 17 +- .../test/navigation_delegate_test.mocks.dart | 262 +- .../test/webview_controller_test.dart | 251 +- .../test/webview_controller_test.mocks.dart | 622 +-- .../test/webview_cookie_manager_test.dart | 24 +- .../webview_cookie_manager_test.mocks.dart | 47 +- .../test/webview_flutter_export_test.dart | 65 +- .../test/webview_widget_test.dart | 64 +- .../test/webview_widget_test.mocks.dart | 531 +- .../webview_flutter_test.dart | 666 +-- .../webview_flutter_test_legacy.dart | 256 +- .../example/lib/legacy/web_view.dart | 88 +- .../example/lib/main.dart | 239 +- .../example/lib/readme_excerpts.dart | 13 +- .../lib/src/android_ssl_auth_error.dart | 13 +- .../lib/src/android_webkit.g.dart | 2923 ++++------- .../lib/src/android_webkit_constants.dart | 3 +- .../lib/src/android_webview_controller.dart | 501 +- .../src/android_webview_cookie_manager.dart | 23 +- .../lib/src/android_webview_platform.dart | 4 +- .../lib/src/legacy/webview_android.dart | 7 +- .../webview_android_cookie_manager.dart | 9 +- .../src/legacy/webview_android_widget.dart | 273 +- .../src/legacy/webview_surface_android.dart | 24 +- .../pigeons/android_webkit.dart | 202 +- .../android_navigation_delegate_test.dart | 183 +- ...ndroid_navigation_delegate_test.mocks.dart | 372 +- .../test/android_webview_controller_test.dart | 832 +-- ...android_webview_controller_test.mocks.dart | 2953 +++++------ .../android_webview_cookie_manager_test.dart | 65 +- ...oid_webview_cookie_manager_test.mocks.dart | 731 +-- .../test/legacy/surface_android_test.dart | 104 +- .../webview_android_cookie_manager_test.dart | 42 +- ...iew_android_cookie_manager_test.mocks.dart | 75 +- .../legacy/webview_android_widget_test.dart | 266 +- .../webview_android_widget_test.mocks.dart | 1294 ++--- .../webview_cookie_manager.dart | 12 +- .../platform_interface/webview_platform.dart | 9 +- .../webview_platform_callbacks_handler.dart | 5 +- .../webview_platform_controller.dart | 76 +- .../lib/src/legacy/types/creation_params.dart | 3 +- .../lib/src/legacy/types/web_settings.dart | 4 +- .../lib/src/legacy/types/webview_cookie.dart | 7 +- .../lib/src/platform_navigation_delegate.dart | 56 +- .../lib/src/platform_webview_controller.dart | 136 +- .../src/platform_webview_cookie_manager.dart | 22 +- .../lib/src/platform_webview_widget.dart | 3 +- .../src/types/javascript_dialog_request.dart | 10 +- .../platform_webview_permission_request.dart | 8 +- .../lib/src/webview_platform.dart | 8 +- .../javascript_channel_registry_test.dart | 92 +- .../webview_cookie_manager_test.dart | 6 +- .../legacy/types/javascript_channel_test.dart | 18 +- .../legacy/types/webview_cookie_test.dart | 7 +- .../platform_navigation_delegate_test.dart | 205 +- .../platform_webview_controller_test.dart | 584 +-- ...latform_webview_controller_test.mocks.dart | 121 +- .../platform_webview_cookie_manager_test.dart | 94 +- .../test/platform_webview_widget_test.dart | 4 +- .../test/types_test.dart | 6 +- ...lutter_platform_interface_export_test.dart | 53 +- .../test/webview_platform_test.dart | 121 +- .../test/webview_platform_test.mocks.dart | 88 +- .../legacy_webview_flutter_test_manual.dart | 6 +- .../webview_flutter_test.dart | 23 +- .../example/lib/legacy/web_view.dart | 50 +- .../webview_flutter_web/example/lib/main.dart | 5 +- .../lib/src/content_type.dart | 9 +- .../lib/src/web_webview_controller.dart | 32 +- .../lib/src/web_webview_platform.dart | 4 +- .../lib/src/webview_flutter_web_legacy.dart | 25 +- .../test/content_type_test.dart | 8 +- .../test/legacy/webview_flutter_web_test.dart | 108 +- .../webview_flutter_web_test.mocks.dart | 251 +- .../test/web_webview_controller_test.dart | 49 +- .../web_webview_controller_test.mocks.dart | 98 +- .../test/web_webview_widget_test.dart | 13 +- .../legacy/webview_flutter_test.dart | 354 +- .../webview_flutter_test.dart | 753 +-- .../example/lib/legacy/web_view.dart | 84 +- .../example/lib/main.dart | 144 +- .../lib/src/common/platform_webview.dart | 3 +- .../lib/src/common/web_kit.g.dart | 2481 ++++----- .../lib/src/common/webkit_constants.dart | 3 +- .../src/legacy/web_kit_webview_widget.dart | 173 +- .../src/legacy/wkwebview_cookie_manager.dart | 11 +- .../lib/src/webkit_ssl_auth_error.dart | 5 +- .../lib/src/webkit_webview_controller.dart | 570 +- .../src/webkit_webview_cookie_manager.dart | 21 +- .../lib/src/webkit_webview_platform.dart | 4 +- .../pigeons/web_kit.dart | 83 +- .../legacy/web_kit_cookie_manager_test.dart | 23 +- .../web_kit_cookie_manager_test.mocks.dart | 175 +- .../legacy/web_kit_webview_widget_test.dart | 770 +-- .../web_kit_webview_widget_test.mocks.dart | 1942 +++---- .../test/webkit_navigation_delegate_test.dart | 646 +-- ...webkit_navigation_delegate_test.mocks.dart | 343 +- .../test/webkit_webview_controller_test.dart | 617 +-- .../webkit_webview_controller_test.mocks.dart | 2091 +++----- .../webkit_webview_cookie_manager_test.dart | 52 +- ...kit_webview_cookie_manager_test.mocks.dart | 251 +- .../test/webkit_webview_widget_test.dart | 138 +- .../webkit_webview_widget_test.mocks.dart | 388 +- .../xdg_directories_test.dart | 18 +- .../xdg_directories/lib/xdg_directories.dart | 34 +- .../test/xdg_directories_test.dart | 17 +- .../flutter_goldens/lib/flutter_goldens.dart | 33 +- .../test/flutter_goldens_test.dart | 70 +- script/tool/lib/src/analyze_command.dart | 136 +- .../branches_for_batch_release_command.dart | 47 +- .../tool/lib/src/build_examples_command.dart | 162 +- script/tool/lib/src/common/cmake.dart | 5 +- script/tool/lib/src/common/core.dart | 3 +- script/tool/lib/src/common/file_utils.dart | 9 +- .../lib/src/common/flutter_command_utils.dart | 18 +- .../lib/src/common/git_version_finder.dart | 33 +- script/tool/lib/src/common/gradle.dart | 3 +- .../tool/lib/src/common/package_command.dart | 116 +- .../src/common/package_looping_command.dart | 93 +- .../lib/src/common/package_state_utils.dart | 45 +- .../src/common/pending_changelog_entry.dart | 19 +- script/tool/lib/src/common/plugin_utils.dart | 27 +- .../tool/lib/src/common/process_runner.dart | 18 +- script/tool/lib/src/common/pub_utils.dart | 10 +- .../lib/src/common/pub_version_finder.dart | 8 +- .../lib/src/common/repository_package.dart | 47 +- script/tool/lib/src/common/xcode.dart | 81 +- .../src/create_all_packages_app_command.dart | 80 +- script/tool/lib/src/custom_test_command.dart | 29 +- script/tool/lib/src/dart_test_command.dart | 50 +- .../lib/src/dependabot_check_command.dart | 10 +- .../tool/lib/src/drive_examples_command.dart | 183 +- .../src/federation_safety_check_command.dart | 43 +- script/tool/lib/src/fetch_deps_command.dart | 76 +- .../lib/src/firebase_test_lab_command.dart | 113 +- script/tool/lib/src/fix_command.dart | 10 +- script/tool/lib/src/format_command.dart | 131 +- script/tool/lib/src/gradle_check_command.dart | 6 +- .../tool/lib/src/license_check_command.dart | 70 +- script/tool/lib/src/list_command.dart | 10 +- script/tool/lib/src/main.dart | 4 +- .../lib/src/make_deps_path_based_command.dart | 86 +- script/tool/lib/src/native_test_command.dart | 163 +- .../tool/lib/src/podspec_check_command.dart | 46 +- .../tool/lib/src/publish_check_command.dart | 61 +- script/tool/lib/src/publish_command.dart | 102 +- .../tool/lib/src/pubspec_check_command.dart | 35 +- script/tool/lib/src/readme_check_command.dart | 26 +- .../src/remove_dev_dependencies_command.dart | 7 +- .../src/repo_package_info_check_command.dart | 14 +- .../lib/src/update_dependency_command.dart | 187 +- .../tool/lib/src/update_excerpts_command.dart | 56 +- .../tool/lib/src/update_min_sdk_command.dart | 14 +- .../lib/src/update_release_info_command.dart | 65 +- .../src/validators/dependabot_validator.dart | 20 +- .../lib/src/validators/gradle_validator.dart | 186 +- .../lib/src/validators/pubspec_validator.dart | 83 +- .../lib/src/validators/readme_validator.dart | 59 +- .../src/validators/repo_info_validator.dart | 78 +- .../version_and_changelog_validator.dart | 74 +- .../tool/lib/src/version_check_command.dart | 18 +- script/tool/test/analyze_command_test.dart | 590 +-- ...anches_for_batch_release_command_test.dart | 157 +- .../test/build_examples_command_test.dart | 470 +- script/tool/test/common/ci_config_test.dart | 38 +- .../tool/test/common/file_filters_test.dart | 48 +- script/tool/test/common/file_utils_test.dart | 40 +- .../test/common/git_version_finder_test.dart | 32 +- script/tool/test/common/gradle_test.dart | 28 +- .../tool/test/common/output_utils_test.dart | 24 +- .../test/common/package_command_test.dart | 1589 ++---- .../common/package_command_test.mocks.dart | 64 +- .../common/package_looping_command_test.dart | 511 +- .../test/common/package_state_utils_test.dart | 172 +- .../tool/test/common/plugin_utils_test.dart | 162 +- script/tool/test/common/pub_utils_test.dart | 35 +- .../test/common/repository_package_test.dart | 146 +- script/tool/test/common/xcode_test.dart | 50 +- .../create_all_packages_app_command_test.dart | 152 +- .../tool/test/custom_test_command_test.dart | 116 +- script/tool/test/dart_test_command_test.dart | 408 +- .../test/dependabot_check_command_test.dart | 91 +- .../test/drive_examples_command_test.dart | 312 +- .../federation_safety_check_command_test.dart | 413 +- script/tool/test/fetch_deps_command_test.dart | 363 +- .../test/firebase_test_lab_command_test.dart | 336 +- script/tool/test/fix_command_test.dart | 22 +- script/tool/test/format_command_test.dart | 362 +- .../tool/test/gradle_check_command_test.dart | 1050 ++-- .../tool/test/license_check_command_test.dart | 428 +- script/tool/test/list_command_test.dart | 55 +- .../make_deps_path_based_command_test.dart | 621 +-- script/tool/test/mocks.dart | 23 +- .../tool/test/native_test_command_test.dart | 868 ++- .../tool/test/podspec_check_command_test.dart | 457 +- .../tool/test/publish_check_command_test.dart | 260 +- script/tool/test/publish_command_test.dart | 1257 ++--- .../tool/test/pubspec_check_command_test.dart | 872 ++- .../tool/test/readme_check_command_test.dart | 319 +- .../remove_dev_dependencies_command_test.dart | 50 +- .../repo_package_info_check_command_test.dart | 259 +- .../test/update_dependency_command_test.dart | 1077 ++-- .../test/update_excerpts_command_test.dart | 156 +- .../test/update_min_sdk_command_test.dart | 18 +- .../update_release_info_command_test.dart | 483 +- script/tool/test/util.dart | 74 +- .../tool/test/version_check_command_test.dart | 1890 +++---- .../test/cupertino_icons_golden_test.dart | 23 +- .../test/cupertino_icons_test.dart | 6 +- .../flutter_svg/example/lib/main.dart | 6 +- .../example/lib/readme_excerpts.dart | 25 +- .../packages/flutter_svg/lib/src/loaders.dart | 63 +- .../lib/src/utilities/compute.dart | 3 +- third_party/packages/flutter_svg/lib/svg.dart | 88 +- .../packages/flutter_svg/test/cache_test.dart | 12 +- .../flutter_svg/test/default_theme_test.dart | 80 +- .../flutter_svg/test/loaders_test.dart | 27 +- .../test/no_width_height_test.dart | 9 +- .../flutter_svg/test/widget_svg_test.dart | 306 +- .../lib/flutter_svg_test.dart | 32 +- .../test/flutter_svg_test_test.dart | 9 +- .../lib/src/lambda_context.dart | 15 +- .../mustache_template/lib/src/node.dart | 14 +- .../mustache_template/lib/src/parser.dart | 58 +- .../mustache_template/lib/src/renderer.dart | 12 +- .../mustache_template/lib/src/scanner.dart | 17 +- .../lib/src/template_exception.dart | 4 +- .../mustache_template/test/feature_test.dart | 357 +- .../test/mustache_specs.dart | 32 +- .../mustache_template/test/parser_test.dart | 51 +- .../mustache_template/tool/download_spec.dart | 18 +- .../packages/path_parsing/example/main.dart | 9 +- .../path_parsing/lib/src/path_parsing.dart | 102 +- .../lib/src/path_segment_type.dart | 48 +- .../test/parse_path_deep_test.dart | 40 +- .../path_parsing/test/parse_path_test.dart | 18 +- 1681 files changed, 70532 insertions(+), 136112 deletions(-) diff --git a/packages/animations/example/lib/container_transition.dart b/packages/animations/example/lib/container_transition.dart index a1fae1499288..3e984514d7dc 100644 --- a/packages/animations/example/lib/container_transition.dart +++ b/packages/animations/example/lib/container_transition.dart @@ -49,8 +49,7 @@ class OpenContainerTransformDemo extends StatefulWidget { } } -class _OpenContainerTransformDemoState - extends State { +class _OpenContainerTransformDemoState extends State { ContainerTransitionType _transitionType = ContainerTransitionType.fade; void _showMarkedAsDoneSnackbar(bool? isMarkedAsDone) { @@ -529,18 +528,18 @@ class _DetailsPage extends StatelessWidget { Text( 'Title', style: Theme.of(context).textTheme.headlineSmall!.copyWith( - color: Colors.black54, - fontSize: 30.0, - ), + color: Colors.black54, + fontSize: 30.0, + ), ), const SizedBox(height: 10), Text( _loremIpsumParagraph, style: Theme.of(context).textTheme.bodyMedium!.copyWith( - color: Colors.black54, - height: 1.5, - fontSize: 16.0, - ), + color: Colors.black54, + height: 1.5, + fontSize: 16.0, + ), ), ], ), diff --git a/packages/animations/example/lib/fade_scale_transition.dart b/packages/animations/example/lib/fade_scale_transition.dart index 176363a47ab5..fdd6726457a4 100644 --- a/packages/animations/example/lib/fade_scale_transition.dart +++ b/packages/animations/example/lib/fade_scale_transition.dart @@ -11,8 +11,7 @@ class FadeScaleTransitionDemo extends StatefulWidget { const FadeScaleTransitionDemo({super.key}); @override - State createState() => - _FadeScaleTransitionDemoState(); + State createState() => _FadeScaleTransitionDemoState(); } class _FadeScaleTransitionDemoState extends State @@ -21,19 +20,18 @@ class _FadeScaleTransitionDemoState extends State @override void initState() { - _controller = - AnimationController( - value: 0.0, - duration: const Duration(milliseconds: 150), - reverseDuration: const Duration(milliseconds: 75), - vsync: this, - )..addStatusListener((AnimationStatus status) { - setState(() { - // setState needs to be called to trigger a rebuild because - // the 'HIDE FAB'/'SHOW FAB' button needs to be updated based - // the latest value of [_controller.status]. - }); + _controller = AnimationController( + value: 0.0, + duration: const Duration(milliseconds: 150), + reverseDuration: const Duration(milliseconds: 75), + vsync: this, + )..addStatusListener((AnimationStatus status) { + setState(() { + // setState needs to be called to trigger a rebuild because + // the 'HIDE FAB'/'SHOW FAB' button needs to be updated based + // the latest value of [_controller.status]. }); + }); super.initState(); } diff --git a/packages/animations/example/lib/fade_through_transition.dart b/packages/animations/example/lib/fade_through_transition.dart index 249c9439436c..7759bc5bdd20 100644 --- a/packages/animations/example/lib/fade_through_transition.dart +++ b/packages/animations/example/lib/fade_through_transition.dart @@ -11,8 +11,7 @@ class FadeThroughTransitionDemo extends StatefulWidget { const FadeThroughTransitionDemo({super.key}); @override - State createState() => - _FadeThroughTransitionDemoState(); + State createState() => _FadeThroughTransitionDemoState(); } class _FadeThroughTransitionDemoState extends State { @@ -25,18 +24,17 @@ class _FadeThroughTransitionDemoState extends State { return Scaffold( appBar: AppBar(title: const Text('Fade through')), body: PageTransitionSwitcher( - transitionBuilder: - ( - Widget child, - Animation animation, - Animation secondaryAnimation, - ) { - return FadeThroughTransition( - animation: animation, - secondaryAnimation: secondaryAnimation, - child: child, - ); - }, + transitionBuilder: ( + Widget child, + Animation animation, + Animation secondaryAnimation, + ) { + return FadeThroughTransition( + animation: animation, + secondaryAnimation: secondaryAnimation, + child: child, + ); + }, child: pageList[pageIndex], ), bottomNavigationBar: BottomNavigationBar( diff --git a/packages/animations/example/lib/shared_axis_transition.dart b/packages/animations/example/lib/shared_axis_transition.dart index 4806644caf29..637d794f20db 100644 --- a/packages/animations/example/lib/shared_axis_transition.dart +++ b/packages/animations/example/lib/shared_axis_transition.dart @@ -17,8 +17,7 @@ class SharedAxisTransitionDemo extends StatefulWidget { } class _SharedAxisTransitionDemoState extends State { - SharedAxisTransitionType? _transitionType = - SharedAxisTransitionType.horizontal; + SharedAxisTransitionType? _transitionType = SharedAxisTransitionType.horizontal; bool _isLoggedIn = false; void _updateTransitionType(SharedAxisTransitionType? newType) { @@ -44,19 +43,18 @@ class _SharedAxisTransitionDemoState extends State { Expanded( child: PageTransitionSwitcher( reverse: !_isLoggedIn, - transitionBuilder: - ( - Widget child, - Animation animation, - Animation secondaryAnimation, - ) { - return SharedAxisTransition( - animation: animation, - secondaryAnimation: secondaryAnimation, - transitionType: _transitionType!, - child: child, - ); - }, + transitionBuilder: ( + Widget child, + Animation animation, + Animation secondaryAnimation, + ) { + return SharedAxisTransition( + animation: animation, + secondaryAnimation: secondaryAnimation, + transitionType: _transitionType!, + child: child, + ); + }, child: _isLoggedIn ? _CoursePage() : _SignInPage(), ), ), diff --git a/packages/animations/lib/src/fade_scale_transition.dart b/packages/animations/lib/src/fade_scale_transition.dart index 9c525ea7f6c5..31b891dbb19f 100644 --- a/packages/animations/lib/src/fade_scale_transition.dart +++ b/packages/animations/lib/src/fade_scale_transition.dart @@ -137,23 +137,21 @@ class FadeScaleTransition extends StatelessWidget { Widget build(BuildContext context) { return DualTransitionBuilder( animation: animation, - forwardBuilder: - (BuildContext context, Animation animation, Widget? child) { - return FadeTransition( - opacity: _fadeInTransition.animate(animation), - child: ScaleTransition( - scale: _scaleInTransition.animate(animation), - child: child, - ), - ); - }, - reverseBuilder: - (BuildContext context, Animation animation, Widget? child) { - return FadeTransition( - opacity: _fadeOutTransition.animate(animation), - child: child, - ); - }, + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return FadeTransition( + opacity: _fadeInTransition.animate(animation), + child: ScaleTransition( + scale: _scaleInTransition.animate(animation), + child: child, + ), + ); + }, + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return FadeTransition( + opacity: _fadeOutTransition.animate(animation), + child: child, + ); + }, child: child, ); } diff --git a/packages/animations/lib/src/fade_through_transition.dart b/packages/animations/lib/src/fade_through_transition.dart index 61a8cb59fa7b..dc86f2d38a28 100644 --- a/packages/animations/lib/src/fade_through_transition.dart +++ b/packages/animations/lib/src/fade_through_transition.dart @@ -222,14 +222,12 @@ class _ZoomedFadeInFadeOut extends StatelessWidget { Widget build(BuildContext context) { return DualTransitionBuilder( animation: animation, - forwardBuilder: - (BuildContext context, Animation animation, Widget? child) { - return _ZoomedFadeIn(animation: animation, child: child); - }, - reverseBuilder: - (BuildContext context, Animation animation, Widget? child) { - return _FadeOut(animation: animation, child: child); - }, + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ZoomedFadeIn(animation: animation, child: child); + }, + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return _FadeOut(animation: animation, child: child); + }, child: child, ); } @@ -244,28 +242,27 @@ class _ZoomedFadeIn extends StatelessWidget { static final CurveTween _inCurve = CurveTween( curve: const Cubic(0.0, 0.0, 0.2, 1.0), ); - static final TweenSequence _scaleIn = - TweenSequence(>[ - TweenSequenceItem( - tween: ConstantTween(0.92), - weight: 6 / 20, - ), - TweenSequenceItem( - tween: Tween(begin: 0.92, end: 1.0).chain(_inCurve), - weight: 14 / 20, - ), - ]); + static final TweenSequence _scaleIn = TweenSequence(>[ + TweenSequenceItem( + tween: ConstantTween(0.92), + weight: 6 / 20, + ), + TweenSequenceItem( + tween: Tween(begin: 0.92, end: 1.0).chain(_inCurve), + weight: 14 / 20, + ), + ]); static final TweenSequence _fadeInOpacity = TweenSequence(>[ - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 6 / 20, - ), - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0).chain(_inCurve), - weight: 14 / 20, - ), - ]); + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 6 / 20, + ), + TweenSequenceItem( + tween: Tween(begin: 0.0, end: 1.0).chain(_inCurve), + weight: 14 / 20, + ), + ]); @override Widget build(BuildContext context) { @@ -287,15 +284,15 @@ class _FadeOut extends StatelessWidget { ); static final TweenSequence _fadeOutOpacity = TweenSequence(>[ - TweenSequenceItem( - tween: Tween(begin: 1.0, end: 0.0).chain(_outCurve), - weight: 6 / 20, - ), - TweenSequenceItem( - tween: ConstantTween(0.0), - weight: 14 / 20, - ), - ]); + TweenSequenceItem( + tween: Tween(begin: 1.0, end: 0.0).chain(_outCurve), + weight: 6 / 20, + ), + TweenSequenceItem( + tween: ConstantTween(0.0), + weight: 14 / 20, + ), + ]); @override Widget build(BuildContext context) { diff --git a/packages/animations/lib/src/modal.dart b/packages/animations/lib/src/modal.dart index 8e9598d578bd..c6fef52589f1 100644 --- a/packages/animations/lib/src/modal.dart +++ b/packages/animations/lib/src/modal.dart @@ -12,13 +12,12 @@ import 'fade_scale_transition.dart'; /// transition. /// /// Used by [PopupRoute]. -typedef _ModalTransitionBuilder = - Widget Function( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ); +typedef _ModalTransitionBuilder = Widget Function( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, +); /// Displays a modal above the current contents of the app. /// @@ -100,9 +99,9 @@ class _ModalRoute extends PopupRoute { required this.builder, RouteSettings? routeSettings, super.filter, - }) : assert(!barrierDismissible || barrierLabel != null), - _transitionBuilder = transitionBuilder, - super(settings: routeSettings); + }) : assert(!barrierDismissible || barrierLabel != null), + _transitionBuilder = transitionBuilder, + super(settings: routeSettings); @override final Color? barrierColor; diff --git a/packages/animations/lib/src/open_container.dart b/packages/animations/lib/src/open_container.dart index a9d90f7b73e3..08d2fce6a4ef 100644 --- a/packages/animations/lib/src/open_container.dart +++ b/packages/animations/lib/src/open_container.dart @@ -16,19 +16,17 @@ typedef CloseContainerActionCallback = void Function({S? returnValue}); /// /// The `action` callback provided to [OpenContainer.openBuilder] can be used /// to close the container. -typedef OpenContainerBuilder = - Widget Function( - BuildContext context, - CloseContainerActionCallback action, - ); +typedef OpenContainerBuilder = Widget Function( + BuildContext context, + CloseContainerActionCallback action, +); /// Signature for a function that creates a [Widget] in closed state within an /// [OpenContainer]. /// /// The `action` callback provided to [OpenContainer.closedBuilder] can be used /// to open the container. -typedef CloseContainerBuilder = - Widget Function(BuildContext context, VoidCallback action); +typedef CloseContainerBuilder = Widget Function(BuildContext context, VoidCallback action); /// The [OpenContainer] widget's fade transition type. /// @@ -338,33 +336,31 @@ class OpenContainerState extends State> { /// Open the container using the given middle color and specific route, /// then call `onClosed` with the returned data after popped. Future openContainer() async { - final Color middleColor = - widget.middleColor ?? Theme.of(context).canvasColor; - final T? data = - await Navigator.of( - context, - rootNavigator: widget.useRootNavigator, - ).push( - _OpenContainerRoute( - closedColor: widget.closedColor, - openColor: widget.openColor, - middleColor: middleColor, - closedElevation: widget.closedElevation, - openElevation: widget.openElevation, - closedShape: widget.closedShape, - openShape: widget.openShape, - closedBuilder: widget.closedBuilder, - openBuilder: widget.openBuilder, - hideableKey: _hideableKey, - closedBuilderKey: _closedBuilderKey, - transitionDuration: widget.transitionDuration, - transitionType: widget.transitionType, - useRootNavigator: widget.useRootNavigator, - routeSettings: widget.routeSettings, - closedShadows: widget.closedShadows, - openShadows: widget.openShadows, - ), - ); + final Color middleColor = widget.middleColor ?? Theme.of(context).canvasColor; + final T? data = await Navigator.of( + context, + rootNavigator: widget.useRootNavigator, + ).push( + _OpenContainerRoute( + closedColor: widget.closedColor, + openColor: widget.openColor, + middleColor: middleColor, + closedElevation: widget.closedElevation, + openElevation: widget.openElevation, + closedShape: widget.closedShape, + openShape: widget.openShape, + closedBuilder: widget.closedBuilder, + openBuilder: widget.openBuilder, + hideableKey: _hideableKey, + closedBuilderKey: _closedBuilderKey, + transitionDuration: widget.transitionDuration, + transitionType: widget.transitionType, + useRootNavigator: widget.useRootNavigator, + routeSettings: widget.routeSettings, + closedShadows: widget.closedShadows, + openShadows: widget.openShadows, + ), + ); if (widget.onClosed != null) { widget.onClosed!(data); } @@ -490,21 +486,21 @@ class _OpenContainerRoute extends ModalRoute { required RouteSettings? routeSettings, required this.closedShadows, required this.openShadows, - }) : _elevationTween = Tween( - begin: closedShadows == null ? closedElevation : 0.0, - end: openShadows == null ? openElevation : 0.0, - ), - _shadowsTween = _getShadowsTween(closedShadows, openShadows), - _shapeTween = ShapeBorderTween(begin: closedShape, end: openShape), - _colorTween = _getColorTween( - transitionType: transitionType, - closedColor: closedColor, - openColor: openColor, - middleColor: middleColor, - ), - _closedOpacityTween = _getClosedOpacityTween(transitionType), - _openOpacityTween = _getOpenOpacityTween(transitionType), - super(settings: routeSettings); + }) : _elevationTween = Tween( + begin: closedShadows == null ? closedElevation : 0.0, + end: openShadows == null ? openElevation : 0.0, + ), + _shadowsTween = _getShadowsTween(closedShadows, openShadows), + _shapeTween = ShapeBorderTween(begin: closedShape, end: openShape), + _colorTween = _getColorTween( + transitionType: transitionType, + closedColor: closedColor, + openColor: openColor, + middleColor: middleColor, + ), + _closedOpacityTween = _getClosedOpacityTween(transitionType), + _openOpacityTween = _getOpenOpacityTween(transitionType), + super(settings: routeSettings); static _FlippableTweenSequence _getColorTween({ required ContainerTransitionType transitionType, @@ -631,15 +627,15 @@ class _OpenContainerRoute extends ModalRoute { static final TweenSequence _scrimFadeInTween = TweenSequence(>[ - TweenSequenceItem( - tween: ColorTween(begin: Colors.transparent, end: Colors.black54), - weight: 1 / 5, - ), - TweenSequenceItem( - tween: ConstantTween(Colors.black54), - weight: 4 / 5, - ), - ]); + TweenSequenceItem( + tween: ColorTween(begin: Colors.transparent, end: Colors.black54), + weight: 1 / 5, + ), + TweenSequenceItem( + tween: ConstantTween(Colors.black54), + weight: 4 / 5, + ), + ]); static final Tween _scrimFadeOutTween = ColorTween( begin: Colors.transparent, end: Colors.black54, @@ -722,12 +718,10 @@ class _OpenContainerRoute extends ModalRoute { required BuildContext navigatorContext, bool delayForSourceRoute = false, }) { - final navigator = - Navigator.of( - navigatorContext, - rootNavigator: useRootNavigator, - ).context.findRenderObject()! - as RenderBox; + final navigator = Navigator.of( + navigatorContext, + rootNavigator: useRootNavigator, + ).context.findRenderObject()! as RenderBox; final Size navSize = _getSize(navigator); _rectTween.end = Offset.zero & navSize; @@ -837,9 +831,7 @@ class _OpenContainerRoute extends ModalRoute { final Animation curvedAnimation = CurvedAnimation( parent: animation, curve: Curves.fastOutSlowIn, - reverseCurve: _transitionWasInterrupted - ? null - : Curves.fastOutSlowIn.flipped, + reverseCurve: _transitionWasInterrupted ? null : Curves.fastOutSlowIn.flipped, ); TweenSequence? colorTween; TweenSequence? closedOpacityTween, openOpacityTween; diff --git a/packages/animations/lib/src/page_transition_switcher.dart b/packages/animations/lib/src/page_transition_switcher.dart index 53d4f7479a0e..72808d800f26 100644 --- a/packages/animations/lib/src/page_transition_switcher.dart +++ b/packages/animations/lib/src/page_transition_switcher.dart @@ -56,8 +56,7 @@ class _ChildEntry { /// The builder should return a widget which contains the given children, laid /// out as desired. It must not return null. The builder should be able to /// handle an empty list of `entries`. -typedef PageTransitionSwitcherLayoutBuilder = - Widget Function(List entries); +typedef PageTransitionSwitcherLayoutBuilder = Widget Function(List entries); /// Signature for builders used to generate custom transitions for /// [PageTransitionSwitcher]. @@ -73,12 +72,11 @@ typedef PageTransitionSwitcherLayoutBuilder = /// incorporate both animations. It will use the primary animation to define how /// its child appears, and the secondary animation to define how its child /// disappears. -typedef PageTransitionSwitcherTransitionBuilder = - Widget Function( - Widget child, - Animation primaryAnimation, - Animation secondaryAnimation, - ); +typedef PageTransitionSwitcherTransitionBuilder = Widget Function( + Widget child, + Animation primaryAnimation, + Animation secondaryAnimation, +); /// A widget that transitions from an old child to a new child whenever [child] /// changes using an animation specified by [transitionBuilder]. @@ -296,8 +294,7 @@ class _PageTransitionSwitcherState extends State final hasNewChild = widget.child != null; final hasOldChild = _currentEntry != null; if (hasNewChild != hasOldChild || - hasNewChild && - !Widget.canUpdate(widget.child!, _currentEntry!.widgetChild)) { + hasNewChild && !Widget.canUpdate(widget.child!, _currentEntry!.widgetChild)) { // Child has changed, fade current entry out and add new entry. _childNumber += 1; _addEntryForNewChild(shouldAnimate: true); @@ -425,9 +422,7 @@ class _PageTransitionSwitcherState extends State @override Widget build(BuildContext context) { return widget.layoutBuilder( - _activeEntries - .map((_ChildEntry entry) => entry.transition) - .toList(), + _activeEntries.map((_ChildEntry entry) => entry.transition).toList(), ); } } diff --git a/packages/animations/lib/src/shared_axis_transition.dart b/packages/animations/lib/src/shared_axis_transition.dart index f361f79cd14f..900b86a38696 100644 --- a/packages/animations/lib/src/shared_axis_transition.dart +++ b/packages/animations/lib/src/shared_axis_transition.dart @@ -233,44 +233,40 @@ class SharedAxisTransition extends StatelessWidget { final Color color = fillColor ?? Theme.of(context).canvasColor; return DualTransitionBuilder( animation: animation, - forwardBuilder: - (BuildContext context, Animation animation, Widget? child) { - return _EnterTransition( - animation: animation, - transitionType: transitionType, - child: child, - ); - }, - reverseBuilder: - (BuildContext context, Animation animation, Widget? child) { - return _ExitTransition( - animation: animation, - transitionType: transitionType, - reverse: true, - fillColor: color, - child: child, - ); - }, + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return _EnterTransition( + animation: animation, + transitionType: transitionType, + child: child, + ); + }, + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ExitTransition( + animation: animation, + transitionType: transitionType, + reverse: true, + fillColor: color, + child: child, + ); + }, child: DualTransitionBuilder( animation: ReverseAnimation(secondaryAnimation), - forwardBuilder: - (BuildContext context, Animation animation, Widget? child) { - return _EnterTransition( - animation: animation, - transitionType: transitionType, - reverse: true, - child: child, - ); - }, - reverseBuilder: - (BuildContext context, Animation animation, Widget? child) { - return _ExitTransition( - animation: animation, - transitionType: transitionType, - fillColor: color, - child: child, - ); - }, + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return _EnterTransition( + animation: animation, + transitionType: transitionType, + reverse: true, + child: child, + ); + }, + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ExitTransition( + animation: animation, + transitionType: transitionType, + fillColor: color, + child: child, + ); + }, child: child, ), ); @@ -349,8 +345,7 @@ class _EnterTransition extends StatelessWidget { return FadeTransition( opacity: _fadeInTransition.animate(animation), child: ScaleTransition( - scale: (!reverse ? _scaleUpTransition : _scaleDownTransition) - .animate(animation), + scale: (!reverse ? _scaleUpTransition : _scaleDownTransition).animate(animation), child: child, ), ); @@ -440,8 +435,7 @@ class _ExitTransition extends StatelessWidget { child: ColoredBox( color: fillColor, child: ScaleTransition( - scale: (!reverse ? _scaleUpTransition : _scaleDownTransition) - .animate(animation), + scale: (!reverse ? _scaleUpTransition : _scaleDownTransition).animate(animation), child: child, ), ), diff --git a/packages/animations/test/dual_transition_builder_test.dart b/packages/animations/test/dual_transition_builder_test.dart index 7c7e25fc8b0e..a19a255e53c3 100644 --- a/packages/animations/test/dual_transition_builder_test.dart +++ b/packages/animations/test/dual_transition_builder_test.dart @@ -16,28 +16,26 @@ void main() { Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween( - begin: 1.0, - end: 0.0, - ).animate(animation), - child: child, - ); - }, + forwardBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: Container(color: Colors.green, height: 100, width: 100), ), ), @@ -86,28 +84,26 @@ void main() { child: Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween( - begin: 1.0, - end: 0.0, - ).animate(animation), - child: child, - ); - }, + forwardBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: const _StatefulTestWidget(name: 'Foo'), ), ), @@ -154,28 +150,26 @@ void main() { Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween( - begin: 1.0, - end: 0.0, - ).animate(animation), - child: child, - ); - }, + forwardBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: Container(color: Colors.green, height: 100, width: 100), ), ), @@ -221,28 +215,26 @@ void main() { Center( child: DualTransitionBuilder( animation: controller, - forwardBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return ScaleTransition(scale: animation, child: child); - }, - reverseBuilder: - ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween( - begin: 1.0, - end: 0.0, - ).animate(animation), - child: child, - ); - }, + forwardBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: ( + BuildContext context, + Animation animation, + Widget? child, + ) { + return FadeTransition( + opacity: Tween( + begin: 1.0, + end: 0.0, + ).animate(animation), + child: child, + ); + }, child: Container(color: Colors.green, height: 100, width: 100), ), ), diff --git a/packages/animations/test/modal_test.dart b/packages/animations/test/modal_test.dart index eb2963176e87..9a3ea6499d8a 100644 --- a/packages/animations/test/modal_test.dart +++ b/packages/animations/test/modal_test.dart @@ -154,7 +154,8 @@ void main() { expect(find.byType(_FlutterLogoModal), findsNothing); }); - testWidgets('showModal builds a new route with specified barrier properties ' + testWidgets( + 'showModal builds a new route with specified barrier properties ' 'with default configuration(FadeScaleTransitionConfiguration)', ( WidgetTester tester, ) async { @@ -196,7 +197,8 @@ void main() { expect(topModalBarrier.semanticsLabel, 'Dismiss'); }); - testWidgets('showModal forwards animation ' + testWidgets( + 'showModal forwards animation ' 'with default configuration(FadeScaleTransitionConfiguration)', ( WidgetTester tester, ) async { @@ -268,7 +270,8 @@ void main() { expect(find.byType(_FlutterLogoModal), findsOneWidget); }); - testWidgets('showModal reverse animation ' + testWidgets( + 'showModal reverse animation ' 'with default configuration(FadeScaleTransitionConfiguration)', ( WidgetTester tester, ) async { @@ -558,13 +561,13 @@ class _FlutterLogoModalState extends State<_FlutterLogoModal> { class _TestModalConfiguration extends ModalConfiguration { _TestModalConfiguration() - : super( - barrierColor: Colors.green, - barrierDismissible: true, - barrierLabel: 'customLabel', - transitionDuration: const Duration(milliseconds: 300), - reverseTransitionDuration: const Duration(milliseconds: 200), - ); + : super( + barrierColor: Colors.green, + barrierDismissible: true, + barrierLabel: 'customLabel', + transitionDuration: const Duration(milliseconds: 300), + reverseTransitionDuration: const Duration(milliseconds: 200), + ); @override Widget transitionBuilder( diff --git a/packages/animations/test/open_container_test.dart b/packages/animations/test/open_container_test.dart index 514138837def..daf8f2e52e63 100644 --- a/packages/animations/test/open_container_test.dart +++ b/packages/animations/test/open_container_test.dart @@ -394,9 +394,7 @@ void main() { matching: find.byType(DecoratedBox), ), ); - final decoration = - (decoratedBoxElement.widget as DecoratedBox).decoration - as ShapeDecoration; + final decoration = (decoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration; expect(decoration.shadows, closedShadows); // Open the container. @@ -407,8 +405,7 @@ void main() { final Element transitioningMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final transitioningMaterial = - transitioningMaterialElement.widget as Material; + final transitioningMaterial = transitioningMaterialElement.widget as Material; expect(transitioningMaterial.elevation, 0.0); final Element transitioningDecoratedBoxElement = tester.firstElement( @@ -420,8 +417,7 @@ void main() { ), ); final transitioningDecoration = - (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration - as ShapeDecoration; + (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration; // Verify shadows are lerping. final double expectedT = Curves.fastOutSlowIn.transform(0.5); @@ -450,8 +446,7 @@ void main() { ), ); final openDecoration = - (openDecoratedBoxElement.widget as DecoratedBox).decoration - as ShapeDecoration; + (openDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration; expect(openDecoration.shadows, openShadows); }); @@ -499,8 +494,7 @@ void main() { final Element transitioningMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final transitioningMaterial = - transitioningMaterialElement.widget as Material; + final transitioningMaterial = transitioningMaterialElement.widget as Material; expect(transitioningMaterial.elevation, lessThan(4.0)); expect(transitioningMaterial.elevation, greaterThan(0.0)); @@ -513,14 +507,14 @@ void main() { ), ); final transitioningDecoration = - (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration - as ShapeDecoration; + (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration; final double expectedT = Curves.fastOutSlowIn.transform(0.5); final BoxShadow expectedShadow = BoxShadow.lerpList( null, openShadows, expectedT, - )!.single; + )! + .single; expect(transitioningDecoration.shadows, hasLength(1)); expect(transitioningDecoration.shadows![0].color, expectedShadow.color); expect( @@ -548,8 +542,7 @@ void main() { ), ); final openDecoration = - (openDecoratedBoxElement.widget as DecoratedBox).decoration - as ShapeDecoration; + (openDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration; expect(openDecoration.shadows, openShadows); }); @@ -590,8 +583,7 @@ void main() { ), ); final srcDecoration = - (srcDecoratedBoxElement.widget as DecoratedBox).decoration - as ShapeDecoration; + (srcDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration; expect(srcDecoration.shadows, closedShadows); await tester.tap(find.text('Closed')); @@ -601,8 +593,7 @@ void main() { final Element transitioningMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final transitioningMaterial = - transitioningMaterialElement.widget as Material; + final transitioningMaterial = transitioningMaterialElement.widget as Material; expect(transitioningMaterial.elevation, greaterThan(0.0)); expect(transitioningMaterial.elevation, lessThan(8.0)); @@ -615,14 +606,14 @@ void main() { ), ); final transitioningDecoration = - (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration - as ShapeDecoration; + (transitioningDecoratedBoxElement.widget as DecoratedBox).decoration as ShapeDecoration; final double expectedT = Curves.fastOutSlowIn.transform(0.5); final BoxShadow expectedShadow = BoxShadow.lerpList( closedShadows, null, expectedT, - )!.single; + )! + .single; expect(transitioningDecoration.shadows, hasLength(1)); expect(transitioningDecoration.shadows![0].color, expectedShadow.color); expect( @@ -1215,9 +1206,7 @@ void main() { await tester.pumpWidget(openContainer); final Size orignalClosedRect = tester.getSize( - find - .ancestor(of: find.text('Closed'), matching: find.byType(Material)) - .first, + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)).first, ); expect(orignalClosedRect, const Size(100, 100)); @@ -1241,9 +1230,7 @@ void main() { expect(find.text('Closed'), findsOneWidget); final Size transitionEndSize = tester.getSize( - find - .ancestor(of: find.text('Open'), matching: find.byType(Material)) - .first, + find.ancestor(of: find.text('Open'), matching: find.byType(Material)).first, ); expect(transitionEndSize, const Size(200, 200)); @@ -1252,9 +1239,7 @@ void main() { expect(find.text('Closed'), findsOneWidget); final Size finalSize = tester.getSize( - find - .ancestor(of: find.text('Closed'), matching: find.byType(Material)) - .first, + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)).first, ); expect(finalSize, const Size(200, 200)); }); @@ -1333,9 +1318,7 @@ void main() { expect(tester.getRect(find.byType(Navigator)), fullNavigator); final Rect materialRectClosed = tester.getRect( - find - .ancestor(of: find.text('Closed'), matching: find.byType(Material)) - .first, + find.ancestor(of: find.text('Closed'), matching: find.byType(Material)).first, ); await tester.tap(find.text('Closed')); @@ -1823,13 +1806,12 @@ void main() { closedBuilder: (BuildContext context, VoidCallback action) { return GestureDetector(onTap: action, child: const Text('Closed')); }, - openBuilder: - (BuildContext context, CloseContainerActionCallback action) { - return GestureDetector( - onTap: () => action(returnValue: true), - child: const Text('Open'), - ); - }, + openBuilder: (BuildContext context, CloseContainerActionCallback action) { + return GestureDetector( + onTap: () => action(returnValue: true), + child: const Text('Open'), + ); + }, ); await tester.pumpWidget(_boilerplate(child: openContainer)); @@ -1861,10 +1843,9 @@ void main() { closedBuilder: (BuildContext context, VoidCallback action) { return Text('Close', key: closedBuilderKey); }, - openBuilder: - (BuildContext context, CloseContainerActionCallback action) { - return const Text('Open'); - }, + openBuilder: (BuildContext context, CloseContainerActionCallback action) { + return const Text('Open'); + }, ); await tester.pumpWidget(_boilerplate(child: openContainer)); @@ -1886,10 +1867,9 @@ void main() { closedBuilder: (BuildContext context, VoidCallback action) { return Text('Close', key: closedBuilderKey); }, - openBuilder: - (BuildContext context, CloseContainerActionCallback action) { - return const Text('Open'); - }, + openBuilder: (BuildContext context, CloseContainerActionCallback action) { + return const Text('Open'); + }, clipBehavior: Clip.none, ); @@ -2186,12 +2166,10 @@ class _SizableContainerState extends State<_SizableContainer> { class _RemoveOpenContainerExample extends StatefulWidget { @override - __RemoveOpenContainerExampleState createState() => - __RemoveOpenContainerExampleState(); + __RemoveOpenContainerExampleState createState() => __RemoveOpenContainerExampleState(); } -class __RemoveOpenContainerExampleState - extends State<_RemoveOpenContainerExample> { +class __RemoveOpenContainerExampleState extends State<_RemoveOpenContainerExample> { bool removeOpenContainerWidget = false; @override @@ -2199,16 +2177,15 @@ class __RemoveOpenContainerExampleState return removeOpenContainerWidget ? const Text('Container has been removed') : OpenContainer( - closedBuilder: (BuildContext context, VoidCallback action) => - Column( - children: [ - const Text('Closed'), - ElevatedButton( - onPressed: action, - child: const Text('Open the container'), - ), - ], + closedBuilder: (BuildContext context, VoidCallback action) => Column( + children: [ + const Text('Closed'), + ElevatedButton( + onPressed: action, + child: const Text('Open the container'), ), + ], + ), openBuilder: (BuildContext context, VoidCallback action) => Column( children: [ const Text('Open'), diff --git a/packages/camera/camera/example/integration_test/camera_test.dart b/packages/camera/camera/example/integration_test/camera_test.dart index 258110e41a1b..d3de641f51e7 100644 --- a/packages/camera/camera/example/integration_test/camera_test.dart +++ b/packages/camera/camera/example/integration_test/camera_test.dart @@ -32,12 +32,8 @@ void main() { }); final presetExpectedSizes = { - ResolutionPreset.low: Platform.isAndroid - ? const Size(240, 320) - : const Size(288, 352), - ResolutionPreset.medium: Platform.isAndroid - ? const Size(480, 720) - : const Size(480, 640), + ResolutionPreset.low: Platform.isAndroid ? const Size(240, 320) : const Size(288, 352), + ResolutionPreset.medium: Platform.isAndroid ? const Size(480, 720) : const Size(480, 640), ResolutionPreset.high: const Size(720, 1280), ResolutionPreset.veryHigh: const Size(1080, 1920), ResolutionPreset.ultraHigh: const Size(2160, 3840), @@ -76,10 +72,7 @@ void main() { // Verify image dimensions are as expected expect(video, isNotNull); - return assertExpectedDimensions( - expectedSize, - Size(video.height, video.width), - ); + return assertExpectedDimensions(expectedSize, Size(video.height, video.width)); } testWidgets( @@ -91,8 +84,7 @@ void main() { } for (final cameraDescription in cameras) { var previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { + for (final MapEntry preset in presetExpectedSizes.entries) { final controller = CameraController(cameraDescription, preset.key); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -119,11 +111,7 @@ void main() { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -133,8 +121,7 @@ void main() { sleep(const Duration(seconds: 2)); final XFile file = await controller.stopVideoRecording(); - final int recordingTime = - DateTime.now().millisecondsSinceEpoch - recordingStart; + final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; final videoFile = File(file.path); final videoController = VideoPlayerController.file(videoFile); @@ -151,11 +138,7 @@ void main() { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -179,8 +162,7 @@ void main() { } final XFile file = await controller.stopVideoRecording(); - final int recordingTime = - DateTime.now().millisecondsSinceEpoch - recordingStart; + final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; final videoFile = File(file.path); final videoController = VideoPlayerController.file(videoFile); @@ -197,11 +179,7 @@ void main() { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); var isDetecting = false; @@ -252,9 +230,7 @@ void main() { return completer.future; } - testWidgets('Set description while recording captures full video', ( - WidgetTester tester, - ) async { + testWidgets('Set description while recording captures full video', (WidgetTester tester) async { final List cameras = await availableCameras(); if (cameras.length < 2) { return; @@ -282,10 +258,7 @@ void main() { final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); - expect( - duration, - greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds), - ); + expect(duration, greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds)); await controller.dispose(); }); @@ -295,11 +268,7 @@ void main() { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); await controller.setDescription(cameras[1]); @@ -307,9 +276,7 @@ void main() { expect(controller.description, cameras[1]); }); - testWidgets('iOS image streaming with imageFormatGroup', ( - WidgetTester tester, - ) async { + testWidgets('iOS image streaming with imageFormatGroup', (WidgetTester tester) async { final List cameras = await availableCameras(); if (cameras.isEmpty) { return; diff --git a/packages/camera/camera/example/lib/main.dart b/packages/camera/camera/example/lib/main.dart index cca528c04fda..a03ed1e4e2a7 100644 --- a/packages/camera/camera/example/lib/main.dart +++ b/packages/camera/camera/example/lib/main.dart @@ -127,6 +127,7 @@ class _CameraExampleHomeState extends State _initializeCameraController(cameraController.description); } } + // #enddocregion AppLifecycle @override @@ -140,8 +141,7 @@ class _CameraExampleHomeState extends State decoration: BoxDecoration( color: Colors.black, border: Border.all( - color: - controller != null && controller!.value.isRecordingVideo + color: controller != null && controller!.value.isRecordingVideo ? Colors.redAccent : Colors.grey, width: 3.0, @@ -157,9 +157,7 @@ class _CameraExampleHomeState extends State _modeControlRowWidget(), Padding( padding: const EdgeInsets.all(5.0), - child: Row( - children: [_cameraTogglesRowWidget(), _thumbnailWidget()], - ), + child: Row(children: [_cameraTogglesRowWidget(), _thumbnailWidget()]), ), ], ), @@ -173,11 +171,7 @@ class _CameraExampleHomeState extends State if (cameraController == null || !cameraController.value.isInitialized) { return const Text( 'Tap a camera', - style: TextStyle( - color: Colors.white, - fontSize: 24.0, - fontWeight: FontWeight.w900, - ), + style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900), ); } else { return Listener( @@ -191,8 +185,7 @@ class _CameraExampleHomeState extends State behavior: HitTestBehavior.opaque, onScaleStart: _handleScaleStart, onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), + onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints), ); }, ), @@ -211,10 +204,7 @@ class _CameraExampleHomeState extends State return; } - _currentScale = (_baseScale * details.scale).clamp( - _minAvailableZoom, - _maxAvailableZoom, - ); + _currentScale = (_baseScale * details.scale).clamp(_minAvailableZoom, _maxAvailableZoom); await controller!.setZoomLevel(_currentScale); } @@ -269,16 +259,12 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.exposure), color: Colors.blue, - onPressed: controller != null - ? onExposureModeButtonPressed - : null, + onPressed: controller != null ? onExposureModeButtonPressed : null, ), IconButton( icon: const Icon(Icons.filter_center_focus), color: Colors.blue, - onPressed: controller != null - ? onFocusModeButtonPressed - : null, + onPressed: controller != null ? onFocusModeButtonPressed : null, ), ] : [], @@ -294,9 +280,7 @@ class _CameraExampleHomeState extends State : Icons.screen_rotation, ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null, ), ], ), @@ -316,36 +300,28 @@ class _CameraExampleHomeState extends State children: [ IconButton( icon: const Icon(Icons.flash_off), - color: controller?.value.flashMode == FlashMode.off - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.off ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.off) : null, ), IconButton( icon: const Icon(Icons.flash_auto), - color: controller?.value.flashMode == FlashMode.auto - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.auto ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.auto) : null, ), IconButton( icon: const Icon(Icons.flash_on), - color: controller?.value.flashMode == FlashMode.always - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.always ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.always) : null, ), IconButton( icon: const Icon(Icons.highlight), - color: controller?.value.flashMode == FlashMode.torch - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.torch) : null, @@ -382,8 +358,7 @@ class _CameraExampleHomeState extends State TextButton( style: styleAuto, onPressed: controller != null - ? () => - onSetExposureModeButtonPressed(ExposureMode.auto) + ? () => onSetExposureModeButtonPressed(ExposureMode.auto) : null, onLongPress: () { if (controller != null) { @@ -396,17 +371,13 @@ class _CameraExampleHomeState extends State TextButton( style: styleLocked, onPressed: controller != null - ? () => onSetExposureModeButtonPressed( - ExposureMode.locked, - ) + ? () => onSetExposureModeButtonPressed(ExposureMode.locked) : null, child: const Text('LOCKED'), ), TextButton( style: styleLocked, - onPressed: controller != null - ? () => controller!.setExposureOffset(0.0) - : null, + onPressed: controller != null ? () => controller!.setExposureOffset(0.0) : null, child: const Text('RESET OFFSET'), ), ], @@ -421,9 +392,7 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: - _minAvailableExposureOffset == - _maxAvailableExposureOffset + onChanged: _minAvailableExposureOffset == _maxAvailableExposureOffset ? null : setExposureOffset, ), @@ -439,9 +408,7 @@ class _CameraExampleHomeState extends State Widget _focusModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - foregroundColor: controller?.value.focusMode == FocusMode.auto - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.focusMode == FocusMode.auto ? Colors.orange : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( foregroundColor: controller?.value.focusMode == FocusMode.locked @@ -517,9 +484,7 @@ class _CameraExampleHomeState extends State : null, ), IconButton( - icon: - cameraController != null && - cameraController.value.isRecordingPaused + icon: cameraController != null && cameraController.value.isRecordingPaused ? const Icon(Icons.play_arrow) : const Icon(Icons.pause), color: Colors.blue, @@ -544,13 +509,10 @@ class _CameraExampleHomeState extends State ), IconButton( icon: const Icon(Icons.pause_presentation), - color: - cameraController != null && cameraController.value.isPreviewPaused + color: cameraController != null && cameraController.value.isPreviewPaused ? Colors.red : Colors.blue, - onPressed: cameraController == null - ? null - : onPausePreviewButtonPressed, + onPressed: cameraController == null ? null : onPausePreviewButtonPressed, ), ], ); @@ -602,9 +564,7 @@ class _CameraExampleHomeState extends State String timestamp() => DateTime.now().millisecondsSinceEpoch.toString(); void showInSnackBar(String message) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message))); } void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) { @@ -630,9 +590,7 @@ class _CameraExampleHomeState extends State } } - Future _initializeCameraController( - CameraDescription cameraDescription, - ) async { + Future _initializeCameraController(CameraDescription cameraDescription) async { final cameraController = CameraController( cameraDescription, kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, @@ -648,9 +606,7 @@ class _CameraExampleHomeState extends State setState(() {}); } if (cameraController.value.hasError) { - showInSnackBar( - 'Camera error ${cameraController.value.errorDescription}', - ); + showInSnackBar('Camera error ${cameraController.value.errorDescription}'); } }); @@ -668,12 +624,8 @@ class _CameraExampleHomeState extends State ), ] : >[], - cameraController.getMaxZoomLevel().then( - (double value) => _maxAvailableZoom = value, - ), - cameraController.getMinZoomLevel().then( - (double value) => _minAvailableZoom = value, - ), + cameraController.getMaxZoomLevel().then((double value) => _maxAvailableZoom = value), + cameraController.getMinZoomLevel().then((double value) => _minAvailableZoom = value), ]); } on CameraException catch (e) { switch (e.code) { diff --git a/packages/camera/camera/example/test/main_test.dart b/packages/camera/camera/example/test/main_test.dart index 9563df089fac..8fd39d651274 100644 --- a/packages/camera/camera/example/test/main_test.dart +++ b/packages/camera/camera/example/test/main_test.dart @@ -15,9 +15,7 @@ void main() { expect(find.byType(SnackBar), findsOneWidget); }); - testWidgets('CameraDescription toggles will not overflow', ( - WidgetTester tester, - ) async { + testWidgets('CameraDescription toggles will not overflow', (WidgetTester tester) async { WidgetsFlutterBinding.ensureInitialized(); // Adds 10 fake camera descriptions. for (var i = 0; i < 10; i++) { diff --git a/packages/camera/camera/example/test_driver/integration_test.dart b/packages/camera/camera/example/test_driver/integration_test.dart index ef65f091ca07..39d763c0900b 100644 --- a/packages/camera/camera/example/test_driver/integration_test.dart +++ b/packages/camera/camera/example/test_driver/integration_test.dart @@ -39,10 +39,7 @@ Future main() async { ]); print('Starting test.'); final FlutterDriver driver = await FlutterDriver.connect(); - final String data = await driver.requestData( - null, - timeout: const Duration(minutes: 1), - ); + final String data = await driver.requestData(null, timeout: const Duration(minutes: 1)); await driver.close(); print('Test finished. Revoking camera permissions...'); Process.runSync('adb', [ diff --git a/packages/camera/camera/lib/src/camera_controller.dart b/packages/camera/camera/lib/src/camera_controller.dart index d941c2e85f66..05d52152b430 100644 --- a/packages/camera/camera/lib/src/camera_controller.dart +++ b/packages/camera/camera/lib/src/camera_controller.dart @@ -185,8 +185,7 @@ class CameraValue { flashMode: flashMode ?? this.flashMode, exposureMode: exposureMode ?? this.exposureMode, focusMode: focusMode ?? this.focusMode, - exposurePointSupported: - exposurePointSupported ?? this.exposurePointSupported, + exposurePointSupported: exposurePointSupported ?? this.exposurePointSupported, focusPointSupported: focusPointSupported ?? this.focusPointSupported, deviceOrientation: deviceOrientation ?? this.deviceOrientation, lockedCaptureOrientation: lockedCaptureOrientation == null @@ -200,8 +199,7 @@ class CameraValue { previewPauseOrientation: previewPauseOrientation == null ? this.previewPauseOrientation : previewPauseOrientation.orNull, - videoStabilizationMode: - videoStabilizationMode ?? this.videoStabilizationMode, + videoStabilizationMode: videoStabilizationMode ?? this.videoStabilizationMode, ); } @@ -272,8 +270,7 @@ class CameraController extends ValueNotifier { /// if unavailable a lower resolution will be used. /// /// See also: [ResolutionPreset]. - ResolutionPreset get resolutionPreset => - mediaSettings.resolutionPreset ?? ResolutionPreset.max; + ResolutionPreset get resolutionPreset => mediaSettings.resolutionPreset ?? ResolutionPreset.max; /// Whether to include audio when recording a video. bool get enableAudio => mediaSettings.enableAudio; @@ -303,8 +300,7 @@ class CameraController extends ValueNotifier { // just called). If the controller has not been initialized at least once, // this value is null. Future? _initializeFuture; - StreamSubscription? - _deviceOrientationSubscription; + StreamSubscription? _deviceOrientationSubscription; /// Checks whether [CameraController.dispose] has completed successfully. /// @@ -358,9 +354,7 @@ class CameraController extends ValueNotifier { ); unawaited( - CameraPlatform.instance.onCameraError(_cameraId).first.then(( - CameraErrorEvent event, - ) { + CameraPlatform.instance.onCameraError(_cameraId).first.then((CameraErrorEvent event) { value = value.copyWith(errorDescription: event.description); }), ); @@ -374,8 +368,7 @@ class CameraController extends ValueNotifier { isInitialized: true, description: description, previewSize: await initializeCompleter.future.then( - (CameraInitializedEvent event) => - Size(event.previewWidth, event.previewHeight), + (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight), ), exposureMode: await initializeCompleter.future.then( (CameraInitializedEvent event) => event.exposureMode, @@ -523,11 +516,11 @@ class CameraController extends ValueNotifier { } try { - _imageStreamSubscription = CameraPlatform.instance - .onStreamedFrameAvailable(_cameraId) - .listen((CameraImageData imageData) { - onAvailable(CameraImage.fromPlatformInterface(imageData)); - }); + _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen( + (CameraImageData imageData) { + onAvailable(CameraImage.fromPlatformInterface(imageData)); + }, + ); value = value.copyWith(isStreamingImages: true); } on PlatformException catch (e) { throw CameraException(e.code, e.message); @@ -630,9 +623,7 @@ class CameraController extends ValueNotifier { } try { - final XFile file = await CameraPlatform.instance.stopVideoRecording( - _cameraId, - ); + final XFile file = await CameraPlatform.instance.stopVideoRecording(_cameraId); value = value.copyWith( isRecordingVideo: false, recordingOrientation: const Optional.absent(), @@ -742,8 +733,10 @@ class CameraController extends ValueNotifier { }) async { _throwIfNotInitialized('setVideoStabilizationMode'); try { - final VideoStabilizationMode? modeToSet = - await _getVideoStabilizationModeToSet(mode, allowFallback); + final VideoStabilizationMode? modeToSet = await _getVideoStabilizationModeToSet( + mode, + allowFallback, + ); // When _getVideoStabilizationModeToSet returns null // it means that the device doesn't support any @@ -754,10 +747,7 @@ class CameraController extends ValueNotifier { if (modeToSet == null) { return; } - await CameraPlatform.instance.setVideoStabilizationMode( - _cameraId, - modeToSet, - ); + await CameraPlatform.instance.setVideoStabilizationMode(_cameraId, modeToSet); value = value.copyWith(videoStabilizationMode: modeToSet); } on PlatformException catch (e) { throw CameraException(e.code, e.message); @@ -768,8 +758,7 @@ class CameraController extends ValueNotifier { VideoStabilizationMode requestedMode, bool allowFallback, ) async { - final Iterable supportedModes = await CameraPlatform - .instance + final Iterable supportedModes = await CameraPlatform.instance .getSupportedVideoStabilizationModes(_cameraId); // If it can't fallback and the specific @@ -785,9 +774,7 @@ class CameraController extends ValueNotifier { VideoStabilizationMode? fallbackMode = requestedMode; while (fallbackMode != null && !supportedModes.contains(fallbackMode)) { - fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode( - fallbackMode, - ); + fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode(fallbackMode); } return fallbackMode; @@ -797,15 +784,12 @@ class CameraController extends ValueNotifier { /// for the selected camera. /// /// [VideoStabilizationMode.off] will always be listed. - Future> - getSupportedVideoStabilizationModes() async { + Future> getSupportedVideoStabilizationModes() async { _throwIfNotInitialized('getSupportedVideoStabilizationModes'); try { final modes = { VideoStabilizationMode.off, - ...await CameraPlatform.instance.getSupportedVideoStabilizationModes( - _cameraId, - ), + ...await CameraPlatform.instance.getSupportedVideoStabilizationModes(_cameraId), }; return modes; } on PlatformException catch (e) { @@ -838,11 +822,8 @@ class CameraController extends ValueNotifier { /// Supplying a `null` value will reset the exposure point to it's default /// value. Future setExposurePoint(Offset? point) async { - if (point != null && - (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { - throw ArgumentError( - 'The values of point should be anywhere between (0,0) and (1,1).', - ); + if (point != null && (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { + throw ArgumentError('The values of point should be anywhere between (0,0) and (1,1).'); } try { @@ -965,9 +946,7 @@ class CameraController extends ValueNotifier { Future unlockCaptureOrientation() async { try { await CameraPlatform.instance.unlockCaptureOrientation(_cameraId); - value = value.copyWith( - lockedCaptureOrientation: const Optional.absent(), - ); + value = value.copyWith(lockedCaptureOrientation: const Optional.absent()); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -978,11 +957,8 @@ class CameraController extends ValueNotifier { /// Supplying a `null` value will reset the focus point to it's default /// value. Future setFocusPoint(Offset? point) async { - if (point != null && - (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { - throw ArgumentError( - 'The values of point should be anywhere between (0,0) and (1,1).', - ); + if (point != null && (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { + throw ArgumentError('The values of point should be anywhere between (0,0) and (1,1).'); } try { await CameraPlatform.instance.setFocusPoint( @@ -995,8 +971,7 @@ class CameraController extends ValueNotifier { } /// Check whether the camera platform supports image streaming. - bool supportsImageStreaming() => - CameraPlatform.instance.supportsImageStreaming(); + bool supportsImageStreaming() => CameraPlatform.instance.supportsImageStreaming(); /// Releases the resources of this camera. @override @@ -1106,9 +1081,7 @@ class Optional extends IterableBase { /// /// The transformer must not return `null`. If it does, an [ArgumentError] is thrown. Optional transform(S Function(T value) transformer) { - return _value == null - ? Optional.absent() - : Optional.of(transformer(_value)); + return _value == null ? Optional.absent() : Optional.of(transformer(_value)); } /// Transforms the Optional value. @@ -1117,14 +1090,11 @@ class Optional extends IterableBase { /// /// Returns [absent()] if the transformer returns `null`. Optional transformNullable(S? Function(T value) transformer) { - return _value == null - ? Optional.absent() - : Optional.fromNullable(transformer(_value)); + return _value == null ? Optional.absent() : Optional.fromNullable(transformer(_value)); } @override - Iterator get iterator => - isPresent ? [_value as T].iterator : Iterable.empty().iterator; + Iterator get iterator => isPresent ? [_value as T].iterator : Iterable.empty().iterator; /// Delegates to the underlying [value] hashCode. @override @@ -1136,8 +1106,6 @@ class Optional extends IterableBase { @override String toString() { - return _value == null - ? 'Optional { absent }' - : 'Optional { value: $_value }'; + return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }'; } } diff --git a/packages/camera/camera/lib/src/camera_image.dart b/packages/camera/camera/lib/src/camera_image.dart index f19bc67462bd..b0fbb301e8e5 100644 --- a/packages/camera/camera/lib/src/camera_image.dart +++ b/packages/camera/camera/lib/src/camera_image.dart @@ -122,9 +122,7 @@ class CameraImage { height = data.height, width = data.width, planes = List.unmodifiable( - data.planes.map( - (CameraImagePlane plane) => Plane._fromPlatformInterface(plane), - ), + data.planes.map((CameraImagePlane plane) => Plane._fromPlatformInterface(plane)), ), lensAperture = data.lensAperture, sensorExposureTime = data.sensorExposureTime, @@ -141,8 +139,7 @@ class CameraImage { sensorSensitivity = data['sensorSensitivity'] as double?, planes = List.unmodifiable( (data['planes'] as List).map( - (dynamic planeData) => - Plane._fromPlatformData(planeData as Map), + (dynamic planeData) => Plane._fromPlatformData(planeData as Map), ), ); diff --git a/packages/camera/camera/test/camera_image_stream_test.dart b/packages/camera/camera/test/camera_image_stream_test.dart index 0a9644fcd8df..e9c12afc7831 100644 --- a/packages/camera/camera/test/camera_image_stream_test.dart +++ b/packages/camera/camera/test/camera_image_stream_test.dart @@ -33,11 +33,7 @@ void main() { () => cameraController.startImageStream((CameraImage image) {}), throwsA( isA() - .having( - (CameraException error) => error.code, - 'code', - 'Uninitialized CameraController', - ) + .having((CameraException error) => error.code, 'code', 'Uninitialized CameraController') .having( (CameraException error) => error.description, 'description', @@ -47,64 +43,54 @@ void main() { ); }); - test( - 'startImageStream() throws $CameraException when recording videos', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - - await cameraController.initialize(); - - cameraController.value = cameraController.value.copyWith( - isRecordingVideo: true, - ); - - expect( - () => cameraController.startImageStream((CameraImage image) {}), - throwsA( - isA().having( - (CameraException error) => error.description, - 'A video recording is already started.', - 'startImageStream was called while a video is being recorded.', - ), - ), - ); - }, - ); - test( - 'startImageStream() throws $CameraException when already streaming images', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, + test('startImageStream() throws $CameraException when recording videos', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + await cameraController.initialize(); + + cameraController.value = cameraController.value.copyWith(isRecordingVideo: true); + + expect( + () => cameraController.startImageStream((CameraImage image) {}), + throwsA( + isA().having( + (CameraException error) => error.description, + 'A video recording is already started.', + 'startImageStream was called while a video is being recorded.', ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - - cameraController.value = cameraController.value.copyWith( - isStreamingImages: true, - ); - expect( - () => cameraController.startImageStream((CameraImage image) {}), - throwsA( - isA().having( - (CameraException error) => error.description, - 'A camera has started streaming images.', - 'startImageStream was called while a camera was streaming images.', - ), + ), + ); + }); + test('startImageStream() throws $CameraException when already streaming images', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + cameraController.value = cameraController.value.copyWith(isStreamingImages: true); + expect( + () => cameraController.startImageStream((CameraImage image) {}), + throwsA( + isA().having( + (CameraException error) => error.description, + 'A camera has started streaming images.', + 'startImageStream was called while a camera was streaming images.', ), - ); - }, - ); + ), + ); + }); test('startImageStream() calls CameraPlatform', () async { final cameraController = CameraController( @@ -140,11 +126,7 @@ void main() { cameraController.stopImageStream, throwsA( isA() - .having( - (CameraException error) => error.code, - 'code', - 'Uninitialized CameraController', - ) + .having((CameraException error) => error.code, 'code', 'Uninitialized CameraController') .having( (CameraException error) => error.description, 'description', @@ -154,31 +136,28 @@ void main() { ); }); - test( - 'stopImageStream() throws $CameraException when not streaming images', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - - expect( - cameraController.stopImageStream, - throwsA( - isA().having( - (CameraException error) => error.description, - 'No camera is streaming images', - 'stopImageStream was called when no camera is streaming images.', - ), + test('stopImageStream() throws $CameraException when not streaming images', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + expect( + cameraController.stopImageStream, + throwsA( + isA().having( + (CameraException error) => error.description, + 'No camera is streaming images', + 'stopImageStream was called when no camera is streaming images.', ), - ); - }, - ); + ), + ); + }); test('stopImageStream() intended behaviour', () async { final cameraController = CameraController( @@ -214,14 +193,9 @@ void main() { await cameraController.initialize(); - await cameraController.startVideoRecording( - onAvailable: (CameraImage image) {}, - ); + await cameraController.startVideoRecording(onAvailable: (CameraImage image) {}); - expect( - mockPlatform.streamCallLog.contains('startVideoCapturing with stream'), - isTrue, - ); + expect(mockPlatform.streamCallLog.contains('startVideoCapturing with stream'), isTrue); }); test('startVideoRecording() by default does not stream', () async { diff --git a/packages/camera/camera/test/camera_image_test.dart b/packages/camera/camera/test/camera_image_test.dart index 6eb594497e39..7771b4c9578b 100644 --- a/packages/camera/camera/test/camera_image_test.dart +++ b/packages/camera/camera/test/camera_image_test.dart @@ -47,17 +47,11 @@ void main() { // Planes. expect(image.planes.length, originalImage.planes.length); for (var i = 0; i < image.planes.length; i++) { - expect( - image.planes[i].bytes.length, - originalImage.planes[i].bytes.length, - ); + expect(image.planes[i].bytes.length, originalImage.planes[i].bytes.length); for (var j = 0; j < image.planes[i].bytes.length; j++) { expect(image.planes[i].bytes[j], originalImage.planes[i].bytes[j]); } - expect( - image.planes[i].bytesPerPixel, - originalImage.planes[i].bytesPerPixel, - ); + expect(image.planes[i].bytesPerPixel, originalImage.planes[i].bytesPerPixel); expect(image.planes[i].bytesPerRow, originalImage.planes[i].bytesPerRow); expect(image.planes[i].width, originalImage.planes[i].width); expect(image.planes[i].height, originalImage.planes[i].height); diff --git a/packages/camera/camera/test/camera_preview_test.dart b/packages/camera/camera/test/camera_preview_test.dart index 912a583e9255..c5dfde4f7383 100644 --- a/packages/camera/camera/test/camera_preview_test.dart +++ b/packages/camera/camera/test/camera_preview_test.dart @@ -10,8 +10,7 @@ import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -class FakeController extends ValueNotifier - implements CameraController { +class FakeController extends ValueNotifier implements CameraController { FakeController() : super(const CameraValue.uninitialized(fakeDescription)); static const CameraDescription fakeDescription = CameraDescription( @@ -146,8 +145,8 @@ class FakeController extends ValueNotifier }) async {} @override - Future> - getSupportedVideoStabilizationModes() async => []; + Future> getSupportedVideoStabilizationModes() async => + []; @override bool supportsImageStreaming() => true; @@ -167,10 +166,9 @@ void main() { isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitDown, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.landscapeRight, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.portraitUp, ), @@ -178,16 +176,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 0); debugDefaultTargetPlatformOverride = null; @@ -206,10 +199,9 @@ void main() { isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.landscapeLeft, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.landscapeLeft, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.landscapeRight, ), @@ -217,16 +209,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 1); debugDefaultTargetPlatformOverride = null; @@ -245,10 +232,9 @@ void main() { isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.landscapeRight, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.portraitDown, ), @@ -256,16 +242,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 2); debugDefaultTargetPlatformOverride = null; @@ -284,10 +265,9 @@ void main() { isInitialized: true, isRecordingVideo: true, deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.landscapeRight, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.landscapeLeft, ), @@ -295,16 +275,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 3); debugDefaultTargetPlatformOverride = null; @@ -322,10 +297,9 @@ void main() { controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitDown, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.portraitUp, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.portraitUp, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.landscapeLeft, ), @@ -333,16 +307,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 0); debugDefaultTargetPlatformOverride = null; @@ -360,10 +329,9 @@ void main() { controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitDown, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.landscapeRight, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.landscapeLeft, ), @@ -371,16 +339,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 1); debugDefaultTargetPlatformOverride = null; @@ -398,10 +361,9 @@ void main() { controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.portraitDown, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.portraitDown, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.landscapeLeft, ), @@ -409,16 +371,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 2); debugDefaultTargetPlatformOverride = null; @@ -436,10 +393,9 @@ void main() { controller.value = controller.value.copyWith( isInitialized: true, deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: - const Optional.fromNullable( - DeviceOrientation.landscapeRight, - ), + lockedCaptureOrientation: const Optional.fromNullable( + DeviceOrientation.landscapeRight, + ), recordingOrientation: const Optional.fromNullable( DeviceOrientation.landscapeLeft, ), @@ -447,16 +403,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 1); debugDefaultTargetPlatformOverride = null; @@ -481,16 +432,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 0); debugDefaultTargetPlatformOverride = null; @@ -515,16 +461,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 1); debugDefaultTargetPlatformOverride = null; @@ -549,16 +490,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 2); debugDefaultTargetPlatformOverride = null; @@ -583,16 +519,11 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsOneWidget); - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.quarterTurns, 3); debugDefaultTargetPlatformOverride = null; @@ -600,9 +531,7 @@ void main() { ); }, skip: kIsWeb); - testWidgets('when not on Android there should not be a rotated box', ( - WidgetTester tester, - ) async { + testWidgets('when not on Android there should not be a rotated box', (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; final controller = FakeController(); addTearDown(controller.dispose); @@ -612,10 +541,7 @@ void main() { ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CameraPreview(controller), - ), + Directionality(textDirection: TextDirection.ltr, child: CameraPreview(controller)), ); expect(find.byType(RotatedBox), findsNothing); expect(find.byType(Texture), findsOneWidget); diff --git a/packages/camera/camera/test/camera_test.dart b/packages/camera/camera/test/camera_test.dart index 913d3391cd9e..899f15c50803 100644 --- a/packages/camera/camera/test/camera_test.dart +++ b/packages/camera/camera/test/camera_test.dart @@ -30,23 +30,14 @@ List get mockAvailableCameras => [ int get mockInitializeCamera => 13; CameraInitializedEvent get mockOnCameraInitializedEvent => - const CameraInitializedEvent( - 13, - 75, - 75, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ); + const CameraInitializedEvent(13, 75, 75, ExposureMode.auto, true, FocusMode.auto, true); DeviceOrientationChangedEvent get mockOnDeviceOrientationChangedEvent => const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); CameraClosingEvent get mockOnCameraClosingEvent => const CameraClosingEvent(13); -CameraErrorEvent get mockOnCameraErrorEvent => - const CameraErrorEvent(13, 'closing'); +CameraErrorEvent get mockOnCameraErrorEvent => const CameraErrorEvent(13, 'closing'); XFile mockTakePicture = XFile('foo/bar.png'); @@ -58,27 +49,21 @@ void main() { WidgetsFlutterBinding.ensureInitialized(); group('camera', () { - test( - 'debugCheckIsDisposed should not throw assertion error when disposed', - () { - const description = MockCameraDescription(); - final controller = CameraController(description, ResolutionPreset.low); + test('debugCheckIsDisposed should not throw assertion error when disposed', () { + const description = MockCameraDescription(); + final controller = CameraController(description, ResolutionPreset.low); - controller.dispose(); + controller.dispose(); - expect(controller.debugCheckIsDisposed, returnsNormally); - }, - ); + expect(controller.debugCheckIsDisposed, returnsNormally); + }); - test( - 'debugCheckIsDisposed should throw assertion error when not disposed', - () { - const description = MockCameraDescription(); - final controller = CameraController(description, ResolutionPreset.low); + test('debugCheckIsDisposed should throw assertion error when not disposed', () { + const description = MockCameraDescription(); + final controller = CameraController(description, ResolutionPreset.low); - expect(() => controller.debugCheckIsDisposed(), throwsAssertionError); - }, - ); + expect(() => controller.debugCheckIsDisposed(), throwsAssertionError); + }); test('availableCameras() has camera', () async { CameraPlatform.instance = MockCameraPlatform(); @@ -204,33 +189,26 @@ void main() { ); }); - test( - 'initialize() throws $CameraException on $PlatformException ', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); + test('initialize() throws $CameraException on $PlatformException ', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - mockPlatformException = true; + mockPlatformException = true; - expect( - cameraController.initialize, - throwsA( - isA().having( - (CameraException error) => error.description, - 'foo', - 'bar', - ), - ), - ); - mockPlatformException = false; - }, - ); + expect( + cameraController.initialize, + throwsA( + isA().having((CameraException error) => error.description, 'foo', 'bar'), + ), + ); + mockPlatformException = false; + }); test('initialize() sets imageFormat', () async { debugDefaultTargetPlatformOverride = TargetPlatform.android; @@ -245,52 +223,45 @@ void main() { ); await cameraController.initialize(); verify( - CameraPlatform.instance.initializeCamera( - 13, - imageFormatGroup: ImageFormatGroup.yuv420, - ), + CameraPlatform.instance.initializeCamera(13, imageFormatGroup: ImageFormatGroup.yuv420), ).called(1); }); - test( - 'setDescription waits for initialize before calling dispose', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - imageFormatGroup: ImageFormatGroup.bgra8888, - ); + test('setDescription waits for initialize before calling dispose', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + imageFormatGroup: ImageFormatGroup.bgra8888, + ); - final initializeCompleter = Completer(); - when( - CameraPlatform.instance.initializeCamera( - mockInitializeCamera, - imageFormatGroup: ImageFormatGroup.bgra8888, - ), - ).thenAnswer((_) => initializeCompleter.future); + final initializeCompleter = Completer(); + when( + CameraPlatform.instance.initializeCamera( + mockInitializeCamera, + imageFormatGroup: ImageFormatGroup.bgra8888, + ), + ).thenAnswer((_) => initializeCompleter.future); - unawaited(cameraController.initialize()); + unawaited(cameraController.initialize()); - final Future setDescriptionFuture = cameraController - .setDescription( - const CameraDescription( - name: 'cam2', - lensDirection: CameraLensDirection.front, - sensorOrientation: 90, - ), - ); - verifyNever(CameraPlatform.instance.dispose(mockInitializeCamera)); + final Future setDescriptionFuture = cameraController.setDescription( + const CameraDescription( + name: 'cam2', + lensDirection: CameraLensDirection.front, + sensorOrientation: 90, + ), + ); + verifyNever(CameraPlatform.instance.dispose(mockInitializeCamera)); - initializeCompleter.complete(); + initializeCompleter.complete(); - await setDescriptionFuture; - verify(CameraPlatform.instance.dispose(mockInitializeCamera)); - }, - ); + await setDescriptionFuture; + verify(CameraPlatform.instance.dispose(mockInitializeCamera)); + }); test('prepareForVideoRecording() calls $CameraPlatform ', () async { final cameraController = CameraController( @@ -335,34 +306,29 @@ void main() { ); }); - test( - 'takePicture() throws $CameraException when takePicture is true', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('takePicture() throws $CameraException when takePicture is true', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isTakingPicture: true, - ); - expect( - cameraController.takePicture(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'Previous capture has not returned yet.', - 'takePicture was called before the previous capture returned.', - ), + cameraController.value = cameraController.value.copyWith(isTakingPicture: true); + expect( + cameraController.takePicture(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'Previous capture has not returned yet.', + 'takePicture was called before the previous capture returned.', ), - ); - }, - ); + ), + ); + }); test('takePicture() returns $XFile', () async { final cameraController = CameraController( @@ -379,127 +345,28 @@ void main() { expect(xFile.path, mockTakePicture.path); }); - test( - 'takePicture() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - - mockPlatformException = true; - expect( - cameraController.takePicture(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'foo', - 'bar', - ), - ), - ); - mockPlatformException = false; - }, - ); - - test( - 'startVideoRecording() throws $CameraException when uninitialized', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - - expect( - cameraController.startVideoRecording(), - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'Uninitialized CameraController', - ) - .having( - (CameraException error) => error.description, - 'description', - 'startVideoRecording() was called on an uninitialized CameraController.', - ), - ), - ); - }, - ); - test( - 'startVideoRecording() throws $CameraException when recording videos', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - - await cameraController.initialize(); - - cameraController.value = cameraController.value.copyWith( - isRecordingVideo: true, - ); - - expect( - cameraController.startVideoRecording(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'A video recording is already started.', - 'startVideoRecording was called when a recording is already started.', - ), - ), - ); - }, - ); - - test( - 'getMaxZoomLevel() throws $CameraException when uninitialized', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); + test('takePicture() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - expect( - cameraController.getMaxZoomLevel, - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'Uninitialized CameraController', - ) - .having( - (CameraException error) => error.description, - 'description', - 'getMaxZoomLevel() was called on an uninitialized CameraController.', - ), - ), - ); - }, - ); + mockPlatformException = true; + expect( + cameraController.takePicture(), + throwsA( + isA().having((CameraException error) => error.description, 'foo', 'bar'), + ), + ); + mockPlatformException = false; + }); - test('getMaxZoomLevel() throws $CameraException when disposed', () async { + test('startVideoRecording() throws $CameraException when uninitialized', () async { final cameraController = CameraController( const CameraDescription( name: 'cam', @@ -509,66 +376,24 @@ void main() { ResolutionPreset.max, ); - await cameraController.initialize(); - await cameraController.dispose(); - expect( - cameraController.getMaxZoomLevel, + cameraController.startVideoRecording(), throwsA( isA() .having( (CameraException error) => error.code, 'code', - 'Disposed CameraController', + 'Uninitialized CameraController', ) .having( (CameraException error) => error.description, 'description', - 'getMaxZoomLevel() was called on a disposed CameraController.', + 'startVideoRecording() was called on an uninitialized CameraController.', ), ), ); }); - - test( - 'getMaxZoomLevel() throws $CameraException when a platform exception occured.', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - - await cameraController.initialize(); - when( - CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera), - ).thenThrow( - CameraException('TEST_ERROR', 'This is a test error messge'), - ); - - expect( - cameraController.getMaxZoomLevel, - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'TEST_ERROR', - ) - .having( - (CameraException error) => error.description, - 'description', - 'This is a test error messge', - ), - ), - ); - }, - ); - - test('getMaxZoomLevel() returns max zoom level.', () async { + test('startVideoRecording() throws $CameraException when recording videos', () async { final cameraController = CameraController( const CameraDescription( name: 'cam', @@ -579,46 +404,22 @@ void main() { ); await cameraController.initialize(); - when( - CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera), - ).thenAnswer((_) => Future.value(42.0)); - - final double maxZoomLevel = await cameraController.getMaxZoomLevel(); - expect(maxZoomLevel, 42.0); - }); - test( - 'getMinZoomLevel() throws $CameraException when uninitialized', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); + cameraController.value = cameraController.value.copyWith(isRecordingVideo: true); - expect( - cameraController.getMinZoomLevel, - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'Uninitialized CameraController', - ) - .having( - (CameraException error) => error.description, - 'description', - 'getMinZoomLevel() was called on an uninitialized CameraController.', - ), + expect( + cameraController.startVideoRecording(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'A video recording is already started.', + 'startVideoRecording was called when a recording is already started.', ), - ); - }, - ); + ), + ); + }); - test('getMinZoomLevel() throws $CameraException when disposed', () async { + test('getMaxZoomLevel() throws $CameraException when uninitialized', () async { final cameraController = CameraController( const CameraDescription( name: 'cam', @@ -628,18 +429,145 @@ void main() { ResolutionPreset.max, ); - await cameraController.initialize(); - await cameraController.dispose(); - expect( - cameraController.getMinZoomLevel, + cameraController.getMaxZoomLevel, throwsA( isA() .having( (CameraException error) => error.code, 'code', - 'Disposed CameraController', + 'Uninitialized CameraController', ) + .having( + (CameraException error) => error.description, + 'description', + 'getMaxZoomLevel() was called on an uninitialized CameraController.', + ), + ), + ); + }); + + test('getMaxZoomLevel() throws $CameraException when disposed', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + await cameraController.initialize(); + await cameraController.dispose(); + + expect( + cameraController.getMaxZoomLevel, + throwsA( + isA() + .having((CameraException error) => error.code, 'code', 'Disposed CameraController') + .having( + (CameraException error) => error.description, + 'description', + 'getMaxZoomLevel() was called on a disposed CameraController.', + ), + ), + ); + }); + + test('getMaxZoomLevel() throws $CameraException when a platform exception occured.', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + await cameraController.initialize(); + when( + CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera), + ).thenThrow(CameraException('TEST_ERROR', 'This is a test error messge')); + + expect( + cameraController.getMaxZoomLevel, + throwsA( + isA() + .having((CameraException error) => error.code, 'code', 'TEST_ERROR') + .having( + (CameraException error) => error.description, + 'description', + 'This is a test error messge', + ), + ), + ); + }); + + test('getMaxZoomLevel() returns max zoom level.', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + await cameraController.initialize(); + when( + CameraPlatform.instance.getMaxZoomLevel(mockInitializeCamera), + ).thenAnswer((_) => Future.value(42.0)); + + final double maxZoomLevel = await cameraController.getMaxZoomLevel(); + expect(maxZoomLevel, 42.0); + }); + + test('getMinZoomLevel() throws $CameraException when uninitialized', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + expect( + cameraController.getMinZoomLevel, + throwsA( + isA() + .having( + (CameraException error) => error.code, + 'code', + 'Uninitialized CameraController', + ) + .having( + (CameraException error) => error.description, + 'description', + 'getMinZoomLevel() was called on an uninitialized CameraController.', + ), + ), + ); + }); + + test('getMinZoomLevel() throws $CameraException when disposed', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + + await cameraController.initialize(); + await cameraController.dispose(); + + expect( + cameraController.getMinZoomLevel, + throwsA( + isA() + .having((CameraException error) => error.code, 'code', 'Disposed CameraController') .having( (CameraException error) => error.description, 'description', @@ -649,43 +577,34 @@ void main() { ); }); - test( - 'getMinZoomLevel() throws $CameraException when a platform exception occured.', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); + test('getMinZoomLevel() throws $CameraException when a platform exception occured.', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); - when( - CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera), - ).thenThrow( - CameraException('TEST_ERROR', 'This is a test error messge'), - ); + await cameraController.initialize(); + when( + CameraPlatform.instance.getMinZoomLevel(mockInitializeCamera), + ).thenThrow(CameraException('TEST_ERROR', 'This is a test error messge')); - expect( - cameraController.getMinZoomLevel, - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'TEST_ERROR', - ) - .having( - (CameraException error) => error.description, - 'description', - 'This is a test error messge', - ), - ), - ); - }, - ); + expect( + cameraController.getMinZoomLevel, + throwsA( + isA() + .having((CameraException error) => error.code, 'code', 'TEST_ERROR') + .having( + (CameraException error) => error.description, + 'description', + 'This is a test error messge', + ), + ), + ); + }); test('getMinZoomLevel() returns max zoom level.', () async { final cameraController = CameraController( @@ -751,11 +670,7 @@ void main() { () => cameraController.setZoomLevel(42.0), throwsA( isA() - .having( - (CameraException error) => error.code, - 'code', - 'Disposed CameraController', - ) + .having((CameraException error) => error.code, 'code', 'Disposed CameraController') .having( (CameraException error) => error.description, 'description', @@ -765,66 +680,52 @@ void main() { ); }); - test( - 'setZoomLevel() throws $CameraException when a platform exception occured.', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); + test('setZoomLevel() throws $CameraException when a platform exception occured.', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.initialize(); - when( - CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0), - ).thenThrow( - CameraException('TEST_ERROR', 'This is a test error messge'), - ); + await cameraController.initialize(); + when( + CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0), + ).thenThrow(CameraException('TEST_ERROR', 'This is a test error messge')); - expect( - () => cameraController.setZoomLevel(42), - throwsA( - isA() - .having( - (CameraException error) => error.code, - 'code', - 'TEST_ERROR', - ) - .having( - (CameraException error) => error.description, - 'description', - 'This is a test error messge', - ), - ), - ); - - reset(CameraPlatform.instance); - }, - ); + expect( + () => cameraController.setZoomLevel(42), + throwsA( + isA() + .having((CameraException error) => error.code, 'code', 'TEST_ERROR') + .having( + (CameraException error) => error.description, + 'description', + 'This is a test error messge', + ), + ), + ); - test( - 'setZoomLevel() completes and calls method channel with correct value.', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); + reset(CameraPlatform.instance); + }); - await cameraController.initialize(); - await cameraController.setZoomLevel(42.0); + test('setZoomLevel() completes and calls method channel with correct value.', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - verify( - CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0), - ).called(1); - }, - ); + await cameraController.initialize(); + await cameraController.setZoomLevel(42.0); + + verify(CameraPlatform.instance.setZoomLevel(mockInitializeCamera, 42.0)).called(1); + }); test('setFlashMode() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -840,50 +741,36 @@ void main() { await cameraController.setFlashMode(FlashMode.always); verify( - CameraPlatform.instance.setFlashMode( - cameraController.cameraId, - FlashMode.always, - ), + CameraPlatform.instance.setFlashMode(cameraController.cameraId, FlashMode.always), ).called(1); }); - test( - 'setFlashMode() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('setFlashMode() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - when( - CameraPlatform.instance.setFlashMode( - cameraController.cameraId, - FlashMode.always, - ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + when( + CameraPlatform.instance.setFlashMode(cameraController.cameraId, FlashMode.always), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.setFlashMode(FlashMode.always), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.setFlashMode(FlashMode.always), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('setExposureMode() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -899,50 +786,36 @@ void main() { await cameraController.setExposureMode(ExposureMode.auto); verify( - CameraPlatform.instance.setExposureMode( - cameraController.cameraId, - ExposureMode.auto, - ), + CameraPlatform.instance.setExposureMode(cameraController.cameraId, ExposureMode.auto), ).called(1); }); - test( - 'setExposureMode() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('setExposureMode() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - when( - CameraPlatform.instance.setExposureMode( - cameraController.cameraId, - ExposureMode.auto, - ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + when( + CameraPlatform.instance.setExposureMode(cameraController.cameraId, ExposureMode.auto), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.setExposureMode(ExposureMode.auto), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.setExposureMode(ExposureMode.auto), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('setExposurePoint() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -965,43 +838,35 @@ void main() { ).called(1); }); - test( - 'setExposurePoint() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('setExposurePoint() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - when( - CameraPlatform.instance.setExposurePoint( - cameraController.cameraId, - const Point(0.5, 0.5), - ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + when( + CameraPlatform.instance.setExposurePoint( + cameraController.cameraId, + const Point(0.5, 0.5), + ), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.setExposurePoint(const Offset(0.5, 0.5)), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.setExposurePoint(const Offset(0.5, 0.5)), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('getMinExposureOffset() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -1020,44 +885,35 @@ void main() { await cameraController.getMinExposureOffset(); - verify( - CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), - ).called(1); + verify(CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId)).called(1); }); - test( - 'getMinExposureOffset() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('getMinExposureOffset() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - when( - CameraPlatform.instance.getMinExposureOffset( - cameraController.cameraId, - ), - ).thenThrow( - CameraException('TEST_ERROR', 'This is a test error message'), - ); + when( + CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), + ).thenThrow(CameraException('TEST_ERROR', 'This is a test error message')); - expect( - cameraController.getMinExposureOffset(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.getMinExposureOffset(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('getMaxExposureOffset() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -1076,44 +932,35 @@ void main() { await cameraController.getMaxExposureOffset(); - verify( - CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), - ).called(1); + verify(CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId)).called(1); }); - test( - 'getMaxExposureOffset() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('getMaxExposureOffset() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - when( - CameraPlatform.instance.getMaxExposureOffset( - cameraController.cameraId, - ), - ).thenThrow( - CameraException('TEST_ERROR', 'This is a test error message'), - ); + when( + CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), + ).thenThrow(CameraException('TEST_ERROR', 'This is a test error message')); - expect( - cameraController.getMaxExposureOffset(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.getMaxExposureOffset(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('getExposureOffsetStepSize() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -1127,53 +974,42 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getExposureOffsetStepSize( - cameraController.cameraId, - ), + CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId), ).thenAnswer((_) => Future.value(0.0)); await cameraController.getExposureOffsetStepSize(); verify( - CameraPlatform.instance.getExposureOffsetStepSize( - cameraController.cameraId, - ), + CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId), ).called(1); }); - test( - 'getExposureOffsetStepSize() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('getExposureOffsetStepSize() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - when( - CameraPlatform.instance.getExposureOffsetStepSize( - cameraController.cameraId, - ), - ).thenThrow( - CameraException('TEST_ERROR', 'This is a test error message'), - ); + when( + CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId), + ).thenThrow(CameraException('TEST_ERROR', 'This is a test error message')); - expect( - cameraController.getExposureOffsetStepSize(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.getExposureOffsetStepSize(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('setExposureOffset() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -1192,167 +1028,110 @@ void main() { CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), ).thenAnswer((_) async => 2.0); when( - CameraPlatform.instance.getExposureOffsetStepSize( - cameraController.cameraId, - ), + CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId), ).thenAnswer((_) async => 1.0); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 1.0, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 1.0), ).thenAnswer((_) async => 1.0); await cameraController.setExposureOffset(1.0); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 1.0, - ), - ).called(1); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 1.0)).called(1); }); - test( - 'setExposureOffset() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - when( - CameraPlatform.instance.getMinExposureOffset( - cameraController.cameraId, - ), - ).thenAnswer((_) async => -1.0); - when( - CameraPlatform.instance.getMaxExposureOffset( - cameraController.cameraId, - ), - ).thenAnswer((_) async => 2.0); - when( - CameraPlatform.instance.getExposureOffsetStepSize( - cameraController.cameraId, - ), - ).thenAnswer((_) async => 1.0); - when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 1.0, - ), - ).thenThrow( - CameraException('TEST_ERROR', 'This is a test error message'), - ); + test('setExposureOffset() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => -1.0); + when( + CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => 2.0); + when( + CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId), + ).thenAnswer((_) async => 1.0); + when( + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 1.0), + ).thenThrow(CameraException('TEST_ERROR', 'This is a test error message')); - expect( - cameraController.setExposureOffset(1.0), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.setExposureOffset(1.0), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); - test( - 'setExposureOffset() throws $CameraException when offset is out of bounds', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - when( - CameraPlatform.instance.getMinExposureOffset( - cameraController.cameraId, - ), - ).thenAnswer((_) async => -1.0); - when( - CameraPlatform.instance.getMaxExposureOffset( - cameraController.cameraId, - ), - ).thenAnswer((_) async => 2.0); - when( - CameraPlatform.instance.getExposureOffsetStepSize( - cameraController.cameraId, - ), - ).thenAnswer((_) async => 1.0); - when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.0, - ), - ).thenAnswer((_) async => 0.0); - when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - -1.0, - ), - ).thenAnswer((_) async => 0.0); - when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 2.0, - ), - ).thenAnswer((_) async => 0.0); + test('setExposureOffset() throws $CameraException when offset is out of bounds', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.getMinExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => -1.0); + when( + CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), + ).thenAnswer((_) async => 2.0); + when( + CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId), + ).thenAnswer((_) async => 1.0); + when( + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.0), + ).thenAnswer((_) async => 0.0); + when( + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -1.0), + ).thenAnswer((_) async => 0.0); + when( + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 2.0), + ).thenAnswer((_) async => 0.0); - expect( - cameraController.setExposureOffset(3.0), - throwsA( - isA().having( - (CameraException error) => error.description, - 'exposureOffsetOutOfBounds', - 'The provided exposure offset was outside the supported range for this device.', - ), + expect( + cameraController.setExposureOffset(3.0), + throwsA( + isA().having( + (CameraException error) => error.description, + 'exposureOffsetOutOfBounds', + 'The provided exposure offset was outside the supported range for this device.', ), - ); - expect( - cameraController.setExposureOffset(-2.0), - throwsA( - isA().having( - (CameraException error) => error.description, - 'exposureOffsetOutOfBounds', - 'The provided exposure offset was outside the supported range for this device.', - ), + ), + ); + expect( + cameraController.setExposureOffset(-2.0), + throwsA( + isA().having( + (CameraException error) => error.description, + 'exposureOffsetOutOfBounds', + 'The provided exposure offset was outside the supported range for this device.', ), - ); + ), + ); - await cameraController.setExposureOffset(0.0); - await cameraController.setExposureOffset(-1.0); - await cameraController.setExposureOffset(2.0); + await cameraController.setExposureOffset(0.0); + await cameraController.setExposureOffset(-1.0); + await cameraController.setExposureOffset(2.0); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.0, - ), - ).called(1); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - -1.0, - ), - ).called(1); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 2.0, - ), - ).called(1); - }, - ); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.0)).called(1); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -1.0)).called(1); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 2.0)).called(1); + }); test('setExposureOffset() rounds offset to nearest step', () async { final cameraController = CameraController( @@ -1371,52 +1150,29 @@ void main() { CameraPlatform.instance.getMaxExposureOffset(cameraController.cameraId), ).thenAnswer((_) async => 1.2); when( - CameraPlatform.instance.getExposureOffsetStepSize( - cameraController.cameraId, - ), + CameraPlatform.instance.getExposureOffsetStepSize(cameraController.cameraId), ).thenAnswer((_) async => 0.4); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - -1.2, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -1.2), ).thenAnswer((_) async => -1.2); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - -0.8, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -0.8), ).thenAnswer((_) async => -0.8); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - -0.4, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -0.4), ).thenAnswer((_) async => -0.4); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.0, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.0), ).thenAnswer((_) async => 0.0); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.4, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.4), ).thenAnswer((_) async => 0.4); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.8, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.8), ).thenAnswer((_) async => 0.8); when( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 1.2, - ), + CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 1.2), ).thenAnswer((_) async => 1.2); await cameraController.setExposureOffset(1.2); @@ -1436,36 +1192,11 @@ void main() { await cameraController.setExposureOffset(-0.6); await cameraController.setExposureOffset(-0.7); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.8, - ), - ).called(2); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - -0.8, - ), - ).called(2); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.0, - ), - ).called(2); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - 0.4, - ), - ).called(4); - verify( - CameraPlatform.instance.setExposureOffset( - cameraController.cameraId, - -0.4, - ), - ).called(4); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.8)).called(2); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -0.8)).called(2); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.0)).called(2); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, 0.4)).called(4); + verify(CameraPlatform.instance.setExposureOffset(cameraController.cameraId, -0.4)).called(4); }); test( @@ -1483,9 +1214,7 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer((_) async => []); // act @@ -1512,12 +1241,8 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); // act final Iterable modes = await cameraController @@ -1528,81 +1253,71 @@ void main() { }, ); - test( - 'getSupportedVideoStabilizationModes() returns off and level1', - () async { - // arrange - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - - await cameraController.initialize(); - when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [ - VideoStabilizationMode.off, - VideoStabilizationMode.level1, - ], - ); - - // act - final Iterable modes = await cameraController - .getSupportedVideoStabilizationModes(); + test('getSupportedVideoStabilizationModes() returns off and level1', () async { + // arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - // assert - expect(modes, [ + await cameraController.initialize(); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer( + (_) async => [ VideoStabilizationMode.off, VideoStabilizationMode.level1, - ]); - }, - ); + ], + ); - test( - 'getSupportedVideoStabilizationModes() returns off, level1 and level2', - () async { - // arrange - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); + // act + final Iterable modes = await cameraController + .getSupportedVideoStabilizationModes(); - await cameraController.initialize(); - when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [ - VideoStabilizationMode.off, - VideoStabilizationMode.level1, - VideoStabilizationMode.level2, - ], - ); + // assert + expect(modes, [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ]); + }); - // act - final Iterable modes = await cameraController - .getSupportedVideoStabilizationModes(); + test('getSupportedVideoStabilizationModes() returns off, level1 and level2', () async { + // arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - // assert - expect(modes, [ + await cameraController.initialize(); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer( + (_) async => [ VideoStabilizationMode.off, VideoStabilizationMode.level1, VideoStabilizationMode.level2, - ]); - }, - ); + ], + ); + + // act + final Iterable modes = await cameraController + .getSupportedVideoStabilizationModes(); + + // assert + expect(modes, [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + ]); + }); test('getSupportedVideoStabilizationModes() returns all modes', () async { // arrange @@ -1617,9 +1332,7 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -1642,56 +1355,44 @@ void main() { ]); }); - test( - 'setVideoStabilizationMode() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); + test('setVideoStabilizationMode() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); - when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [ - VideoStabilizationMode.off, - VideoStabilizationMode.level1, - ], - ); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); - when( - CameraPlatform.instance.setVideoStabilizationMode( - cameraController.cameraId, - VideoStabilizationMode.level1, - ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level1, - ), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test( 'setVideoStabilizationMode() with fallback never calls CameraPlatform.instance.setVideoStabilizationMode when no supported mode is available', @@ -1712,26 +1413,16 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer((_) async => []); clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.off, - ); - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level1, - ); - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level2, - ); - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level3, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3); // assert verifyNever( @@ -1782,19 +1473,13 @@ void main() { ), ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.off, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off); // assert verify( @@ -1847,19 +1532,13 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level1, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1); // assert verify( @@ -1911,19 +1590,13 @@ void main() { ), ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level2, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2); // assert verify( @@ -1975,19 +1648,13 @@ void main() { ), ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level3, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3); // assert verify( @@ -2039,9 +1706,7 @@ void main() { ), ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2052,9 +1717,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.off, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off); // assert verify( @@ -2107,9 +1770,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2119,9 +1780,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level1, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1); // assert verify( @@ -2174,9 +1833,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2187,9 +1844,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level2, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2); // assert verify( @@ -2242,9 +1897,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2255,9 +1908,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level3, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3); // assert verify( @@ -2310,9 +1961,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2325,9 +1974,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.off, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.off); // assert verify( @@ -2379,9 +2026,7 @@ void main() { ), ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2394,9 +2039,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level1, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level1); // assert verify( @@ -2449,9 +2092,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2464,9 +2105,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level2, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level2); // assert verify( @@ -2519,9 +2158,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -2534,9 +2171,7 @@ void main() { clearInteractions(CameraPlatform.instance); // act - await cameraController.setVideoStabilizationMode( - VideoStabilizationMode.level3, - ); + await cameraController.setVideoStabilizationMode(VideoStabilizationMode.level3); // assert verify( @@ -2582,9 +2217,7 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer((_) async => []); clearInteractions(CameraPlatform.instance); @@ -2638,9 +2271,7 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer((_) async => []); clearInteractions(CameraPlatform.instance); @@ -2652,13 +2283,7 @@ void main() { VideoStabilizationMode.level1, allowFallback: false, ), - throwsA( - isA().having( - (ArgumentError error) => error.name, - 'name', - 'mode', - ), - ), + throwsA(isA().having((ArgumentError error) => error.name, 'name', 'mode')), ); // assert @@ -2704,9 +2329,7 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer((_) async => []); clearInteractions(CameraPlatform.instance); @@ -2718,13 +2341,7 @@ void main() { VideoStabilizationMode.level2, allowFallback: false, ), - throwsA( - isA().having( - (ArgumentError error) => error.name, - 'name', - 'mode', - ), - ), + throwsA(isA().having((ArgumentError error) => error.name, 'name', 'mode')), ); // assert @@ -2770,9 +2387,7 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer((_) async => []); clearInteractions(CameraPlatform.instance); @@ -2784,13 +2399,7 @@ void main() { VideoStabilizationMode.level3, allowFallback: false, ), - throwsA( - isA().having( - (ArgumentError error) => error.name, - 'name', - 'mode', - ), - ), + throwsA(isA().having((ArgumentError error) => error.name, 'name', 'mode')), ); // assert @@ -2843,12 +2452,8 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); @@ -2902,12 +2507,8 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); @@ -2918,13 +2519,7 @@ void main() { VideoStabilizationMode.level1, allowFallback: false, ), - throwsA( - isA().having( - (ArgumentError error) => error.name, - 'name', - 'mode', - ), - ), + throwsA(isA().having((ArgumentError error) => error.name, 'name', 'mode')), ); // assert @@ -2970,12 +2565,8 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); @@ -2986,13 +2577,7 @@ void main() { VideoStabilizationMode.level2, allowFallback: false, ), - throwsA( - isA().having( - (ArgumentError error) => error.name, - 'name', - 'mode', - ), - ), + throwsA(isA().having((ArgumentError error) => error.name, 'name', 'mode')), ); // assert @@ -3038,12 +2623,8 @@ void main() { await cameraController.initialize(); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), - ).thenAnswer( - (_) async => [VideoStabilizationMode.off], - ); + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), + ).thenAnswer((_) async => [VideoStabilizationMode.off]); clearInteractions(CameraPlatform.instance); @@ -3054,13 +2635,7 @@ void main() { VideoStabilizationMode.level3, allowFallback: false, ), - throwsA( - isA().having( - (ArgumentError error) => error.name, - 'name', - 'mode', - ), - ), + throwsA(isA().having((ArgumentError error) => error.name, 'name', 'mode')), ); // assert @@ -3113,9 +2688,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -3182,9 +2755,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -3251,9 +2822,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -3270,13 +2839,7 @@ void main() { VideoStabilizationMode.level2, allowFallback: false, ), - throwsA( - isA().having( - (ArgumentError error) => error.name, - 'name', - 'mode', - ), - ), + throwsA(isA().having((ArgumentError error) => error.name, 'name', 'mode')), ); // assert @@ -3329,9 +2892,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -3400,9 +2961,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -3478,9 +3037,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -3549,9 +3106,7 @@ void main() { ).thenAnswer((_) => Future(() {})); when( - CameraPlatform.instance.getSupportedVideoStabilizationModes( - mockInitializeCamera, - ), + CameraPlatform.instance.getSupportedVideoStabilizationModes(mockInitializeCamera), ).thenAnswer( (_) async => [ VideoStabilizationMode.off, @@ -3598,7 +3153,46 @@ void main() { }, ); - test('pausePreview() calls $CameraPlatform', () async { + test('pausePreview() calls $CameraPlatform', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + deviceOrientation: DeviceOrientation.portraitUp, + ); + + await cameraController.pausePreview(); + + verify(CameraPlatform.instance.pausePreview(cameraController.cameraId)).called(1); + expect(cameraController.value.isPreviewPaused, equals(true)); + expect(cameraController.value.previewPauseOrientation, DeviceOrientation.portraitUp); + }); + + test('pausePreview() does not call $CameraPlatform when already paused', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith(isPreviewPaused: true); + + await cameraController.pausePreview(); + + verifyNever(CameraPlatform.instance.pausePreview(cameraController.cameraId)); + expect(cameraController.value.isPreviewPaused, equals(true)); + }); + + test('pausePreview() sets previewPauseOrientation according to locked orientation', () async { final cameraController = CameraController( const CameraDescription( name: 'cam', @@ -3609,112 +3203,47 @@ void main() { ); await cameraController.initialize(); cameraController.value = cameraController.value.copyWith( + isPreviewPaused: false, deviceOrientation: DeviceOrientation.portraitUp, + lockedCaptureOrientation: const Optional.of( + DeviceOrientation.landscapeRight, + ), ); await cameraController.pausePreview(); - verify( - CameraPlatform.instance.pausePreview(cameraController.cameraId), - ).called(1); - expect(cameraController.value.isPreviewPaused, equals(true)); + expect(cameraController.value.deviceOrientation, equals(DeviceOrientation.portraitUp)); expect( cameraController.value.previewPauseOrientation, - DeviceOrientation.portraitUp, + equals(DeviceOrientation.landscapeRight), ); }); - test( - 'pausePreview() does not call $CameraPlatform when already paused', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: true, - ); - - await cameraController.pausePreview(); - - verifyNever( - CameraPlatform.instance.pausePreview(cameraController.cameraId), - ); - expect(cameraController.value.isPreviewPaused, equals(true)); - }, - ); - - test( - 'pausePreview() sets previewPauseOrientation according to locked orientation', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: false, - deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: const Optional.of( - DeviceOrientation.landscapeRight, - ), - ); - - await cameraController.pausePreview(); - - expect( - cameraController.value.deviceOrientation, - equals(DeviceOrientation.portraitUp), - ); - expect( - cameraController.value.previewPauseOrientation, - equals(DeviceOrientation.landscapeRight), - ); - }, - ); - - test( - 'pausePreview() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - when( - CameraPlatform.instance.pausePreview(cameraController.cameraId), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + test('pausePreview() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.pausePreview(cameraController.cameraId), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.pausePreview(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.pausePreview(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('resumePreview() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -3726,79 +3255,58 @@ void main() { ResolutionPreset.max, ); await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: true, - ); + cameraController.value = cameraController.value.copyWith(isPreviewPaused: true); await cameraController.resumePreview(); - verify( - CameraPlatform.instance.resumePreview(cameraController.cameraId), - ).called(1); + verify(CameraPlatform.instance.resumePreview(cameraController.cameraId)).called(1); expect(cameraController.value.isPreviewPaused, equals(false)); }); - test( - 'resumePreview() does not call $CameraPlatform when not paused', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: false, - ); + test('resumePreview() does not call $CameraPlatform when not paused', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith(isPreviewPaused: false); - await cameraController.resumePreview(); + await cameraController.resumePreview(); - verifyNever( - CameraPlatform.instance.resumePreview(cameraController.cameraId), - ); - expect(cameraController.value.isPreviewPaused, equals(false)); - }, - ); + verifyNever(CameraPlatform.instance.resumePreview(cameraController.cameraId)); + expect(cameraController.value.isPreviewPaused, equals(false)); + }); - test( - 'resumePreview() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: true, - ); - when( - CameraPlatform.instance.resumePreview(cameraController.cameraId), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + test('resumePreview() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith(isPreviewPaused: true); + when( + CameraPlatform.instance.resumePreview(cameraController.cameraId), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.resumePreview(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.resumePreview(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('lockCaptureOrientation() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -3812,13 +3320,8 @@ void main() { await cameraController.initialize(); await cameraController.lockCaptureOrientation(); - expect( - cameraController.value.lockedCaptureOrientation, - equals(DeviceOrientation.portraitUp), - ); - await cameraController.lockCaptureOrientation( - DeviceOrientation.landscapeRight, - ); + expect(cameraController.value.lockedCaptureOrientation, equals(DeviceOrientation.portraitUp)); + await cameraController.lockCaptureOrientation(DeviceOrientation.landscapeRight); expect( cameraController.value.lockedCaptureOrientation, equals(DeviceOrientation.landscapeRight), @@ -3838,42 +3341,34 @@ void main() { ).called(1); }); - test( - 'lockCaptureOrientation() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - when( - CameraPlatform.instance.lockCaptureOrientation( - cameraController.cameraId, - DeviceOrientation.portraitUp, - ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + test('lockCaptureOrientation() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.lockCaptureOrientation( + cameraController.cameraId, + DeviceOrientation.portraitUp, + ), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('unlockCaptureOrientation() calls $CameraPlatform', () async { final cameraController = CameraController( @@ -3889,48 +3384,34 @@ void main() { await cameraController.unlockCaptureOrientation(); expect(cameraController.value.lockedCaptureOrientation, equals(null)); - verify( - CameraPlatform.instance.unlockCaptureOrientation( - cameraController.cameraId, - ), - ).called(1); + verify(CameraPlatform.instance.unlockCaptureOrientation(cameraController.cameraId)).called(1); }); - test( - 'unlockCaptureOrientation() throws $CameraException on $PlatformException', - () async { - final cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - when( - CameraPlatform.instance.unlockCaptureOrientation( - cameraController.cameraId, - ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', - ), - ); + test('unlockCaptureOrientation() throws $CameraException on $PlatformException', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.unlockCaptureOrientation(cameraController.cameraId), + ).thenThrow(PlatformException(code: 'TEST_ERROR', message: 'This is a test error message')); - expect( - cameraController.unlockCaptureOrientation(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + expect( + cameraController.unlockCaptureOrientation(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', ), - ); - }, - ); + ), + ); + }); test('error from onCameraError is received', () async { final cameraController = CameraController( @@ -3944,17 +3425,12 @@ void main() { await cameraController.initialize(); expect(cameraController.value.hasError, isTrue); - expect( - cameraController.value.errorDescription, - mockOnCameraErrorEvent.description, - ); + expect(cameraController.value.errorDescription, mockOnCameraErrorEvent.description); }); }); } -class MockCameraPlatform extends Mock - with MockPlatformInterfaceMixin - implements CameraPlatform { +class MockCameraPlatform extends Mock with MockPlatformInterfaceMixin implements CameraPlatform { @override Future initializeCamera( int? cameraId, { @@ -4005,9 +3481,7 @@ class MockCameraPlatform extends Mock @override Stream onDeviceOrientationChanged() => - Stream.value( - mockOnDeviceOrientationChangedEvent, - ); + Stream.value(mockOnDeviceOrientationChangedEvent); @override Future takePicture(int cameraId) => mockPlatformException @@ -4033,135 +3507,90 @@ class MockCameraPlatform extends Mock } @override - Future lockCaptureOrientation( - int? cameraId, - DeviceOrientation? orientation, - ) async => super.noSuchMethod( - Invocation.method(#lockCaptureOrientation, [ - cameraId, - orientation, - ]), - ); + Future lockCaptureOrientation(int? cameraId, DeviceOrientation? orientation) async => super + .noSuchMethod(Invocation.method(#lockCaptureOrientation, [cameraId, orientation])); @override Future unlockCaptureOrientation(int? cameraId) async => - super.noSuchMethod( - Invocation.method(#unlockCaptureOrientation, [cameraId]), - ); + super.noSuchMethod(Invocation.method(#unlockCaptureOrientation, [cameraId])); @override Future pausePreview(int? cameraId) async => super.noSuchMethod(Invocation.method(#pausePreview, [cameraId])); @override - Future resumePreview(int? cameraId) async => super.noSuchMethod( - Invocation.method(#resumePreview, [cameraId]), - ); + Future resumePreview(int? cameraId) async => + super.noSuchMethod(Invocation.method(#resumePreview, [cameraId])); @override - Future getMaxZoomLevel(int? cameraId) async => - super.noSuchMethod( - Invocation.method(#getMaxZoomLevel, [cameraId]), - returnValue: Future.value(1.0), - ) - as Future; + Future getMaxZoomLevel(int? cameraId) async => super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, [cameraId]), + returnValue: Future.value(1.0), + ) as Future; @override - Future getMinZoomLevel(int? cameraId) async => - super.noSuchMethod( - Invocation.method(#getMinZoomLevel, [cameraId]), - returnValue: Future.value(0.0), - ) - as Future; + Future getMinZoomLevel(int? cameraId) async => super.noSuchMethod( + Invocation.method(#getMinZoomLevel, [cameraId]), + returnValue: Future.value(0.0), + ) as Future; @override Future setZoomLevel(int? cameraId, double? zoom) async => - super.noSuchMethod( - Invocation.method(#setZoomLevel, [cameraId, zoom]), - ); + super.noSuchMethod(Invocation.method(#setZoomLevel, [cameraId, zoom])); @override Future setFlashMode(int? cameraId, FlashMode? mode) async => - super.noSuchMethod( - Invocation.method(#setFlashMode, [cameraId, mode]), - ); + super.noSuchMethod(Invocation.method(#setFlashMode, [cameraId, mode])); @override Future setExposureMode(int? cameraId, ExposureMode? mode) async => - super.noSuchMethod( - Invocation.method(#setExposureMode, [cameraId, mode]), - ); + super.noSuchMethod(Invocation.method(#setExposureMode, [cameraId, mode])); @override Future setExposurePoint(int? cameraId, Point? point) async => - super.noSuchMethod( - Invocation.method(#setExposurePoint, [cameraId, point]), - ); + super.noSuchMethod(Invocation.method(#setExposurePoint, [cameraId, point])); @override - Future getMinExposureOffset(int? cameraId) async => - super.noSuchMethod( - Invocation.method(#getMinExposureOffset, [cameraId]), - returnValue: Future.value(0.0), - ) - as Future; + Future getMinExposureOffset(int? cameraId) async => super.noSuchMethod( + Invocation.method(#getMinExposureOffset, [cameraId]), + returnValue: Future.value(0.0), + ) as Future; @override - Future getMaxExposureOffset(int? cameraId) async => - super.noSuchMethod( - Invocation.method(#getMaxExposureOffset, [cameraId]), - returnValue: Future.value(1.0), - ) - as Future; + Future getMaxExposureOffset(int? cameraId) async => super.noSuchMethod( + Invocation.method(#getMaxExposureOffset, [cameraId]), + returnValue: Future.value(1.0), + ) as Future; @override - Future getExposureOffsetStepSize(int? cameraId) async => - super.noSuchMethod( - Invocation.method(#getExposureOffsetStepSize, [cameraId]), - returnValue: Future.value(1.0), - ) - as Future; + Future getExposureOffsetStepSize(int? cameraId) async => super.noSuchMethod( + Invocation.method(#getExposureOffsetStepSize, [cameraId]), + returnValue: Future.value(1.0), + ) as Future; @override - Future setExposureOffset(int? cameraId, double? offset) async => - super.noSuchMethod( - Invocation.method(#setExposureOffset, [cameraId, offset]), - returnValue: Future.value(1.0), - ) - as Future; + Future setExposureOffset(int? cameraId, double? offset) async => super.noSuchMethod( + Invocation.method(#setExposureOffset, [cameraId, offset]), + returnValue: Future.value(1.0), + ) as Future; @override - Future> getSupportedVideoStabilizationModes( - int cameraId, - ) { + Future> getSupportedVideoStabilizationModes(int cameraId) { return super.noSuchMethod( - Invocation.method(#getSupportedVideoStabilizationModes, [ - cameraId, - ]), - returnValue: Future>.value( - [], - ), - ) - as Future>; + Invocation.method(#getSupportedVideoStabilizationModes, [cameraId]), + returnValue: Future>.value([]), + ) as Future>; } @override - Future setVideoStabilizationMode( - int cameraId, - VideoStabilizationMode mode, - ) async => super.noSuchMethod( - Invocation.method(#setVideoStabilizationMode, [cameraId, mode]), - ); + Future setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) async => + super.noSuchMethod(Invocation.method(#setVideoStabilizationMode, [cameraId, mode])); } class MockCameraDescription extends CameraDescription { /// Creates a new camera description with the given properties. const MockCameraDescription() - : super( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ); + : super(name: 'Test', lensDirection: CameraLensDirection.back, sensorOrientation: 0); @override CameraLensDirection get lensDirection => CameraLensDirection.back; diff --git a/packages/camera/camera/test/camera_value_test.dart b/packages/camera/camera/test/camera_value_test.dart index 3d52cf809583..5ddcb6ebfd5c 100644 --- a/packages/camera/camera/test/camera_value_test.dart +++ b/packages/camera/camera/test/camera_value_test.dart @@ -43,10 +43,7 @@ void main() { expect(cameraValue.exposureMode, ExposureMode.auto); expect(cameraValue.exposurePointSupported, true); expect(cameraValue.deviceOrientation, DeviceOrientation.portraitUp); - expect( - cameraValue.lockedCaptureOrientation, - DeviceOrientation.portraitUp, - ); + expect(cameraValue.lockedCaptureOrientation, DeviceOrientation.portraitUp); expect(cameraValue.recordingOrientation, DeviceOrientation.portraitUp); expect(cameraValue.isPreviewPaused, false); expect(cameraValue.previewPauseOrientation, DeviceOrientation.portraitUp); @@ -54,9 +51,7 @@ void main() { }); test('Can be created as uninitialized', () { - const cameraValue = CameraValue.uninitialized( - FakeController.fakeDescription, - ); + const cameraValue = CameraValue.uninitialized(FakeController.fakeDescription); expect(cameraValue, isA()); expect(cameraValue.isInitialized, isFalse); diff --git a/packages/camera/camera_android/example/integration_test/camera_test.dart b/packages/camera/camera_android/example/integration_test/camera_test.dart index 01621c32682d..0fc7d5ca8ad8 100644 --- a/packages/camera/camera_android/example/integration_test/camera_test.dart +++ b/packages/camera/camera_android/example/integration_test/camera_test.dart @@ -69,24 +69,19 @@ void main() { // Verify image dimensions are as expected expect(video, isNotNull); - return assertExpectedDimensions( - expectedSize, - Size(video.height, video.width), - ); + return assertExpectedDimensions(expectedSize, Size(video.height, video.width)); } testWidgets( 'Capture specific video resolutions', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final cameraDescription in cameras) { var previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { + for (final MapEntry preset in presetExpectedSizes.entries) { final controller = CameraController( cameraDescription, mediaSettings: MediaSettings(resolutionPreset: preset.key), @@ -111,8 +106,7 @@ void main() { ); testWidgets('Pause and resume video recording', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } @@ -146,8 +140,7 @@ void main() { sleep(const Duration(milliseconds: 500)); final XFile file = await controller.stopVideoRecording(); - final int recordingTime = - DateTime.now().millisecondsSinceEpoch - recordingStart; + final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; final videoFile = File(file.path); final videoController = VideoPlayerController.file(videoFile); @@ -159,8 +152,7 @@ void main() { }); testWidgets('Set description while recording', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.length < 2) { return; } @@ -196,8 +188,7 @@ void main() { }); testWidgets('Set description', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.length < 2) { return; } @@ -211,8 +202,7 @@ void main() { }); testWidgets('image streaming', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } @@ -241,8 +231,7 @@ void main() { }); testWidgets('recording with image stream', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } @@ -279,14 +268,12 @@ void main() { group('Camera settings', () { Future getCamera() async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); expect(cameras.isNotEmpty, equals(true)); // Prefer back camera, as it allows more customizations. final CameraDescription cameraDescription = cameras.firstWhere( - (CameraDescription description) => - description.lensDirection == CameraLensDirection.back, + (CameraDescription description) => description.lensDirection == CameraLensDirection.back, orElse: () => cameras.first, ); return cameraDescription; @@ -315,10 +302,7 @@ void main() { for (final fps in [10, 30]) { final controller = CameraController( cameraDescription, - mediaSettings: MediaSettings( - resolutionPreset: ResolutionPreset.medium, - fps: fps, - ), + mediaSettings: MediaSettings(resolutionPreset: ResolutionPreset.medium, fps: fps), ); await startRecording(controller); diff --git a/packages/camera/camera_android/example/lib/camera_controller.dart b/packages/camera/camera_android/example/lib/camera_controller.dart index 33cafe13e447..b3b96ffb7877 100644 --- a/packages/camera/camera_android/example/lib/camera_controller.dart +++ b/packages/camera/camera_android/example/lib/camera_controller.dart @@ -173,9 +173,7 @@ class CameraController extends ValueNotifier { /// Creates a new camera controller in an uninitialized state. CameraController( CameraDescription cameraDescription, { - MediaSettings mediaSettings = const MediaSettings( - resolutionPreset: ResolutionPreset.medium, - ), + MediaSettings mediaSettings = const MediaSettings(resolutionPreset: ResolutionPreset.medium), this.imageFormatGroup, }) : _mediaSettings = mediaSettings, super(CameraValue.uninitialized(cameraDescription)); @@ -196,8 +194,7 @@ class CameraController extends ValueNotifier { bool _isDisposed = false; StreamSubscription? _imageStreamSubscription; FutureOr? _initCalled; - StreamSubscription? - _deviceOrientationSubscription; + StreamSubscription? _deviceOrientationSubscription; /// The camera identifier with which the controller is associated. int get cameraId => _cameraId; @@ -208,16 +205,13 @@ class CameraController extends ValueNotifier { Future _initializeWithDescription(CameraDescription description) async { final initializeCompleter = Completer(); - _deviceOrientationSubscription = CameraPlatform.instance - .onDeviceOrientationChanged() - .listen((DeviceOrientationChangedEvent event) { - value = value.copyWith(deviceOrientation: event.orientation); - }); + _deviceOrientationSubscription = CameraPlatform.instance.onDeviceOrientationChanged().listen(( + DeviceOrientationChangedEvent event, + ) { + value = value.copyWith(deviceOrientation: event.orientation); + }); - _cameraId = await CameraPlatform.instance.createCameraWithSettings( - description, - _mediaSettings, - ); + _cameraId = await CameraPlatform.instance.createCameraWithSettings(description, _mediaSettings); unawaited( CameraPlatform.instance.onCameraInitialized(_cameraId).first.then(( @@ -236,8 +230,7 @@ class CameraController extends ValueNotifier { isInitialized: true, description: description, previewSize: await initializeCompleter.future.then( - (CameraInitializedEvent event) => - Size(event.previewWidth, event.previewHeight), + (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight), ), exposureMode: await initializeCompleter.future.then( (CameraInitializedEvent event) => event.exposureMode, @@ -302,14 +295,12 @@ class CameraController extends ValueNotifier { } /// Start streaming images from platform camera. - Future startImageStream( - void Function(CameraImageData image) onAvailable, - ) async { - _imageStreamSubscription = CameraPlatform.instance - .onStreamedFrameAvailable(_cameraId) - .listen((CameraImageData imageData) { - onAvailable(imageData); - }); + Future startImageStream(void Function(CameraImageData image) onAvailable) async { + _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen(( + CameraImageData imageData, + ) { + onAvailable(imageData); + }); value = value.copyWith(isStreamingImages: true); } @@ -324,9 +315,7 @@ class CameraController extends ValueNotifier { /// /// The video is returned as a [XFile] after calling [stopVideoRecording]. /// Throws a [CameraException] if the capture fails. - Future startVideoRecording({ - void Function(CameraImageData image)? streamCallback, - }) async { + Future startVideoRecording({void Function(CameraImageData image)? streamCallback}) async { await CameraPlatform.instance.startVideoCapturing( VideoCaptureOptions(_cameraId, streamCallback: streamCallback), ); @@ -348,9 +337,7 @@ class CameraController extends ValueNotifier { await stopImageStream(); } - final XFile file = await CameraPlatform.instance.stopVideoRecording( - _cameraId, - ); + final XFile file = await CameraPlatform.instance.stopVideoRecording(_cameraId); value = value.copyWith( isRecordingVideo: false, isRecordingPaused: false, @@ -397,8 +384,7 @@ class CameraController extends ValueNotifier { ]); // Round to the closest step if needed - final double stepSize = await CameraPlatform.instance - .getExposureOffsetStepSize(_cameraId); + final double stepSize = await CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); if (stepSize > 0) { final double inv = 1.0 / stepSize; double roundedOffset = (offset * inv).roundToDouble() / inv; @@ -417,23 +403,16 @@ class CameraController extends ValueNotifier { /// /// If [orientation] is omitted, the current device orientation is used. Future lockCaptureOrientation() async { - await CameraPlatform.instance.lockCaptureOrientation( - _cameraId, - value.deviceOrientation, - ); + await CameraPlatform.instance.lockCaptureOrientation(_cameraId, value.deviceOrientation); value = value.copyWith( - lockedCaptureOrientation: Optional.of( - value.deviceOrientation, - ), + lockedCaptureOrientation: Optional.of(value.deviceOrientation), ); } /// Unlocks the capture orientation. Future unlockCaptureOrientation() async { await CameraPlatform.instance.unlockCaptureOrientation(_cameraId); - value = value.copyWith( - lockedCaptureOrientation: const Optional.absent(), - ); + value = value.copyWith(lockedCaptureOrientation: const Optional.absent()); } /// Sets the focus mode for taking pictures. @@ -535,9 +514,7 @@ class Optional extends IterableBase { /// /// The transformer must not return `null`. If it does, an [ArgumentError] is thrown. Optional transform(S Function(T value) transformer) { - return _value == null - ? Optional.absent() - : Optional.of(transformer(_value as T)); + return _value == null ? Optional.absent() : Optional.of(transformer(_value as T)); } /// Transforms the Optional value. @@ -552,8 +529,7 @@ class Optional extends IterableBase { } @override - Iterator get iterator => - isPresent ? [_value as T].iterator : Iterable.empty().iterator; + Iterator get iterator => isPresent ? [_value as T].iterator : Iterable.empty().iterator; /// Delegates to the underlying [value] hashCode. @override @@ -565,8 +541,6 @@ class Optional extends IterableBase { @override String toString() { - return _value == null - ? 'Optional { absent }' - : 'Optional { value: $_value }'; + return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }'; } } diff --git a/packages/camera/camera_android/example/lib/camera_preview.dart b/packages/camera/camera_android/example/lib/camera_preview.dart index 0a768b340639..7e8d6438ff65 100644 --- a/packages/camera/camera_android/example/lib/camera_preview.dart +++ b/packages/camera/camera_android/example/lib/camera_preview.dart @@ -26,12 +26,9 @@ class CameraPreview extends StatelessWidget { valueListenable: controller, builder: (BuildContext context, Object? value, Widget? child) { final double cameraAspectRatio = - controller.value.previewSize!.width / - controller.value.previewSize!.height; + controller.value.previewSize!.width / controller.value.previewSize!.height; return AspectRatio( - aspectRatio: _isLandscape() - ? cameraAspectRatio - : (1 / cameraAspectRatio), + aspectRatio: _isLandscape() ? cameraAspectRatio : (1 / cameraAspectRatio), child: Stack( fit: StackFit.expand, children: [ diff --git a/packages/camera/camera_android/example/lib/main.dart b/packages/camera/camera_android/example/lib/main.dart index b669f6ac6831..3b996569aaf9 100644 --- a/packages/camera/camera_android/example/lib/main.dart +++ b/packages/camera/camera_android/example/lib/main.dart @@ -138,8 +138,7 @@ class _CameraExampleHomeState extends State decoration: BoxDecoration( color: Colors.black, border: Border.all( - color: - controller != null && controller!.value.isRecordingVideo + color: controller != null && controller!.value.isRecordingVideo ? Colors.redAccent : Colors.grey, width: 3.0, @@ -155,9 +154,7 @@ class _CameraExampleHomeState extends State _modeControlRowWidget(), Padding( padding: const EdgeInsets.all(5.0), - child: Row( - children: [_cameraTogglesRowWidget(), _thumbnailWidget()], - ), + child: Row(children: [_cameraTogglesRowWidget(), _thumbnailWidget()]), ), ], ), @@ -171,11 +168,7 @@ class _CameraExampleHomeState extends State if (cameraController == null || !cameraController.value.isInitialized) { return const Text( 'Tap a camera', - style: TextStyle( - color: Colors.white, - fontSize: 24.0, - fontWeight: FontWeight.w900, - ), + style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900), ); } else { return Listener( @@ -189,8 +182,7 @@ class _CameraExampleHomeState extends State behavior: HitTestBehavior.opaque, onScaleStart: _handleScaleStart, onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), + onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints), ); }, ), @@ -209,15 +201,9 @@ class _CameraExampleHomeState extends State return; } - _currentScale = (_baseScale * details.scale).clamp( - _minAvailableZoom, - _maxAvailableZoom, - ); + _currentScale = (_baseScale * details.scale).clamp(_minAvailableZoom, _maxAvailableZoom); - await CameraPlatform.instance.setZoomLevel( - controller!.cameraId, - _currentScale, - ); + await CameraPlatform.instance.setZoomLevel(controller!.cameraId, _currentScale); } /// Display the thumbnail of the captured image or video. @@ -242,13 +228,9 @@ class _CameraExampleHomeState extends State // pointing to a location within the browser. It may be displayed // either with Image.network or Image.memory after loading the image // bytes to memory. - kIsWeb - ? Image.network(imageFile!.path) - : Image.file(File(imageFile!.path))) + kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path))) : Container( - decoration: BoxDecoration( - border: Border.all(color: Colors.pink), - ), + decoration: BoxDecoration(border: Border.all(color: Colors.pink)), child: Center( child: AspectRatio( aspectRatio: localVideoController.value.aspectRatio, @@ -281,16 +263,12 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.exposure), color: Colors.blue, - onPressed: controller != null - ? onExposureModeButtonPressed - : null, + onPressed: controller != null ? onExposureModeButtonPressed : null, ), IconButton( icon: const Icon(Icons.filter_center_focus), color: Colors.blue, - onPressed: controller != null - ? onFocusModeButtonPressed - : null, + onPressed: controller != null ? onFocusModeButtonPressed : null, ), ] : [], @@ -306,9 +284,7 @@ class _CameraExampleHomeState extends State : Icons.screen_rotation, ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null, ), ], ), @@ -328,36 +304,28 @@ class _CameraExampleHomeState extends State children: [ IconButton( icon: const Icon(Icons.flash_off), - color: controller?.value.flashMode == FlashMode.off - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.off ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.off) : null, ), IconButton( icon: const Icon(Icons.flash_auto), - color: controller?.value.flashMode == FlashMode.auto - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.auto ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.auto) : null, ), IconButton( icon: const Icon(Icons.flash_on), - color: controller?.value.flashMode == FlashMode.always - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.always ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.always) : null, ), IconButton( icon: const Icon(Icons.highlight), - color: controller?.value.flashMode == FlashMode.torch - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.torch) : null, @@ -394,15 +362,11 @@ class _CameraExampleHomeState extends State TextButton( style: styleAuto, onPressed: controller != null - ? () => - onSetExposureModeButtonPressed(ExposureMode.auto) + ? () => onSetExposureModeButtonPressed(ExposureMode.auto) : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance.setExposurePoint( - controller!.cameraId, - null, - ); + CameraPlatform.instance.setExposurePoint(controller!.cameraId, null); showInSnackBar('Resetting exposure point'); } }, @@ -411,17 +375,13 @@ class _CameraExampleHomeState extends State TextButton( style: styleLocked, onPressed: controller != null - ? () => onSetExposureModeButtonPressed( - ExposureMode.locked, - ) + ? () => onSetExposureModeButtonPressed(ExposureMode.locked) : null, child: const Text('LOCKED'), ), TextButton( style: styleLocked, - onPressed: controller != null - ? () => controller!.setExposureOffset(0.0) - : null, + onPressed: controller != null ? () => controller!.setExposureOffset(0.0) : null, child: const Text('RESET OFFSET'), ), ], @@ -436,9 +396,7 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: - _minAvailableExposureOffset == - _maxAvailableExposureOffset + onChanged: _minAvailableExposureOffset == _maxAvailableExposureOffset ? null : setExposureOffset, ), @@ -454,9 +412,7 @@ class _CameraExampleHomeState extends State Widget _focusModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - foregroundColor: controller?.value.focusMode == FocusMode.auto - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.focusMode == FocusMode.auto ? Colors.orange : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( foregroundColor: controller?.value.focusMode == FocusMode.locked @@ -482,10 +438,7 @@ class _CameraExampleHomeState extends State : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance.setFocusPoint( - controller!.cameraId, - null, - ); + CameraPlatform.instance.setFocusPoint(controller!.cameraId, null); } showInSnackBar('Resetting focus point'); }, @@ -563,13 +516,10 @@ class _CameraExampleHomeState extends State ), IconButton( icon: const Icon(Icons.pause_presentation), - color: - cameraController != null && cameraController.value.isPreviewPaused + color: cameraController != null && cameraController.value.isPreviewPaused ? Colors.red : Colors.blue, - onPressed: cameraController == null - ? null - : onPausePreviewButtonPressed, + onPressed: cameraController == null ? null : onPausePreviewButtonPressed, ), ], ); @@ -616,9 +566,7 @@ class _CameraExampleHomeState extends State String timestamp() => DateTime.now().millisecondsSinceEpoch.toString(); void showInSnackBar(String message) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message))); } void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) { @@ -644,15 +592,11 @@ class _CameraExampleHomeState extends State } } - Future _initializeCameraController( - CameraDescription cameraDescription, - ) async { + Future _initializeCameraController(CameraDescription cameraDescription) async { final cameraController = CameraController( cameraDescription, mediaSettings: MediaSettings( - resolutionPreset: kIsWeb - ? ResolutionPreset.max - : ResolutionPreset.medium, + resolutionPreset: kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, enableAudio: enableAudio, ), imageFormatGroup: ImageFormatGroup.jpeg, @@ -675,14 +619,10 @@ class _CameraExampleHomeState extends State ? >[ CameraPlatform.instance .getMinExposureOffset(cameraController.cameraId) - .then( - (double value) => _minAvailableExposureOffset = value, - ), + .then((double value) => _minAvailableExposureOffset = value), CameraPlatform.instance .getMaxExposureOffset(cameraController.cameraId) - .then( - (double value) => _maxAvailableExposureOffset = value, - ), + .then((double value) => _maxAvailableExposureOffset = value), ] : >[], CameraPlatform.instance diff --git a/packages/camera/camera_android/example/test_driver/integration_test.dart b/packages/camera/camera_android/example/test_driver/integration_test.dart index ef65f091ca07..39d763c0900b 100644 --- a/packages/camera/camera_android/example/test_driver/integration_test.dart +++ b/packages/camera/camera_android/example/test_driver/integration_test.dart @@ -39,10 +39,7 @@ Future main() async { ]); print('Starting test.'); final FlutterDriver driver = await FlutterDriver.connect(); - final String data = await driver.requestData( - null, - timeout: const Duration(minutes: 1), - ); + final String data = await driver.requestData(null, timeout: const Duration(minutes: 1)); await driver.close(); print('Test finished. Revoking camera permissions...'); Process.runSync('adb', [ diff --git a/packages/camera/camera_android/lib/src/android_camera.dart b/packages/camera/camera_android/lib/src/android_camera.dart index 9f7d580f2364..c42e1a23c315 100644 --- a/packages/camera/camera_android/lib/src/android_camera.dart +++ b/packages/camera/camera_android/lib/src/android_camera.dart @@ -17,8 +17,7 @@ import 'utils.dart'; /// The Android implementation of [CameraPlatform] that uses method channels. class AndroidCamera extends CameraPlatform { /// Creates a new [CameraPlatform] instance. - AndroidCamera({@visibleForTesting CameraApi? hostApi}) - : _hostApi = hostApi ?? CameraApi(); + AndroidCamera({@visibleForTesting CameraApi? hostApi}) : _hostApi = hostApi ?? CameraApi(); /// Registers this class as the default instance of [CameraPlatform]. static void registerWith() { @@ -30,8 +29,7 @@ class AndroidCamera extends CameraPlatform { /// The name of the channel that device events from the platform side are /// sent on. @visibleForTesting - static const String deviceEventChannelName = - 'plugins.flutter.io/camera_android/fromPlatform'; + static const String deviceEventChannelName = 'plugins.flutter.io/camera_android/fromPlatform'; /// The controller we need to broadcast the different events coming /// from handleMethodCall, specific to camera events. @@ -51,8 +49,7 @@ class AndroidCamera extends CameraPlatform { /// Map of camera IDs to camera-level callback handlers listening to their /// respective platform channels. @visibleForTesting - final Map hostCameraHandlers = - {}; + final Map hostCameraHandlers = {}; // The stream to receive frames from the native code. StreamSubscription? _platformImageStreamSubscription; @@ -60,23 +57,18 @@ class AndroidCamera extends CameraPlatform { // The stream for vending frames to platform interface clients. StreamController? _frameStreamController; - Stream _cameraEvents(int cameraId) => cameraEventStreamController - .stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => + cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { try { final List cameraDescriptions = await _hostApi .getAvailableCameras(); - return cameraDescriptions.map(( - PlatformCameraDescription cameraDescription, - ) { + return cameraDescriptions.map((PlatformCameraDescription cameraDescription) { return CameraDescription( name: cameraDescription.name, - lensDirection: cameraLensDirectionFromPlatform( - cameraDescription.lensDirection, - ), + lensDirection: cameraLensDirectionFromPlatform(cameraDescription.lensDirection), sensorOrientation: cameraDescription.sensorOrientation, ); }).toList(); @@ -101,10 +93,7 @@ class AndroidCamera extends CameraPlatform { MediaSettings? mediaSettings, ) async { try { - return await _hostApi.create( - cameraDescription.name, - mediaSettingsToPlatform(mediaSettings), - ); + return await _hostApi.create(cameraDescription.name, mediaSettingsToPlatform(mediaSettings)); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -139,9 +128,7 @@ class AndroidCamera extends CameraPlatform { @override Future dispose(int cameraId) async { - final HostCameraMessageHandler? handler = hostCameraHandlers.remove( - cameraId, - ); + final HostCameraMessageHandler? handler = hostCameraHandlers.remove(cameraId); handler?.dispose(); await _hostApi.dispose(); @@ -179,13 +166,8 @@ class AndroidCamera extends CameraPlatform { } @override - Future lockCaptureOrientation( - int cameraId, - DeviceOrientation orientation, - ) async { - await _hostApi.lockCaptureOrientation( - deviceOrientationToPlatform(orientation), - ); + Future lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async { + await _hostApi.lockCaptureOrientation(deviceOrientationToPlatform(orientation)); } @override @@ -204,10 +186,7 @@ class AndroidCamera extends CameraPlatform { Future prepareForVideoRecording() async {} @override - Future startVideoRecording( - int cameraId, { - Duration? maxVideoDuration, - }) async { + Future startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -229,12 +208,10 @@ class AndroidCamera extends CameraPlatform { } @override - Future pauseVideoRecording(int cameraId) => - _hostApi.pauseVideoRecording(); + Future pauseVideoRecording(int cameraId) => _hostApi.pauseVideoRecording(); @override - Future resumeVideoRecording(int cameraId) => - _hostApi.resumeVideoRecording(); + Future resumeVideoRecording(int cameraId) => _hostApi.resumeVideoRecording(); @override bool supportsImageStreaming() => true; @@ -248,9 +225,7 @@ class AndroidCamera extends CameraPlatform { return _frameStreamController!.stream; } - StreamController _installStreamController({ - void Function()? onListen, - }) { + StreamController _installStreamController({void Function()? onListen}) { _frameStreamController = StreamController( onListen: onListen ?? () {}, onPause: _onFrameStreamPauseResume, @@ -270,16 +245,12 @@ class AndroidCamera extends CameraPlatform { } void _startStreamListener() { - const cameraEventChannel = EventChannel( - 'plugins.flutter.io/camera_android/imageStream', - ); - _platformImageStreamSubscription = cameraEventChannel - .receiveBroadcastStream() - .listen((dynamic imageData) { - _frameStreamController!.add( - cameraImageFromPlatformData(imageData as Map), - ); - }); + const cameraEventChannel = EventChannel('plugins.flutter.io/camera_android/imageStream'); + _platformImageStreamSubscription = cameraEventChannel.receiveBroadcastStream().listen(( + dynamic imageData, + ) { + _frameStreamController!.add(cameraImageFromPlatformData(imageData as Map)); + }); } FutureOr _onFrameStreamCancel() async { @@ -374,9 +345,7 @@ class AndroidCamera extends CameraPlatform { } @override - Future setDescriptionWhileRecording( - CameraDescription description, - ) async { + Future setDescriptionWhileRecording(CameraDescription description) async { await _hostApi.setDescriptionWhileRecording(description.name); } diff --git a/packages/camera/camera_android/lib/src/messages.g.dart b/packages/camera/camera_android/lib/src/messages.g.dart index e4c047452511..8c1034bd117d 100644 --- a/packages/camera/camera_android/lib/src/messages.g.dart +++ b/packages/camera/camera_android/lib/src/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -54,12 +48,7 @@ bool _deepEquals(Object? a, Object? b) { enum PlatformCameraLensDirection { front, back, external } /// Pigeon equivalent of [DeviceOrientation]. -enum PlatformDeviceOrientation { - portraitUp, - portraitDown, - landscapeLeft, - landscapeRight, -} +enum PlatformDeviceOrientation { portraitUp, portraitDown, landscapeLeft, landscapeRight } /// Pigeon equivalent of [ExposureMode]. enum PlatformExposureMode { auto, locked } @@ -115,8 +104,7 @@ class PlatformCameraDescription { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraDescription || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraDescription || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -210,10 +198,7 @@ class PlatformSize { static PlatformSize decode(Object result) { result as List; - return PlatformSize( - width: result[0]! as double, - height: result[1]! as double, - ); + return PlatformSize(width: result[0]! as double, height: result[1]! as double); } @override @@ -292,13 +277,7 @@ class PlatformMediaSettings { bool enableAudio; List _toList() { - return [ - resolutionPreset, - fps, - videoBitrate, - audioBitrate, - enableAudio, - ]; + return [resolutionPreset, fps, videoBitrate, audioBitrate, enableAudio]; } Object encode() { @@ -426,13 +405,11 @@ class CameraApi { /// Constructor for [CameraApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - CameraApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + CameraApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -443,15 +420,13 @@ class CameraApi { Future> getAvailableCameras() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -466,29 +441,24 @@ class CameraApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } /// Creates a new camera with the given name and settings and returns its ID. - Future create( - String cameraName, - PlatformMediaSettings mediaSettings, - ) async { + Future create(String cameraName, PlatformMediaSettings mediaSettings) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.create$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraName, mediaSettings], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraName, + mediaSettings, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -511,17 +481,13 @@ class CameraApi { Future initialize(PlatformImageFormatGroup imageFormat) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.initialize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [imageFormat], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([imageFormat]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -539,15 +505,13 @@ class CameraApi { Future dispose() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.dispose$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -562,22 +526,16 @@ class CameraApi { } /// Locks the camera with the given ID to the given orientation. - Future lockCaptureOrientation( - PlatformDeviceOrientation orientation, - ) async { + Future lockCaptureOrientation(PlatformDeviceOrientation orientation) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.lockCaptureOrientation$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [orientation], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([orientation]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -595,15 +553,13 @@ class CameraApi { Future unlockCaptureOrientation() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.unlockCaptureOrientation$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -622,15 +578,13 @@ class CameraApi { Future takePicture() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.takePicture$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -653,17 +607,13 @@ class CameraApi { Future startVideoRecording(bool enableStream) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enableStream], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enableStream]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -682,15 +632,13 @@ class CameraApi { Future stopVideoRecording() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -713,15 +661,13 @@ class CameraApi { Future pauseVideoRecording() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.pauseVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -739,15 +685,13 @@ class CameraApi { Future resumeVideoRecording() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.resumeVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -765,15 +709,13 @@ class CameraApi { Future startImageStream() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.startImageStream$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -791,15 +733,13 @@ class CameraApi { Future stopImageStream() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.stopImageStream$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -817,17 +757,13 @@ class CameraApi { Future setFlashMode(PlatformFlashMode flashMode) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setFlashMode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [flashMode], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([flashMode]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -845,17 +781,13 @@ class CameraApi { Future setExposureMode(PlatformExposureMode exposureMode) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setExposureMode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [exposureMode], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([exposureMode]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -875,17 +807,13 @@ class CameraApi { Future setExposurePoint(PlatformPoint? point) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setExposurePoint$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [point], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([point]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -903,15 +831,13 @@ class CameraApi { Future getMinExposureOffset() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.getMinExposureOffset$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -934,15 +860,13 @@ class CameraApi { Future getMaxExposureOffset() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.getMaxExposureOffset$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -965,15 +889,13 @@ class CameraApi { Future getExposureOffsetStepSize() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.getExposureOffsetStepSize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -997,17 +919,13 @@ class CameraApi { Future setExposureOffset(double offset) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setExposureOffset$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [offset], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([offset]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1030,17 +948,13 @@ class CameraApi { Future setFocusMode(PlatformFocusMode focusMode) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setFocusMode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [focusMode], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([focusMode]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1060,17 +974,13 @@ class CameraApi { Future setFocusPoint(PlatformPoint? point) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setFocusPoint$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [point], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([point]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1088,15 +998,13 @@ class CameraApi { Future getMaxZoomLevel() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.getMaxZoomLevel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1119,15 +1027,13 @@ class CameraApi { Future getMinZoomLevel() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.getMinZoomLevel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1150,17 +1056,13 @@ class CameraApi { Future setZoomLevel(double zoom) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setZoomLevel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [zoom], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([zoom]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1178,15 +1080,13 @@ class CameraApi { Future pausePreview() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.pausePreview$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1204,15 +1104,13 @@ class CameraApi { Future resumePreview() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.resumePreview$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1232,17 +1130,13 @@ class CameraApi { Future setDescriptionWhileRecording(String description) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_android.CameraApi.setDescriptionWhileRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [description], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([description]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1269,12 +1163,9 @@ abstract class CameraGlobalEventApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1328,12 +1219,9 @@ abstract class CameraEventApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android.CameraEventApi.initialized$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1347,8 +1235,7 @@ abstract class CameraEventApi { 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.initialized was null.', ); final List args = (message as List?)!; - final PlatformCameraState? arg_initialState = - (args[0] as PlatformCameraState?); + final PlatformCameraState? arg_initialState = (args[0] as PlatformCameraState?); assert( arg_initialState != null, 'Argument for dev.flutter.pigeon.camera_android.CameraEventApi.initialized was null, expected non-null PlatformCameraState.', @@ -1367,8 +1254,7 @@ abstract class CameraEventApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android.CameraEventApi.error$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1401,8 +1287,7 @@ abstract class CameraEventApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android.CameraEventApi.closed$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, diff --git a/packages/camera/camera_android/lib/src/type_conversion.dart b/packages/camera/camera_android/lib/src/type_conversion.dart index 1daa5261ef1f..87d007bf9d84 100644 --- a/packages/camera/camera_android/lib/src/type_conversion.dart +++ b/packages/camera/camera_android/lib/src/type_conversion.dart @@ -18,9 +18,8 @@ CameraImageData cameraImageFromPlatformData(Map data) { sensorSensitivity: data['sensorSensitivity'] as double?, planes: List.unmodifiable( (data['planes'] as List).map( - (dynamic planeData) => _cameraImagePlaneFromPlatformData( - planeData as Map, - ), + (dynamic planeData) => + _cameraImagePlaneFromPlatformData(planeData as Map), ), ), ); diff --git a/packages/camera/camera_android/lib/src/utils.dart b/packages/camera/camera_android/lib/src/utils.dart index 554bf78480e8..320a0967f8ab 100644 --- a/packages/camera/camera_android/lib/src/utils.dart +++ b/packages/camera/camera_android/lib/src/utils.dart @@ -10,28 +10,24 @@ import 'package:flutter/services.dart'; import 'messages.g.dart'; /// Converts a [PlatformCameraLensDirection] to [CameraLensDirection]. -CameraLensDirection cameraLensDirectionFromPlatform( - PlatformCameraLensDirection direction, -) => switch (direction) { - PlatformCameraLensDirection.front => CameraLensDirection.front, - PlatformCameraLensDirection.back => CameraLensDirection.back, - PlatformCameraLensDirection.external => CameraLensDirection.external, -}; +CameraLensDirection cameraLensDirectionFromPlatform(PlatformCameraLensDirection direction) => + switch (direction) { + PlatformCameraLensDirection.front => CameraLensDirection.front, + PlatformCameraLensDirection.back => CameraLensDirection.back, + PlatformCameraLensDirection.external => CameraLensDirection.external, + }; /// Converts a [PlatformDeviceOrientation] to [DeviceOrientation]. -DeviceOrientation deviceOrientationFromPlatform( - PlatformDeviceOrientation orientation, -) => switch (orientation) { - PlatformDeviceOrientation.portraitUp => DeviceOrientation.portraitUp, - PlatformDeviceOrientation.portraitDown => DeviceOrientation.portraitDown, - PlatformDeviceOrientation.landscapeLeft => DeviceOrientation.landscapeLeft, - PlatformDeviceOrientation.landscapeRight => DeviceOrientation.landscapeRight, -}; +DeviceOrientation deviceOrientationFromPlatform(PlatformDeviceOrientation orientation) => + switch (orientation) { + PlatformDeviceOrientation.portraitUp => DeviceOrientation.portraitUp, + PlatformDeviceOrientation.portraitDown => DeviceOrientation.portraitDown, + PlatformDeviceOrientation.landscapeLeft => DeviceOrientation.landscapeLeft, + PlatformDeviceOrientation.landscapeRight => DeviceOrientation.landscapeRight, + }; /// Converts a [DeviceOrientation] to [PlatformDeviceOrientation]. -PlatformDeviceOrientation deviceOrientationToPlatform( - DeviceOrientation orientation, -) { +PlatformDeviceOrientation deviceOrientationToPlatform(DeviceOrientation orientation) { switch (orientation) { case DeviceOrientation.portraitUp: return PlatformDeviceOrientation.portraitUp; @@ -49,11 +45,10 @@ PlatformDeviceOrientation deviceOrientationToPlatform( } /// Converts a [PlatformExposureMode] to [ExposureMode]. -ExposureMode exposureModeFromPlatform(PlatformExposureMode exposureMode) => - switch (exposureMode) { - PlatformExposureMode.auto => ExposureMode.auto, - PlatformExposureMode.locked => ExposureMode.locked, - }; +ExposureMode exposureModeFromPlatform(PlatformExposureMode exposureMode) => switch (exposureMode) { + PlatformExposureMode.auto => ExposureMode.auto, + PlatformExposureMode.locked => ExposureMode.locked, +}; /// Converts a [ExposureMode] to [PlatformExposureMode]. PlatformExposureMode exposureModeToPlatform(ExposureMode exposureMode) { @@ -70,11 +65,10 @@ PlatformExposureMode exposureModeToPlatform(ExposureMode exposureMode) { } /// Converts a [PlatformFocusMode] to [FocusMode]. -FocusMode focusModeFromPlatform(PlatformFocusMode focusMode) => - switch (focusMode) { - PlatformFocusMode.auto => FocusMode.auto, - PlatformFocusMode.locked => FocusMode.locked, - }; +FocusMode focusModeFromPlatform(PlatformFocusMode focusMode) => switch (focusMode) { + PlatformFocusMode.auto => FocusMode.auto, + PlatformFocusMode.locked => FocusMode.locked, +}; /// Converts a [FocusMode] to [PlatformFocusMode]. PlatformFocusMode focusModeToPlatform(FocusMode focusMode) { @@ -91,26 +85,24 @@ PlatformFocusMode focusModeToPlatform(FocusMode focusMode) { } /// Converts a [ResolutionPreset] to [PlatformResolutionPreset]. -PlatformResolutionPreset resolutionPresetToPlatform(ResolutionPreset? preset) => - switch (preset) { - ResolutionPreset.low => PlatformResolutionPreset.low, - ResolutionPreset.medium => PlatformResolutionPreset.medium, - ResolutionPreset.high => PlatformResolutionPreset.high, - ResolutionPreset.veryHigh => PlatformResolutionPreset.veryHigh, - ResolutionPreset.ultraHigh => PlatformResolutionPreset.ultraHigh, - ResolutionPreset.max => PlatformResolutionPreset.max, - _ => PlatformResolutionPreset.high, - }; +PlatformResolutionPreset resolutionPresetToPlatform(ResolutionPreset? preset) => switch (preset) { + ResolutionPreset.low => PlatformResolutionPreset.low, + ResolutionPreset.medium => PlatformResolutionPreset.medium, + ResolutionPreset.high => PlatformResolutionPreset.high, + ResolutionPreset.veryHigh => PlatformResolutionPreset.veryHigh, + ResolutionPreset.ultraHigh => PlatformResolutionPreset.ultraHigh, + ResolutionPreset.max => PlatformResolutionPreset.max, + _ => PlatformResolutionPreset.high, +}; /// Converts a [MediaSettings] to [PlatformMediaSettings]. -PlatformMediaSettings mediaSettingsToPlatform(MediaSettings? settings) => - PlatformMediaSettings( - resolutionPreset: resolutionPresetToPlatform(settings?.resolutionPreset), - enableAudio: settings?.enableAudio ?? false, - videoBitrate: settings?.videoBitrate, - audioBitrate: settings?.audioBitrate, - fps: settings?.fps, - ); +PlatformMediaSettings mediaSettingsToPlatform(MediaSettings? settings) => PlatformMediaSettings( + resolutionPreset: resolutionPresetToPlatform(settings?.resolutionPreset), + enableAudio: settings?.enableAudio ?? false, + videoBitrate: settings?.videoBitrate, + audioBitrate: settings?.audioBitrate, + fps: settings?.fps, +); /// Converts an [ImageFormatGroup] to [PlatformImageFormatGroup]. /// diff --git a/packages/camera/camera_android/pigeons/messages.dart b/packages/camera/camera_android/pigeons/messages.dart index 4489fe3f6fb8..4783b4783189 100644 --- a/packages/camera/camera_android/pigeons/messages.dart +++ b/packages/camera/camera_android/pigeons/messages.dart @@ -28,12 +28,7 @@ class PlatformCameraDescription { } /// Pigeon equivalent of [DeviceOrientation]. -enum PlatformDeviceOrientation { - portraitUp, - portraitDown, - landscapeLeft, - landscapeRight, -} +enum PlatformDeviceOrientation { portraitUp, portraitDown, landscapeLeft, landscapeRight } /// Pigeon equivalent of [ExposureMode]. enum PlatformExposureMode { auto, locked } diff --git a/packages/camera/camera_android/test/android_camera_test.dart b/packages/camera/camera_android/test/android_camera_test.dart index 8321001ed954..d004600702f4 100644 --- a/packages/camera/camera_android/test/android_camera_test.dart +++ b/packages/camera/camera_android/test/android_camera_test.dart @@ -126,90 +126,65 @@ void main() { }, ); - test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - final camera = AndroidCamera(hostApi: mockCameraApi); - when( - mockCameraApi.create( - 'Test', - argThat( - predicate( - (PlatformMediaSettings settings) => - settings.resolutionPreset == - PlatformResolutionPreset.high && - !settings.enableAudio, - ), - ), - ), - ).thenThrow( - CameraException( - 'TESTING_ERROR_CODE', - 'Mock error message used during testing.', - ), - ); - - // Act - expect( - () => camera.createCamera( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, + test('Should throw CameraException when create throws a PlatformException', () { + // Arrange + final camera = AndroidCamera(hostApi: mockCameraApi); + when( + mockCameraApi.create( + 'Test', + argThat( + predicate( + (PlatformMediaSettings settings) => + settings.resolutionPreset == PlatformResolutionPreset.high && + !settings.enableAudio, ), - ResolutionPreset.high, ), - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), - ), - ); - }, - ); + ), + ).thenThrow(CameraException('TESTING_ERROR_CODE', 'Mock error message used during testing.')); - test( - 'Should throw CameraException when initialize throws a PlatformException', - () { - // Arrange - final camera = AndroidCamera(hostApi: mockCameraApi); - when( - mockCameraApi.initialize(PlatformImageFormatGroup.yuv420), - ).thenThrow( - CameraException( - 'TESTING_ERROR_CODE', - 'Mock error message used during testing.', + // Act + expect( + () => camera.createCamera( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, ), - ); + ResolutionPreset.high, + ), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); - // Act - expect( - () => camera.initializeCamera(0), - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), - ), - ); - }, - ); + test('Should throw CameraException when initialize throws a PlatformException', () { + // Arrange + final camera = AndroidCamera(hostApi: mockCameraApi); + when( + mockCameraApi.initialize(PlatformImageFormatGroup.yuv420), + ).thenThrow(CameraException('TESTING_ERROR_CODE', 'Mock error message used during testing.')); + + // Act + expect( + () => camera.initializeCamera(0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); test('Should send initialization data', () async { // Arrange @@ -239,23 +214,13 @@ void main() { // Act final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; // Assert expect(cameraId, 1); - verify( - mockCameraApi.initialize(PlatformImageFormatGroup.yuv420), - ).called(1); + verify(mockCameraApi.initialize(PlatformImageFormatGroup.yuv420)).called(1); }); test('Should send a disposal call on dispose', () async { @@ -283,15 +248,7 @@ void main() { ); final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; @@ -321,23 +278,14 @@ void main() { ); final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; }); test('Should receive initialized event', () async { // Act - final Stream eventStream = camera - .onCameraInitialized(cameraId); + final Stream eventStream = camera.onCameraInitialized(cameraId); final streamQueue = StreamQueue(eventStream); // Emit test events @@ -370,9 +318,7 @@ void main() { test('Should receive camera closing events', () async { // Act - final Stream eventStream = camera.onCameraClosing( - cameraId, - ); + final Stream eventStream = camera.onCameraClosing(cameraId); final streamQueue = StreamQueue(eventStream); // Emit test events @@ -392,9 +338,7 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = camera.onCameraError( - cameraId, - ); + final Stream errorStream = camera.onCameraError(cameraId); final streamQueue = StreamQueue(errorStream); // Emit test events @@ -414,18 +358,13 @@ void main() { test('Should receive device orientation change events', () async { // Act - final Stream eventStream = camera - .onDeviceOrientationChanged(); - final streamQueue = StreamQueue( - eventStream, - ); + final Stream eventStream = camera.onDeviceOrientationChanged(); + final streamQueue = StreamQueue(eventStream); // Emit test events const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); for (var i = 0; i < 3; i++) { - camera.hostHandler.deviceOrientationChanged( - PlatformDeviceOrientation.portraitUp, - ); + camera.hostHandler.deviceOrientationChanged(PlatformDeviceOrientation.portraitUp); } // Assert @@ -456,95 +395,70 @@ void main() { ); final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; }); - test( - 'Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final returnData = [ - PlatformCameraDescription( - name: 'Test 1', - lensDirection: PlatformCameraLensDirection.front, - sensorOrientation: 1, - ), - PlatformCameraDescription( - name: 'Test 2', - lensDirection: PlatformCameraLensDirection.back, - sensorOrientation: 2, - ), - ]; - when( - mockCameraApi.getAvailableCameras(), - ).thenAnswer((_) async => returnData); - - // Act - final List cameras = await camera.availableCameras(); + test('Should fetch CameraDescription instances for available cameras', () async { + // Arrange + final returnData = [ + PlatformCameraDescription( + name: 'Test 1', + lensDirection: PlatformCameraLensDirection.front, + sensorOrientation: 1, + ), + PlatformCameraDescription( + name: 'Test 2', + lensDirection: PlatformCameraLensDirection.back, + sensorOrientation: 2, + ), + ]; + when(mockCameraApi.getAvailableCameras()).thenAnswer((_) async => returnData); - // Assert - expect(cameras.length, returnData.length); - for (var i = 0; i < returnData.length; i++) { - final PlatformCameraDescription platformCameraDescription = - returnData[i]; - final cameraDescription = CameraDescription( - name: platformCameraDescription.name, - lensDirection: cameraLensDirectionFromPlatform( - platformCameraDescription.lensDirection, - ), - sensorOrientation: platformCameraDescription.sensorOrientation, - ); - expect(cameras[i], cameraDescription); - } - }, - ); + // Act + final List cameras = await camera.availableCameras(); - test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - // Arrange - when(mockCameraApi.getAvailableCameras()).thenThrow( - PlatformException( - code: 'TESTING_ERROR_CODE', - message: 'Mock error message used during testing.', - ), + // Assert + expect(cameras.length, returnData.length); + for (var i = 0; i < returnData.length; i++) { + final PlatformCameraDescription platformCameraDescription = returnData[i]; + final cameraDescription = CameraDescription( + name: platformCameraDescription.name, + lensDirection: cameraLensDirectionFromPlatform(platformCameraDescription.lensDirection), + sensorOrientation: platformCameraDescription.sensorOrientation, ); + expect(cameras[i], cameraDescription); + } + }); - // Act - expect( - camera.availableCameras, - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), - ), - ); - }, - ); + test('Should throw CameraException when availableCameras throws a PlatformException', () { + // Arrange + when(mockCameraApi.getAvailableCameras()).thenThrow( + PlatformException( + code: 'TESTING_ERROR_CODE', + message: 'Mock error message used during testing.', + ), + ); + + // Act + expect( + camera.availableCameras, + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); test('Should take a picture and return an XFile instance', () async { // Arrange - when( - mockCameraApi.takePicture(), - ).thenAnswer((_) async => '/test/path.jpg'); + when(mockCameraApi.takePicture()).thenAnswer((_) async => '/test/path.jpg'); // Act final XFile file = await camera.takePicture(cameraId); @@ -568,10 +482,7 @@ void main() { // Arrange // Act await camera.startVideoCapturing( - VideoCaptureOptions( - cameraId, - streamCallback: (CameraImageData imageData) {}, - ), + VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}), ); // Assert @@ -581,9 +492,7 @@ void main() { test('Should stop a video recording and return the file', () async { // Arrange - when( - mockCameraApi.stopVideoRecording(), - ).thenAnswer((_) async => '/test/path.mp4'); + when(mockCameraApi.stopVideoRecording()).thenAnswer((_) async => '/test/path.mp4'); // Act final XFile file = await camera.stopVideoRecording(cameraId); @@ -622,9 +531,7 @@ void main() { await camera.setDescriptionWhileRecording(camera2Description); // Assert - verify( - mockCameraApi.setDescriptionWhileRecording(camera2Description.name), - ).called(1); + verify(mockCameraApi.setDescriptionWhileRecording(camera2Description.name)).called(1); }); test('Should set the flash mode', () async { @@ -649,12 +556,8 @@ void main() { await camera.setExposureMode(cameraId, ExposureMode.locked); // Assert - verify( - mockCameraApi.setExposureMode(PlatformExposureMode.auto), - ).called(1); - verify( - mockCameraApi.setExposureMode(PlatformExposureMode.locked), - ).called(1); + verify(mockCameraApi.setExposureMode(PlatformExposureMode.auto)).called(1); + verify(mockCameraApi.setExposureMode(PlatformExposureMode.locked)).called(1); }); test('Should set the exposure point', () async { @@ -666,11 +569,7 @@ void main() { // Assert verify( mockCameraApi.setExposurePoint( - argThat( - predicate( - (PlatformPoint point) => point.x == 0.4 && point.y == 0.5, - ), - ), + argThat(predicate((PlatformPoint point) => point.x == 0.4 && point.y == 0.5)), ), ).called(1); verify(mockCameraApi.setExposurePoint(null)).called(1); @@ -681,9 +580,7 @@ void main() { when(mockCameraApi.getMinExposureOffset()).thenAnswer((_) async => 2.0); // Act - final double minExposureOffset = await camera.getMinExposureOffset( - cameraId, - ); + final double minExposureOffset = await camera.getMinExposureOffset(cameraId); // Assert expect(minExposureOffset, 2.0); @@ -694,9 +591,7 @@ void main() { when(mockCameraApi.getMaxExposureOffset()).thenAnswer((_) async => 2.0); // Act - final double maxExposureOffset = await camera.getMaxExposureOffset( - cameraId, - ); + final double maxExposureOffset = await camera.getMaxExposureOffset(cameraId); // Assert expect(maxExposureOffset, 2.0); @@ -704,9 +599,7 @@ void main() { test('Should get the exposure offset step size', () async { // Arrange - when( - mockCameraApi.getExposureOffsetStepSize(), - ).thenAnswer((_) async => 0.25); + when(mockCameraApi.getExposureOffsetStepSize()).thenAnswer((_) async => 0.25); // Act final double stepSize = await camera.getExposureOffsetStepSize(cameraId); @@ -777,44 +670,30 @@ void main() { verify(mockCameraApi.setZoomLevel(2.0)).called(1); }); - test( - 'Should throw CameraException when illegal zoom level is supplied', - () async { - // Arrange - when(mockCameraApi.setZoomLevel(-1.0)).thenThrow( - PlatformException(code: 'ZOOM_ERROR', message: 'Illegal zoom error'), - ); - - // Act & assert - expect( - () => camera.setZoomLevel(cameraId, -1.0), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') - .having( - (CameraException e) => e.description, - 'description', - 'Illegal zoom error', - ), - ), - ); - }, - ); + test('Should throw CameraException when illegal zoom level is supplied', () async { + // Arrange + when( + mockCameraApi.setZoomLevel(-1.0), + ).thenThrow(PlatformException(code: 'ZOOM_ERROR', message: 'Illegal zoom error')); + + // Act & assert + expect( + () => camera.setZoomLevel(cameraId, -1.0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') + .having((CameraException e) => e.description, 'description', 'Illegal zoom error'), + ), + ); + }); test('Should lock the capture orientation', () async { // Arrange // Act - await camera.lockCaptureOrientation( - cameraId, - DeviceOrientation.portraitUp, - ); + await camera.lockCaptureOrientation(cameraId, DeviceOrientation.portraitUp); // Assert - verify( - mockCameraApi.lockCaptureOrientation( - PlatformDeviceOrientation.portraitUp, - ), - ).called(1); + verify(mockCameraApi.lockCaptureOrientation(PlatformDeviceOrientation.portraitUp)).called(1); }); test('Should unlock the capture orientation', () async { diff --git a/packages/camera/camera_android/test/android_camera_test.mocks.dart b/packages/camera/camera_android/test/android_camera_test.mocks.dart index 53cd6e9489a1..5a04b8434304 100644 --- a/packages/camera/camera_android/test/android_camera_test.mocks.dart +++ b/packages/camera/camera_android/test/android_camera_test.mocks.dart @@ -27,293 +27,222 @@ import 'package:mockito/src/dummies.dart' as _i3; /// See the documentation for Mockito's code generation for more information. class MockCameraApi extends _i1.Mock implements _i2.CameraApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future> getAvailableCameras() => - (super.noSuchMethod( - Invocation.method(#getAvailableCameras, []), - returnValue: _i4.Future>.value( - <_i2.PlatformCameraDescription>[], - ), - returnValueForMissingStub: - _i4.Future>.value( - <_i2.PlatformCameraDescription>[], - ), - ) - as _i4.Future>); + _i4.Future> getAvailableCameras() => (super.noSuchMethod( + Invocation.method(#getAvailableCameras, []), + returnValue: _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + returnValueForMissingStub: _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + ) as _i4.Future>); @override - _i4.Future create( - String? cameraName, - _i2.PlatformMediaSettings? mediaSettings, - ) => + _i4.Future create(String? cameraName, _i2.PlatformMediaSettings? mediaSettings) => (super.noSuchMethod( - Invocation.method(#create, [cameraName, mediaSettings]), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) - as _i4.Future); + Invocation.method(#create, [cameraName, mediaSettings]), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) as _i4.Future); @override - _i4.Future initialize(_i2.PlatformImageFormatGroup? imageFormat) => - (super.noSuchMethod( - Invocation.method(#initialize, [imageFormat]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future initialize(_i2.PlatformImageFormatGroup? imageFormat) => (super.noSuchMethod( + Invocation.method(#initialize, [imageFormat]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future dispose() => - (super.noSuchMethod( - Invocation.method(#dispose, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future dispose() => (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future lockCaptureOrientation( - _i2.PlatformDeviceOrientation? orientation, - ) => + _i4.Future lockCaptureOrientation(_i2.PlatformDeviceOrientation? orientation) => (super.noSuchMethod( - Invocation.method(#lockCaptureOrientation, [orientation]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#lockCaptureOrientation, [orientation]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future unlockCaptureOrientation() => - (super.noSuchMethod( - Invocation.method(#unlockCaptureOrientation, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future unlockCaptureOrientation() => (super.noSuchMethod( + Invocation.method(#unlockCaptureOrientation, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future takePicture() => - (super.noSuchMethod( - Invocation.method(#takePicture, []), - returnValue: _i4.Future.value( - _i3.dummyValue(this, Invocation.method(#takePicture, [])), - ), - returnValueForMissingStub: _i4.Future.value( - _i3.dummyValue(this, Invocation.method(#takePicture, [])), - ), - ) - as _i4.Future); + _i4.Future takePicture() => (super.noSuchMethod( + Invocation.method(#takePicture, []), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + ) as _i4.Future); @override - _i4.Future startVideoRecording(bool? enableStream) => - (super.noSuchMethod( - Invocation.method(#startVideoRecording, [enableStream]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future startVideoRecording(bool? enableStream) => (super.noSuchMethod( + Invocation.method(#startVideoRecording, [enableStream]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future stopVideoRecording() => - (super.noSuchMethod( - Invocation.method(#stopVideoRecording, []), - returnValue: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#stopVideoRecording, []), - ), - ), - returnValueForMissingStub: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#stopVideoRecording, []), - ), - ), - ) - as _i4.Future); + _i4.Future stopVideoRecording() => (super.noSuchMethod( + Invocation.method(#stopVideoRecording, []), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#stopVideoRecording, [])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#stopVideoRecording, [])), + ), + ) as _i4.Future); @override - _i4.Future pauseVideoRecording() => - (super.noSuchMethod( - Invocation.method(#pauseVideoRecording, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future pauseVideoRecording() => (super.noSuchMethod( + Invocation.method(#pauseVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future resumeVideoRecording() => - (super.noSuchMethod( - Invocation.method(#resumeVideoRecording, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future resumeVideoRecording() => (super.noSuchMethod( + Invocation.method(#resumeVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future startImageStream() => - (super.noSuchMethod( - Invocation.method(#startImageStream, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future startImageStream() => (super.noSuchMethod( + Invocation.method(#startImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future stopImageStream() => - (super.noSuchMethod( - Invocation.method(#stopImageStream, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future stopImageStream() => (super.noSuchMethod( + Invocation.method(#stopImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setFlashMode(_i2.PlatformFlashMode? flashMode) => - (super.noSuchMethod( - Invocation.method(#setFlashMode, [flashMode]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setFlashMode(_i2.PlatformFlashMode? flashMode) => (super.noSuchMethod( + Invocation.method(#setFlashMode, [flashMode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setExposureMode(_i2.PlatformExposureMode? exposureMode) => - (super.noSuchMethod( - Invocation.method(#setExposureMode, [exposureMode]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setExposureMode(_i2.PlatformExposureMode? exposureMode) => (super.noSuchMethod( + Invocation.method(#setExposureMode, [exposureMode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setExposurePoint(_i2.PlatformPoint? point) => - (super.noSuchMethod( - Invocation.method(#setExposurePoint, [point]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setExposurePoint(_i2.PlatformPoint? point) => (super.noSuchMethod( + Invocation.method(#setExposurePoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getMinExposureOffset() => - (super.noSuchMethod( - Invocation.method(#getMinExposureOffset, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getMinExposureOffset() => (super.noSuchMethod( + Invocation.method(#getMinExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future getMaxExposureOffset() => - (super.noSuchMethod( - Invocation.method(#getMaxExposureOffset, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getMaxExposureOffset() => (super.noSuchMethod( + Invocation.method(#getMaxExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future getExposureOffsetStepSize() => - (super.noSuchMethod( - Invocation.method(#getExposureOffsetStepSize, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getExposureOffsetStepSize() => (super.noSuchMethod( + Invocation.method(#getExposureOffsetStepSize, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future setExposureOffset(double? offset) => - (super.noSuchMethod( - Invocation.method(#setExposureOffset, [offset]), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future setExposureOffset(double? offset) => (super.noSuchMethod( + Invocation.method(#setExposureOffset, [offset]), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future setFocusMode(_i2.PlatformFocusMode? focusMode) => - (super.noSuchMethod( - Invocation.method(#setFocusMode, [focusMode]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setFocusMode(_i2.PlatformFocusMode? focusMode) => (super.noSuchMethod( + Invocation.method(#setFocusMode, [focusMode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setFocusPoint(_i2.PlatformPoint? point) => - (super.noSuchMethod( - Invocation.method(#setFocusPoint, [point]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setFocusPoint(_i2.PlatformPoint? point) => (super.noSuchMethod( + Invocation.method(#setFocusPoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getMaxZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getMaxZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getMaxZoomLevel() => (super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future getMinZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getMinZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getMinZoomLevel() => (super.noSuchMethod( + Invocation.method(#getMinZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future setZoomLevel(double? zoom) => - (super.noSuchMethod( - Invocation.method(#setZoomLevel, [zoom]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setZoomLevel(double? zoom) => (super.noSuchMethod( + Invocation.method(#setZoomLevel, [zoom]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future pausePreview() => - (super.noSuchMethod( - Invocation.method(#pausePreview, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future pausePreview() => (super.noSuchMethod( + Invocation.method(#pausePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future resumePreview() => - (super.noSuchMethod( - Invocation.method(#resumePreview, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future resumePreview() => (super.noSuchMethod( + Invocation.method(#resumePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setDescriptionWhileRecording(String? description) => - (super.noSuchMethod( - Invocation.method(#setDescriptionWhileRecording, [description]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setDescriptionWhileRecording(String? description) => (super.noSuchMethod( + Invocation.method(#setDescriptionWhileRecording, [description]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/camera/camera_android/test/method_channel_mock.dart b/packages/camera/camera_android/test/method_channel_mock.dart index 8c9f5d8a643d..a02b6287c359 100644 --- a/packages/camera/camera_android/test/method_channel_mock.dart +++ b/packages/camera/camera_android/test/method_channel_mock.dart @@ -6,13 +6,12 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class MethodChannelMock { - MethodChannelMock({ - required String channelName, - this.delay, - required this.methods, - }) : methodChannel = MethodChannel(channelName) { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(methodChannel, _handler); + MethodChannelMock({required String channelName, this.delay, required this.methods}) + : methodChannel = MethodChannel(channelName) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + methodChannel, + _handler, + ); } final Duration? delay; diff --git a/packages/camera/camera_android/test/type_conversion_test.dart b/packages/camera/camera_android/test/type_conversion_test.dart index 77f82a5847f0..904332fc948a 100644 --- a/packages/camera/camera_android/test/type_conversion_test.dart +++ b/packages/camera/camera_android/test/type_conversion_test.dart @@ -10,25 +10,23 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('CameraImageData can be created', () { - final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 1, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final CameraImageData cameraImage = cameraImageFromPlatformData({ + 'format': 1, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.height, 1); expect(cameraImage.width, 4); expect(cameraImage.format.group, ImageFormatGroup.unknown); @@ -36,48 +34,44 @@ void main() { }); test('CameraImageData has ImageFormatGroup.yuv420', () { - final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final CameraImageData cameraImage = cameraImageFromPlatformData({ + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('CameraImageData has ImageFormatGroup.nv21', () { - final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 17, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final CameraImageData cameraImage = cameraImageFromPlatformData({ + 'format': 17, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.nv21); }); } diff --git a/packages/camera/camera_android/test/utils_test.dart b/packages/camera/camera_android/test/utils_test.dart index ed89cb10fc33..c8cf63495f13 100644 --- a/packages/camera/camera_android/test/utils_test.dart +++ b/packages/camera/camera_android/test/utils_test.dart @@ -48,14 +48,8 @@ void main() { }); test('exposureModeFromPlatform() should convert correctly', () { - expect( - exposureModeFromPlatform(PlatformExposureMode.auto), - ExposureMode.auto, - ); - expect( - exposureModeFromPlatform(PlatformExposureMode.locked), - ExposureMode.locked, - ); + expect(exposureModeFromPlatform(PlatformExposureMode.auto), ExposureMode.auto); + expect(exposureModeFromPlatform(PlatformExposureMode.locked), ExposureMode.locked); }); test('focusModeFromPlatform() should convert correctly', () { diff --git a/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart b/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart index 145186e6cd4a..41bf38381de5 100644 --- a/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart +++ b/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart @@ -43,31 +43,23 @@ void main() { testWidgets('availableCameras only supports valid back or front cameras', ( WidgetTester tester, ) async { - final List availableCameras = await CameraPlatform - .instance + final List availableCameras = await CameraPlatform.instance .availableCameras(); for (final cameraDescription in availableCameras) { - expect( - cameraDescription.lensDirection, - isNot(CameraLensDirection.external), - ); + expect(cameraDescription.lensDirection, isNot(CameraLensDirection.external)); expect(cameraDescription.sensorOrientation, anyOf(0, 90, 180, 270)); } }); - testWidgets('Preview takes expected resolution from preset', ( - WidgetTester tester, - ) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + testWidgets('Preview takes expected resolution from preset', (WidgetTester tester) async { + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final cameraDescription in cameras) { var previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { + for (final MapEntry preset in presetExpectedSizes.entries) { final controller = CameraController( cameraDescription, mediaSettings: MediaSettings(resolutionPreset: preset.key), @@ -100,15 +92,13 @@ void main() { testWidgets('Images from streaming have expected resolution from preset', ( WidgetTester tester, ) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final cameraDescription in cameras) { var previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { + for (final MapEntry preset in presetExpectedSizes.entries) { final controller = CameraController( cameraDescription, mediaSettings: MediaSettings(resolutionPreset: preset.key), @@ -148,9 +138,7 @@ void main() { final controller = CameraController( cameras[0], - mediaSettings: const MediaSettings( - resolutionPreset: ResolutionPreset.low, - ), + mediaSettings: const MediaSettings(resolutionPreset: ResolutionPreset.low), ); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -161,8 +149,7 @@ void main() { await Future.delayed(const Duration(seconds: 2)); final XFile file = await controller.stopVideoRecording(); - final int postStopTime = - DateTime.now().millisecondsSinceEpoch - recordingStart; + final int postStopTime = DateTime.now().millisecondsSinceEpoch - recordingStart; final videoFile = File(file.path); final videoController = VideoPlayerController.file(videoFile); @@ -181,9 +168,7 @@ void main() { final controller = CameraController( cameras[0], - mediaSettings: const MediaSettings( - resolutionPreset: ResolutionPreset.low, - ), + mediaSettings: const MediaSettings(resolutionPreset: ResolutionPreset.low), ); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -208,8 +193,7 @@ void main() { } final XFile file = await controller.stopVideoRecording(); - final int recordingTime = - DateTime.now().millisecondsSinceEpoch - recordingStart; + final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; final videoFile = File(file.path); final videoController = VideoPlayerController.file(videoFile); @@ -220,9 +204,7 @@ void main() { expect(duration, lessThan(recordingTime - timePaused)); }); - testWidgets('Set description while recording captures full video', ( - WidgetTester tester, - ) async { + testWidgets('Set description while recording captures full video', (WidgetTester tester) async { final List cameras = await availableCameras(); if (cameras.length < 2) { return; @@ -258,10 +240,7 @@ void main() { final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); - expect( - duration, - greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds), - ); + expect(duration, greaterThanOrEqualTo(const Duration(seconds: 4).inMilliseconds)); await controller.dispose(); }); } diff --git a/packages/camera/camera_android_camerax/example/lib/camera_controller.dart b/packages/camera/camera_android_camerax/example/lib/camera_controller.dart index 7d456043fa4a..a6f20d0bf127 100644 --- a/packages/camera/camera_android_camerax/example/lib/camera_controller.dart +++ b/packages/camera/camera_android_camerax/example/lib/camera_controller.dart @@ -179,8 +179,7 @@ class CameraValue { flashMode: flashMode ?? this.flashMode, exposureMode: exposureMode ?? this.exposureMode, focusMode: focusMode ?? this.focusMode, - exposurePointSupported: - exposurePointSupported ?? this.exposurePointSupported, + exposurePointSupported: exposurePointSupported ?? this.exposurePointSupported, focusPointSupported: focusPointSupported ?? this.focusPointSupported, deviceOrientation: deviceOrientation ?? this.deviceOrientation, lockedCaptureOrientation: lockedCaptureOrientation == null @@ -228,11 +227,8 @@ class CameraValue { /// To show the camera preview on the screen use a [CameraPreview] widget. class CameraController extends ValueNotifier { /// Creates a new camera controller in an uninitialized state. - CameraController( - CameraDescription description, { - this.mediaSettings, - this.imageFormatGroup, - }) : super(CameraValue.uninitialized(description)); + CameraController(CameraDescription description, {this.mediaSettings, this.imageFormatGroup}) + : super(CameraValue.uninitialized(description)); /// The properties of the camera device controlled by this controller. CameraDescription get description => value.description; @@ -258,8 +254,7 @@ class CameraController extends ValueNotifier { bool _isDisposed = false; StreamSubscription? _imageStreamSubscription; FutureOr? _initCalled; - StreamSubscription? - _deviceOrientationSubscription; + StreamSubscription? _deviceOrientationSubscription; /// Checks whether [CameraController.dispose] has completed successfully. /// @@ -289,11 +284,11 @@ class CameraController extends ValueNotifier { try { final initializeCompleter = Completer(); - _deviceOrientationSubscription = CameraPlatform.instance - .onDeviceOrientationChanged() - .listen((DeviceOrientationChangedEvent event) { - value = value.copyWith(deviceOrientation: event.orientation); - }); + _deviceOrientationSubscription = CameraPlatform.instance.onDeviceOrientationChanged().listen(( + DeviceOrientationChangedEvent event, + ) { + value = value.copyWith(deviceOrientation: event.orientation); + }); _cameraId = await CameraPlatform.instance.createCameraWithSettings( description, @@ -316,8 +311,7 @@ class CameraController extends ValueNotifier { value = value.copyWith( isInitialized: true, previewSize: await initializeCompleter.future.then( - (CameraInitializedEvent event) => - Size(event.previewWidth, event.previewHeight), + (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight), ), exposureMode: await initializeCompleter.future.then( (CameraInitializedEvent event) => event.exposureMode, @@ -447,11 +441,11 @@ class CameraController extends ValueNotifier { } try { - _imageStreamSubscription = CameraPlatform.instance - .onStreamedFrameAvailable(_cameraId) - .listen((CameraImageData imageData) { - onAvailable(CameraImage.fromPlatformInterface(imageData)); - }); + _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen( + (CameraImageData imageData) { + onAvailable(CameraImage.fromPlatformInterface(imageData)); + }, + ); value = value.copyWith(isStreamingImages: true); } on PlatformException catch (e) { throw CameraException(e.code, e.message); @@ -556,9 +550,7 @@ class CameraController extends ValueNotifier { } try { - final XFile file = await CameraPlatform.instance.stopVideoRecording( - _cameraId, - ); + final XFile file = await CameraPlatform.instance.stopVideoRecording(_cameraId); value = value.copyWith( isRecordingVideo: false, recordingOrientation: const Optional.absent(), @@ -691,11 +683,8 @@ class CameraController extends ValueNotifier { /// Supplying a `null` value will reset the exposure point to it's default /// value. Future setExposurePoint(Offset? point) async { - if (point != null && - (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { - throw ArgumentError( - 'The values of point should be anywhere between (0,0) and (1,1).', - ); + if (point != null && (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { + throw ArgumentError('The values of point should be anywhere between (0,0) and (1,1).'); } try { @@ -818,9 +807,7 @@ class CameraController extends ValueNotifier { Future unlockCaptureOrientation() async { try { await CameraPlatform.instance.unlockCaptureOrientation(_cameraId); - value = value.copyWith( - lockedCaptureOrientation: const Optional.absent(), - ); + value = value.copyWith(lockedCaptureOrientation: const Optional.absent()); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -831,11 +818,8 @@ class CameraController extends ValueNotifier { /// Supplying a `null` value will reset the focus point to it's default /// value. Future setFocusPoint(Offset? point) async { - if (point != null && - (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { - throw ArgumentError( - 'The values of point should be anywhere between (0,0) and (1,1).', - ); + if (point != null && (point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) { + throw ArgumentError('The values of point should be anywhere between (0,0) and (1,1).'); } try { await CameraPlatform.instance.setFocusPoint( @@ -955,9 +939,7 @@ class Optional extends IterableBase { /// /// The transformer must not return `null`. If it does, an [ArgumentError] is thrown. Optional transform(S Function(T value) transformer) { - return _value == null - ? Optional.absent() - : Optional.of(transformer(_value as T)); + return _value == null ? Optional.absent() : Optional.of(transformer(_value as T)); } /// Transforms the Optional value. @@ -972,8 +954,7 @@ class Optional extends IterableBase { } @override - Iterator get iterator => - isPresent ? [_value as T].iterator : Iterable.empty().iterator; + Iterator get iterator => isPresent ? [_value as T].iterator : Iterable.empty().iterator; /// Delegates to the underlying [value] hashCode. @override @@ -985,8 +966,6 @@ class Optional extends IterableBase { @override String toString() { - return _value == null - ? 'Optional { absent }' - : 'Optional { value: $_value }'; + return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }'; } } diff --git a/packages/camera/camera_android_camerax/example/lib/camera_image.dart b/packages/camera/camera_android_camerax/example/lib/camera_image.dart index ff7de7a735b6..d6c144bebf01 100644 --- a/packages/camera/camera_android_camerax/example/lib/camera_image.dart +++ b/packages/camera/camera_android_camerax/example/lib/camera_image.dart @@ -122,9 +122,7 @@ class CameraImage { height = data.height, width = data.width, planes = List.unmodifiable( - data.planes.map( - (CameraImagePlane plane) => Plane._fromPlatformInterface(plane), - ), + data.planes.map((CameraImagePlane plane) => Plane._fromPlatformInterface(plane)), ), lensAperture = data.lensAperture, sensorExposureTime = data.sensorExposureTime, @@ -141,8 +139,7 @@ class CameraImage { sensorSensitivity = data['sensorSensitivity'] as double?, planes = List.unmodifiable( (data['planes'] as List).map( - (dynamic planeData) => - Plane._fromPlatformData(planeData as Map), + (dynamic planeData) => Plane._fromPlatformData(planeData as Map), ), ); diff --git a/packages/camera/camera_android_camerax/example/lib/main.dart b/packages/camera/camera_android_camerax/example/lib/main.dart index c3aba39ed60f..f53ed1433020 100644 --- a/packages/camera/camera_android_camerax/example/lib/main.dart +++ b/packages/camera/camera_android_camerax/example/lib/main.dart @@ -126,6 +126,7 @@ class _CameraExampleHomeState extends State _initializeCameraController(cameraController.description); } } + // #enddocregion AppLifecycle @override @@ -139,8 +140,7 @@ class _CameraExampleHomeState extends State decoration: BoxDecoration( color: Colors.black, border: Border.all( - color: - controller != null && controller!.value.isRecordingVideo + color: controller != null && controller!.value.isRecordingVideo ? Colors.redAccent : Colors.grey, width: 3.0, @@ -156,9 +156,7 @@ class _CameraExampleHomeState extends State _modeControlRowWidget(), Padding( padding: const EdgeInsets.all(5.0), - child: Row( - children: [_cameraTogglesRowWidget(), _thumbnailWidget()], - ), + child: Row(children: [_cameraTogglesRowWidget(), _thumbnailWidget()]), ), ], ), @@ -172,11 +170,7 @@ class _CameraExampleHomeState extends State if (cameraController == null || !cameraController.value.isInitialized) { return const Text( 'Tap a camera', - style: TextStyle( - color: Colors.white, - fontSize: 24.0, - fontWeight: FontWeight.w900, - ), + style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900), ); } else { return Listener( @@ -190,8 +184,7 @@ class _CameraExampleHomeState extends State behavior: HitTestBehavior.opaque, onScaleStart: _handleScaleStart, onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), + onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints), ); }, ), @@ -210,10 +203,7 @@ class _CameraExampleHomeState extends State return; } - _currentScale = (_baseScale * details.scale).clamp( - _minAvailableZoom, - _maxAvailableZoom, - ); + _currentScale = (_baseScale * details.scale).clamp(_minAvailableZoom, _maxAvailableZoom); await controller!.setZoomLevel(_currentScale); } @@ -240,13 +230,9 @@ class _CameraExampleHomeState extends State // pointing to a location within the browser. It may be displayed // either with Image.network or Image.memory after loading the image // bytes to memory. - kIsWeb - ? Image.network(imageFile!.path) - : Image.file(File(imageFile!.path))) + kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path))) : Container( - decoration: BoxDecoration( - border: Border.all(color: Colors.pink), - ), + decoration: BoxDecoration(border: Border.all(color: Colors.pink)), child: Center( child: AspectRatio( aspectRatio: localVideoController.value.aspectRatio, @@ -279,16 +265,12 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.exposure), color: Colors.blue, - onPressed: controller != null - ? onExposureModeButtonPressed - : null, + onPressed: controller != null ? onExposureModeButtonPressed : null, ), IconButton( icon: const Icon(Icons.filter_center_focus), color: Colors.blue, - onPressed: controller != null - ? onFocusModeButtonPressed - : null, + onPressed: controller != null ? onFocusModeButtonPressed : null, ), ] : [], @@ -304,9 +286,7 @@ class _CameraExampleHomeState extends State : Icons.screen_rotation, ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null, ), ], ), @@ -326,36 +306,28 @@ class _CameraExampleHomeState extends State children: [ IconButton( icon: const Icon(Icons.flash_off), - color: controller?.value.flashMode == FlashMode.off - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.off ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.off) : null, ), IconButton( icon: const Icon(Icons.flash_auto), - color: controller?.value.flashMode == FlashMode.auto - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.auto ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.auto) : null, ), IconButton( icon: const Icon(Icons.flash_on), - color: controller?.value.flashMode == FlashMode.always - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.always ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.always) : null, ), IconButton( icon: const Icon(Icons.highlight), - color: controller?.value.flashMode == FlashMode.torch - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.torch) : null, @@ -392,15 +364,11 @@ class _CameraExampleHomeState extends State TextButton( style: styleAuto, onPressed: controller != null - ? () => - onSetExposureModeButtonPressed(ExposureMode.auto) + ? () => onSetExposureModeButtonPressed(ExposureMode.auto) : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance.setExposurePoint( - controller!.cameraId, - null, - ); + CameraPlatform.instance.setExposurePoint(controller!.cameraId, null); showInSnackBar('Resetting exposure point'); } }, @@ -409,17 +377,13 @@ class _CameraExampleHomeState extends State TextButton( style: styleLocked, onPressed: controller != null - ? () => onSetExposureModeButtonPressed( - ExposureMode.locked, - ) + ? () => onSetExposureModeButtonPressed(ExposureMode.locked) : null, child: const Text('LOCKED'), ), TextButton( style: styleLocked, - onPressed: controller != null - ? () => controller!.setExposureOffset(0.0) - : null, + onPressed: controller != null ? () => controller!.setExposureOffset(0.0) : null, child: const Text('RESET OFFSET'), ), ], @@ -435,9 +399,7 @@ class _CameraExampleHomeState extends State max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), onChanged: (_) {}, - onChangeEnd: - _minAvailableExposureOffset == - _maxAvailableExposureOffset + onChangeEnd: _minAvailableExposureOffset == _maxAvailableExposureOffset ? null : setExposureOffset, ), @@ -453,9 +415,7 @@ class _CameraExampleHomeState extends State Widget _focusModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - foregroundColor: controller?.value.focusMode == FocusMode.auto - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.focusMode == FocusMode.auto ? Colors.orange : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( foregroundColor: controller?.value.focusMode == FocusMode.locked @@ -481,10 +441,7 @@ class _CameraExampleHomeState extends State : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance.setFocusPoint( - controller!.cameraId, - null, - ); + CameraPlatform.instance.setFocusPoint(controller!.cameraId, null); } showInSnackBar('Resetting focus point'); }, @@ -526,14 +483,10 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.videocam), color: Colors.blue, - onPressed: cameraController == null - ? null - : onVideoRecordButtonPressed, + onPressed: cameraController == null ? null : onVideoRecordButtonPressed, ), IconButton( - icon: - cameraController != null && - cameraController.value.isRecordingPaused + icon: cameraController != null && cameraController.value.isRecordingPaused ? const Icon(Icons.play_arrow) : const Icon(Icons.pause), color: Colors.blue, @@ -554,13 +507,10 @@ class _CameraExampleHomeState extends State ), IconButton( icon: const Icon(Icons.pause_presentation), - color: - cameraController != null && cameraController.value.isPreviewPaused + color: cameraController != null && cameraController.value.isPreviewPaused ? Colors.red : Colors.blue, - onPressed: cameraController == null - ? null - : onPausePreviewButtonPressed, + onPressed: cameraController == null ? null : onPausePreviewButtonPressed, ), ], ); @@ -607,9 +557,7 @@ class _CameraExampleHomeState extends State String timestamp() => DateTime.now().millisecondsSinceEpoch.toString(); void showInSnackBar(String message) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message))); } void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) { @@ -635,9 +583,7 @@ class _CameraExampleHomeState extends State } } - Future _initializeCameraController( - CameraDescription cameraDescription, - ) async { + Future _initializeCameraController(CameraDescription cameraDescription) async { final cameraController = CameraController( cameraDescription, mediaSettings: MediaSettings( @@ -658,9 +604,7 @@ class _CameraExampleHomeState extends State setState(() {}); } if (cameraController.value.hasError) { - showInSnackBar( - 'Camera error ${cameraController.value.errorDescription}', - ); + showInSnackBar('Camera error ${cameraController.value.errorDescription}'); } }); @@ -678,12 +622,8 @@ class _CameraExampleHomeState extends State ), ] : >[], - cameraController.getMaxZoomLevel().then( - (double value) => _maxAvailableZoom = value, - ), - cameraController.getMinZoomLevel().then( - (double value) => _minAvailableZoom = value, - ), + cameraController.getMaxZoomLevel().then((double value) => _maxAvailableZoom = value), + cameraController.getMinZoomLevel().then((double value) => _minAvailableZoom = value), ]); } on CameraException catch (e) { switch (e.code) { diff --git a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart index e52e4bd09cf1..41a44ac4cd85 100644 --- a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart +++ b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart @@ -8,8 +8,7 @@ import 'dart:math' show Point; import 'package:async/async.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/foundation.dart' show Uint8List; -import 'package:flutter/services.dart' - show DeviceOrientation, PlatformException; +import 'package:flutter/services.dart' show DeviceOrientation, PlatformException; import 'package:flutter/widgets.dart' show Texture, Widget, visibleForTesting; import 'package:stream_transform/stream_transform.dart'; import 'camerax_library.dart'; @@ -71,28 +70,24 @@ class AndroidCameraCameraX extends CameraPlatform { String? videoOutputPath; /// Handles access to system resources. - late final SystemServicesManager systemServicesManager = - SystemServicesManager( - onCameraError: (_, String errorDescription) { - cameraErrorStreamController.add(errorDescription); - }, - ); + late final SystemServicesManager systemServicesManager = SystemServicesManager( + onCameraError: (_, String errorDescription) { + cameraErrorStreamController.add(errorDescription); + }, + ); /// Handles retrieving media orientation for a device. - late final DeviceOrientationManager deviceOrientationManager = - DeviceOrientationManager( - onDeviceOrientationChanged: (_, String orientation) { - final DeviceOrientation deviceOrientation = - _deserializeDeviceOrientation(orientation); - deviceOrientationChangedStreamController.add( - DeviceOrientationChangedEvent(deviceOrientation), - ); - }, + late final DeviceOrientationManager deviceOrientationManager = DeviceOrientationManager( + onDeviceOrientationChanged: (_, String orientation) { + final DeviceOrientation deviceOrientation = _deserializeDeviceOrientation(orientation); + deviceOrientationChangedStreamController.add( + DeviceOrientationChangedEvent(deviceOrientation), ); + }, + ); /// Stream that emits an event when the corresponding video recording is finalized. - static final StreamController - videoRecordingEventStreamController = + static final StreamController videoRecordingEventStreamController = StreamController.broadcast(); /// Stream that emits the errors caused by camera usage on the native side. @@ -112,12 +107,11 @@ class AndroidCameraCameraX extends CameraPlatform { final StreamQueue videoRecordingEventStreamQueue = StreamQueue(videoRecordingEventStreamController.stream); - late final VideoRecordEventListener _videoRecordingEventListener = - VideoRecordEventListener( - onEvent: (_, VideoRecordEvent event) { - videoRecordingEventStreamController.add(event); - }, - ); + late final VideoRecordEventListener _videoRecordingEventListener = VideoRecordEventListener( + onEvent: (_, VideoRecordEvent event) { + videoRecordingEventStreamController.add(event); + }, + ); /// Whether or not [preview] has been bound to the lifecycle of the camera by /// [createCamera]. @@ -161,9 +155,8 @@ class AndroidCameraCameraX extends CameraPlatform { StreamController.broadcast(); /// The stream of camera events for the camera with ID cameraId. - Stream _cameraEvents(int cameraId) => cameraEventStreamController - .stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => + cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId); /// The controller we need to stream image data. @visibleForTesting @@ -217,8 +210,7 @@ class AndroidCameraCameraX extends CameraPlatform { bool shouldSetDefaultRotation = false; /// Error code indicating that an exposure offset value failed to be set. - static const String setExposureOffsetFailedErrorCode = - 'setExposureOffsetFailed'; + static const String setExposureOffsetFailedErrorCode = 'setExposureOffsetFailed'; /// The currently set [FocusMeteringAction] used to enable auto-focus and /// auto-exposure. @@ -245,8 +237,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// Error code indicating that exposure compensation is not supported by /// CameraX for the device. - static const String exposureCompensationNotSupported = - 'exposureCompensationNotSupported'; + static const String exposureCompensationNotSupported = 'exposureCompensationNotSupported'; /// Whether or not the created camera is front facing. @visibleForTesting @@ -299,8 +290,8 @@ class AndroidCameraCameraX extends CameraPlatform { final cameraDescriptions = []; processCameraProvider ??= await ProcessCameraProvider.getInstance(); - final List cameraInfos = - (await processCameraProvider!.getAvailableCameraInfos()).cast(); + final List cameraInfos = (await processCameraProvider!.getAvailableCameraInfos()) + .cast(); CameraLensDirection? cameraLensDirection; int? cameraSensorOrientation; @@ -321,9 +312,7 @@ class AndroidCameraCameraX extends CameraPlatform { } cameraSensorOrientation = cameraInfo.sensorRotationDegrees; - cameraName = await Camera2CameraInfo.from( - cameraInfo: cameraInfo, - ).getCameraId(); + cameraName = await Camera2CameraInfo.from(cameraInfo: cameraInfo).getCameraId(); _savedCameras[cameraName] = cameraInfo; @@ -374,8 +363,9 @@ class AndroidCameraCameraX extends CameraPlatform { MediaSettings? mediaSettings, ) async { enableRecordingAudio = mediaSettings?.enableAudio ?? false; - final CameraPermissionsError? error = await systemServicesManager - .requestCameraPermissions(enableRecordingAudio); + final CameraPermissionsError? error = await systemServicesManager.requestCameraPermissions( + enableRecordingAudio, + ); if (error != null) { throw CameraException(error.errorCode, error.description); @@ -384,27 +374,25 @@ class AndroidCameraCameraX extends CameraPlatform { final CameraInfo? chosenCameraInfo = _savedCameras[cameraDescription.name]; // Save CameraSelector that matches cameraDescription. - final LensFacing cameraSelectorLensDirection = - _getCameraSelectorLensDirection(cameraDescription.lensDirection); + final LensFacing cameraSelectorLensDirection = _getCameraSelectorLensDirection( + cameraDescription.lensDirection, + ); cameraIsFrontFacing = cameraSelectorLensDirection == LensFacing.front; cameraSelector = CameraSelector(cameraInfoForFilter: chosenCameraInfo); // Start listening for device orientation changes preceding camera creation. - unawaited( - deviceOrientationManager.startListeningForDeviceOrientationChange(), - ); + unawaited(deviceOrientationManager.startListeningForDeviceOrientationChange()); // Determine ResolutionSelector and QualitySelector based on // resolutionPreset for camera UseCases. - _presetResolutionSelector = _getResolutionSelectorFromPreset( - mediaSettings?.resolutionPreset, - ); + _presetResolutionSelector = _getResolutionSelectorFromPreset(mediaSettings?.resolutionPreset); final int? targetFps = mediaSettings?.fps; if (targetFps != null) { _targetFpsRange = CameraIntegerRange(lower: targetFps, upper: targetFps); } - final QualitySelector? presetQualitySelector = - _getQualitySelectorFromPreset(mediaSettings?.resolutionPreset); + final QualitySelector? presetQualitySelector = _getQualitySelectorFromPreset( + mediaSettings?.resolutionPreset, + ); // Retrieve a fresh ProcessCameraProvider instance. processCameraProvider ??= await ProcessCameraProvider.getInstance(); @@ -415,34 +403,27 @@ class AndroidCameraCameraX extends CameraPlatform { resolutionSelector: _presetResolutionSelector, targetFpsRange: _targetFpsRange, ); - _flutterSurfaceTextureId = await preview!.setSurfaceProvider( - systemServicesManager, - ); + _flutterSurfaceTextureId = await preview!.setSurfaceProvider(systemServicesManager); // Configure ImageCapture instance. imageCapture = ImageCapture( resolutionSelector: _presetResolutionSelector, - /* use CameraX default target rotation */ targetRotation: - await deviceOrientationManager.getDefaultDisplayRotation(), + /* use CameraX default target rotation */ targetRotation: await deviceOrientationManager + .getDefaultDisplayRotation(), ); // Configure VideoCapture and Recorder instances. recorder = Recorder(qualitySelector: presetQualitySelector); - videoCapture = VideoCapture.withOutput( - videoOutput: recorder!, - targetFpsRange: _targetFpsRange, - ); + videoCapture = VideoCapture.withOutput(videoOutput: recorder!, targetFpsRange: _targetFpsRange); // Retrieve info required for correcting the rotation of the camera preview // if necessary. sensorOrientationDegrees = cameraDescription.sensorOrientation.toDouble(); - _handlesCropAndRotation = await preview! - .surfaceProducerHandlesCropAndRotation(); + _handlesCropAndRotation = await preview!.surfaceProducerHandlesCropAndRotation(); _initialDeviceOrientation = _deserializeDeviceOrientation( await deviceOrientationManager.getUiOrientation(), ); - _initialDefaultDisplayRotation = await deviceOrientationManager - .getDefaultDisplayRotation(); + _initialDefaultDisplayRotation = await deviceOrientationManager.getDefaultDisplayRotation(); return _flutterSurfaceTextureId; } @@ -474,8 +455,9 @@ class AndroidCameraCameraX extends CameraPlatform { } // Configure ImageAnalysis instance. // Defaults to YUV_420_888 image format. - _imageAnalysisOutputImageFormat = - _imageAnalysisOutputFormatFromImageFormatGroup(imageFormatGroup); + _imageAnalysisOutputImageFormat = _imageAnalysisOutputFormatFromImageFormatGroup( + imageFormatGroup, + ); imageAnalysis = ImageAnalysis( resolutionSelector: _presetResolutionSelector, targetFpsRange: _targetFpsRange, @@ -485,10 +467,11 @@ class AndroidCameraCameraX extends CameraPlatform { // Bind configured UseCases to ProcessCameraProvider instance & mark Preview // instance as bound but not paused. Video capture is bound at first use // instead of here. - camera = await processCameraProvider!.bindToLifecycle( - cameraSelector!, - [preview!, imageCapture!, imageAnalysis!], - ); + camera = await processCameraProvider!.bindToLifecycle(cameraSelector!, [ + preview!, + imageCapture!, + imageAnalysis!, + ]); await _updateCameraInfoAndLiveCameraState(_flutterSurfaceTextureId); previewInitiallyBound = true; _previewIsPaused = false; @@ -497,8 +480,7 @@ class AndroidCameraCameraX extends CameraPlatform { // configured camera: // Retrieve preview resolution. - final ResolutionInfo previewResolutionInfo = (await preview! - .getResolutionInfo())!; + final ResolutionInfo previewResolutionInfo = (await preview!.getResolutionInfo())!; // Mark auto-focus, auto-exposure and setting points for focus & exposure // as available operations as CameraX does its best across devices to @@ -554,16 +536,12 @@ class AndroidCameraCameraX extends CameraPlatform { /// The camera with ID [cameraId] experienced an error. @override Stream onCameraError(int cameraId) { - return StreamGroup.mergeBroadcast( - >[ - cameraErrorStreamController.stream.map(( - String errorDescription, - ) { - return CameraErrorEvent(cameraId, errorDescription); - }), - _cameraEvents(cameraId).whereType(), - ], - ); + return StreamGroup.mergeBroadcast(>[ + cameraErrorStreamController.stream.map((String errorDescription) { + return CameraErrorEvent(cameraId, errorDescription); + }), + _cameraEvents(cameraId).whereType(), + ]); } /// The camera with ID [cameraId] finished recording a video. @@ -574,10 +552,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// Locks the capture orientation of camera with ID [cameraId]. @override - Future lockCaptureOrientation( - int cameraId, - DeviceOrientation orientation, - ) async { + Future lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async { // Flag that (1) default rotation for UseCases will need to be set manually // if orientation is ever unlocked and (2) the capture orientation is locked // and should not be changed until unlocked. @@ -585,9 +560,7 @@ class AndroidCameraCameraX extends CameraPlatform { captureOrientationLocked = true; // Get target rotation based on locked orientation. - final int targetLockedRotation = _getRotationConstantFromDeviceOrientation( - orientation, - ); + final int targetLockedRotation = _getRotationConstantFromDeviceOrientation(orientation); // Update UseCases to use target device orientation. await imageCapture!.setTargetRotation(targetLockedRotation); @@ -628,16 +601,14 @@ class AndroidCameraCameraX extends CameraPlatform { @override Future getMinExposureOffset(int cameraId) async { final ExposureState exposureState = cameraInfo!.exposureState; - return exposureState.exposureCompensationRange.lower * - exposureState.exposureCompensationStep; + return exposureState.exposureCompensationRange.lower * exposureState.exposureCompensationStep; } /// Gets the maximum supported exposure offset for the camera with ID [cameraId] in EV units. @override Future getMaxExposureOffset(int cameraId) async { final ExposureState exposureState = cameraInfo!.exposureState; - return exposureState.exposureCompensationRange.upper * - exposureState.exposureCompensationStep; + return exposureState.exposureCompensationRange.upper * exposureState.exposureCompensationStep; } /// Sets the focus mode for taking pictures with camera with ID [cameraId] @@ -674,9 +645,7 @@ class AndroidCameraCameraX extends CameraPlatform { if (currentFocusMeteringAction != null) { final List possibleCurrentAfPoints = currentFocusMeteringAction!.meteringPointsAf; - lockedFocusPoint = possibleCurrentAfPoints.isEmpty - ? null - : possibleCurrentAfPoints.first; + lockedFocusPoint = possibleCurrentAfPoints.isEmpty ? null : possibleCurrentAfPoints.first; } // If there isn't, lock center of entire sensor area by default. @@ -686,11 +655,7 @@ class AndroidCameraCameraX extends CameraPlatform { width: 1, height: 1, ); - lockedFocusPoint = await meteringPointFactory.createPointWithSize( - 0.5, - 0.5, - 1, - ); + lockedFocusPoint = await meteringPointFactory.createPointWithSize(0.5, 0.5, 1); _defaultFocusPointLocked = true; } @@ -715,8 +680,7 @@ class AndroidCameraCameraX extends CameraPlatform { // If focus mode was just locked and exposure mode is not, set auto exposure // mode to ensure that disabling auto-cancel does not interfere with // automatic exposure metering. - if (_currentExposureMode == ExposureMode.auto && - _currentFocusMode == FocusMode.locked) { + if (_currentExposureMode == ExposureMode.auto && _currentFocusMode == FocusMode.locked) { await setExposureMode(cameraId, _currentExposureMode); } } @@ -727,8 +691,7 @@ class AndroidCameraCameraX extends CameraPlatform { @override Future getExposureOffsetStepSize(int cameraId) async { final ExposureState exposureState = cameraInfo!.exposureState; - final double exposureOffsetStepSize = - exposureState.exposureCompensationStep; + final double exposureOffsetStepSize = exposureState.exposureCompensationStep; if (exposureOffsetStepSize == 0) { // CameraX returns a step size of 0 if exposure compensation is not // supported for the device. @@ -752,8 +715,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// Returns the (rounded) offset value that was set. @override Future setExposureOffset(int cameraId, double offset) async { - final double exposureOffsetStepSize = - cameraInfo!.exposureState.exposureCompensationStep; + final double exposureOffsetStepSize = cameraInfo!.exposureState.exposureCompensationStep; if (exposureOffsetStepSize == 0) { throw CameraException( exposureCompensationNotSupported, @@ -763,8 +725,7 @@ class AndroidCameraCameraX extends CameraPlatform { // (Exposure compensation index) * (exposure offset step size) = // (exposure offset). - final int roundedExposureCompensationIndex = - (offset / exposureOffsetStepSize).round(); + final int roundedExposureCompensationIndex = (offset / exposureOffsetStepSize).round(); try { final int? newIndex = await cameraControl.setExposureCompensationIndex( @@ -824,15 +785,11 @@ class AndroidCameraCameraX extends CameraPlatform { /// is unset by setting [ExposureMode.auto]. @override Future setExposureMode(int cameraId, ExposureMode mode) async { - final camera2Control = Camera2CameraControl.from( - cameraControl: cameraControl, - ); + final camera2Control = Camera2CameraControl.from(cameraControl: cameraControl); final lockExposureMode = mode == ExposureMode.locked; final captureRequestOptions = CaptureRequestOptions( - options: { - CaptureRequest.controlAELock: lockExposureMode, - }, + options: {CaptureRequest.controlAELock: lockExposureMode}, ); try { @@ -895,19 +852,14 @@ class AndroidCameraCameraX extends CameraPlatform { } @override - Future> getSupportedVideoStabilizationModes( - int cameraId, - ) async { + Future> getSupportedVideoStabilizationModes(int cameraId) async { return (await _getSupportedVideoStabilizationModeMap(cameraId)).keys; } /// Throws a [ArgumentError] when an unsupported [mode] is /// supplied. @override - Future setVideoStabilizationMode( - int cameraId, - VideoStabilizationMode mode, - ) async { + Future setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) async { final Map availableModes = await _getSupportedVideoStabilizationModeMap(cameraId); @@ -922,16 +874,15 @@ class AndroidCameraCameraX extends CameraPlatform { }, ); - final camera2Control = Camera2CameraControl.from( - cameraControl: cameraControl, - ); + final camera2Control = Camera2CameraControl.from(cameraControl: cameraControl); await camera2Control.addCaptureRequestOptions(captureRequestOptions); } /// Gets a map of video stabilization control modes that are supported for the /// selected camera, indexed by the respective [VideoStabilizationMode]. - Future> - _getSupportedVideoStabilizationModeMap(int cameraId) async { + Future> _getSupportedVideoStabilizationModeMap( + int cameraId, + ) async { if (cameraInfo == null) { return {}; } @@ -940,9 +891,8 @@ class AndroidCameraCameraX extends CameraPlatform { final List controlModes = await camera2CameraInfo.getCameraCharacteristic( - CameraCharacteristics.controlAvailableVideoStabilizationModes, - ) - as List? ?? + CameraCharacteristics.controlAvailableVideoStabilizationModes, + ) as List? ?? const []; final modes = { @@ -977,20 +927,17 @@ class AndroidCameraCameraX extends CameraPlatform { /// you must start the recording with [startVideoCapturing] /// with `enablePersistentRecording` set to `true`. @override - Future setDescriptionWhileRecording( - CameraDescription description, - ) async { + Future setDescriptionWhileRecording(CameraDescription description) async { if (recording == null) { - cameraErrorStreamController.add( - 'Camera description not set. No active video recording.', - ); + cameraErrorStreamController.add('Camera description not set. No active video recording.'); return; } final CameraInfo? chosenCameraInfo = _savedCameras[description.name]; // Save CameraSelector that matches cameraDescription. - final LensFacing cameraSelectorLensDirection = - _getCameraSelectorLensDirection(description.lensDirection); + final LensFacing cameraSelectorLensDirection = _getCameraSelectorLensDirection( + description.lensDirection, + ); cameraIsFrontFacing = cameraSelectorLensDirection == LensFacing.front; cameraSelector = CameraSelector(cameraInfoForFilter: chosenCameraInfo); @@ -999,19 +946,14 @@ class AndroidCameraCameraX extends CameraPlatform { if (!_previewIsPaused) { useCases.add(preview!); } - if (imageCapture != null && - await processCameraProvider!.isBound(imageCapture!)) { + if (imageCapture != null && await processCameraProvider!.isBound(imageCapture!)) { useCases.add(imageCapture!); } - if (imageAnalysis != null && - await processCameraProvider!.isBound(imageAnalysis!)) { + if (imageAnalysis != null && await processCameraProvider!.isBound(imageAnalysis!)) { useCases.add(imageAnalysis!); } await processCameraProvider?.unbindAll(); - camera = await processCameraProvider?.bindToLifecycle( - cameraSelector!, - useCases, - ); + camera = await processCameraProvider?.bindToLifecycle(cameraSelector!, useCases); // Retrieve info required for correcting the rotation of the camera preview sensorOrientationDegrees = description.sensorOrientation.toDouble(); @@ -1042,10 +984,9 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - final Stream deviceOrientationStream = - onDeviceOrientationChanged().map( - (DeviceOrientationChangedEvent e) => e.orientation, - ); + final Stream deviceOrientationStream = onDeviceOrientationChanged().map( + (DeviceOrientationChangedEvent e) => e.orientation, + ); final Widget preview = Texture(textureId: cameraId); return RotatedPreviewDelegate( @@ -1081,9 +1022,7 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - final String picturePath = await imageCapture!.takePicture( - systemServicesManager, - ); + final String picturePath = await imageCapture!.takePicture(systemServicesManager); return XFile(picturePath); } @@ -1145,10 +1084,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// /// This method is deprecated in favour of [startVideoCapturing]. @override - Future startVideoRecording( - int cameraId, { - Duration? maxVideoDuration, - }) async { + Future startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -1164,8 +1100,7 @@ class AndroidCameraCameraX extends CameraPlatform { // There is currently an active recording, so do not start a new one. return; } - final dynamic Function(CameraImageData)? streamCallback = - options.streamCallback; + final dynamic Function(CameraImageData)? streamCallback = options.streamCallback; if (streamCallback == null) { // For potential performance improvements, unbind imageAnalysis if not in use. // See https://developer.android.com/media/camera/camerax/architecture#combine-use-cases @@ -1183,10 +1118,7 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - videoOutputPath = await systemServicesManager.getTempFilePath( - videoPrefix, - '.mp4', - ); + videoOutputPath = await systemServicesManager.getTempFilePath(videoPrefix, '.mp4'); pendingRecording = await recorder!.prepareRecording(videoOutputPath!); if (options.enablePersistentRecording) { @@ -1251,9 +1183,7 @@ class AndroidCameraCameraX extends CameraPlatform { await _unbindUseCaseFromLifecycle(videoCapture!); final videoFile = XFile(videoOutputPath!); - cameraEventStreamController.add( - VideoRecordedEvent(cameraId, videoFile, /* duration */ null), - ); + cameraEventStreamController.add(VideoRecordedEvent(cameraId, videoFile, /* duration */ null)); return videoFile; } @@ -1321,10 +1251,7 @@ class AndroidCameraCameraX extends CameraPlatform { return; } - camera = await processCameraProvider!.bindToLifecycle( - cameraSelector!, - [useCase], - ); + camera = await processCameraProvider!.bindToLifecycle(cameraSelector!, [useCase]); await _updateCameraInfoAndLiveCameraState(cameraId); } @@ -1348,8 +1275,7 @@ class AndroidCameraCameraX extends CameraPlatform { final cameraImagePlanes = []; // Determine image planes. - if (_imageAnalysisOutputImageFormat == - imageAnalysisOutputImageFormatNv21) { + if (_imageAnalysisOutputImageFormat == imageAnalysisOutputImageFormatNv21) { // Convert three generically YUV_420_888 formatted image planes into one singular // NV21 formatted image plane if NV21 was requested for image streaming. The conversion // should be null safe. @@ -1383,8 +1309,7 @@ class AndroidCameraCameraX extends CameraPlatform { // Determine image format. CameraImageFormat? cameraImageFormat; - if (_imageAnalysisOutputImageFormat == - imageAnalysisOutputImageFormatNv21) { + if (_imageAnalysisOutputImageFormat == imageAnalysisOutputImageFormatNv21) { // Manually override ImageFormat to NV21 if set for image streaming as CameraX // still reports YUV_420_888 if the underlying format is NV21. cameraImageFormat = const CameraImageFormat( @@ -1411,9 +1336,7 @@ class AndroidCameraCameraX extends CameraPlatform { await imageProxy.close(); } - await imageAnalysis!.setAnalyzer( - Analyzer(analyze: (_, ImageProxy image) => analyze(image)), - ); + await imageAnalysis!.setAnalyzer(Analyzer(analyze: (_, ImageProxy image) => analyze(image))); } /// Unbinds [useCase] from camera lifecycle controlled by the @@ -1496,9 +1419,7 @@ class AndroidCameraCameraX extends CameraPlatform { // Callback method used to implement the behavior described above: void onChanged(CameraState state) { if (state.type == CameraStateType.closing) { - weakThis.target!.cameraEventStreamController.add( - CameraClosingEvent(cameraId), - ); + weakThis.target!.cameraEventStreamController.add(CameraClosingEvent(cameraId)); } if (state.error != null) { late final String errorDescription; @@ -1524,8 +1445,7 @@ class AndroidCameraCameraX extends CameraPlatform { errorDescription = 'The camera could not be opened because "Do Not Disturb" mode is enabled. Please disable this mode, and try opening the camera again.'; case CameraStateErrorCode.unknown: - errorDescription = - 'There was an unspecified issue with the current camera state.'; + errorDescription = 'There was an unspecified issue with the current camera state.'; } weakThis.target!.cameraEventStreamController.add( CameraErrorEvent(cameraId, errorDescription), @@ -1533,18 +1453,14 @@ class AndroidCameraCameraX extends CameraPlatform { } } - return Observer( - onChanged: (_, CameraState value) => onChanged(value), - ); + return Observer(onChanged: (_, CameraState value) => onChanged(value)); } // Methods for mapping Flutter camera constants to CameraX constants: /// Returns [CameraSelector] lens direction that maps to specified /// [CameraLensDirection]. - LensFacing _getCameraSelectorLensDirection( - CameraLensDirection lensDirection, - ) { + LensFacing _getCameraSelectorLensDirection(CameraLensDirection lensDirection) { switch (lensDirection) { case CameraLensDirection.front: return LensFacing.front; @@ -1576,9 +1492,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// /// If the specified [preset] is unavailable, the camera will fall back to the /// closest lower resolution available. - ResolutionSelector? _getResolutionSelectorFromPreset( - ResolutionPreset? preset, - ) { + ResolutionSelector? _getResolutionSelectorFromPreset(ResolutionPreset? preset) { const ResolutionStrategyFallbackRule fallbackRule = ResolutionStrategyFallbackRule.closestLowerThenHigher; @@ -1614,9 +1528,7 @@ class AndroidCameraCameraX extends CameraPlatform { boundSize: CameraSize(width: boundSize.width, height: boundSize.height), fallbackRule: fallbackRule, ); - final resolutionFilter = ResolutionFilter.createWithOnePreferredSize( - preferredSize: boundSize, - ); + final resolutionFilter = ResolutionFilter.createWithOnePreferredSize(preferredSize: boundSize); final AspectRatioStrategy? aspectRatioStrategy = aspectRatio == null ? null : AspectRatioStrategy( @@ -1658,14 +1570,9 @@ class AndroidCameraCameraX extends CameraPlatform { // We will choose the next highest video quality if the one desired // is unavailable. - final fallbackStrategy = FallbackStrategy.lowerQualityOrHigherThan( - quality: videoQuality, - ); + final fallbackStrategy = FallbackStrategy.lowerQualityOrHigherThan(quality: videoQuality); - return QualitySelector.from( - quality: videoQuality, - fallbackStrategy: fallbackStrategy, - ); + return QualitySelector.from(quality: videoQuality, fallbackStrategy: fallbackStrategy); } // Methods for configuring auto-focus and auto-exposure: @@ -1733,14 +1640,14 @@ class AndroidCameraCameraX extends CameraPlatform { return false; } - final Iterable<(MeteringPoint, MeteringMode)> originalMeteringPoints = - _combineMeteringPoints(currentFocusMeteringAction!); + final Iterable<(MeteringPoint, MeteringMode)> originalMeteringPoints = _combineMeteringPoints( + currentFocusMeteringAction!, + ); // Remove metering point with specified meteringMode from current focus // and metering action, as only one focus or exposure point may be set // at once in this plugin. - final List<(MeteringPoint, MeteringMode)> - newMeteringPointInfos = originalMeteringPoints + final List<(MeteringPoint, MeteringMode)> newMeteringPointInfos = originalMeteringPoints .where( ((MeteringPoint, MeteringMode) meteringPointInfo) => // meteringPointInfo may technically include points without a @@ -1768,9 +1675,7 @@ class AndroidCameraCameraX extends CameraPlatform { } // Add any additional metering points in order as specified by input lists. - newMeteringPointInfos.skip(1).forEach(( - (MeteringPoint point, MeteringMode) info, - ) { + newMeteringPointInfos.skip(1).forEach(((MeteringPoint point, MeteringMode) info) { actionBuilder.addPointWithMode(info.$1, info.$2); }); currentFocusMeteringAction = await actionBuilder.build(); @@ -1807,17 +1712,16 @@ class AndroidCameraCameraX extends CameraPlatform { unawaited(actionBuilder.disableAutoCancel()); } - newMeteringPointInfos.skip(1).forEach(( - (MeteringPoint point, MeteringMode mode) info, - ) { + newMeteringPointInfos.skip(1).forEach(((MeteringPoint point, MeteringMode mode) info) { actionBuilder.addPointWithMode(info.$1, info.$2); }); currentFocusMeteringAction = await actionBuilder.build(); } try { - final FocusMeteringResult? result = await cameraControl - .startFocusAndMetering(currentFocusMeteringAction!); + final FocusMeteringResult? result = await cameraControl.startFocusAndMetering( + currentFocusMeteringAction!, + ); if (result == null) { cameraErrorStreamController.add( @@ -1827,9 +1731,7 @@ class AndroidCameraCameraX extends CameraPlatform { return result?.isFocusSuccessful ?? false; } on PlatformException catch (e) { - cameraErrorStreamController.add( - e.message ?? 'Starting focus and metering failed.', - ); + cameraErrorStreamController.add(e.message ?? 'Starting focus and metering failed.'); // Surfacing error to differentiate an operation cancellation from an // illegal argument exception at a plugin layer. rethrow; @@ -1849,18 +1751,9 @@ class AndroidCameraCameraX extends CameraPlatform { } return <(MeteringPoint, MeteringMode)>[ - ...toMeteringPointRecords( - focusMeteringAction.meteringPointsAf, - MeteringMode.af, - ), - ...toMeteringPointRecords( - focusMeteringAction.meteringPointsAe, - MeteringMode.ae, - ), - ...toMeteringPointRecords( - focusMeteringAction.meteringPointsAwb, - MeteringMode.awb, - ), + ...toMeteringPointRecords(focusMeteringAction.meteringPointsAf, MeteringMode.af), + ...toMeteringPointRecords(focusMeteringAction.meteringPointsAe, MeteringMode.ae), + ...toMeteringPointRecords(focusMeteringAction.meteringPointsAwb, MeteringMode.awb), ]; } @@ -1868,9 +1761,7 @@ class AndroidCameraCameraX extends CameraPlatform { try { await cameraControl.enableTorch(value); } on PlatformException catch (e) { - cameraErrorStreamController.add( - e.message ?? 'The camera was unable to change torch modes.', - ); + cameraErrorStreamController.add(e.message ?? 'The camera was unable to change torch modes.'); } } @@ -1885,9 +1776,7 @@ class AndroidCameraCameraX extends CameraPlatform { case 'PORTRAIT_UP': return DeviceOrientation.portraitUp; default: - throw ArgumentError( - '"$orientation" is not a valid DeviceOrientation value', - ); + throw ArgumentError('"$orientation" is not a valid DeviceOrientation value'); } } } diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_library.dart b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart index 1731bca4680b..4670a9448aa9 100644 --- a/packages/camera/camera_android_camerax/lib/src/camerax_library.dart +++ b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart @@ -166,10 +166,7 @@ class LiveData extends camerax.LiveData { @override // ignore: non_constant_identifier_names LiveData pigeon_copy() { - return LiveData.detached( - type: type, - pigeon_binaryMessenger: pigeon_binaryMessenger, - ); + return LiveData.detached(type: type, pigeon_binaryMessenger: pigeon_binaryMessenger); } } @@ -185,10 +182,7 @@ class Observer extends camerax.Observer { if (GenericsPigeonOverrides.observerNew != null) { return GenericsPigeonOverrides.observerNew!(onChanged: onChanged); } - return Observer.pigeonNew( - pigeon_binaryMessenger: binaryMessenger, - onChanged: onChanged, - ); + return Observer.pigeonNew(pigeon_binaryMessenger: binaryMessenger, onChanged: onChanged); } /// Constructs an [Observer]. diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart b/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart index 7b642695e0b0..d7be3d97d3e0 100644 --- a/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart +++ b/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart @@ -21,11 +21,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -45,8 +41,7 @@ List wrapResponse({ @visibleForTesting class PigeonOverrides { /// Overrides [CameraSize.new]. - static CameraSize Function({required int width, required int height})? - cameraSize_new; + static CameraSize Function({required int width, required int height})? cameraSize_new; /// Overrides [CameraIntegerRange.new]. static CameraIntegerRange Function({required int lower, required int upper})? @@ -59,28 +54,19 @@ class PigeonOverrides { observer_new; /// Overrides [CameraSelector.new]. - static CameraSelector Function({ - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - })? + static CameraSelector Function({LensFacing? requireLensFacing, CameraInfo? cameraInfoForFilter})? cameraSelector_new; /// Overrides [SystemServicesManager.new]. static SystemServicesManager Function({ - required void Function( - SystemServicesManager pigeon_instance, - String errorDescription, - ) + required void Function(SystemServicesManager pigeon_instance, String errorDescription) onCameraError, })? systemServicesManager_new; /// Overrides [DeviceOrientationManager.new]. static DeviceOrientationManager Function({ - required void Function( - DeviceOrientationManager pigeon_instance, - String orientation, - ) + required void Function(DeviceOrientationManager pigeon_instance, String orientation) onDeviceOrientationChanged, })? deviceOrientationManager_new; @@ -110,10 +96,7 @@ class PigeonOverrides { /// Overrides [VideoRecordEventListener.new]. static VideoRecordEventListener Function({ - required void Function( - VideoRecordEventListener pigeon_instance, - VideoRecordEvent event, - ) + required void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event) onEvent, })? videoRecordEventListener_new; @@ -205,9 +188,7 @@ class PigeonOverrides { focusMeteringActionBuilder_withMode; /// Overrides [CaptureRequestOptions.new]. - static CaptureRequestOptions Function({ - required Map options, - })? + static CaptureRequestOptions Function({required Map options})? captureRequestOptions_new; /// Overrides [Camera2CameraControl.from]. @@ -219,8 +200,7 @@ class PigeonOverrides { resolutionFilter_createWithOnePreferredSize; /// Overrides [Camera2CameraInfo.from]. - static Camera2CameraInfo Function({required CameraInfo cameraInfo})? - camera2CameraInfo_from; + static Camera2CameraInfo Function({required CameraInfo cameraInfo})? camera2CameraInfo_from; /// Overrides [DisplayOrientedMeteringPointFactory.new]. static DisplayOrientedMeteringPointFactory Function({ @@ -240,8 +220,7 @@ class PigeonOverrides { static ResolutionStrategy? resolutionStrategy_highestAvailableStrategy; /// Overrides [AspectRatioStrategy.ratio_16_9FallbackAutoStrategy]. - static AspectRatioStrategy? - aspectRatioStrategy_ratio_16_9FallbackAutoStrategy; + static AspectRatioStrategy? aspectRatioStrategy_ratio_16_9FallbackAutoStrategy; /// Overrides [AspectRatioStrategy.ratio_4_3FallbackAutoStrategy]. static AspectRatioStrategy? aspectRatioStrategy_ratio_4_3FallbackAutoStrategy; @@ -253,27 +232,22 @@ class PigeonOverrides { static CaptureRequestKey? captureRequest_controlVideoStabilizationMode; /// Overrides [CameraCharacteristics.infoSupportedHardwareLevel]. - static CameraCharacteristicsKey? - cameraCharacteristics_infoSupportedHardwareLevel; + static CameraCharacteristicsKey? cameraCharacteristics_infoSupportedHardwareLevel; /// Overrides [CameraCharacteristics.sensorOrientation]. static CameraCharacteristicsKey? cameraCharacteristics_sensorOrientation; /// Overrides [CameraCharacteristics.controlAvailableVideoStabilizationModes]. - static CameraCharacteristicsKey? - cameraCharacteristics_controlAvailableVideoStabilizationModes; + static CameraCharacteristicsKey? cameraCharacteristics_controlAvailableVideoStabilizationModes; /// Overrides [ProcessCameraProvider.getInstance]. - static Future Function()? - processCameraProvider_getInstance; + static Future Function()? processCameraProvider_getInstance; /// Overrides [ImageProxyUtils.getNv21Buffer]. - static Future Function(int, int, List)? - imageProxyUtils_getNv21Buffer; + static Future Function(int, int, List)? imageProxyUtils_getNv21Buffer; /// Overrides [QualitySelector.getResolution]. - static Future Function(CameraInfo, VideoQuality)? - qualitySelector_getResolution; + static Future Function(CameraInfo, VideoQuality)? qualitySelector_getResolution; /// Sets all overridden ProxyApi class members to null. static void pigeon_reset() { @@ -333,8 +307,7 @@ abstract class PigeonInternalProxyApiBaseClass { PigeonInternalProxyApiBaseClass({ this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + }) : pigeon_instanceManager = pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -404,8 +377,8 @@ class PigeonInstanceManager { // by calling instanceManager.getIdentifier() inside of `==` while this was a // HashMap). final Expando _identifiers = Expando(); - final Map> - _weakInstances = >{}; + final Map> _weakInstances = + >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -420,8 +393,7 @@ class PigeonInstanceManager { return PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); } WidgetsFlutterBinding.ensureInitialized(); - final _PigeonInternalInstanceManagerApi api = - _PigeonInternalInstanceManagerApi(); + final _PigeonInternalInstanceManagerApi api = _PigeonInternalInstanceManagerApi(); // Clears the native `PigeonInstanceManager` on the initial use of the Dart one. api.clear(); final PigeonInstanceManager instanceManager = PigeonInstanceManager( @@ -429,163 +401,59 @@ class PigeonInstanceManager { api.removeStrongReference(identifier); }, ); - _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager, - ); - CameraSize.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ResolutionInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraIntegerRange.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoRecordEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoRecordEventStart.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoRecordEventFinalize.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - MeteringPoint.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - Observer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraSelector.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ProcessCameraProvider.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - UseCase.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + _PigeonInternalInstanceManagerApi.setUpMessageHandlers(instanceManager: instanceManager); + CameraSize.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ResolutionInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraIntegerRange.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoRecordEvent.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoRecordEventStart.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoRecordEventFinalize.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + MeteringPoint.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + Observer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraSelector.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ProcessCameraProvider.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + UseCase.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); Camera.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); - SystemServicesManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraPermissionsError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - DeviceOrientationManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - Preview.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoCapture.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoOutput.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - Recorder.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoRecordEventListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - PendingRecording.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - Recording.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ImageCapture.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ResolutionStrategy.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ResolutionSelector.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AspectRatioStrategy.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraState.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ExposureState.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ZoomState.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ImageAnalysis.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - Analyzer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraStateStateError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - LiveData.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ImageProxy.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ImageProxyUtils.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - PlaneProxy.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - QualitySelector.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - FallbackStrategy.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraControl.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - FocusMeteringActionBuilder.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - FocusMeteringAction.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - FocusMeteringResult.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CaptureRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CaptureRequestKey.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CaptureRequestOptions.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - Camera2CameraControl.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ResolutionFilter.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraCharacteristicsKey.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CameraCharacteristics.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - Camera2CameraInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - MeteringPointFactory.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + SystemServicesManager.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraPermissionsError.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + DeviceOrientationManager.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + Preview.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoCapture.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoOutput.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + Recorder.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoRecordEventListener.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + PendingRecording.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + Recording.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ImageCapture.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ResolutionStrategy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ResolutionSelector.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AspectRatioStrategy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraState.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ExposureState.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ZoomState.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ImageAnalysis.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + Analyzer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraStateStateError.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + LiveData.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ImageProxy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ImageProxyUtils.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + PlaneProxy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + QualitySelector.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + FallbackStrategy.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraControl.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + FocusMeteringActionBuilder.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + FocusMeteringAction.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + FocusMeteringResult.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CaptureRequest.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CaptureRequestKey.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CaptureRequestOptions.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + Camera2CameraControl.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ResolutionFilter.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraCharacteristicsKey.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CameraCharacteristics.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + Camera2CameraInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + MeteringPointFactory.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); DisplayOrientedMeteringPointFactory.pigeon_setUpMessageHandlers( pigeon_instanceManager: instanceManager, ); @@ -605,9 +473,7 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = WeakReference( - instance, - ); + _weakInstances[identifier] = WeakReference(instance); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -668,21 +534,15 @@ class PigeonInstanceManager { /// /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. - T? getInstanceWithWeakReference( - int identifier, - ) { - final PigeonInternalProxyApiBaseClass? weakInstance = - _weakInstances[identifier]?.target; + T? getInstanceWithWeakReference(int identifier) { + final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; if (weakInstance == null) { - final PigeonInternalProxyApiBaseClass? strongInstance = - _strongInstances[identifier]; + final PigeonInternalProxyApiBaseClass? strongInstance = _strongInstances[identifier]; if (strongInstance != null) { - final PigeonInternalProxyApiBaseClass copy = strongInstance - .pigeon_copy(); + final PigeonInternalProxyApiBaseClass copy = strongInstance.pigeon_copy(); _identifiers[copy] = identifier; - _weakInstances[identifier] = - WeakReference(copy); + _weakInstances[identifier] = WeakReference(copy); _finalizer.attach(copy, identifier, detach: copy); return copy as T; } @@ -704,10 +564,7 @@ class PigeonInstanceManager { /// /// Throws assertion error if the instance or its identifier has already been /// added. - void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, - int identifier, - ) { + void addHostCreatedInstance(PigeonInternalProxyApiBaseClass instance, int identifier) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -718,8 +575,7 @@ class PigeonInstanceManager { /// Whether this manager contains the given [identifier]. bool containsIdentifier(int identifier) { - return _weakInstances.containsKey(identifier) || - _strongInstances.containsKey(identifier); + return _weakInstances.containsKey(identifier) || _strongInstances.containsKey(identifier); } int _nextUniqueIdentifier() { @@ -768,9 +624,7 @@ class _PigeonInternalInstanceManagerApi { 'Argument for dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', ); try { - (instanceManager ?? PigeonInstanceManager.instance).remove( - arg_identifier!, - ); + (instanceManager ?? PigeonInstanceManager.instance).remove(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -792,9 +646,7 @@ class _PigeonInternalInstanceManagerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [identifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([identifier]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -853,9 +705,7 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager.getInstanceWithWeakReference( - readValue(buffer)! as int, - ); + return instanceManager.getInstanceWithWeakReference(readValue(buffer)! as int); default: return super.readValueOfType(type, buffer); } @@ -1172,14 +1022,10 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : CameraXFlashMode.values[value]; case 137: final value = readValue(buffer) as int?; - return value == null - ? null - : ResolutionStrategyFallbackRule.values[value]; + return value == null ? null : ResolutionStrategyFallbackRule.values[value]; case 138: final value = readValue(buffer) as int?; - return value == null - ? null - : AspectRatioStrategyFallbackRule.values[value]; + return value == null ? null : AspectRatioStrategyFallbackRule.values[value]; case 139: final value = readValue(buffer) as int?; return value == null ? null : CameraStateErrorCode.values[value]; @@ -1217,10 +1063,8 @@ class CameraSize extends PigeonInternalProxyApiBaseClass { required this.width, required this.height, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraSize; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSize; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_defaultConstructor'; @@ -1229,9 +1073,11 @@ class CameraSize extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, width, height], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + width, + height, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1275,10 +1121,9 @@ class CameraSize extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CameraSize Function(int width, int height)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1311,17 +1156,16 @@ class CameraSize extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_width!, arg_height!) ?? - CameraSize.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - width: arg_width!, - height: arg_height!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_width!, arg_height!) ?? + CameraSize.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + width: arg_width!, + height: arg_height!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1371,10 +1215,9 @@ class ResolutionInfo extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ResolutionInfo Function(CameraSize resolution)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1402,16 +1245,15 @@ class ResolutionInfo extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance was null, expected non-null CameraSize.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_resolution!) ?? - ResolutionInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resolution: arg_resolution!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolution!) ?? + ResolutionInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolution: arg_resolution!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1448,10 +1290,7 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { required int upper, }) { if (PigeonOverrides.cameraIntegerRange_new != null) { - return PigeonOverrides.cameraIntegerRange_new!( - lower: lower, - upper: upper, - ); + return PigeonOverrides.cameraIntegerRange_new!(lower: lower, upper: upper); } return CameraIntegerRange.pigeon_new( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -1468,10 +1307,8 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { required this.lower, required this.upper, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraIntegerRange; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraIntegerRange; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_defaultConstructor'; @@ -1480,9 +1317,11 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, lower, upper], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + lower, + upper, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1511,10 +1350,8 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { required this.upper, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecCameraIntegerRange = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraIntegerRange = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// The lower endpoint. final int lower; @@ -1528,10 +1365,9 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CameraIntegerRange Function(int lower, int upper)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1564,17 +1400,16 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_lower!, arg_upper!) ?? - CameraIntegerRange.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - lower: arg_lower!, - upper: arg_upper!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_lower!, arg_upper!) ?? + CameraIntegerRange.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + lower: arg_lower!, + upper: arg_upper!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1608,10 +1443,7 @@ class VideoRecordEvent extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - VideoRecordEvent.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + VideoRecordEvent.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -1619,10 +1451,9 @@ class VideoRecordEvent extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, VideoRecordEvent Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1645,15 +1476,14 @@ class VideoRecordEvent extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEvent.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoRecordEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoRecordEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1696,10 +1526,9 @@ class VideoRecordEventStart extends VideoRecordEvent { PigeonInstanceManager? pigeon_instanceManager, VideoRecordEventStart Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1722,15 +1551,14 @@ class VideoRecordEventStart extends VideoRecordEvent { 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventStart.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoRecordEventStart.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoRecordEventStart.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1773,10 +1601,9 @@ class VideoRecordEventFinalize extends VideoRecordEvent { PigeonInstanceManager? pigeon_instanceManager, VideoRecordEventFinalize Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1799,15 +1626,14 @@ class VideoRecordEventFinalize extends VideoRecordEvent { 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventFinalize.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoRecordEventFinalize.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoRecordEventFinalize.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1840,10 +1666,7 @@ class MeteringPoint extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - MeteringPoint.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + MeteringPoint.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecMeteringPoint = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -1854,10 +1677,9 @@ class MeteringPoint extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, MeteringPoint Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1880,15 +1702,14 @@ class MeteringPoint extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPoint.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - MeteringPoint.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + MeteringPoint.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1907,19 +1728,15 @@ class MeteringPoint extends PigeonInternalProxyApiBaseClass { /// It is the percentage of the sensor width/height (or crop region /// width/height if crop region is set). Future getSize() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecMeteringPoint; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMeteringPoint; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.getSize'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.getSize'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1973,10 +1790,8 @@ class Observer extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onChanged, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecObserver; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecObserver; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Observer.pigeon_defaultConstructor'; @@ -1985,9 +1800,9 @@ class Observer extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2045,10 +1860,9 @@ class Observer extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, void Function(Observer pigeon_instance, Object value)? onChanged, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2076,10 +1890,7 @@ class Observer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.Observer.onChanged was null, expected non-null Object.', ); try { - (onChanged ?? arg_pigeon_instance!.onChanged).call( - arg_pigeon_instance!, - arg_value!, - ); + (onChanged ?? arg_pigeon_instance!.onChanged).call(arg_pigeon_instance!, arg_value!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2144,10 +1955,9 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2185,22 +1995,21 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null, expected non-null ExposureState.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_sensorRotationDegrees!, - arg_lensFacing!, - arg_exposureState!, - ) ?? - CameraInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - sensorRotationDegrees: arg_sensorRotationDegrees!, - lensFacing: arg_lensFacing!, - exposureState: arg_exposureState!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_sensorRotationDegrees!, + arg_lensFacing!, + arg_exposureState!, + ) ?? + CameraInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + sensorRotationDegrees: arg_sensorRotationDegrees!, + lensFacing: arg_lensFacing!, + exposureState: arg_exposureState!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2216,8 +2025,7 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { /// A LiveData of the camera's state. Future getCameraState() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraInfo; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getCameraState'; @@ -2226,9 +2034,7 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2250,8 +2056,7 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { /// A LiveData of ZoomState. Future getZoomState() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraInfo; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getZoomState'; @@ -2260,9 +2065,7 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2326,10 +2129,8 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { LensFacing? requireLensFacing, CameraInfo? cameraInfoForFilter, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraSelector; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_defaultConstructor'; @@ -2338,13 +2139,11 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [ - pigeonVar_instanceIdentifier, - requireLensFacing, - cameraInfoForFilter, - ], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + requireLensFacing, + cameraInfoForFilter, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2366,21 +2165,16 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - CameraSelector.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + CameraSelector.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraSelector = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// A static `CameraSelector` that selects the default back facing camera. - static final CameraSelector _defaultBackCamera = - pigeonVar_defaultBackCamera(); + static final CameraSelector _defaultBackCamera = pigeonVar_defaultBackCamera(); /// A static `CameraSelector` that selects the default front facing camera. - static final CameraSelector _defaultFrontCamera = - pigeonVar_defaultFrontCamera(); + static final CameraSelector _defaultFrontCamera = pigeonVar_defaultFrontCamera(); /// A static `CameraSelector` that selects the default back facing camera. static CameraSelector get defaultBackCamera => @@ -2396,10 +2190,9 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CameraSelector Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2422,15 +2215,14 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CameraSelector.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraSelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2446,12 +2238,14 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { static CameraSelector pigeonVar_defaultBackCamera() { final CameraSelector pigeonVar_instance = CameraSelector.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultBackCamera'; @@ -2460,9 +2254,9 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2481,12 +2275,14 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { static CameraSelector pigeonVar_defaultFrontCamera() { final CameraSelector pigeonVar_instance = CameraSelector.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultFrontCamera'; @@ -2495,9 +2291,9 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2517,19 +2313,18 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { /// Filters the input `CameraInfo`s using the `CameraFilter`s assigned to the /// selector. Future> filter(List cameraInfos) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraSelector; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.filter'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.filter'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, cameraInfos], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + cameraInfos, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2573,10 +2368,8 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecProcessCameraProvider = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecProcessCameraProvider = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -2584,10 +2377,9 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ProcessCameraProvider Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2610,15 +2402,14 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ProcessCameraProvider.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ProcessCameraProvider.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2640,10 +2431,9 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { if (PigeonOverrides.processCameraProvider_getInstance != null) { return PigeonOverrides.processCameraProvider_getInstance!(); } - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getInstance'; @@ -2684,9 +2474,7 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2707,10 +2495,7 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { } /// Binds the collection of `UseCase` to a `LifecycleOwner`. - Future bindToLifecycle( - CameraSelector cameraSelector, - List useCases, - ) async { + Future bindToLifecycle(CameraSelector cameraSelector, List useCases) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProcessCameraProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -2721,9 +2506,11 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, cameraSelector, useCases], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + cameraSelector, + useCases, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2755,9 +2542,7 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, useCase], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, useCase]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2789,9 +2574,7 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, useCases], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, useCases]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2819,9 +2602,7 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2854,10 +2635,7 @@ class UseCase extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - UseCase.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + UseCase.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -2865,10 +2643,9 @@ class UseCase extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, UseCase Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2891,15 +2668,14 @@ class UseCase extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.UseCase.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - UseCase.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + UseCase.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2951,10 +2727,9 @@ class Camera extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, Camera Function(CameraControl cameraControl)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2982,16 +2757,15 @@ class Camera extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance was null, expected non-null CameraControl.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_cameraControl!) ?? - Camera.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - cameraControl: arg_cameraControl!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_cameraControl!) ?? + Camera.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + cameraControl: arg_cameraControl!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3007,19 +2781,15 @@ class Camera extends PigeonInternalProxyApiBaseClass { /// Returns information about this camera. Future getCameraInfo() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCamera; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.Camera.getCameraInfo'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera.getCameraInfo'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3054,16 +2824,11 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { factory SystemServicesManager({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function( - SystemServicesManager pigeon_instance, - String errorDescription, - ) + required void Function(SystemServicesManager pigeon_instance, String errorDescription) onCameraError, }) { if (PigeonOverrides.systemServicesManager_new != null) { - return PigeonOverrides.systemServicesManager_new!( - onCameraError: onCameraError, - ); + return PigeonOverrides.systemServicesManager_new!(onCameraError: onCameraError); } return SystemServicesManager.pigeon_new( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -3078,8 +2843,7 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onCameraError, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecSystemServicesManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3090,9 +2854,9 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3120,10 +2884,8 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { required this.onCameraError, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecSystemServicesManager = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecSystemServicesManager = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Callback method. /// @@ -3144,26 +2906,17 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - SystemServicesManager pigeon_instance, - String errorDescription, - ) - onCameraError; + final void Function(SystemServicesManager pigeon_instance, String errorDescription) onCameraError; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - SystemServicesManager pigeon_instance, - String errorDescription, - )? - onCameraError, + void Function(SystemServicesManager pigeon_instance, String errorDescription)? onCameraError, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3180,8 +2933,7 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError was null.', ); final List args = (message as List?)!; - final SystemServicesManager? arg_pigeon_instance = - (args[0] as SystemServicesManager?); + final SystemServicesManager? arg_pigeon_instance = (args[0] as SystemServicesManager?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError was null, expected non-null SystemServicesManager.', @@ -3209,9 +2961,7 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { } } - Future requestCameraPermissions( - bool enableAudio, - ) async { + Future requestCameraPermissions(bool enableAudio) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecSystemServicesManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3222,9 +2972,10 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enableAudio], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + enableAudio, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3252,9 +3003,11 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, prefix, suffix], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + prefix, + suffix, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3306,13 +3059,11 @@ class CameraPermissionsError extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - CameraPermissionsError Function(String errorCode, String description)? - pigeon_newInstance, + CameraPermissionsError Function(String errorCode, String description)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3345,17 +3096,16 @@ class CameraPermissionsError extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance was null, expected non-null String.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_errorCode!, arg_description!) ?? - CameraPermissionsError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - errorCode: arg_errorCode!, - description: arg_description!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_errorCode!, arg_description!) ?? + CameraPermissionsError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + errorCode: arg_errorCode!, + description: arg_description!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3386,10 +3136,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { factory DeviceOrientationManager({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function( - DeviceOrientationManager pigeon_instance, - String orientation, - ) + required void Function(DeviceOrientationManager pigeon_instance, String orientation) onDeviceOrientationChanged, }) { if (PigeonOverrides.deviceOrientationManager_new != null) { @@ -3410,8 +3157,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onDeviceOrientationChanged, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDeviceOrientationManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3422,9 +3168,9 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3452,10 +3198,8 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { required this.onDeviceOrientationChanged, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecDeviceOrientationManager = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecDeviceOrientationManager = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Callback method. /// @@ -3476,10 +3220,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - DeviceOrientationManager pigeon_instance, - String orientation, - ) + final void Function(DeviceOrientationManager pigeon_instance, String orientation) onDeviceOrientationChanged; static void pigeon_setUpMessageHandlers({ @@ -3489,10 +3230,9 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { void Function(DeviceOrientationManager pigeon_instance, String orientation)? onDeviceOrientationChanged, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3521,9 +3261,10 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged was null, expected non-null String.', ); try { - (onDeviceOrientationChanged ?? - arg_pigeon_instance!.onDeviceOrientationChanged) - .call(arg_pigeon_instance!, arg_orientation!); + (onDeviceOrientationChanged ?? arg_pigeon_instance!.onDeviceOrientationChanged).call( + arg_pigeon_instance!, + arg_orientation!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3548,9 +3289,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3576,9 +3315,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3604,9 +3341,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3637,9 +3372,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3704,10 +3437,8 @@ class Preview extends UseCase { int? targetRotation, CameraIntegerRange? targetFpsRange, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPreview; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_defaultConstructor'; @@ -3716,13 +3447,12 @@ class Preview extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - resolutionSelector, - targetRotation, - targetFpsRange, - ]); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + resolutionSelector, + targetRotation, + targetFpsRange, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3759,13 +3489,11 @@ class Preview extends UseCase { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - Preview Function(ResolutionSelector? resolutionSelector)? - pigeon_newInstance, + Preview Function(ResolutionSelector? resolutionSelector)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3787,19 +3515,17 @@ class Preview extends UseCase { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_newInstance was null, expected non-null int.', ); - final ResolutionSelector? arg_resolutionSelector = - (args[1] as ResolutionSelector?); + final ResolutionSelector? arg_resolutionSelector = (args[1] as ResolutionSelector?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_resolutionSelector) ?? - Preview.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resolutionSelector: arg_resolutionSelector, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolutionSelector) ?? + Preview.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: arg_resolutionSelector, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3821,11 +3547,8 @@ class Preview extends UseCase { /// 2. Sets this method with the created `SurfaceProvider`. /// 3. Returns the texture id of the `TextureEntry` that provided the /// `SurfaceProducer`. - Future setSurfaceProvider( - SystemServicesManager systemServicesManager, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPreview; + Future setSurfaceProvider(SystemServicesManager systemServicesManager) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.setSurfaceProvider'; @@ -3834,9 +3557,10 @@ class Preview extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, systemServicesManager], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + systemServicesManager, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3859,8 +3583,7 @@ class Preview extends UseCase { /// Releases the `SurfaceProducer` created in `setSurfaceProvider` if one was /// created. Future releaseSurfaceProvider() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPreview; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.releaseSurfaceProvider'; @@ -3869,9 +3592,7 @@ class Preview extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3888,8 +3609,7 @@ class Preview extends UseCase { /// Gets selected resolution information of the `Preview`. Future getResolutionInfo() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPreview; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.getResolutionInfo'; @@ -3898,9 +3618,7 @@ class Preview extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3917,8 +3635,7 @@ class Preview extends UseCase { /// Sets the target rotation. Future setTargetRotation(int rotation) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPreview; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.setTargetRotation'; @@ -3927,9 +3644,7 @@ class Preview extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, rotation], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, rotation]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3947,8 +3662,7 @@ class Preview extends UseCase { /// Returns whether or not the preview's surface producer handles correctly /// rotating the camera preview automatically. Future surfaceProducerHandlesCropAndRotation() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPreview; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.surfaceProducerHandlesCropAndRotation'; @@ -3957,9 +3671,7 @@ class Preview extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4022,10 +3734,8 @@ class VideoCapture extends UseCase { required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoCapture; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.withOutput'; @@ -4034,9 +3744,11 @@ class VideoCapture extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, videoOutput, targetFpsRange], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + videoOutput, + targetFpsRange, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4058,10 +3770,8 @@ class VideoCapture extends UseCase { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - VideoCapture.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + VideoCapture.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecVideoCapture = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -4072,10 +3782,9 @@ class VideoCapture extends UseCase { PigeonInstanceManager? pigeon_instanceManager, VideoCapture Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4098,15 +3807,14 @@ class VideoCapture extends UseCase { 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoCapture.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoCapture.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoCapture.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4122,8 +3830,7 @@ class VideoCapture extends UseCase { /// Gets the VideoOutput associated with this VideoCapture. Future getOutput() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoCapture; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.getOutput'; @@ -4132,9 +3839,7 @@ class VideoCapture extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4156,8 +3861,7 @@ class VideoCapture extends UseCase { /// Sets the desired rotation of the output video. Future setTargetRotation(int rotation) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoCapture; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.setTargetRotation'; @@ -4166,9 +3870,7 @@ class VideoCapture extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, rotation], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, rotation]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4201,10 +3903,7 @@ class VideoOutput extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - VideoOutput.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + VideoOutput.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -4212,10 +3911,9 @@ class VideoOutput extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, VideoOutput Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4238,15 +3936,14 @@ class VideoOutput extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoOutput.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoOutput.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoOutput.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4305,10 +4002,8 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { int? targetVideoEncodingBitRate, QualitySelector? qualitySelector, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecorder; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_defaultConstructor'; @@ -4317,13 +4012,12 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - aspectRatio, - targetVideoEncodingBitRate, - qualitySelector, - ]); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + aspectRatio, + targetVideoEncodingBitRate, + qualitySelector, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4345,10 +4039,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - Recorder.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + Recorder.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecRecorder = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -4359,10 +4050,9 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { PigeonInstanceManager? pigeon_instanceManager, Recorder Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4385,15 +4075,14 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { 'Argument for dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - Recorder.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Recorder.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4409,8 +4098,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { /// Gets the aspect ratio of this Recorder. Future getAspectRatio() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecorder; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.getAspectRatio'; @@ -4419,9 +4107,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4443,8 +4129,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { /// Gets the target video encoding bitrate of this Recorder. Future getTargetVideoEncodingBitRate() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecorder; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.getTargetVideoEncodingBitRate'; @@ -4453,9 +4138,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4477,8 +4160,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { /// The quality selector of this Recorder. Future getQualitySelector() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecorder; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.getQualitySelector'; @@ -4487,9 +4169,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4511,8 +4191,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { /// Prepares a recording that will be saved to a File. Future prepareRecording(String path) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecorder; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.prepareRecording'; @@ -4521,9 +4200,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, path], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, path]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4557,10 +4234,7 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { factory VideoRecordEventListener({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function( - VideoRecordEventListener pigeon_instance, - VideoRecordEvent event, - ) + required void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event) onEvent, }) { if (PigeonOverrides.videoRecordEventListener_new != null) { @@ -4579,8 +4253,7 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onEvent, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoRecordEventListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4591,9 +4264,9 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4621,10 +4294,8 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { required this.onEvent, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecVideoRecordEventListener = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecVideoRecordEventListener = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Callback method. /// @@ -4645,26 +4316,17 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoRecordEventListener pigeon_instance, - VideoRecordEvent event, - ) - onEvent; + final void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event) onEvent; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - VideoRecordEventListener pigeon_instance, - VideoRecordEvent event, - )? - onEvent, + void Function(VideoRecordEventListener pigeon_instance, VideoRecordEvent event)? onEvent, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4693,10 +4355,7 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent was null, expected non-null VideoRecordEvent.', ); try { - (onEvent ?? arg_pigeon_instance!.onEvent).call( - arg_pigeon_instance!, - arg_event!, - ); + (onEvent ?? arg_pigeon_instance!.onEvent).call(arg_pigeon_instance!, arg_event!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4729,10 +4388,7 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - PendingRecording.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + PendingRecording.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecPendingRecording = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -4743,10 +4399,9 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, PendingRecording Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4769,15 +4424,14 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.PendingRecording.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - PendingRecording.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + PendingRecording.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4793,8 +4447,7 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { /// Enables/disables audio to be recorded for this recording. Future withAudioEnabled(bool initialMuted) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPendingRecording; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.withAudioEnabled'; @@ -4803,9 +4456,10 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, initialMuted], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + initialMuted, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4835,8 +4489,7 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { /// first create the recording as persistent recording, /// then rebind the [VideoCapture] it's associated with to a different camera. Future asPersistentRecording() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPendingRecording; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.asPersistentRecording'; @@ -4845,9 +4498,7 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4869,8 +4520,7 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { /// Starts the recording, making it an active recording. Future start(VideoRecordEventListener listener) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecPendingRecording; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.start'; @@ -4879,9 +4529,7 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, listener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, listener]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4919,10 +4567,7 @@ class Recording extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - Recording.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + Recording.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecRecording = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -4933,10 +4578,9 @@ class Recording extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, Recording Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4959,15 +4603,14 @@ class Recording extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.Recording.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - Recording.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Recording.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4983,19 +4626,15 @@ class Recording extends PigeonInternalProxyApiBaseClass { /// Close this recording. Future close() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecording; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.Recording.close'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.close'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5012,19 +4651,15 @@ class Recording extends PigeonInternalProxyApiBaseClass { /// Pauses the current recording if active. Future pause() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecording; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.Recording.pause'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.pause'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5041,19 +4676,15 @@ class Recording extends PigeonInternalProxyApiBaseClass { /// Resumes the current recording if paused. Future resume() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecording; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.Recording.resume'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.resume'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5072,19 +4703,15 @@ class Recording extends PigeonInternalProxyApiBaseClass { /// /// This method is equivalent to calling `close`. Future stop() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecRecording; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.Recording.stop'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.stop'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5143,10 +4770,8 @@ class ImageCapture extends UseCase { int? targetRotation, CameraXFlashMode? flashMode, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageCapture; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_defaultConstructor'; @@ -5155,14 +4780,12 @@ class ImageCapture extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [ - pigeonVar_instanceIdentifier, - resolutionSelector, - targetRotation, - flashMode, - ], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + resolutionSelector, + targetRotation, + flashMode, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5199,13 +4822,11 @@ class ImageCapture extends UseCase { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - ImageCapture Function(ResolutionSelector? resolutionSelector)? - pigeon_newInstance, + ImageCapture Function(ResolutionSelector? resolutionSelector)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5227,19 +4848,17 @@ class ImageCapture extends UseCase { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_newInstance was null, expected non-null int.', ); - final ResolutionSelector? arg_resolutionSelector = - (args[1] as ResolutionSelector?); + final ResolutionSelector? arg_resolutionSelector = (args[1] as ResolutionSelector?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_resolutionSelector) ?? - ImageCapture.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resolutionSelector: arg_resolutionSelector, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolutionSelector) ?? + ImageCapture.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: arg_resolutionSelector, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5255,8 +4874,7 @@ class ImageCapture extends UseCase { /// Set the flash mode. Future setFlashMode(CameraXFlashMode flashMode) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageCapture; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setFlashMode'; @@ -5265,9 +4883,7 @@ class ImageCapture extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, flashMode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, flashMode]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5283,11 +4899,8 @@ class ImageCapture extends UseCase { } /// Captures a new still image for in memory access. - Future takePicture( - SystemServicesManager systemServicesManager, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageCapture; + Future takePicture(SystemServicesManager systemServicesManager) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.takePicture'; @@ -5296,9 +4909,10 @@ class ImageCapture extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, systemServicesManager], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + systemServicesManager, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5320,8 +4934,7 @@ class ImageCapture extends UseCase { /// Sets the desired rotation of the output image. Future setTargetRotation(int rotation) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageCapture; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setTargetRotation'; @@ -5330,9 +4943,7 @@ class ImageCapture extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, rotation], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, rotation]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5389,10 +5000,8 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecResolutionStrategy; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_defaultConstructor'; @@ -5401,9 +5010,11 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, boundSize, fallbackRule], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + boundSize, + fallbackRule, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5425,24 +5036,17 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - ResolutionStrategy.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + ResolutionStrategy.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecResolutionStrategy = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecResolutionStrategy = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// A resolution strategy chooses the highest available resolution. - static final ResolutionStrategy _highestAvailableStrategy = - pigeonVar_highestAvailableStrategy(); + static final ResolutionStrategy _highestAvailableStrategy = pigeonVar_highestAvailableStrategy(); /// A resolution strategy chooses the highest available resolution. static ResolutionStrategy get highestAvailableStrategy => - PigeonOverrides.resolutionStrategy_highestAvailableStrategy ?? - _highestAvailableStrategy; + PigeonOverrides.resolutionStrategy_highestAvailableStrategy ?? _highestAvailableStrategy; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5450,10 +5054,9 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ResolutionStrategy Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5476,15 +5079,14 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ResolutionStrategy.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ResolutionStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5499,14 +5101,15 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { } static ResolutionStrategy pigeonVar_highestAvailableStrategy() { - final ResolutionStrategy pigeonVar_instance = - ResolutionStrategy.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final ResolutionStrategy pigeonVar_instance = ResolutionStrategy.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.highestAvailableStrategy'; @@ -5515,9 +5118,9 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5536,8 +5139,7 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { /// The specified bound size. Future getBoundSize() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecResolutionStrategy; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getBoundSize'; @@ -5546,9 +5148,7 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5566,8 +5166,7 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { /// The fallback rule for choosing an alternate size when the specified bound /// size is unavailable. Future getFallbackRule() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecResolutionStrategy; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getFallbackRule'; @@ -5576,9 +5175,7 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5643,10 +5240,8 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { this.resolutionStrategy, AspectRatioStrategy? aspectRatioStrategy, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecResolutionSelector; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_defaultConstructor'; @@ -5655,13 +5250,12 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - resolutionFilter, - resolutionStrategy, - aspectRatioStrategy, - ]); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + resolutionFilter, + resolutionStrategy, + aspectRatioStrategy, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5690,10 +5284,8 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { this.resolutionStrategy, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecResolutionSelector = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecResolutionSelector = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// The resolution filter to output the final desired sizes list. final ResolutionFilter? resolutionFilter; @@ -5711,10 +5303,9 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5736,25 +5327,19 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_newInstance was null, expected non-null int.', ); - final ResolutionFilter? arg_resolutionFilter = - (args[1] as ResolutionFilter?); - final ResolutionStrategy? arg_resolutionStrategy = - (args[2] as ResolutionStrategy?); + final ResolutionFilter? arg_resolutionFilter = (args[1] as ResolutionFilter?); + final ResolutionStrategy? arg_resolutionStrategy = (args[2] as ResolutionStrategy?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_resolutionFilter, - arg_resolutionStrategy, - ) ?? - ResolutionSelector.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resolutionFilter: arg_resolutionFilter, - resolutionStrategy: arg_resolutionStrategy, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolutionFilter, arg_resolutionStrategy) ?? + ResolutionSelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionFilter: arg_resolutionFilter, + resolutionStrategy: arg_resolutionStrategy, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5772,8 +5357,7 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { /// `AspectRatioStrategy.ratio_4_3FallbackAutoStrategy` if none is specified /// when creating the ResolutionSelector. Future getAspectRatioStrategy() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecResolutionSelector; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.getAspectRatioStrategy'; @@ -5782,9 +5366,7 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5851,10 +5433,8 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { required AspectRatio preferredAspectRatio, required AspectRatioStrategyFallbackRule fallbackRule, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAspectRatioStrategy; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_defaultConstructor'; @@ -5863,13 +5443,11 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [ - pigeonVar_instanceIdentifier, - preferredAspectRatio, - fallbackRule, - ], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + preferredAspectRatio, + fallbackRule, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5891,15 +5469,10 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - AspectRatioStrategy.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + AspectRatioStrategy.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecAspectRatioStrategy = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAspectRatioStrategy = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// The pre-defined aspect ratio strategy that selects sizes with RATIO_16_9 /// in priority. @@ -5929,10 +5502,9 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AspectRatioStrategy Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5955,15 +5527,14 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AspectRatioStrategy.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AspectRatioStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5978,14 +5549,15 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { } static AspectRatioStrategy pigeonVar_ratio_16_9FallbackAutoStrategy() { - final AspectRatioStrategy pigeonVar_instance = - AspectRatioStrategy.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final AspectRatioStrategy pigeonVar_instance = AspectRatioStrategy.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_16_9FallbackAutoStrategy'; @@ -5994,9 +5566,9 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6014,14 +5586,15 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { } static AspectRatioStrategy pigeonVar_ratio_4_3FallbackAutoStrategy() { - final AspectRatioStrategy pigeonVar_instance = - AspectRatioStrategy.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final AspectRatioStrategy pigeonVar_instance = AspectRatioStrategy.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_4_3FallbackAutoStrategy'; @@ -6030,9 +5603,9 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6052,8 +5625,7 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { /// The specified fallback rule for choosing the aspect ratio when the /// preferred aspect ratio is not available. Future getFallbackRule() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAspectRatioStrategy; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getFallbackRule'; @@ -6062,9 +5634,7 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6086,8 +5656,7 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { /// The specified preferred aspect ratio. Future getPreferredAspectRatio() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAspectRatioStrategy; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getPreferredAspectRatio'; @@ -6096,9 +5665,7 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6153,13 +5720,11 @@ class CameraState extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - CameraState Function(CameraStateType type, CameraStateStateError? error)? - pigeon_newInstance, + CameraState Function(CameraStateType type, CameraStateStateError? error)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6186,20 +5751,18 @@ class CameraState extends PigeonInternalProxyApiBaseClass { arg_type != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance was null, expected non-null CameraStateType.', ); - final CameraStateStateError? arg_error = - (args[2] as CameraStateStateError?); + final CameraStateStateError? arg_error = (args[2] as CameraStateStateError?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_type!, arg_error) ?? - CameraState.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - error: arg_error, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_type!, arg_error) ?? + CameraState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + error: arg_error, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6257,10 +5820,9 @@ class ExposureState extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6294,21 +5856,19 @@ class ExposureState extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance was null, expected non-null double.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_exposureCompensationRange!, - arg_exposureCompensationStep!, - ) ?? - ExposureState.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - exposureCompensationRange: - arg_exposureCompensationRange!, - exposureCompensationStep: arg_exposureCompensationStep!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_exposureCompensationRange!, + arg_exposureCompensationStep!, + ) ?? + ExposureState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + exposureCompensationRange: arg_exposureCompensationRange!, + exposureCompensationStep: arg_exposureCompensationStep!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6359,13 +5919,11 @@ class ZoomState extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - ZoomState Function(double minZoomRatio, double maxZoomRatio)? - pigeon_newInstance, + ZoomState Function(double minZoomRatio, double maxZoomRatio)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6398,20 +5956,16 @@ class ZoomState extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance was null, expected non-null double.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_minZoomRatio!, - arg_maxZoomRatio!, - ) ?? - ZoomState.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - minZoomRatio: arg_minZoomRatio!, - maxZoomRatio: arg_maxZoomRatio!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_minZoomRatio!, arg_maxZoomRatio!) ?? + ZoomState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + minZoomRatio: arg_minZoomRatio!, + maxZoomRatio: arg_maxZoomRatio!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6476,10 +6030,8 @@ class ImageAnalysis extends UseCase { CameraIntegerRange? targetFpsRange, int? outputImageFormat, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageAnalysis; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_defaultConstructor'; @@ -6488,14 +6040,13 @@ class ImageAnalysis extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - resolutionSelector, - targetRotation, - targetFpsRange, - outputImageFormat, - ]); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + resolutionSelector, + targetRotation, + targetFpsRange, + outputImageFormat, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6532,13 +6083,11 @@ class ImageAnalysis extends UseCase { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - ImageAnalysis Function(ResolutionSelector? resolutionSelector)? - pigeon_newInstance, + ImageAnalysis Function(ResolutionSelector? resolutionSelector)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6560,19 +6109,17 @@ class ImageAnalysis extends UseCase { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_newInstance was null, expected non-null int.', ); - final ResolutionSelector? arg_resolutionSelector = - (args[1] as ResolutionSelector?); + final ResolutionSelector? arg_resolutionSelector = (args[1] as ResolutionSelector?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_resolutionSelector) ?? - ImageAnalysis.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resolutionSelector: arg_resolutionSelector, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolutionSelector) ?? + ImageAnalysis.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: arg_resolutionSelector, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6588,8 +6135,7 @@ class ImageAnalysis extends UseCase { /// Sets an analyzer to receive and analyze images. Future setAnalyzer(Analyzer analyzer) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageAnalysis; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setAnalyzer'; @@ -6598,9 +6144,7 @@ class ImageAnalysis extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, analyzer], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, analyzer]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6617,8 +6161,7 @@ class ImageAnalysis extends UseCase { /// Removes a previously set analyzer. Future clearAnalyzer() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageAnalysis; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.clearAnalyzer'; @@ -6627,9 +6170,7 @@ class ImageAnalysis extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6646,8 +6187,7 @@ class ImageAnalysis extends UseCase { /// Sets the target rotation. Future setTargetRotation(int rotation) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageAnalysis; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setTargetRotation'; @@ -6656,9 +6196,7 @@ class ImageAnalysis extends UseCase { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, rotation], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, rotation]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6708,10 +6246,8 @@ class Analyzer extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.analyze, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAnalyzer; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAnalyzer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Analyzer.pigeon_defaultConstructor'; @@ -6720,9 +6256,9 @@ class Analyzer extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6780,10 +6316,9 @@ class Analyzer extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, void Function(Analyzer pigeon_instance, ImageProxy image)? analyze, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6811,10 +6346,7 @@ class Analyzer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze was null, expected non-null ImageProxy.', ); try { - (analyze ?? arg_pigeon_instance!.analyze).call( - arg_pigeon_instance!, - arg_image!, - ); + (analyze ?? arg_pigeon_instance!.analyze).call(arg_pigeon_instance!, arg_image!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6860,13 +6392,11 @@ class CameraStateStateError extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - CameraStateStateError Function(CameraStateErrorCode code)? - pigeon_newInstance, + CameraStateStateError Function(CameraStateErrorCode code)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6888,23 +6418,21 @@ class CameraStateStateError extends PigeonInternalProxyApiBaseClass { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance was null, expected non-null int.', ); - final CameraStateErrorCode? arg_code = - (args[1] as CameraStateErrorCode?); + final CameraStateErrorCode? arg_code = (args[1] as CameraStateErrorCode?); assert( arg_code != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance was null, expected non-null CameraStateErrorCode.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_code!) ?? - CameraStateStateError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - code: arg_code!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_code!) ?? + CameraStateStateError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + code: arg_code!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6959,10 +6487,9 @@ class LiveData extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, LiveData Function(LiveDataSupportedType type)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6984,23 +6511,21 @@ class LiveData extends PigeonInternalProxyApiBaseClass { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance was null, expected non-null int.', ); - final LiveDataSupportedType? arg_type = - (args[1] as LiveDataSupportedType?); + final LiveDataSupportedType? arg_type = (args[1] as LiveDataSupportedType?); assert( arg_type != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance was null, expected non-null LiveDataSupportedType.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_type!) ?? - LiveData.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_type!) ?? + LiveData.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7017,19 +6542,15 @@ class LiveData extends PigeonInternalProxyApiBaseClass { /// Adds the given observer to the observers list within the lifespan of the /// given owner. Future observe(Observer observer) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecLiveData; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.LiveData.observe'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.observe'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, observer], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, observer]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7046,8 +6567,7 @@ class LiveData extends PigeonInternalProxyApiBaseClass { /// Removes all observers that are tied to the given `LifecycleOwner`. Future removeObservers() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecLiveData; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.removeObservers'; @@ -7056,9 +6576,7 @@ class LiveData extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7075,19 +6593,15 @@ class LiveData extends PigeonInternalProxyApiBaseClass { /// Returns the current value. Future getValue() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecLiveData; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.LiveData.getValue'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.getValue'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7147,10 +6661,9 @@ class ImageProxy extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ImageProxy Function(int format, int width, int height)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7188,22 +6701,17 @@ class ImageProxy extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_format!, - arg_width!, - arg_height!, - ) ?? - ImageProxy.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - format: arg_format!, - width: arg_width!, - height: arg_height!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_format!, arg_width!, arg_height!) ?? + ImageProxy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + format: arg_format!, + width: arg_width!, + height: arg_height!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7219,19 +6727,15 @@ class ImageProxy extends PigeonInternalProxyApiBaseClass { /// Returns the array of planes. Future> getPlanes() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageProxy; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageProxy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.getPlanes'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.getPlanes'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7253,19 +6757,15 @@ class ImageProxy extends PigeonInternalProxyApiBaseClass { /// Closes the underlying `android.media.Image`. Future close() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImageProxy; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageProxy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.close'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.close'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7299,10 +6799,7 @@ class ImageProxyUtils extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - ImageProxyUtils.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + ImageProxyUtils.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecImageProxyUtils = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -7313,10 +6810,9 @@ class ImageProxyUtils extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ImageProxyUtils Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7339,15 +6835,14 @@ class ImageProxyUtils extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxyUtils.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ImageProxyUtils.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ImageProxyUtils.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7370,16 +6865,11 @@ class ImageProxyUtils extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, }) async { if (PigeonOverrides.imageProxyUtils_getNv21Buffer != null) { - return PigeonOverrides.imageProxyUtils_getNv21Buffer!( - imageWidth, - imageHeight, - planes, - ); + return PigeonOverrides.imageProxyUtils_getNv21Buffer!(imageWidth, imageHeight, planes); } - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxyUtils.getNv21Buffer'; @@ -7388,9 +6878,11 @@ class ImageProxyUtils extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [imageWidth, imageHeight, planes], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + imageWidth, + imageHeight, + planes, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7450,13 +6942,11 @@ class PlaneProxy extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - PlaneProxy Function(Uint8List buffer, int pixelStride, int rowStride)? - pigeon_newInstance, + PlaneProxy Function(Uint8List buffer, int pixelStride, int rowStride)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7494,22 +6984,17 @@ class PlaneProxy extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_buffer!, - arg_pixelStride!, - arg_rowStride!, - ) ?? - PlaneProxy.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - buffer: arg_buffer!, - pixelStride: arg_pixelStride!, - rowStride: arg_rowStride!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_buffer!, arg_pixelStride!, arg_rowStride!) ?? + PlaneProxy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + buffer: arg_buffer!, + pixelStride: arg_pixelStride!, + rowStride: arg_rowStride!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7569,21 +7054,20 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { required VideoQuality quality, FallbackStrategy? fallbackStrategy, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecQualitySelector; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecQualitySelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.from'; + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.from'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, quality, fallbackStrategy], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + quality, + fallbackStrategy, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7629,10 +7113,8 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { required List qualities, FallbackStrategy? fallbackStrategy, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecQualitySelector; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecQualitySelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.fromOrderedList'; @@ -7641,9 +7123,11 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, qualities, fallbackStrategy], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + qualities, + fallbackStrategy, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7665,10 +7149,7 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - QualitySelector.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + QualitySelector.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecQualitySelector = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -7679,10 +7160,9 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, QualitySelector Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7705,15 +7185,14 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.QualitySelector.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - QualitySelector.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + QualitySelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7735,15 +7214,11 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, }) async { if (PigeonOverrides.qualitySelector_getResolution != null) { - return PigeonOverrides.qualitySelector_getResolution!( - cameraInfo, - quality, - ); + return PigeonOverrides.qualitySelector_getResolution!(cameraInfo, quality); } - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.getResolution'; @@ -7752,9 +7227,10 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraInfo, quality], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraInfo, + quality, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7792,9 +7268,7 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { required VideoQuality quality, }) { if (PigeonOverrides.fallbackStrategy_higherQualityOrLowerThan != null) { - return PigeonOverrides.fallbackStrategy_higherQualityOrLowerThan!( - quality: quality, - ); + return PigeonOverrides.fallbackStrategy_higherQualityOrLowerThan!(quality: quality); } return FallbackStrategy.pigeon_higherQualityOrLowerThan( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -7811,10 +7285,8 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required VideoQuality quality, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecFallbackStrategy; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityOrLowerThan'; @@ -7823,9 +7295,10 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, quality], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + quality, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7850,9 +7323,7 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { required VideoQuality quality, }) { if (PigeonOverrides.fallbackStrategy_higherQualityThan != null) { - return PigeonOverrides.fallbackStrategy_higherQualityThan!( - quality: quality, - ); + return PigeonOverrides.fallbackStrategy_higherQualityThan!(quality: quality); } return FallbackStrategy.pigeon_higherQualityThan( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -7869,10 +7340,8 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required VideoQuality quality, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecFallbackStrategy; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityThan'; @@ -7881,9 +7350,10 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, quality], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + quality, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7908,9 +7378,7 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { required VideoQuality quality, }) { if (PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan != null) { - return PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan!( - quality: quality, - ); + return PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan!(quality: quality); } return FallbackStrategy.pigeon_lowerQualityOrHigherThan( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -7927,10 +7395,8 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required VideoQuality quality, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecFallbackStrategy; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityOrHigherThan'; @@ -7939,9 +7405,10 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, quality], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + quality, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7966,9 +7433,7 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { required VideoQuality quality, }) { if (PigeonOverrides.fallbackStrategy_lowerQualityThan != null) { - return PigeonOverrides.fallbackStrategy_lowerQualityThan!( - quality: quality, - ); + return PigeonOverrides.fallbackStrategy_lowerQualityThan!(quality: quality); } return FallbackStrategy.pigeon_lowerQualityThan( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -7985,10 +7450,8 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required VideoQuality quality, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecFallbackStrategy; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityThan'; @@ -7997,9 +7460,10 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, quality], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + quality, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8021,10 +7485,7 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - FallbackStrategy.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + FallbackStrategy.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecFallbackStrategy = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -8035,10 +7496,9 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, FallbackStrategy Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8061,15 +7521,14 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - FallbackStrategy.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + FallbackStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8103,10 +7562,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - CameraControl.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + CameraControl.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraControl = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -8117,10 +7573,9 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CameraControl Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8143,15 +7598,14 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraControl.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CameraControl.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraControl.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8167,8 +7621,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { /// Enable the torch or disable the torch. Future enableTorch(bool torch) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraControl; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.enableTorch'; @@ -8177,9 +7630,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, torch], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, torch]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8196,8 +7647,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { /// Sets current zoom by ratio. Future setZoomRatio(double ratio) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraControl; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.setZoomRatio'; @@ -8206,9 +7656,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, ratio], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, ratio]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8225,11 +7673,8 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { /// Starts a focus and metering action configured by the /// `FocusMeteringAction`. - Future startFocusAndMetering( - FocusMeteringAction action, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraControl; + Future startFocusAndMetering(FocusMeteringAction action) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.startFocusAndMetering'; @@ -8238,9 +7683,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, action], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, action]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8257,8 +7700,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { /// Cancels current FocusMeteringAction and clears AF/AE/AWB regions. Future cancelFocusAndMetering() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraControl; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.cancelFocusAndMetering'; @@ -8267,9 +7709,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8286,8 +7726,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { /// Set the exposure compensation value for the camera. Future setExposureCompensationIndex(int index) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCameraControl; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.setExposureCompensationIndex'; @@ -8296,9 +7735,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, index], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, index]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8351,8 +7788,7 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required MeteringPoint point, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -8363,9 +7799,10 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, point], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + point, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8390,10 +7827,7 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { required MeteringMode mode, }) { if (PigeonOverrides.focusMeteringActionBuilder_withMode != null) { - return PigeonOverrides.focusMeteringActionBuilder_withMode!( - point: point, - mode: mode, - ); + return PigeonOverrides.focusMeteringActionBuilder_withMode!(point: point, mode: mode); } return FocusMeteringActionBuilder.pigeon_withMode( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -8411,8 +7845,7 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { required MeteringPoint point, required MeteringMode mode, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -8423,9 +7856,11 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, point, mode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + point, + mode, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -8452,10 +7887,8 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecFocusMeteringActionBuilder = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecFocusMeteringActionBuilder = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -8463,10 +7896,9 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, FocusMeteringActionBuilder Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8489,15 +7921,14 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - FocusMeteringActionBuilder.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + FocusMeteringActionBuilder.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8523,9 +7954,7 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, point], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, point]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8552,9 +7981,11 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, point, mode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + point, + mode, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8581,9 +8012,7 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8610,9 +8039,7 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8683,10 +8110,9 @@ class FocusMeteringAction extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8708,20 +8134,20 @@ class FocusMeteringAction extends PigeonInternalProxyApiBaseClass { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null int.', ); - final List? arg_meteringPointsAe = - (args[1] as List?)?.cast(); + final List? arg_meteringPointsAe = (args[1] as List?) + ?.cast(); assert( arg_meteringPointsAe != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List.', ); - final List? arg_meteringPointsAf = - (args[2] as List?)?.cast(); + final List? arg_meteringPointsAf = (args[2] as List?) + ?.cast(); assert( arg_meteringPointsAf != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List.', ); - final List? arg_meteringPointsAwb = - (args[3] as List?)?.cast(); + final List? arg_meteringPointsAwb = (args[3] as List?) + ?.cast(); assert( arg_meteringPointsAwb != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List.', @@ -8732,24 +8158,23 @@ class FocusMeteringAction extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null bool.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_meteringPointsAe!, - arg_meteringPointsAf!, - arg_meteringPointsAwb!, - arg_isAutoCancelEnabled!, - ) ?? - FocusMeteringAction.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - meteringPointsAe: arg_meteringPointsAe!, - meteringPointsAf: arg_meteringPointsAf!, - meteringPointsAwb: arg_meteringPointsAwb!, - isAutoCancelEnabled: arg_isAutoCancelEnabled!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_meteringPointsAe!, + arg_meteringPointsAf!, + arg_meteringPointsAwb!, + arg_isAutoCancelEnabled!, + ) ?? + FocusMeteringAction.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + meteringPointsAe: arg_meteringPointsAe!, + meteringPointsAf: arg_meteringPointsAf!, + meteringPointsAwb: arg_meteringPointsAwb!, + isAutoCancelEnabled: arg_isAutoCancelEnabled!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8800,10 +8225,9 @@ class FocusMeteringResult extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, FocusMeteringResult Function(bool isFocusSuccessful)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8831,16 +8255,15 @@ class FocusMeteringResult extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance was null, expected non-null bool.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_isFocusSuccessful!) ?? - FocusMeteringResult.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - isFocusSuccessful: arg_isFocusSuccessful!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_isFocusSuccessful!) ?? + FocusMeteringResult.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + isFocusSuccessful: arg_isFocusSuccessful!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8874,10 +8297,7 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - CaptureRequest.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + CaptureRequest.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); /// Whether auto-exposure (AE) is currently locked to its latest calculated /// values. @@ -8919,10 +8339,9 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CaptureRequest Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8945,15 +8364,14 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequest.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CaptureRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CaptureRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8968,14 +8386,15 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { } static CaptureRequestKey pigeonVar_controlAELock() { - final CaptureRequestKey pigeonVar_instance = - CaptureRequestKey.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final CaptureRequestKey pigeonVar_instance = CaptureRequestKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlAELock'; @@ -8984,9 +8403,9 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -9004,14 +8423,15 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { } static CaptureRequestKey pigeonVar_controlVideoStabilizationMode() { - final CaptureRequestKey pigeonVar_instance = - CaptureRequestKey.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final CaptureRequestKey pigeonVar_instance = CaptureRequestKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlVideoStabilizationMode'; @@ -9020,9 +8440,9 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -9058,10 +8478,7 @@ class CaptureRequestKey extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - CaptureRequestKey.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + CaptureRequestKey.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -9069,10 +8486,9 @@ class CaptureRequestKey extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CaptureRequestKey Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -9095,15 +8511,14 @@ class CaptureRequestKey extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestKey.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CaptureRequestKey.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CaptureRequestKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -9151,8 +8566,7 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required Map options, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCaptureRequestOptions; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -9163,9 +8577,10 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, options], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + options, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -9192,10 +8607,8 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecCaptureRequestOptions = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCaptureRequestOptions = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -9203,10 +8616,9 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CaptureRequestOptions Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -9229,15 +8641,14 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CaptureRequestOptions.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CaptureRequestOptions.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -9264,9 +8675,7 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, key], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, key]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -9302,9 +8711,7 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { required CameraControl cameraControl, }) { if (PigeonOverrides.camera2CameraControl_from != null) { - return PigeonOverrides.camera2CameraControl_from!( - cameraControl: cameraControl, - ); + return PigeonOverrides.camera2CameraControl_from!(cameraControl: cameraControl); } return Camera2CameraControl.pigeon_from( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -9320,8 +8727,7 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required CameraControl cameraControl, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -9332,9 +8738,10 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, cameraControl], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + cameraControl, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -9361,10 +8768,8 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecCamera2CameraControl = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCamera2CameraControl = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -9372,10 +8777,9 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, Camera2CameraControl Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -9398,15 +8802,14 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - Camera2CameraControl.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Camera2CameraControl.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -9433,9 +8836,7 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, bundle], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, bundle]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -9487,10 +8888,8 @@ class ResolutionFilter extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required CameraSize preferredSize, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecResolutionFilter; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionFilter; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.createWithOnePreferredSize'; @@ -9499,9 +8898,10 @@ class ResolutionFilter extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, preferredSize], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + preferredSize, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -9523,10 +8923,7 @@ class ResolutionFilter extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - ResolutionFilter.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + ResolutionFilter.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecResolutionFilter = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -9537,10 +8934,9 @@ class ResolutionFilter extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ResolutionFilter Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -9563,15 +8959,14 @@ class ResolutionFilter extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ResolutionFilter.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ResolutionFilter.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -9615,10 +9010,9 @@ class CameraCharacteristicsKey extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CameraCharacteristicsKey Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -9641,15 +9035,14 @@ class CameraCharacteristicsKey extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristicsKey.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CameraCharacteristicsKey.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraCharacteristicsKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -9700,8 +9093,7 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { /// Value is int. /// /// This key is available on all devices. - static final CameraCharacteristicsKey _sensorOrientation = - pigeonVar_sensorOrientation(); + static final CameraCharacteristicsKey _sensorOrientation = pigeonVar_sensorOrientation(); /// List of video stabilization modes for android.control.videoStabilizationMode /// that are supported by this camera device. @@ -9709,8 +9101,7 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { /// Value is `ControlAvailableVideoStabilizationMode`. /// /// This key is available on all devices. - static final CameraCharacteristicsKey - _controlAvailableVideoStabilizationModes = + static final CameraCharacteristicsKey _controlAvailableVideoStabilizationModes = pigeonVar_controlAvailableVideoStabilizationModes(); /// Generally classifies the overall set of the camera device functionality. @@ -9729,8 +9120,7 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { /// /// This key is available on all devices. static CameraCharacteristicsKey get sensorOrientation => - PigeonOverrides.cameraCharacteristics_sensorOrientation ?? - _sensorOrientation; + PigeonOverrides.cameraCharacteristics_sensorOrientation ?? _sensorOrientation; /// List of video stabilization modes for android.control.videoStabilizationMode /// that are supported by this camera device. @@ -9739,8 +9129,7 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { /// /// This key is available on all devices. static CameraCharacteristicsKey get controlAvailableVideoStabilizationModes => - PigeonOverrides - .cameraCharacteristics_controlAvailableVideoStabilizationModes ?? + PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes ?? _controlAvailableVideoStabilizationModes; static void pigeon_setUpMessageHandlers({ @@ -9749,10 +9138,9 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, CameraCharacteristics Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -9775,15 +9163,14 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CameraCharacteristics.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraCharacteristics.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -9798,14 +9185,15 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { } static CameraCharacteristicsKey pigeonVar_infoSupportedHardwareLevel() { - final CameraCharacteristicsKey pigeonVar_instance = - CameraCharacteristicsKey.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final CameraCharacteristicsKey pigeonVar_instance = CameraCharacteristicsKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.infoSupportedHardwareLevel'; @@ -9814,9 +9202,9 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -9834,14 +9222,15 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { } static CameraCharacteristicsKey pigeonVar_sensorOrientation() { - final CameraCharacteristicsKey pigeonVar_instance = - CameraCharacteristicsKey.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final CameraCharacteristicsKey pigeonVar_instance = CameraCharacteristicsKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.sensorOrientation'; @@ -9850,9 +9239,9 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -9869,16 +9258,16 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { return pigeonVar_instance; } - static CameraCharacteristicsKey - pigeonVar_controlAvailableVideoStabilizationModes() { - final CameraCharacteristicsKey pigeonVar_instance = - CameraCharacteristicsKey.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + static CameraCharacteristicsKey pigeonVar_controlAvailableVideoStabilizationModes() { + final CameraCharacteristicsKey pigeonVar_instance = CameraCharacteristicsKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.controlAvailableVideoStabilizationModes'; @@ -9887,9 +9276,9 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -9942,10 +9331,8 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required CameraInfo cameraInfo, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCamera2CameraInfo; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.from'; @@ -9954,9 +9341,10 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, cameraInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + cameraInfo, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -9978,15 +9366,10 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - Camera2CameraInfo.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + Camera2CameraInfo.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecCamera2CameraInfo = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCamera2CameraInfo = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -9994,10 +9377,9 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, Camera2CameraInfo Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -10020,15 +9402,14 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - Camera2CameraInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Camera2CameraInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -10044,8 +9425,7 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { /// Gets the string camera ID. Future getCameraId() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCamera2CameraInfo; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraId'; @@ -10054,9 +9434,7 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -10078,8 +9456,7 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { /// Gets a camera characteristic value. Future getCameraCharacteristic(CameraCharacteristicsKey key) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCamera2CameraInfo; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraCharacteristic'; @@ -10088,9 +9465,7 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, key], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, key]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -10128,10 +9503,8 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecMeteringPointFactory = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecMeteringPointFactory = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -10139,10 +9512,9 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, MeteringPointFactory Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -10165,15 +9537,14 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - MeteringPointFactory.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + MeteringPointFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -10199,9 +9570,7 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, x, y], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, x, y]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -10222,11 +9591,7 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { } /// Creates a MeteringPoint by x, y, size. - Future createPointWithSize( - double x, - double y, - double size, - ) async { + Future createPointWithSize(double x, double y, double size) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMeteringPointFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -10237,9 +9602,12 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, x, y, size], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + x, + y, + size, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -10311,8 +9679,7 @@ class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { required double width, required double height, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDisplayOrientedMeteringPointFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -10323,9 +9690,12 @@ class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, cameraInfo, width, height], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + cameraInfo, + width, + height, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -10352,8 +9722,7 @@ class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { super.pigeon_instanceManager, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecDisplayOrientedMeteringPointFactory = + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecDisplayOrientedMeteringPointFactory = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ @@ -10362,10 +9731,9 @@ class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { PigeonInstanceManager? pigeon_instanceManager, DisplayOrientedMeteringPointFactory Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -10388,15 +9756,14 @@ class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { 'Argument for dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - DisplayOrientedMeteringPointFactory.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + DisplayOrientedMeteringPointFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart b/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart index cf79195424d0..aa0899e3d85b 100644 --- a/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart +++ b/packages/camera/camera_android_camerax/lib/src/image_reader_rotated_preview.dart @@ -71,19 +71,15 @@ final class ImageReaderRotatedPreview extends StatefulWidget { State createState() => _ImageReaderRotatedPreviewState(); } -final class _ImageReaderRotatedPreviewState - extends State { +final class _ImageReaderRotatedPreviewState extends State { late DeviceOrientation deviceOrientation; late Future defaultDisplayRotationDegrees; late StreamSubscription deviceOrientationSubscription; Future _getCurrentDefaultDisplayRotationDegrees() async { - final int currentDefaultDisplayRotationQuarterTurns = await widget - .deviceOrientationManager + final int currentDefaultDisplayRotationQuarterTurns = await widget.deviceOrientationManager .getDefaultDisplayRotation(); - return getQuarterTurnsFromSurfaceRotationConstant( - currentDefaultDisplayRotationQuarterTurns, - ) * + return getQuarterTurnsFromSurfaceRotationConstant(currentDefaultDisplayRotationQuarterTurns) * 90; } @@ -91,14 +87,9 @@ final class _ImageReaderRotatedPreviewState void initState() { deviceOrientation = widget.initialDeviceOrientation; defaultDisplayRotationDegrees = Future.value( - getQuarterTurnsFromSurfaceRotationConstant( - widget.initialDefaultDisplayRotation, - ) * - 90, + getQuarterTurnsFromSurfaceRotationConstant(widget.initialDefaultDisplayRotation) * 90, ); - deviceOrientationSubscription = widget.deviceOrientation.listen(( - DeviceOrientation event, - ) { + deviceOrientationSubscription = widget.deviceOrientation.listen((DeviceOrientation event) { // Ensure that we aren't updating the state if the widget is being destroyed. if (!mounted) { return; @@ -106,8 +97,7 @@ final class _ImageReaderRotatedPreviewState setState(() { deviceOrientation = event; - defaultDisplayRotationDegrees = - _getCurrentDefaultDisplayRotationDegrees(); + defaultDisplayRotationDegrees = _getCurrentDefaultDisplayRotationDegrees(); }); }); super.initState(); @@ -122,17 +112,13 @@ final class _ImageReaderRotatedPreviewState // Rotate the camera preview according to // https://developer.android.com/media/camera/camera2/camera-preview#orientation_calculation. double rotationDegrees = - (sensorOrientationDegrees - - currentDefaultDisplayRotationDegrees * sign + - 360) % - 360; + (sensorOrientationDegrees - currentDefaultDisplayRotationDegrees * sign + 360) % 360; // Then, subtract the rotation already applied in the CameraPreview widget // (see camera/camera/lib/src/camera_preview.dart) that is not correct // for this plugin. final double extraRotationDegrees = - getPreAppliedQuarterTurnsRotationFromDeviceOrientation(orientation) * - 90; + getPreAppliedQuarterTurnsRotationFromDeviceOrientation(orientation) * 90; rotationDegrees -= extraRotationDegrees; return rotationDegrees; @@ -171,10 +157,7 @@ final class _ImageReaderRotatedPreviewState } } - return RotatedBox( - quarterTurns: rotationDegrees ~/ 90, - child: cameraPreview, - ); + return RotatedBox(quarterTurns: rotationDegrees ~/ 90, child: cameraPreview); } else { return const SizedBox.shrink(); } diff --git a/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart b/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart index ab1193f5679f..838ef71e784a 100644 --- a/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart +++ b/packages/camera/camera_android_camerax/lib/src/rotated_preview_utils.dart @@ -24,9 +24,7 @@ int getQuarterTurnsFromSurfaceRotationConstant(int surfaceRotationConstant) { /// Returns the clockwise quarter turns applied by the CameraPreview widget /// based on [orientation], the current device orientation (see /// camera/camera/lib/src/camera_preview.dart). -int getPreAppliedQuarterTurnsRotationFromDeviceOrientation( - DeviceOrientation orientation, -) { +int getPreAppliedQuarterTurnsRotationFromDeviceOrientation(DeviceOrientation orientation) { return switch (orientation) { DeviceOrientation.portraitUp => 0, DeviceOrientation.landscapeRight => 1, diff --git a/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart b/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart index ded79a039d28..a2a1b62553aa 100644 --- a/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart +++ b/packages/camera/camera_android_camerax/lib/src/surface_texture_rotated_preview.dart @@ -50,31 +50,24 @@ final class SurfaceTextureRotatedPreview extends StatefulWidget { State createState() => _SurfaceTextureRotatedPreviewState(); } -final class _SurfaceTextureRotatedPreviewState - extends State { +final class _SurfaceTextureRotatedPreviewState extends State { late StreamSubscription deviceOrientationSubscription; late int preappliedRotationQuarterTurns; late Future defaultDisplayRotationQuarterTurns; Future _getCurrentDefaultDisplayRotationQuarterTurns() async { - final int currentDefaultDisplayRotationQuarterTurns = await widget - .deviceOrientationManager + final int currentDefaultDisplayRotationQuarterTurns = await widget.deviceOrientationManager .getDefaultDisplayRotation(); - return getQuarterTurnsFromSurfaceRotationConstant( - currentDefaultDisplayRotationQuarterTurns, - ); + return getQuarterTurnsFromSurfaceRotationConstant(currentDefaultDisplayRotationQuarterTurns); } @override void initState() { - preappliedRotationQuarterTurns = - getPreAppliedQuarterTurnsRotationFromDeviceOrientation( - widget.initialDeviceOrientation, - ); + preappliedRotationQuarterTurns = getPreAppliedQuarterTurnsRotationFromDeviceOrientation( + widget.initialDeviceOrientation, + ); defaultDisplayRotationQuarterTurns = Future.value( - getQuarterTurnsFromSurfaceRotationConstant( - widget.initialDefaultDisplayRotation, - ), + getQuarterTurnsFromSurfaceRotationConstant(widget.initialDefaultDisplayRotation), ); deviceOrientationSubscription = widget.deviceOrientationStream.listen(( DeviceOrientation event, @@ -85,10 +78,10 @@ final class _SurfaceTextureRotatedPreviewState } setState(() { - preappliedRotationQuarterTurns = - getPreAppliedQuarterTurnsRotationFromDeviceOrientation(event); - defaultDisplayRotationQuarterTurns = - _getCurrentDefaultDisplayRotationQuarterTurns(); + preappliedRotationQuarterTurns = getPreAppliedQuarterTurnsRotationFromDeviceOrientation( + event, + ); + defaultDisplayRotationQuarterTurns = _getCurrentDefaultDisplayRotationQuarterTurns(); }); }); super.initState(); @@ -114,10 +107,7 @@ final class _SurfaceTextureRotatedPreviewState final int rotationCorrection = currentDefaultDisplayRotation - preappliedRotationQuarterTurns; - return RotatedBox( - quarterTurns: rotationCorrection, - child: widget.child, - ); + return RotatedBox(quarterTurns: rotationCorrection, child: widget.child); } else { return const SizedBox.shrink(); } diff --git a/packages/camera/camera_android_camerax/pigeons/camerax_library.dart b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart index 611157f65248..61bf6c5978a4 100644 --- a/packages/camera/camera_android_camerax/pigeons/camerax_library.dart +++ b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart @@ -10,8 +10,7 @@ import 'package:pigeon/pigeon.dart'; PigeonOptions( copyrightHeader: 'pigeons/copyright.txt', dartOut: 'lib/src/camerax_library.g.dart', - kotlinOut: - 'android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt', + kotlinOut: 'android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt', kotlinOptions: KotlinOptions( package: 'io.flutter.plugins.camerax', errorClassName: 'CameraXError', @@ -21,9 +20,7 @@ import 'package:pigeon/pigeon.dart'; /// Immutable class for describing width and height dimensions in pixels. /// /// See https://developer.android.com/reference/android/util/Size.html. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Size'), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Size')) abstract class CameraSize { CameraSize(); @@ -39,9 +36,7 @@ abstract class CameraSize { /// /// See https://developer.android.com/reference/androidx/camera/core/ResolutionInfo. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.ResolutionInfo', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ResolutionInfo'), ) abstract class ResolutionInfo { /// Returns the output resolution used for the use case. @@ -120,9 +115,7 @@ enum LiveDataSupportedType { cameraState, zoomState } /// This is the equivalent to `android.util.Range`. /// /// See https://developer.android.com/reference/android/util/Range.html. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Range<*>'), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Range<*>')) abstract class CameraIntegerRange { CameraIntegerRange(); @@ -163,9 +156,7 @@ enum VideoQuality { /// /// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.VideoRecordEvent', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.VideoRecordEvent'), ) abstract class VideoRecordEvent {} @@ -193,11 +184,7 @@ abstract class VideoRecordEventFinalize extends VideoRecordEvent {} /// sensor coordinate system for focus and metering purpose. /// /// See https://developer.android.com/reference/androidx/camera/core/MeteringPoint. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.MeteringPoint', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.MeteringPoint')) abstract class MeteringPoint { /// Size of the MeteringPoint width and height (ranging from 0 to 1). /// @@ -226,11 +213,7 @@ enum MeteringMode { /// A simple callback that can receive from LiveData. /// /// See https://developer.android.com/reference/androidx/lifecycle/Observer. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.lifecycle.Observer<*>', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.lifecycle.Observer<*>')) abstract class Observer { Observer(); @@ -241,11 +224,7 @@ abstract class Observer { /// An interface for retrieving camera information. /// /// See https://developer.android.com/reference/androidx/camera/core/CameraInfo. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.CameraInfo', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraInfo')) abstract class CameraInfo { /// Returns the sensor rotation in degrees, relative to the device's "natural" /// (default) orientation. @@ -288,15 +267,10 @@ enum LensFacing { /// /// See https://developer.android.com/reference/androidx/camera/core/CameraSelector. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.CameraSelector', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraSelector'), ) abstract class CameraSelector { - CameraSelector( - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - ); + CameraSelector(LensFacing? requireLensFacing, CameraInfo? cameraInfoForFilter); /// A static `CameraSelector` that selects the default back facing camera. @static @@ -346,11 +320,7 @@ abstract class ProcessCameraProvider { /// The use case which all other use cases are built on top of. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/UseCase. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.UseCase', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.UseCase')) abstract class UseCase {} /// The camera interface is used to control the flow of data to use cases, @@ -358,11 +328,7 @@ abstract class UseCase {} /// camera via CameraInfo. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/Camera. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.Camera', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.Camera')) abstract class Camera { /// The `CameraControl` for the Camera. late CameraControl cameraControl; @@ -413,11 +379,7 @@ abstract class DeviceOrientationManager { /// A use case that provides a camera preview stream for displaying on-screen. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/Preview. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.Preview', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.Preview')) abstract class Preview extends UseCase { Preview(int? targetRotation, CameraIntegerRange? targetFpsRange); @@ -452,16 +414,11 @@ abstract class Preview extends UseCase { /// /// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoCapture. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.VideoCapture<*>', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.VideoCapture<*>'), ) abstract class VideoCapture extends UseCase { /// Create a `VideoCapture` associated with the given `VideoOutput`. - VideoCapture.withOutput( - VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - ); + VideoCapture.withOutput(VideoOutput videoOutput, CameraIntegerRange? targetFpsRange); /// Gets the VideoOutput associated with this VideoCapture. VideoOutput getOutput(); @@ -473,28 +430,16 @@ abstract class VideoCapture extends UseCase { /// A class that will produce video data from a Surface. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoOutput. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.VideoOutput', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.VideoOutput')) abstract class VideoOutput {} /// An implementation of `VideoOutput` for starting video recordings that are /// saved to a File, ParcelFileDescriptor, or MediaStore. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recorder. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.Recorder', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.Recorder')) abstract class Recorder implements VideoOutput { - Recorder( - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - ); + Recorder(int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector); /// Gets the aspect ratio of this Recorder. int getAspectRatio(); @@ -521,9 +466,7 @@ abstract class VideoRecordEventListener { /// /// See https://developer.android.com/reference/kotlin/androidx/camera/video/PendingRecording. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.PendingRecording', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.PendingRecording'), ) abstract class PendingRecording { /// Enables/disables audio to be recorded for this recording. @@ -547,11 +490,7 @@ abstract class PendingRecording { /// Provides controls for the currently active recording. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recording. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.Recording', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.Recording')) abstract class Recording { /// Close this recording. void close(); @@ -592,11 +531,7 @@ enum CameraXFlashMode { /// A use case for taking a picture. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.ImageCapture', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageCapture')) abstract class ImageCapture extends UseCase { ImageCapture(int? targetRotation, CameraXFlashMode? flashMode); @@ -655,10 +590,7 @@ enum ResolutionStrategyFallbackRule { ), ) abstract class ResolutionStrategy { - ResolutionStrategy( - CameraSize boundSize, - ResolutionStrategyFallbackRule fallbackRule, - ); + ResolutionStrategy(CameraSize boundSize, ResolutionStrategyFallbackRule fallbackRule); /// A resolution strategy chooses the highest available resolution. @static @@ -720,8 +652,7 @@ enum AspectRatioStrategyFallbackRule { /// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'androidx.camera.core.resolutionselector.AspectRatioStrategy', + fullClassName: 'androidx.camera.core.resolutionselector.AspectRatioStrategy', ), ) abstract class AspectRatioStrategy { @@ -753,11 +684,7 @@ abstract class AspectRatioStrategy { /// Represents the different states the camera can be in. /// /// See https://developer.android.com/reference/androidx/camera/core/CameraState. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.CameraState', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraState')) abstract class CameraState { /// The camera's state. late CameraStateType type; @@ -769,11 +696,7 @@ abstract class CameraState { /// An interface which contains the camera exposure related information. /// /// See https://developer.android.com/reference/androidx/camera/core/ExposureState. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.ExposureState', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ExposureState')) abstract class ExposureState { /// Get the maximum and minimum exposure compensation values for /// `CameraControl.setExposureCompensationIndex`. @@ -786,11 +709,7 @@ abstract class ExposureState { /// An interface which contains the zoom related information from a camera. /// /// See https://developer.android.com/reference/androidx/camera/core/ZoomState. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.ZoomState', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ZoomState')) abstract class ZoomState { /// The minimum zoom ratio. late double minZoomRatio; @@ -803,17 +722,9 @@ abstract class ZoomState { /// analysis on. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.ImageAnalysis', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageAnalysis')) abstract class ImageAnalysis extends UseCase { - ImageAnalysis( - int? targetRotation, - CameraIntegerRange? targetFpsRange, - int? outputImageFormat, - ); + ImageAnalysis(int? targetRotation, CameraIntegerRange? targetFpsRange, int? outputImageFormat); late final ResolutionSelector? resolutionSelector; @@ -900,8 +811,7 @@ abstract class CameraStateStateError { /// See https://developer.android.com/reference/androidx/lifecycle/LiveData. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper', + fullClassName: 'io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper', ), ) abstract class LiveData { @@ -922,11 +832,7 @@ abstract class LiveData { /// An image proxy which has a similar interface as `android.media.Image`. /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.ImageProxy', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageProxy')) abstract class ImageProxy { /// The image format. late int format; @@ -949,11 +855,7 @@ abstract class ImageProxy { abstract class ImageProxyUtils { /// Returns a single buffer that is representative of three NV21-compatible [planes]. @static - Uint8List getNv21Buffer( - int imageWidth, - int imageHeight, - List planes, - ); + Uint8List getNv21Buffer(int imageWidth, int imageHeight, List planes); } /// A plane proxy which has an analogous interface as @@ -961,9 +863,7 @@ abstract class ImageProxyUtils { /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy.PlaneProxy. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.ImageProxy.PlaneProxy', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.ImageProxy.PlaneProxy'), ) abstract class PlaneProxy { /// The pixels buffer. @@ -981,22 +881,14 @@ abstract class PlaneProxy { /// /// See https://developer.android.com/reference/kotlin/androidx/camera/video/QualitySelector. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.QualitySelector', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.QualitySelector'), ) abstract class QualitySelector { /// Gets an instance of QualitySelector with a desired quality. - QualitySelector.from( - VideoQuality quality, - FallbackStrategy? fallbackStrategy, - ); + QualitySelector.from(VideoQuality quality, FallbackStrategy? fallbackStrategy); /// Gets an instance of QualitySelector with ordered desired qualities. - QualitySelector.fromOrderedList( - List qualities, - FallbackStrategy? fallbackStrategy, - ); + QualitySelector.fromOrderedList(List qualities, FallbackStrategy? fallbackStrategy); /// Gets the corresponding resolution from the input quality. @static @@ -1009,9 +901,7 @@ abstract class QualitySelector { /// /// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.video.FallbackStrategy', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.video.FallbackStrategy'), ) abstract class FallbackStrategy { /// Returns a fallback strategy that will choose the quality that is closest @@ -1036,11 +926,7 @@ abstract class FallbackStrategy { /// camera. /// /// See https://developer.android.com/reference/androidx/camera/core/CameraControl. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.CameraControl', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.CameraControl')) abstract class CameraControl { /// Enable the torch or disable the torch. @async @@ -1097,9 +983,7 @@ abstract class FocusMeteringActionBuilder { /// /// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.FocusMeteringAction', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.FocusMeteringAction'), ) abstract class FocusMeteringAction { /// All MeteringPoints used for AE regions. @@ -1119,9 +1003,7 @@ abstract class FocusMeteringAction { /// /// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringResult. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.FocusMeteringResult', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.FocusMeteringResult'), ) abstract class FocusMeteringResult { /// If auto focus is successful. @@ -1133,9 +1015,7 @@ abstract class FocusMeteringResult { /// /// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'android.hardware.camera2.CaptureRequest', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.hardware.camera2.CaptureRequest'), ) abstract class CaptureRequest { /// Whether auto-exposure (AE) is currently locked to its latest calculated @@ -1285,9 +1165,7 @@ abstract class Camera2CameraInfo { /// /// See https://developer.android.com/reference/androidx/camera/core/MeteringPointFactory. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'androidx.camera.core.MeteringPointFactory', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'androidx.camera.core.MeteringPointFactory'), ) abstract class MeteringPointFactory { /// Creates a MeteringPoint by x, y. @@ -1307,14 +1185,9 @@ abstract class MeteringPointFactory { fullClassName: 'androidx.camera.core.DisplayOrientedMeteringPointFactory', ), ) -abstract class DisplayOrientedMeteringPointFactory - extends MeteringPointFactory { +abstract class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { /// Creates a DisplayOrientedMeteringPointFactory for converting View (x, y) /// into a MeteringPoint based on the current display's rotation and /// CameraInfo. - DisplayOrientedMeteringPointFactory( - CameraInfo cameraInfo, - double width, - double height, - ); + DisplayOrientedMeteringPointFactory(CameraInfo cameraInfo, double width, double height); } diff --git a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart index 71ed3d58ccde..edfcdc597df3 100644 --- a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart +++ b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart @@ -9,8 +9,7 @@ import 'package:async/async.dart'; import 'package:camera_android_camerax/camera_android_camerax.dart'; import 'package:camera_android_camerax/src/camerax_library.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; -import 'package:flutter/services.dart' - show DeviceOrientation, PlatformException, Uint8List; +import 'package:flutter/services.dart' show DeviceOrientation, PlatformException, Uint8List; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -78,23 +77,14 @@ void main() { final testCameraStateError = CameraStateStateError.pigeon_detached( code: CameraStateErrorCode.doNotDisturbModeEnabled, ); - final Stream cameraClosingEventStream = camera - .onCameraClosing(cameraId); - final cameraClosingStreamQueue = StreamQueue( - cameraClosingEventStream, - ); - final Stream cameraErrorEventStream = camera - .onCameraError(cameraId); - final cameraErrorStreamQueue = StreamQueue( - cameraErrorEventStream, - ); + final Stream cameraClosingEventStream = camera.onCameraClosing(cameraId); + final cameraClosingStreamQueue = StreamQueue(cameraClosingEventStream); + final Stream cameraErrorEventStream = camera.onCameraError(cameraId); + final cameraErrorStreamQueue = StreamQueue(cameraErrorEventStream); observer.onChanged( observer, - CameraState.pigeon_detached( - type: CameraStateType.closing, - error: testCameraStateError, - ), + CameraState.pigeon_detached(type: CameraStateType.closing, error: testCameraStateError), ); final cameraClosingEventSent = @@ -120,10 +110,7 @@ void main() { createWithOnePreferredSizeResolutionFilter, FallbackStrategy Function({required VideoQuality quality})? lowerQualityOrHigherThanFallbackStrategy, - QualitySelector Function({ - required VideoQuality quality, - FallbackStrategy? fallbackStrategy, - })? + QualitySelector Function({required VideoQuality quality, FallbackStrategy? fallbackStrategy})? fromQualitySelector, Preview Function({ int? targetRotation, @@ -131,10 +118,7 @@ void main() { ResolutionSelector? resolutionSelector, })? newPreview, - VideoCapture Function({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - })? + VideoCapture Function({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange})? withOutputVideoCapture, ImageAnalysis Function({ ResolutionSelector? resolutionSelector, @@ -143,19 +127,13 @@ void main() { CameraIntegerRange? targetFpsRange, })? newImageAnalysis, - Analyzer Function({required void Function(Analyzer, ImageProxy) analyze})? - newAnalyzer, - Future Function( - int imageWidth, - int imageHeight, - List planes, - )? + Analyzer Function({required void Function(Analyzer, ImageProxy) analyze})? newAnalyzer, + Future Function(int imageWidth, int imageHeight, List planes)? getNv21BufferImageProxyUtils, }) { final AspectRatioStrategy ratio_4_3FallbackAutoStrategyAspectRatioStrategy = MockAspectRatioStrategy(); - final ResolutionStrategy highestAvailableStrategyResolutionStrategy = - MockResolutionStrategy(); + final ResolutionStrategy highestAvailableStrategyResolutionStrategy = MockResolutionStrategy(); PigeonOverrides.processCameraProvider_getInstance = () async { return mockProcessCameraProvider; }; @@ -180,16 +158,10 @@ void main() { ResolutionSelector? resolutionSelector, }) { final mockPreview = MockPreview(); - final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: MockCameraSize(), - ); - when( - mockPreview.surfaceProducerHandlesCropAndRotation(), - ).thenAnswer((_) async => false); + final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); + when(mockPreview.surfaceProducerHandlesCropAndRotation()).thenAnswer((_) async => false); when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); return mockPreview; }; PigeonOverrides.imageCapture_new = @@ -199,17 +171,11 @@ void main() { ResolutionSelector? resolutionSelector, }) { final mockImageCapture = MockImageCapture(); - when( - mockImageCapture.resolutionSelector, - ).thenReturn(resolutionSelector); + when(mockImageCapture.resolutionSelector).thenReturn(resolutionSelector); return mockImageCapture; }; PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - }) { + ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) { final mockRecorder = MockRecorder(); when( mockRecorder.getQualitySelector(), @@ -218,10 +184,7 @@ void main() { }; PigeonOverrides.videoCapture_withOutput = withOutputVideoCapture ?? - ({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - }) { + ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) { return MockVideoCapture(); }; PigeonOverrides.imageAnalysis_new = @@ -233,23 +196,14 @@ void main() { ResolutionSelector? resolutionSelector, }) { final mockImageAnalysis = MockImageAnalysis(); - when( - mockImageAnalysis.resolutionSelector, - ).thenReturn(resolutionSelector); + when(mockImageAnalysis.resolutionSelector).thenReturn(resolutionSelector); return mockImageAnalysis; }; PigeonOverrides.resolutionStrategy_new = - ({ - required CameraSize boundSize, - required ResolutionStrategyFallbackRule fallbackRule, - }) { + ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) { final resolutionStrategy = MockResolutionStrategy(); - when( - resolutionStrategy.getBoundSize(), - ).thenAnswer((_) async => boundSize); - when( - resolutionStrategy.getFallbackRule(), - ).thenAnswer((_) async => fallbackRule); + when(resolutionStrategy.getBoundSize()).thenAnswer((_) async => boundSize); + when(resolutionStrategy.getFallbackRule()).thenAnswer((_) async => fallbackRule); return resolutionStrategy; }; PigeonOverrides.resolutionSelector_new = @@ -260,16 +214,10 @@ void main() { }) { final mockResolutionSelector = MockResolutionSelector(); when(mockResolutionSelector.getAspectRatioStrategy()).thenAnswer( - (_) async => - aspectRatioStrategy ?? - AspectRatioStrategy.ratio_4_3FallbackAutoStrategy, + (_) async => aspectRatioStrategy ?? AspectRatioStrategy.ratio_4_3FallbackAutoStrategy, ); - when( - mockResolutionSelector.resolutionStrategy, - ).thenReturn(resolutionStrategy); - when( - mockResolutionSelector.resolutionFilter, - ).thenReturn(resolutionFilter); + when(mockResolutionSelector.resolutionStrategy).thenReturn(resolutionStrategy); + when(mockResolutionSelector.resolutionFilter).thenReturn(resolutionFilter); return mockResolutionSelector; }; PigeonOverrides.qualitySelector_from = @@ -277,21 +225,15 @@ void main() { ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { return MockQualitySelector(); }; - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; + GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { return MockSystemServicesManager(); }; PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final manager = MockDeviceOrientationManager(); when(manager.getUiOrientation()).thenAnswer((_) async { return 'PORTRAIT_UP'; @@ -304,9 +246,7 @@ void main() { required AspectRatioStrategyFallbackRule fallbackRule, }) { final mockAspectRatioStrategy = MockAspectRatioStrategy(); - when( - mockAspectRatioStrategy.getFallbackRule(), - ).thenAnswer((_) async => fallbackRule); + when(mockAspectRatioStrategy.getFallbackRule()).thenAnswer((_) async => fallbackRule); when( mockAspectRatioStrategy.getPreferredAspectRatio(), ).thenAnswer((_) async => preferredAspectRatio); @@ -317,17 +257,13 @@ void main() { ({required CameraSize preferredSize}) => MockResolutionFilter(); PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { final camera2cameraInfo = MockCamera2CameraInfo(); - when( - camera2cameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => 90); + when(camera2cameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => 90); return camera2cameraInfo; }; - PigeonOverrides.cameraSize_new = - ({required int width, required int height}) { - return CameraSize.pigeon_detached(width: width, height: height); - }; - PigeonOverrides.cameraCharacteristics_sensorOrientation = - MockCameraCharacteristicsKey(); + PigeonOverrides.cameraSize_new = ({required int width, required int height}) { + return CameraSize.pigeon_detached(width: width, height: height); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = MockCameraCharacteristicsKey(); PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = lowerQualityOrHigherThanFallbackStrategy ?? ({required VideoQuality quality}) { @@ -337,10 +273,9 @@ void main() { highestAvailableStrategyResolutionStrategy; PigeonOverrides.aspectRatioStrategy_ratio_4_3FallbackAutoStrategy = ratio_4_3FallbackAutoStrategyAspectRatioStrategy; - PigeonOverrides.fallbackStrategy_lowerQualityThan = - ({required VideoQuality quality}) { - return MockFallbackStrategy(); - }; + PigeonOverrides.fallbackStrategy_lowerQualityThan = ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; PigeonOverrides.analyzer_new = newAnalyzer ?? ({required void Function(Analyzer, ImageProxy) analyze}) { @@ -358,10 +293,7 @@ void main() { /// Modifies the creation of [MeteringPoint]s and [FocusMeteringAction]s to /// return objects detached from a native object. void setUpOverridesForExposureAndFocus({ - FocusMeteringActionBuilder Function({ - required MeteringPoint point, - required MeteringMode mode, - })? + FocusMeteringActionBuilder Function({required MeteringPoint point, required MeteringMode mode})? withModeFocusMeteringActionBuilder, DisplayOrientedMeteringPointFactory Function({ required dynamic cameraInfo, @@ -372,11 +304,7 @@ void main() { }) { PigeonOverrides.displayOrientedMeteringPointFactory_new = newDisplayOrientedMeteringPointFactory ?? - ({ - required dynamic cameraInfo, - required double width, - required double height, - }) { + ({required dynamic cameraInfo, required double width, required double height}) { final mockFactory = MockDisplayOrientedMeteringPointFactory(); when(mockFactory.createPoint(any, any)).thenAnswer( (Invocation invocation) async => TestMeteringPoint.detached( @@ -414,22 +342,14 @@ void main() { meteringPointsAwb.add(point); } - when(mockBuilder.addPointWithMode(any, any)).thenAnswer(( - Invocation invocation, - ) async { + when(mockBuilder.addPointWithMode(any, any)).thenAnswer((Invocation invocation) async { switch (invocation.positionalArguments[1]) { case MeteringMode.ae: - meteringPointsAe.add( - invocation.positionalArguments.first as MeteringPoint, - ); + meteringPointsAe.add(invocation.positionalArguments.first as MeteringPoint); case MeteringMode.af: - meteringPointsAf.add( - invocation.positionalArguments.first as MeteringPoint, - ); + meteringPointsAf.add(invocation.positionalArguments.first as MeteringPoint); case MeteringMode.awb: - meteringPointsAwb.add( - invocation.positionalArguments.first as MeteringPoint, - ); + meteringPointsAwb.add(invocation.positionalArguments.first as MeteringPoint); } }); @@ -453,10 +373,7 @@ void main() { void setUpOverridesForSettingFocusandExposurePoints( CameraControl cameraControlForComparison, Camera2CameraControl camera2cameraControl, { - FocusMeteringActionBuilder Function({ - required MeteringPoint point, - required MeteringMode mode, - })? + FocusMeteringActionBuilder Function({required MeteringPoint point, required MeteringMode mode})? withModeFocusMeteringActionBuilder, DisplayOrientedMeteringPointFactory Function({ required dynamic cameraInfo, @@ -468,106 +385,86 @@ void main() { setUpOverridesForExposureAndFocus(); if (withModeFocusMeteringActionBuilder != null) { - PigeonOverrides.focusMeteringActionBuilder_withMode = - withModeFocusMeteringActionBuilder; + PigeonOverrides.focusMeteringActionBuilder_withMode = withModeFocusMeteringActionBuilder; } if (newDisplayOrientedMeteringPointFactory != null) { PigeonOverrides.displayOrientedMeteringPointFactory_new = newDisplayOrientedMeteringPointFactory; } - PigeonOverrides.camera2CameraControl_from = - ({required CameraControl cameraControl}) => - cameraControl == cameraControlForComparison - ? camera2cameraControl - : Camera2CameraControl.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) => + cameraControl == cameraControlForComparison + ? camera2cameraControl + : Camera2CameraControl.pigeon_detached(); - PigeonOverrides.captureRequestOptions_new = - ({required Map options}) { - final mockCaptureRequestOptions = MockCaptureRequestOptions(); - options.forEach((CaptureRequestKey key, Object? value) { - when( - mockCaptureRequestOptions.getCaptureRequestOption(key), - ).thenAnswer((_) async => value); - }); - return mockCaptureRequestOptions; - }; - PigeonOverrides.captureRequest_controlAELock = - CaptureRequestKey.pigeon_detached(); + PigeonOverrides + .captureRequestOptions_new = ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlAELock = CaptureRequestKey.pigeon_detached(); } - test( - 'Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final camera = AndroidCameraCameraX(); - final returnData = [ - { - 'name': '0', - 'lensFacing': 'back', - 'sensorOrientation': 0, - }, - { - 'name': '1', - 'lensFacing': 'front', - 'sensorOrientation': 90, - }, - ]; - - // Create mocks to use - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockFrontCameraInfo = MockCameraInfo(); - final mockBackCameraInfo = MockCameraInfo(); + test('Should fetch CameraDescription instances for available cameras', () async { + // Arrange + final camera = AndroidCameraCameraX(); + final returnData = [ + {'name': '0', 'lensFacing': 'back', 'sensorOrientation': 0}, + {'name': '1', 'lensFacing': 'front', 'sensorOrientation': 90}, + ]; - // Tell plugin to create mock CameraSelectors for testing. - PigeonOverrides.processCameraProvider_getInstance = () async => - mockProcessCameraProvider; - PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { - final camera2cameraInfo = MockCamera2CameraInfo(); - var cameraId = ''; - if (cameraInfo == mockBackCameraInfo) { - cameraId = '0'; - } else if (cameraInfo == mockFrontCameraInfo) { - cameraId = '1'; - } - when(camera2cameraInfo.getCameraId()).thenAnswer((_) async => cameraId); - return camera2cameraInfo; - }; - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { - return MockSystemServicesManager(); - }; + // Create mocks to use + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockFrontCameraInfo = MockCameraInfo(); + final mockBackCameraInfo = MockCameraInfo(); - // Mock calls to native platform - when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( - (_) async => [mockBackCameraInfo, mockFrontCameraInfo], - ); - when(mockBackCameraInfo.sensorRotationDegrees).thenReturn(0); - when(mockBackCameraInfo.lensFacing).thenReturn(LensFacing.back); - - when(mockFrontCameraInfo.sensorRotationDegrees).thenReturn(90); - when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front); - - final List cameraDescriptions = await camera - .availableCameras(); - - expect(cameraDescriptions.length, returnData.length); - for (var i = 0; i < returnData.length; i++) { - final Map typedData = - (returnData[i] as Map).cast(); - final cameraDescription = CameraDescription( - name: typedData['name']! as String, - lensDirection: (typedData['lensFacing']! as String) == 'front' - ? CameraLensDirection.front - : CameraLensDirection.back, - sensorOrientation: typedData['sensorOrientation']! as int, - ); - expect(cameraDescriptions[i], cameraDescription); + // Tell plugin to create mock CameraSelectors for testing. + PigeonOverrides.processCameraProvider_getInstance = () async => mockProcessCameraProvider; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final camera2cameraInfo = MockCamera2CameraInfo(); + var cameraId = ''; + if (cameraInfo == mockBackCameraInfo) { + cameraId = '0'; + } else if (cameraInfo == mockFrontCameraInfo) { + cameraId = '1'; } - }, - ); + when(camera2cameraInfo.getCameraId()).thenAnswer((_) async => cameraId); + return camera2cameraInfo; + }; + PigeonOverrides.systemServicesManager_new = + ({required void Function(SystemServicesManager, String) onCameraError}) { + return MockSystemServicesManager(); + }; + + // Mock calls to native platform + when( + mockProcessCameraProvider.getAvailableCameraInfos(), + ).thenAnswer((_) async => [mockBackCameraInfo, mockFrontCameraInfo]); + when(mockBackCameraInfo.sensorRotationDegrees).thenReturn(0); + when(mockBackCameraInfo.lensFacing).thenReturn(LensFacing.back); + + when(mockFrontCameraInfo.sensorRotationDegrees).thenReturn(90); + when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front); + + final List cameraDescriptions = await camera.availableCameras(); + + expect(cameraDescriptions.length, returnData.length); + for (var i = 0; i < returnData.length; i++) { + final Map typedData = (returnData[i] as Map) + .cast(); + final cameraDescription = CameraDescription( + name: typedData['name']! as String, + lensDirection: (typedData['lensFacing']! as String) == 'front' + ? CameraLensDirection.front + : CameraLensDirection.back, + sensorOrientation: typedData['sensorOrientation']! as int, + ); + expect(cameraDescriptions[i], cameraDescription); + } + }); test( 'createCamera requests permissions, starts listening for device orientation changes, updates camera state observers, and returns flutter surface texture ID', @@ -634,18 +531,11 @@ void main() { return mockImageCapture; }; PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - }) { + ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) { return mockRecorder; }; PigeonOverrides.videoCapture_withOutput = - ({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - }) { + ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) { return mockVideoCapture; }; PigeonOverrides.imageAnalysis_new = @@ -658,10 +548,7 @@ void main() { return mockImageAnalysis; }; PigeonOverrides.resolutionStrategy_new = - ({ - required CameraSize boundSize, - required ResolutionStrategyFallbackRule fallbackRule, - }) { + ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) { return MockResolutionStrategy(); }; PigeonOverrides.resolutionSelector_new = @@ -673,10 +560,7 @@ void main() { return MockResolutionSelector(); }; PigeonOverrides.qualitySelector_from = - ({ - required VideoQuality quality, - FallbackStrategy? fallbackStrategy, - }) { + ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { return MockQualitySelector(); }; GenericsPigeonOverrides.observerNew = @@ -684,28 +568,19 @@ void main() { return Observer.detached(onChanged: onChanged); }; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { - when( - mockSystemServicesManager.requestCameraPermissions(any), - ).thenAnswer((_) async { + ({required void Function(SystemServicesManager, String) onCameraError}) { + when(mockSystemServicesManager.requestCameraPermissions(any)).thenAnswer((_) async { cameraPermissionsRequested = true; return null; }); return mockSystemServicesManager; }; PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final manager = MockDeviceOrientationManager(); - when(manager.startListeningForDeviceOrientationChange()).thenAnswer( - (_) async { - startedListeningForDeviceOrientationChanges = true; - }, - ); + when(manager.startListeningForDeviceOrientationChange()).thenAnswer((_) async { + startedListeningForDeviceOrientationChanges = true; + }); when(manager.getUiOrientation()).thenAnswer((_) async { return 'PORTRAIT_UP'; }); @@ -725,40 +600,34 @@ void main() { PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { final camera2cameraInfo = MockCamera2CameraInfo(); when( - camera2cameraInfo.getCameraCharacteristic( - mockCameraCharacteristicsKey, - ), + camera2cameraInfo.getCameraCharacteristic(mockCameraCharacteristicsKey), ).thenAnswer((_) async => testSensorOrientation); return camera2cameraInfo; }; - PigeonOverrides.cameraSize_new = - ({required int width, required int height}) { - return MockCameraSize(); - }; - PigeonOverrides.cameraCharacteristics_sensorOrientation = - mockCameraCharacteristicsKey; + PigeonOverrides.cameraSize_new = ({required int width, required int height}) { + return MockCameraSize(); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey; PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) { return MockFallbackStrategy(); }; camera.processCameraProvider = mockProcessCameraProvider; - PigeonOverrides.cameraIntegerRange_new = - CameraIntegerRange.pigeon_detached; + PigeonOverrides.cameraIntegerRange_new = CameraIntegerRange.pigeon_detached; when( mockPreview.setSurfaceProvider(mockSystemServicesManager), ).thenAnswer((_) async => testSurfaceTextureId); when( - mockProcessCameraProvider.bindToLifecycle( - mockBackCameraSelector, - [mockPreview, mockImageCapture, mockImageAnalysis], - ), + mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, [ + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => mockLiveCameraState); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState); expect( await camera.createCameraWithSettings( @@ -815,13 +684,9 @@ void main() { final mockProcessCameraProvider = MockProcessCameraProvider(); final mockCameraInfo = MockCameraInfo(); - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); camera.processCameraProvider = mockProcessCameraProvider; // Tell plugin to create mock/detached objects for testing createCamera @@ -841,30 +706,15 @@ void main() { switch (resolutionPreset) { case ResolutionPreset.low: - expectedBoundSize = CameraSize.pigeon_detached( - width: 320, - height: 240, - ); + expectedBoundSize = CameraSize.pigeon_detached(width: 320, height: 240); case ResolutionPreset.medium: - expectedBoundSize = CameraSize.pigeon_detached( - width: 720, - height: 480, - ); + expectedBoundSize = CameraSize.pigeon_detached(width: 720, height: 480); case ResolutionPreset.high: - expectedBoundSize = CameraSize.pigeon_detached( - width: 1280, - height: 720, - ); + expectedBoundSize = CameraSize.pigeon_detached(width: 1280, height: 720); case ResolutionPreset.veryHigh: - expectedBoundSize = CameraSize.pigeon_detached( - width: 1920, - height: 1080, - ); + expectedBoundSize = CameraSize.pigeon_detached(width: 1920, height: 1080); case ResolutionPreset.ultraHigh: - expectedBoundSize = CameraSize.pigeon_detached( - width: 3840, - height: 2160, - ); + expectedBoundSize = CameraSize.pigeon_detached(width: 3840, height: 2160); case ResolutionPreset.max: continue; } @@ -877,8 +727,7 @@ void main() { expect(previewSize?.width, equals(expectedBoundSize.width)); expect(previewSize?.height, equals(expectedBoundSize.height)); expect( - await camera.preview!.resolutionSelector!.resolutionStrategy! - .getFallbackRule(), + await camera.preview!.resolutionSelector!.resolutionStrategy!.getFallbackRule(), ResolutionStrategyFallbackRule.closestLowerThenHigher, ); @@ -890,8 +739,7 @@ void main() { expect(imageCaptureSize?.width, equals(expectedBoundSize.width)); expect(imageCaptureSize?.height, equals(expectedBoundSize.height)); expect( - await camera.imageCapture!.resolutionSelector!.resolutionStrategy! - .getFallbackRule(), + await camera.imageCapture!.resolutionSelector!.resolutionStrategy!.getFallbackRule(), ResolutionStrategyFallbackRule.closestLowerThenHigher, ); @@ -903,18 +751,13 @@ void main() { expect(imageAnalysisSize?.width, equals(expectedBoundSize.width)); expect(imageAnalysisSize?.height, equals(expectedBoundSize.height)); expect( - await camera.imageAnalysis!.resolutionSelector!.resolutionStrategy! - .getFallbackRule(), + await camera.imageAnalysis!.resolutionSelector!.resolutionStrategy!.getFallbackRule(), ResolutionStrategyFallbackRule.closestLowerThenHigher, ); } // Test max case. - await camera.createCamera( - testCameraDescription, - ResolutionPreset.max, - enableAudio: true, - ); + await camera.createCamera(testCameraDescription, ResolutionPreset.max, enableAudio: true); expect( camera.preview!.resolutionSelector!.resolutionStrategy, @@ -930,10 +773,7 @@ void main() { ); // Test null case. - final int flutterSurfaceTextureId = await camera.createCamera( - testCameraDescription, - null, - ); + final int flutterSurfaceTextureId = await camera.createCamera(testCameraDescription, null); await camera.initializeCamera(flutterSurfaceTextureId); expect(camera.preview!.resolutionSelector, isNull); @@ -966,20 +806,15 @@ void main() { CameraSize? lastSetPreferredSize; setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, - createWithOnePreferredSizeResolutionFilter: - ({required CameraSize preferredSize}) { - lastSetPreferredSize = preferredSize; - return MockResolutionFilter(); - }, + createWithOnePreferredSizeResolutionFilter: ({required CameraSize preferredSize}) { + lastSetPreferredSize = preferredSize; + return MockResolutionFilter(); + }, ); - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); camera.processCameraProvider = mockProcessCameraProvider; // Test non-null resolution presets. @@ -995,90 +830,48 @@ void main() { switch (resolutionPreset) { case ResolutionPreset.low: - expectedPreferredResolution = CameraSize.pigeon_detached( - width: 320, - height: 240, - ); + expectedPreferredResolution = CameraSize.pigeon_detached(width: 320, height: 240); case ResolutionPreset.medium: - expectedPreferredResolution = CameraSize.pigeon_detached( - width: 720, - height: 480, - ); + expectedPreferredResolution = CameraSize.pigeon_detached(width: 720, height: 480); case ResolutionPreset.high: - expectedPreferredResolution = CameraSize.pigeon_detached( - width: 1280, - height: 720, - ); + expectedPreferredResolution = CameraSize.pigeon_detached(width: 1280, height: 720); case ResolutionPreset.veryHigh: - expectedPreferredResolution = CameraSize.pigeon_detached( - width: 1920, - height: 1080, - ); + expectedPreferredResolution = CameraSize.pigeon_detached(width: 1920, height: 1080); case ResolutionPreset.ultraHigh: - expectedPreferredResolution = CameraSize.pigeon_detached( - width: 3840, - height: 2160, - ); + expectedPreferredResolution = CameraSize.pigeon_detached(width: 3840, height: 2160); case ResolutionPreset.max: expectedPreferredResolution = null; } if (expectedPreferredResolution == null) { expect(camera.preview!.resolutionSelector!.resolutionFilter, isNull); - expect( - camera.imageCapture!.resolutionSelector!.resolutionFilter, - isNull, - ); - expect( - camera.imageAnalysis!.resolutionSelector!.resolutionFilter, - isNull, - ); + expect(camera.imageCapture!.resolutionSelector!.resolutionFilter, isNull); + expect(camera.imageAnalysis!.resolutionSelector!.resolutionFilter, isNull); continue; } - expect( - lastSetPreferredSize?.width, - equals(expectedPreferredResolution.width), - ); - expect( - lastSetPreferredSize?.height, - equals(expectedPreferredResolution.height), - ); + expect(lastSetPreferredSize?.width, equals(expectedPreferredResolution.width)); + expect(lastSetPreferredSize?.height, equals(expectedPreferredResolution.height)); final CameraSize? imageCaptureSize = await camera .imageCapture! .resolutionSelector! .resolutionStrategy! .getBoundSize(); - expect( - imageCaptureSize?.width, - equals(expectedPreferredResolution.width), - ); - expect( - imageCaptureSize?.height, - equals(expectedPreferredResolution.height), - ); + expect(imageCaptureSize?.width, equals(expectedPreferredResolution.width)); + expect(imageCaptureSize?.height, equals(expectedPreferredResolution.height)); final CameraSize? imageAnalysisSize = await camera .imageAnalysis! .resolutionSelector! .resolutionStrategy! .getBoundSize(); - expect( - imageAnalysisSize?.width, - equals(expectedPreferredResolution.width), - ); - expect( - imageAnalysisSize?.height, - equals(expectedPreferredResolution.height), - ); + expect(imageAnalysisSize?.width, equals(expectedPreferredResolution.width)); + expect(imageAnalysisSize?.height, equals(expectedPreferredResolution.height)); } // Test null case. - final int flutterSurfaceTextureId = await camera.createCamera( - testCameraDescription, - null, - ); + final int flutterSurfaceTextureId = await camera.createCamera(testCameraDescription, null); await camera.initializeCamera(flutterSurfaceTextureId); expect(camera.preview!.resolutionSelector, isNull); @@ -1110,13 +903,9 @@ void main() { // Tell plugin to create mock/detached objects for testing createCamera // as needed. setUpOverridesForTestingUseCaseConfiguration(mockProcessCameraProvider); - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); camera.processCameraProvider = mockProcessCameraProvider; // Test non-null resolution presets. @@ -1151,21 +940,17 @@ void main() { equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy), ); expect( - await camera.imageCapture!.resolutionSelector! - .getAspectRatioStrategy(), + await camera.imageCapture!.resolutionSelector!.getAspectRatioStrategy(), equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy), ); expect( - await camera.imageAnalysis!.resolutionSelector! - .getAspectRatioStrategy(), + await camera.imageAnalysis!.resolutionSelector!.getAspectRatioStrategy(), equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy), ); continue; } - final AspectRatioStrategy previewStrategy = await camera - .preview! - .resolutionSelector! + final AspectRatioStrategy previewStrategy = await camera.preview!.resolutionSelector! .getAspectRatioStrategy(); final AspectRatioStrategy imageCaptureStrategy = await camera .imageCapture! @@ -1177,32 +962,14 @@ void main() { .getAspectRatioStrategy(); // Check aspect ratio. - expect( - await previewStrategy.getPreferredAspectRatio(), - equals(expectedAspectRatio), - ); - expect( - await imageCaptureStrategy.getPreferredAspectRatio(), - equals(expectedAspectRatio), - ); - expect( - await imageAnalysisStrategy.getPreferredAspectRatio(), - equals(expectedAspectRatio), - ); + expect(await previewStrategy.getPreferredAspectRatio(), equals(expectedAspectRatio)); + expect(await imageCaptureStrategy.getPreferredAspectRatio(), equals(expectedAspectRatio)); + expect(await imageAnalysisStrategy.getPreferredAspectRatio(), equals(expectedAspectRatio)); // Check fallback rule. - expect( - await previewStrategy.getFallbackRule(), - equals(expectedFallbackRule), - ); - expect( - await imageCaptureStrategy.getFallbackRule(), - equals(expectedFallbackRule), - ); - expect( - await imageAnalysisStrategy.getFallbackRule(), - equals(expectedFallbackRule), - ); + expect(await previewStrategy.getFallbackRule(), equals(expectedFallbackRule)); + expect(await imageCaptureStrategy.getFallbackRule(), equals(expectedFallbackRule)); + expect(await imageAnalysisStrategy.getFallbackRule(), equals(expectedFallbackRule)); } // Test null case. @@ -1268,12 +1035,8 @@ void main() { CameraIntegerRange? targetFpsRange, ResolutionSelector? resolutionSelector, }) { - final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: MockCameraSize(), - ); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); + final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); return mockPreview; }; PigeonOverrides.imageCapture_new = @@ -1285,18 +1048,11 @@ void main() { return mockImageCapture; }; PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - }) { + ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) { return mockRecorder; }; PigeonOverrides.videoCapture_withOutput = - ({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - }) { + ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) { return mockVideoCapture; }; PigeonOverrides.imageAnalysis_new = @@ -1309,10 +1065,7 @@ void main() { return mockImageAnalysis; }; PigeonOverrides.resolutionStrategy_new = - ({ - required CameraSize boundSize, - required ResolutionStrategyFallbackRule fallbackRule, - }) { + ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) { return MockResolutionStrategy(); }; PigeonOverrides.resolutionSelector_new = @@ -1324,10 +1077,7 @@ void main() { return MockResolutionSelector(); }; PigeonOverrides.qualitySelector_from = - ({ - required VideoQuality quality, - FallbackStrategy? fallbackStrategy, - }) { + ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { return MockQualitySelector(); }; GenericsPigeonOverrides.observerNew = @@ -1335,16 +1085,11 @@ void main() { return Observer.detached(onChanged: onChanged); }; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { return MockSystemServicesManager(); }; PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final manager = MockDeviceOrientationManager(); when(manager.getUiOrientation()).thenAnswer((_) async { return 'PORTRAIT_UP'; @@ -1364,38 +1109,32 @@ void main() { }; PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { when( - mockCamera2CameraInfo.getCameraCharacteristic( - mockCameraCharacteristicsKey, - ), + mockCamera2CameraInfo.getCameraCharacteristic(mockCameraCharacteristicsKey), ).thenAnswer((_) async => testSensorOrientation); return mockCamera2CameraInfo; }; - PigeonOverrides.cameraSize_new = - ({required int width, required int height}) { - return MockCameraSize(); - }; - PigeonOverrides.cameraCharacteristics_sensorOrientation = - mockCameraCharacteristicsKey; + PigeonOverrides.cameraSize_new = ({required int width, required int height}) { + return MockCameraSize(); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey; PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) { return MockFallbackStrategy(); }; when( - mockProcessCameraProvider.bindToLifecycle( - mockBackCameraSelector, - [mockPreview, mockImageCapture, mockImageAnalysis], - ), + mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, [ + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl); camera.processCameraProvider = mockProcessCameraProvider; - PigeonOverrides.cameraIntegerRange_new = - CameraIntegerRange.pigeon_detached; + PigeonOverrides.cameraIntegerRange_new = CameraIntegerRange.pigeon_detached; final int flutterSurfaceTextureId = await camera.createCameraWithSettings( testCameraDescription, @@ -1411,10 +1150,11 @@ void main() { // Verify expected UseCases were bound. verify( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [mockPreview, mockImageCapture, mockImageAnalysis], - ), + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), ); // Verify the camera's CameraInfo instance got updated. @@ -1429,547 +1169,443 @@ void main() { }, ); - test( - 'createCamera properly sets preset resolution for video capture use case', - () async { - final camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const testSensorOrientation = 90; - const testCameraDescription = CameraDescription( - name: 'cameraName', - lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation, - ); - const enableAudio = true; - final mockCamera = MockCamera(); + test('createCamera properly sets preset resolution for video capture use case', () async { + final camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( + name: 'cameraName', + lensDirection: testLensDirection, + sensorOrientation: testSensorOrientation, + ); + const enableAudio = true; + final mockCamera = MockCamera(); - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockCameraInfo = MockCameraInfo(); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); - // Tell plugin to create mock/detached objects for testing createCamera - // as needed. - VideoQuality? fallbackStrategyVideoQuality; - VideoQuality? qualitySelectorVideoQuality; - FallbackStrategy? setFallbackStrategy; - final mockFallbackStrategy = MockFallbackStrategy(); - final mockQualitySelector = MockQualitySelector(); - setUpOverridesForTestingUseCaseConfiguration( - mockProcessCameraProvider, - lowerQualityOrHigherThanFallbackStrategy: - ({required VideoQuality quality}) { - fallbackStrategyVideoQuality = quality; - return mockFallbackStrategy; - }, - fromQualitySelector: - ({ - required VideoQuality quality, - FallbackStrategy? fallbackStrategy, - }) { - qualitySelectorVideoQuality = quality; - setFallbackStrategy = fallbackStrategy; - return mockQualitySelector; - }, - ); + // Tell plugin to create mock/detached objects for testing createCamera + // as needed. + VideoQuality? fallbackStrategyVideoQuality; + VideoQuality? qualitySelectorVideoQuality; + FallbackStrategy? setFallbackStrategy; + final mockFallbackStrategy = MockFallbackStrategy(); + final mockQualitySelector = MockQualitySelector(); + setUpOverridesForTestingUseCaseConfiguration( + mockProcessCameraProvider, + lowerQualityOrHigherThanFallbackStrategy: ({required VideoQuality quality}) { + fallbackStrategyVideoQuality = quality; + return mockFallbackStrategy; + }, + fromQualitySelector: ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { + qualitySelectorVideoQuality = quality; + setFallbackStrategy = fallbackStrategy; + return mockQualitySelector; + }, + ); - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - - // Test non-null resolution presets. - for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { - await camera.createCamera( - testCameraDescription, - resolutionPreset, - enableAudio: enableAudio, - ); - - VideoQuality? expectedVideoQuality; - switch (resolutionPreset) { - case ResolutionPreset.low: - // 240p is not supported by CameraX. - case ResolutionPreset.medium: - expectedVideoQuality = VideoQuality.SD; - case ResolutionPreset.high: - expectedVideoQuality = VideoQuality.HD; - case ResolutionPreset.veryHigh: - expectedVideoQuality = VideoQuality.FHD; - case ResolutionPreset.ultraHigh: - expectedVideoQuality = VideoQuality.UHD; - case ResolutionPreset.max: - expectedVideoQuality = VideoQuality.highest; - } - - expect( - await camera.recorder!.getQualitySelector(), - mockQualitySelector, - ); - expect(qualitySelectorVideoQuality, equals(expectedVideoQuality)); - expect(fallbackStrategyVideoQuality, equals(expectedVideoQuality)); - expect(setFallbackStrategy, equals(mockFallbackStrategy)); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); + + // Test non-null resolution presets. + for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { + await camera.createCamera(testCameraDescription, resolutionPreset, enableAudio: enableAudio); + + VideoQuality? expectedVideoQuality; + switch (resolutionPreset) { + case ResolutionPreset.low: + // 240p is not supported by CameraX. + case ResolutionPreset.medium: + expectedVideoQuality = VideoQuality.SD; + case ResolutionPreset.high: + expectedVideoQuality = VideoQuality.HD; + case ResolutionPreset.veryHigh: + expectedVideoQuality = VideoQuality.FHD; + case ResolutionPreset.ultraHigh: + expectedVideoQuality = VideoQuality.UHD; + case ResolutionPreset.max: + expectedVideoQuality = VideoQuality.highest; } - qualitySelectorVideoQuality = null; - setFallbackStrategy = null; - - // Test null case. - await camera.createCamera(testCameraDescription, null); - expect( - await camera.recorder!.getQualitySelector(), - isNot(equals(mockQualitySelector)), - ); - }, - ); - - test( - 'createCamera sets sensorOrientationDegrees and enableRecordingAudio as expected', - () async { - final camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const testSensorOrientation = 90; - const testCameraDescription = CameraDescription( - name: 'cameraName', - lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation, - ); - const enableAudio = true; - const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; - const testHandlesCropAndRotation = true; - - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final mockCamera = MockCamera(); - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockCameraInfo = MockCameraInfo(); - - // The proxy needed for this test is the same as testing resolution - // presets except for mocking the retrieval of the sensor and current - // UI orientation. - setUpOverridesForTestingUseCaseConfiguration( - mockProcessCameraProvider, - newPreview: - ({ - int? targetRotation, - CameraIntegerRange? targetFpsRange, - ResolutionSelector? resolutionSelector, - }) { - final mockPreview = MockPreview(); - when( - mockPreview.surfaceProducerHandlesCropAndRotation(), - ).thenAnswer((_) async => testHandlesCropAndRotation); - when( - mockPreview.resolutionSelector, - ).thenReturn(resolutionSelector); - return mockPreview; - }, - ); - - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - - await camera.createCamera( - testCameraDescription, - testResolutionPreset, - enableAudio: enableAudio, - ); - - expect(camera.sensorOrientationDegrees, testSensorOrientation); - expect(camera.enableRecordingAudio, isTrue); - }, - ); - - test( - 'createCamera and initializeCamera sets targetFps as expected', - () async { - final camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const testSensorOrientation = 90; - const testCameraDescription = CameraDescription( - name: 'cameraName', - lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation, - ); - const fastTargetFps = 60; - const testCameraId = 12; - final mockCamera = MockCamera(); - - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockCameraInfo = MockCameraInfo(); - - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - camera.processCameraProvider = mockProcessCameraProvider; - PigeonOverrides.cameraIntegerRange_new = - CameraIntegerRange.pigeon_detached; + expect(await camera.recorder!.getQualitySelector(), mockQualitySelector); + expect(qualitySelectorVideoQuality, equals(expectedVideoQuality)); + expect(fallbackStrategyVideoQuality, equals(expectedVideoQuality)); + expect(setFallbackStrategy, equals(mockFallbackStrategy)); + } - CameraIntegerRange? targetPreviewFpsRange; - CameraIntegerRange? targetVideoCaptureFpsRange; - CameraIntegerRange? targetImageAnalysisFpsRange; + qualitySelectorVideoQuality = null; + setFallbackStrategy = null; - setUpOverridesForTestingUseCaseConfiguration( - mockProcessCameraProvider, - newPreview: - ({ - ResolutionSelector? resolutionSelector, - CameraIntegerRange? targetFpsRange, - int? targetRotation, - }) { - targetPreviewFpsRange = targetFpsRange; - final mockPreview = MockPreview(); - final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: MockCameraSize(), - ); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); - return mockPreview; - }, - withOutputVideoCapture: - ({ - CameraIntegerRange? targetFpsRange, - required VideoOutput videoOutput, - }) { - targetVideoCaptureFpsRange = targetFpsRange; - return MockVideoCapture(); - }, - newImageAnalysis: - ({ - int? outputImageFormat, - ResolutionSelector? resolutionSelector, - CameraIntegerRange? targetFpsRange, - int? targetRotation, - }) { - targetImageAnalysisFpsRange = targetFpsRange; - return MockImageAnalysis(); - }, - ); + // Test null case. + await camera.createCamera(testCameraDescription, null); + expect(await camera.recorder!.getQualitySelector(), isNot(equals(mockQualitySelector))); + }); - await camera.createCameraWithSettings( - testCameraDescription, - const MediaSettings(fps: fastTargetFps), - ); - await camera.initializeCamera(testCameraId); + test('createCamera sets sensorOrientationDegrees and enableRecordingAudio as expected', () async { + final camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( + name: 'cameraName', + lensDirection: testLensDirection, + sensorOrientation: testSensorOrientation, + ); + const enableAudio = true; + const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; + const testHandlesCropAndRotation = true; - expect(targetPreviewFpsRange?.lower, fastTargetFps); - expect(targetPreviewFpsRange?.upper, fastTargetFps); - expect(targetVideoCaptureFpsRange?.lower, fastTargetFps); - expect(targetVideoCaptureFpsRange?.upper, fastTargetFps); - expect(targetImageAnalysisFpsRange?.lower, fastTargetFps); - expect(targetImageAnalysisFpsRange?.upper, fastTargetFps); - }, - ); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final mockCamera = MockCamera(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); - test( - 'createCamera properly selects specific back camera by specifying a CameraInfo', - () async { - // Arrange - final camera = AndroidCameraCameraX(); - final returnData = [ - { - 'name': '0', - 'lensFacing': 'back', - 'sensorOrientation': 0, - }, - { - 'name': '1', - 'lensFacing': 'back', - 'sensorOrientation': 0, - }, - { - 'name': '2', - 'lensFacing': 'front', - 'sensorOrientation': 0, - }, - ]; + // The proxy needed for this test is the same as testing resolution + // presets except for mocking the retrieval of the sensor and current + // UI orientation. + setUpOverridesForTestingUseCaseConfiguration( + mockProcessCameraProvider, + newPreview: + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) { + final mockPreview = MockPreview(); + when( + mockPreview.surfaceProducerHandlesCropAndRotation(), + ).thenAnswer((_) async => testHandlesCropAndRotation); + when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); + return mockPreview; + }, + ); - var mockCameraInfosList = []; - final cameraNameToInfos = {}; + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); - const testSensorOrientation = 0; + await camera.createCamera( + testCameraDescription, + testResolutionPreset, + enableAudio: enableAudio, + ); - // Mocks for objects created by availableCameras. - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockFrontCameraSelector = MockCameraSelector(); - final mockBackCameraSelector = MockCameraSelector(); - final mockChosenCameraInfoCameraSelector = MockCameraSelector(); + expect(camera.sensorOrientationDegrees, testSensorOrientation); + expect(camera.enableRecordingAudio, isTrue); + }); - final mockFrontCameraInfo = MockCameraInfo(); - final mockBackCameraInfoOne = MockCameraInfo(); - final mockBackCameraInfoTwo = MockCameraInfo(); + test('createCamera and initializeCamera sets targetFps as expected', () async { + final camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( + name: 'cameraName', + lensDirection: testLensDirection, + sensorOrientation: testSensorOrientation, + ); + const fastTargetFps = 60; + const testCameraId = 12; + final mockCamera = MockCamera(); - when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front); - when(mockBackCameraInfoOne.lensFacing).thenReturn(LensFacing.back); - when(mockBackCameraInfoTwo.lensFacing).thenReturn(LensFacing.back); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final mockPreview = MockPreview(); - final mockImageCapture = MockImageCapture(); - final mockImageAnalysis = MockImageAnalysis(); - final mockRecorder = MockRecorder(); - final mockVideoCapture = MockVideoCapture(); - final mockCamera = MockCamera(); - final mockCameraInfo = MockCameraInfo(); - final mockCameraControl = MockCameraControl(); - final mockCamera2CameraInfo = MockCamera2CameraInfo(); - final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey(); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); + camera.processCameraProvider = mockProcessCameraProvider; + PigeonOverrides.cameraIntegerRange_new = CameraIntegerRange.pigeon_detached; - // Tell plugin to create mock/detached objects and stub method calls for the - // testing of availableCameras and createCamera. - PigeonOverrides.processCameraProvider_getInstance = () { - return Future.value(mockProcessCameraProvider); - }; - PigeonOverrides.cameraSelector_new = - ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { - switch (requireLensFacing) { - case LensFacing.front: - return mockFrontCameraSelector; - case LensFacing.back: - case LensFacing.external: - case LensFacing.unknown: - case null: - } - if (cameraInfoForFilter == mockBackCameraInfoOne) { - return mockChosenCameraInfoCameraSelector; - } + CameraIntegerRange? targetPreviewFpsRange; + CameraIntegerRange? targetVideoCaptureFpsRange; + CameraIntegerRange? targetImageAnalysisFpsRange; - return mockBackCameraSelector; - }; - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { - return MockSystemServicesManager(); - }; - PigeonOverrides.preview_new = + setUpOverridesForTestingUseCaseConfiguration( + mockProcessCameraProvider, + newPreview: ({ - int? targetRotation, - CameraIntegerRange? targetFpsRange, ResolutionSelector? resolutionSelector, + CameraIntegerRange? targetFpsRange, + int? targetRotation, }) { + targetPreviewFpsRange = targetFpsRange; + final mockPreview = MockPreview(); + final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); return mockPreview; - }; - PigeonOverrides.imageCapture_new = + }, + withOutputVideoCapture: + ({CameraIntegerRange? targetFpsRange, required VideoOutput videoOutput}) { + targetVideoCaptureFpsRange = targetFpsRange; + return MockVideoCapture(); + }, + newImageAnalysis: ({ - int? targetRotation, - CameraXFlashMode? flashMode, + int? outputImageFormat, ResolutionSelector? resolutionSelector, - }) { - return mockImageCapture; - }; - PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - }) { - return mockRecorder; - }; - PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - }) { - return mockRecorder; - }; - PigeonOverrides.videoCapture_withOutput = - ({ - required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange, - }) { - return mockVideoCapture; - }; - PigeonOverrides.imageAnalysis_new = - ({ int? targetRotation, - CameraIntegerRange? targetFpsRange, - int? outputImageFormat, - ResolutionSelector? resolutionSelector, }) { - return mockImageAnalysis; - }; - PigeonOverrides.resolutionStrategy_new = - ({ - required CameraSize boundSize, - required ResolutionStrategyFallbackRule fallbackRule, - }) { - return MockResolutionStrategy(); - }; - PigeonOverrides.resolutionSelector_new = - ({ - AspectRatioStrategy? aspectRatioStrategy, - ResolutionStrategy? resolutionStrategy, - ResolutionFilter? resolutionFilter, - }) { - return MockResolutionSelector(); - }; - PigeonOverrides.resolutionSelector_new = - ({ - AspectRatioStrategy? aspectRatioStrategy, - ResolutionStrategy? resolutionStrategy, - ResolutionFilter? resolutionFilter, - }) { - return MockResolutionSelector(); - }; - PigeonOverrides.qualitySelector_from = - ({ - required VideoQuality quality, - FallbackStrategy? fallbackStrategy, - }) { - return MockQualitySelector(); - }; - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; - PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { - final manager = MockDeviceOrientationManager(); - when(manager.getUiOrientation()).thenAnswer((_) async { - return 'PORTRAIT_UP'; - }); - return manager; - }; - PigeonOverrides.aspectRatioStrategy_new = - ({ - required AspectRatio preferredAspectRatio, - required AspectRatioStrategyFallbackRule fallbackRule, - }) { - return MockAspectRatioStrategy(); - }; - PigeonOverrides.resolutionFilter_createWithOnePreferredSize = - ({required CameraSize preferredSize}) { - return MockResolutionFilter(); - }; - PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { - var cameraId = ''; - if (cameraInfo == mockBackCameraInfoOne) { - cameraId = '0'; - } else if (cameraInfo == mockBackCameraInfoTwo) { - cameraId = '1'; - } else if (cameraInfo == mockFrontCameraInfo) { - cameraId = '2'; - } - when( - mockCamera2CameraInfo.getCameraId(), - ).thenAnswer((_) async => cameraId); - when( - mockCamera2CameraInfo.getCameraCharacteristic( - mockCameraCharacteristicsKey, - ), - ).thenAnswer((_) async => testSensorOrientation); - return mockCamera2CameraInfo; - }; - PigeonOverrides.cameraSize_new = - ({required int width, required int height}) { - return MockCameraSize(); - }; - PigeonOverrides.cameraCharacteristics_sensorOrientation = - mockCameraCharacteristicsKey; - PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = - ({required VideoQuality quality}) { - return MockFallbackStrategy(); - }; - PigeonOverrides.cameraIntegerRange_new = - ({required int lower, required int upper}) { - return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0); - }; + targetImageAnalysisFpsRange = targetFpsRange; + return MockImageAnalysis(); + }, + ); - // Mock calls to native platform - when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer(( - _, - ) async { - mockCameraInfosList = [ - mockBackCameraInfoOne, - mockBackCameraInfoTwo, - mockFrontCameraInfo, - ]; - return [ - mockBackCameraInfoOne, - mockBackCameraInfoTwo, - mockFrontCameraInfo, - ]; - }); + await camera.createCameraWithSettings( + testCameraDescription, + const MediaSettings(fps: fastTargetFps), + ); + await camera.initializeCamera(testCameraId); + + expect(targetPreviewFpsRange?.lower, fastTargetFps); + expect(targetPreviewFpsRange?.upper, fastTargetFps); + expect(targetVideoCaptureFpsRange?.lower, fastTargetFps); + expect(targetVideoCaptureFpsRange?.upper, fastTargetFps); + expect(targetImageAnalysisFpsRange?.lower, fastTargetFps); + expect(targetImageAnalysisFpsRange?.upper, fastTargetFps); + }); - final List cameraDescriptions = await camera - .availableCameras(); - expect(cameraDescriptions.length, returnData.length); - - for (var i = 0; i < returnData.length; i++) { - final Map savedData = - (returnData[i] as Map).cast(); - - cameraNameToInfos[savedData['name']! as String] = - mockCameraInfosList[i]; - final cameraDescription = CameraDescription( - name: savedData['name']! as String, - lensDirection: (savedData['lensFacing']! as String) == 'front' - ? CameraLensDirection.front - : CameraLensDirection.back, - sensorOrientation: savedData['sensorOrientation']! as int, - ); - expect(cameraDescriptions[i], cameraDescription); - expect(cameraNameToInfos.containsKey(cameraDescription.name), isTrue); + test('createCamera properly selects specific back camera by specifying a CameraInfo', () async { + // Arrange + final camera = AndroidCameraCameraX(); + final returnData = [ + {'name': '0', 'lensFacing': 'back', 'sensorOrientation': 0}, + {'name': '1', 'lensFacing': 'back', 'sensorOrientation': 0}, + {'name': '2', 'lensFacing': 'front', 'sensorOrientation': 0}, + ]; + + var mockCameraInfosList = []; + final cameraNameToInfos = {}; + + const testSensorOrientation = 0; + + // Mocks for objects created by availableCameras. + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockFrontCameraSelector = MockCameraSelector(); + final mockBackCameraSelector = MockCameraSelector(); + final mockChosenCameraInfoCameraSelector = MockCameraSelector(); + + final mockFrontCameraInfo = MockCameraInfo(); + final mockBackCameraInfoOne = MockCameraInfo(); + final mockBackCameraInfoTwo = MockCameraInfo(); + + when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front); + when(mockBackCameraInfoOne.lensFacing).thenReturn(LensFacing.back); + when(mockBackCameraInfoTwo.lensFacing).thenReturn(LensFacing.back); + + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final mockPreview = MockPreview(); + final mockImageCapture = MockImageCapture(); + final mockImageAnalysis = MockImageAnalysis(); + final mockRecorder = MockRecorder(); + final mockVideoCapture = MockVideoCapture(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey(); + + // Tell plugin to create mock/detached objects and stub method calls for the + // testing of availableCameras and createCamera. + PigeonOverrides.processCameraProvider_getInstance = () { + return Future.value(mockProcessCameraProvider); + }; + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + switch (requireLensFacing) { + case LensFacing.front: + return mockFrontCameraSelector; + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } + if (cameraInfoForFilter == mockBackCameraInfoOne) { + return mockChosenCameraInfoCameraSelector; + } + + return mockBackCameraSelector; + }; + PigeonOverrides.systemServicesManager_new = + ({required void Function(SystemServicesManager, String) onCameraError}) { + return MockSystemServicesManager(); + }; + PigeonOverrides.preview_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) { + return mockPreview; + }; + PigeonOverrides.imageCapture_new = + ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) { + return mockImageCapture; + }; + PigeonOverrides.recorder_new = + ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) { + return mockRecorder; + }; + PigeonOverrides.recorder_new = + ({int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector}) { + return mockRecorder; + }; + PigeonOverrides.videoCapture_withOutput = + ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) { + return mockVideoCapture; + }; + PigeonOverrides.imageAnalysis_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + }) { + return mockImageAnalysis; + }; + PigeonOverrides.resolutionStrategy_new = + ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) { + return MockResolutionStrategy(); + }; + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) { + return MockResolutionSelector(); + }; + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) { + return MockResolutionSelector(); + }; + PigeonOverrides.qualitySelector_from = + ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { + return MockQualitySelector(); + }; + GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.deviceOrientationManager_new = + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { + final manager = MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.aspectRatioStrategy_new = + ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) { + return MockAspectRatioStrategy(); + }; + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = + ({required CameraSize preferredSize}) { + return MockResolutionFilter(); + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + var cameraId = ''; + if (cameraInfo == mockBackCameraInfoOne) { + cameraId = '0'; + } else if (cameraInfo == mockBackCameraInfoTwo) { + cameraId = '1'; + } else if (cameraInfo == mockFrontCameraInfo) { + cameraId = '2'; } - - when( - mockProcessCameraProvider.bindToLifecycle( - mockChosenCameraInfoCameraSelector, - [mockPreview, mockImageCapture, mockImageAnalysis], - ), - ).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCamera2CameraInfo.getCameraId()).thenAnswer((_) async => cameraId); when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl); - - camera.processCameraProvider = mockProcessCameraProvider; + mockCamera2CameraInfo.getCameraCharacteristic(mockCameraCharacteristicsKey), + ).thenAnswer((_) async => testSensorOrientation); + return mockCamera2CameraInfo; + }; + PigeonOverrides.cameraSize_new = ({required int width, required int height}) { + return MockCameraSize(); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey; + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; + PigeonOverrides.cameraIntegerRange_new = ({required int lower, required int upper}) { + return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0); + }; - // Verify the camera name used to create camera is associated with mockBackCameraInfoOne. - expect( - cameraNameToInfos[cameraDescriptions[0].name], + // Mock calls to native platform + when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer((_) async { + mockCameraInfosList = [ mockBackCameraInfoOne, - ); + mockBackCameraInfoTwo, + mockFrontCameraInfo, + ]; + return [mockBackCameraInfoOne, mockBackCameraInfoTwo, mockFrontCameraInfo]; + }); - // Creating a camera with settings using a specific camera from - // available cameras. - await camera.createCameraWithSettings( - cameraDescriptions[0], - const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, - ), + final List cameraDescriptions = await camera.availableCameras(); + expect(cameraDescriptions.length, returnData.length); + + for (var i = 0; i < returnData.length; i++) { + final Map savedData = (returnData[i] as Map) + .cast(); + + cameraNameToInfos[savedData['name']! as String] = mockCameraInfosList[i]; + final cameraDescription = CameraDescription( + name: savedData['name']! as String, + lensDirection: (savedData['lensFacing']! as String) == 'front' + ? CameraLensDirection.front + : CameraLensDirection.back, + sensorOrientation: savedData['sensorOrientation']! as int, ); + expect(cameraDescriptions[i], cameraDescription); + expect(cameraNameToInfos.containsKey(cameraDescription.name), isTrue); + } - // Verify CameraSelector is chosen based on specified cameraInfo. - expect(camera.cameraSelector, equals(mockChosenCameraInfoCameraSelector)); - }, - ); + when( + mockProcessCameraProvider.bindToLifecycle(mockChosenCameraInfoCameraSelector, [ + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); + when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl); + + camera.processCameraProvider = mockProcessCameraProvider; + + // Verify the camera name used to create camera is associated with mockBackCameraInfoOne. + expect(cameraNameToInfos[cameraDescriptions[0].name], mockBackCameraInfoOne); + + // Creating a camera with settings using a specific camera from + // available cameras. + await camera.createCameraWithSettings( + cameraDescriptions[0], + const MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ), + ); + + // Verify CameraSelector is chosen based on specified cameraInfo. + expect(camera.cameraSelector, equals(mockChosenCameraInfoCameraSelector)); + }); test( 'initializeCamera throws a CameraException when createCamera has not been called before initializedCamera', @@ -2000,35 +1636,24 @@ void main() { final mockCameraInfo = MockCameraInfo(); final mockLiveCameraState = MockLiveCameraState(); final mockPreview = MockPreview(); - final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: MockCameraSize(), - ); + final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => mockLiveCameraState); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); - when( - mockPreview.setSurfaceProvider(any), - ).thenAnswer((_) async => testSurfaceTextureId); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); + when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => testSurfaceTextureId); camera.processCameraProvider = mockProcessCameraProvider; // Tell plugin to create mock/detached objects for testing createCamera // as needed. setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, - newPreview: - ({ - ResolutionSelector? resolutionSelector, - int? targetRotation, - CameraIntegerRange? targetFpsRange, - }) => mockPreview, + newPreview: ({ + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + }) => mockPreview, ); // Create and initialize camera. @@ -2043,102 +1668,82 @@ void main() { await testCameraClosingObserver( camera, testSurfaceTextureId, - verify(mockLiveCameraState.observe(captureAny)).captured.single - as Observer, + verify(mockLiveCameraState.observe(captureAny)).captured.single as Observer, ), isTrue, ); }); - test( - 'initializeCamera sets image format of ImageAnalysis use case as expected', - () async { - final camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const testSensorOrientation = 90; - const testCameraDescription = CameraDescription( - name: 'cameraName', - lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation, - ); - const enableAudio = true; - final mockCamera = MockCamera(); - const testSurfaceTextureId = 244; + test('initializeCamera sets image format of ImageAnalysis use case as expected', () async { + final camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( + name: 'cameraName', + lensDirection: testLensDirection, + sensorOrientation: testSensorOrientation, + ); + const enableAudio = true; + final mockCamera = MockCamera(); + const testSurfaceTextureId = 244; - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockCameraInfo = MockCameraInfo(); - final mockLiveCameraState = MockLiveCameraState(); - final mockPreview = MockPreview(); - final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: MockCameraSize(), - ); - final mockImageAnalysis = MockImageAnalysis(); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); + final mockLiveCameraState = MockLiveCameraState(); + final mockPreview = MockPreview(); + final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); + final mockImageAnalysis = MockImageAnalysis(); - // Configure mocks for camera initialization. - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => mockLiveCameraState); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); - when( - mockPreview.setSurfaceProvider(any), - ).thenAnswer((_) async => testSurfaceTextureId); - camera.processCameraProvider = mockProcessCameraProvider; + // Configure mocks for camera initialization. + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); + when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => testSurfaceTextureId); + camera.processCameraProvider = mockProcessCameraProvider; - for (final ImageFormatGroup imageFormatGroup in ImageFormatGroup.values) { - // Get CameraX image format constant for imageFormatGroup. - final int? cameraXImageFormat = switch (imageFormatGroup) { - ImageFormatGroup.yuv420 => - AndroidCameraCameraX.imageAnalysisOutputImageFormatYuv420_888, - ImageFormatGroup.nv21 => - AndroidCameraCameraX.imageAnalysisOutputImageFormatNv21, - _ => null, - }; - // Tell plugin to create mock/detached objects for testing createCamera - // as needed. - int? imageAnalysisOutputImageFormat; - setUpOverridesForTestingUseCaseConfiguration( - mockProcessCameraProvider, - newImageAnalysis: - ({ - ResolutionSelector? resolutionSelector, - int? targetRotation, - CameraIntegerRange? targetFpsRange, - int? outputImageFormat, - }) { - imageAnalysisOutputImageFormat = outputImageFormat; - return mockImageAnalysis; - }, - newPreview: - ({ - ResolutionSelector? resolutionSelector, - int? targetRotation, - CameraIntegerRange? targetFpsRange, - }) => mockPreview, - ); + for (final ImageFormatGroup imageFormatGroup in ImageFormatGroup.values) { + // Get CameraX image format constant for imageFormatGroup. + final int? cameraXImageFormat = switch (imageFormatGroup) { + ImageFormatGroup.yuv420 => AndroidCameraCameraX.imageAnalysisOutputImageFormatYuv420_888, + ImageFormatGroup.nv21 => AndroidCameraCameraX.imageAnalysisOutputImageFormatNv21, + _ => null, + }; + // Tell plugin to create mock/detached objects for testing createCamera + // as needed. + int? imageAnalysisOutputImageFormat; + setUpOverridesForTestingUseCaseConfiguration( + mockProcessCameraProvider, + newImageAnalysis: + ({ + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + }) { + imageAnalysisOutputImageFormat = outputImageFormat; + return mockImageAnalysis; + }, + newPreview: ({ + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + }) => mockPreview, + ); - // Create and initialize camera. - await camera.createCameraWithSettings( - testCameraDescription, - const MediaSettings(enableAudio: enableAudio), - ); - await camera.initializeCamera( - testSurfaceTextureId, - imageFormatGroup: imageFormatGroup, - ); + // Create and initialize camera. + await camera.createCameraWithSettings( + testCameraDescription, + const MediaSettings(enableAudio: enableAudio), + ); + await camera.initializeCamera(testSurfaceTextureId, imageFormatGroup: imageFormatGroup); - // Test image format group is set as expected. - expect(imageAnalysisOutputImageFormat, cameraXImageFormat); - } - }, - ); + // Test image format group is set as expected. + expect(imageAnalysisOutputImageFormat, cameraXImageFormat); + } + }); test('initializeCamera sends expected CameraInitializedEvent', () async { final camera = AndroidCameraCameraX(); @@ -2156,10 +1761,7 @@ void main() { final Camera mockCamera = MockCamera(); final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: CameraSize.pigeon_detached( - width: resolutionWidth, - height: resolutionHeight, - ), + resolution: CameraSize.pigeon_detached(width: resolutionWidth, height: resolutionHeight), ); // Mocks for (typically attached) objects created by createCamera. @@ -2184,93 +1786,78 @@ void main() { return mockBackCameraSelector; } }; - PigeonOverrides.preview_new = - ({ - int? targetRotation, - CameraIntegerRange? targetFpsRange, - ResolutionSelector? resolutionSelector, - }) => mockPreview; - PigeonOverrides.imageCapture_new = - ({ - int? targetRotation, - CameraXFlashMode? flashMode, - ResolutionSelector? resolutionSelector, - }) => mockImageCapture; - PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - }) => MockRecorder(); - PigeonOverrides.videoCapture_withOutput = - ({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - }) => MockVideoCapture(); - PigeonOverrides.imageAnalysis_new = - ({ - int? targetRotation, - CameraIntegerRange? targetFpsRange, - int? outputImageFormat, - ResolutionSelector? resolutionSelector, - }) => mockImageAnalysis; - PigeonOverrides.resolutionStrategy_new = - ({ - required CameraSize boundSize, - required ResolutionStrategyFallbackRule fallbackRule, - }) => MockResolutionStrategy(); - PigeonOverrides.resolutionSelector_new = - ({ - AspectRatioStrategy? aspectRatioStrategy, - ResolutionStrategy? resolutionStrategy, - ResolutionFilter? resolutionFilter, - }) => MockResolutionSelector(); - PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = - ({required VideoQuality quality}) => MockFallbackStrategy(); - PigeonOverrides.qualitySelector_from = - ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) => - MockQualitySelector(); - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) => MockSystemServicesManager(); + PigeonOverrides.preview_new = ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) => mockPreview; + PigeonOverrides.imageCapture_new = ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) => mockImageCapture; + PigeonOverrides.recorder_new = ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) => MockRecorder(); + PigeonOverrides.videoCapture_withOutput = ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) => MockVideoCapture(); + PigeonOverrides.imageAnalysis_new = ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + }) => mockImageAnalysis; + PigeonOverrides.resolutionStrategy_new = ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + }) => MockResolutionStrategy(); + PigeonOverrides.resolutionSelector_new = ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) => MockResolutionSelector(); + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) => + MockFallbackStrategy(); + PigeonOverrides.qualitySelector_from = ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + }) => MockQualitySelector(); + GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = ({ + required void Function(SystemServicesManager, String) onCameraError, + }) => MockSystemServicesManager(); PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final manager = MockDeviceOrientationManager(); when(manager.getUiOrientation()).thenAnswer((_) async { return 'PORTRAIT_UP'; }); return manager; }; - PigeonOverrides.aspectRatioStrategy_new = - ({ - required AspectRatio preferredAspectRatio, - required AspectRatioStrategyFallbackRule fallbackRule, - }) => MockAspectRatioStrategy(); - PigeonOverrides.resolutionFilter_createWithOnePreferredSize = - ({required CameraSize preferredSize}) => MockResolutionFilter(); + PigeonOverrides.aspectRatioStrategy_new = ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) => MockAspectRatioStrategy(); + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = ({ + required CameraSize preferredSize, + }) => MockResolutionFilter(); PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { final mockCamera2CameraInfo = MockCamera2CameraInfo(); - when( - mockCamera2CameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => 90); + when(mockCamera2CameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => 90); return mockCamera2CameraInfo; }; - PigeonOverrides.cameraSize_new = - ({required int width, required int height}) => MockCameraSize(); - PigeonOverrides.cameraCharacteristics_sensorOrientation = - MockCameraCharacteristicsKey(); - PigeonOverrides.cameraIntegerRange_new = - ({required int lower, required int upper}) { - return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0); - }; + PigeonOverrides.cameraSize_new = ({required int width, required int height}) => + MockCameraSize(); + PigeonOverrides.cameraCharacteristics_sensorOrientation = MockCameraCharacteristicsKey(); + PigeonOverrides.cameraIntegerRange_new = ({required int lower, required int upper}) { + return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0); + }; final testCameraInitializedEvent = CameraInitializedEvent( cameraId, @@ -2286,18 +1873,15 @@ void main() { when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => cameraId); when( - mockProcessCameraProvider.bindToLifecycle( - mockBackCameraSelector, - [mockPreview, mockImageCapture, mockImageAnalysis], - ), + mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, [ + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); await camera.createCameraWithSettings( testCameraDescription, @@ -2328,17 +1912,13 @@ void main() { var stoppedListeningForDeviceOrientationChange = false; final camera = AndroidCameraCameraX(); PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final mockDeviceOrientationManager = MockDeviceOrientationManager(); - when( - mockDeviceOrientationManager - .stopListeningForDeviceOrientationChange(), - ).thenAnswer((_) async { - stoppedListeningForDeviceOrientationChange = true; - }); + when(mockDeviceOrientationManager.stopListeningForDeviceOrientationChange()).thenAnswer( + (_) async { + stoppedListeningForDeviceOrientationChange = true; + }, + ); return mockDeviceOrientationManager; }; @@ -2360,8 +1940,7 @@ void main() { test('onCameraInitialized stream emits CameraInitializedEvents', () async { final camera = AndroidCameraCameraX(); const cameraId = 16; - final Stream eventStream = camera - .onCameraInitialized(cameraId); + final Stream eventStream = camera.onCameraInitialized(cameraId); final streamQueue = StreamQueue(eventStream); const testEvent = CameraInitializedEvent( cameraId, @@ -2385,9 +1964,7 @@ void main() { final camera = AndroidCameraCameraX(); const cameraId = 99; const cameraClosingEvent = CameraClosingEvent(cameraId); - final Stream eventStream = camera.onCameraClosing( - cameraId, - ); + final Stream eventStream = camera.onCameraClosing(cameraId); final streamQueue = StreamQueue(eventStream); camera.cameraEventStreamController.add(cameraClosingEvent); @@ -2404,23 +1981,14 @@ void main() { const cameraId = 27; const firstTestErrorDescription = 'Test error description 1!'; const secondTestErrorDescription = 'Test error description 2!'; - const secondCameraErrorEvent = CameraErrorEvent( - cameraId, - secondTestErrorDescription, - ); - final Stream eventStream = camera.onCameraError( - cameraId, - ); + const secondCameraErrorEvent = CameraErrorEvent(cameraId, secondTestErrorDescription); + final Stream eventStream = camera.onCameraError(cameraId); final streamQueue = StreamQueue(eventStream); PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { final mockSystemServicesManager = MockSystemServicesManager(); - when( - mockSystemServicesManager.onCameraError, - ).thenReturn(onCameraError); + when(mockSystemServicesManager.onCameraError).thenReturn(onCameraError); return mockSystemServicesManager; }; @@ -2444,20 +2012,12 @@ void main() { 'onDeviceOrientationChanged stream emits changes in device orientation detected by system services', () async { final camera = AndroidCameraCameraX(); - final Stream eventStream = camera - .onDeviceOrientationChanged(); - final streamQueue = StreamQueue( - eventStream, - ); - const testEvent = DeviceOrientationChangedEvent( - DeviceOrientation.portraitDown, - ); + final Stream eventStream = camera.onDeviceOrientationChanged(); + final streamQueue = StreamQueue(eventStream); + const testEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitDown); PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final mockDeviceOrientationManager = MockDeviceOrientationManager(); when( mockDeviceOrientationManager.onDeviceOrientationChanged, @@ -2484,9 +2044,7 @@ void main() { camera.processCameraProvider = MockProcessCameraProvider(); camera.preview = MockPreview(); - when( - camera.processCameraProvider!.isBound(camera.preview!), - ).thenAnswer((_) async => true); + when(camera.processCameraProvider!.isBound(camera.preview!)).thenAnswer((_) async => true); await camera.pausePreview(579); @@ -2505,9 +2063,7 @@ void main() { await camera.pausePreview(632); - verifyNever( - camera.processCameraProvider!.unbind([camera.preview!]), - ); + verifyNever(camera.processCameraProvider!.unbind([camera.preview!])); }, ); @@ -2525,28 +2081,22 @@ void main() { camera.cameraSelector = MockCameraSelector(); camera.preview = MockPreview(); - when( - camera.processCameraProvider!.isBound(camera.preview!), - ).thenAnswer((_) async => true); + when(camera.processCameraProvider!.isBound(camera.preview!)).thenAnswer((_) async => true); when( - mockProcessCameraProvider.bindToLifecycle( - camera.cameraSelector, - [camera.preview!], - ), + mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, [ + camera.preview!, + ]), ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => mockLiveCameraState); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState); await camera.resumePreview(78); verifyNever( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [camera.preview!], - ), + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + camera.preview!, + ]), ); verifyNever(mockLiveCameraState.observe(any)); expect(camera.cameraInfo, isNot(mockCameraInfo)); @@ -2577,31 +2127,26 @@ void main() { }; when( - mockProcessCameraProvider.bindToLifecycle( - camera.cameraSelector, - [camera.preview!], - ), + mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, [ + camera.preview!, + ]), ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => mockLiveCameraState); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => mockLiveCameraState); when(mockCamera.cameraControl).thenReturn(mockCameraControl); await camera.resumePreview(78); verify( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [camera.preview!], - ), + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + camera.preview!, + ]), ); expect( await testCameraClosingObserver( camera, 78, - verify(mockLiveCameraState.observe(captureAny)).captured.single - as Observer, + verify(mockLiveCameraState.observe(captureAny)).captured.single as Observer, ), isTrue, ); @@ -2612,22 +2157,16 @@ void main() { // Further `buildPreview` testing concerning the Widget that it returns is // located in preview_rotation_test.dart. - test( - 'buildPreview throws an exception if the preview is not bound to the lifecycle', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 73; + test('buildPreview throws an exception if the preview is not bound to the lifecycle', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 73; - // Tell camera that createCamera has not been called and thus, preview has - // not been bound to the lifecycle of the camera. - camera.previewInitiallyBound = false; + // Tell camera that createCamera has not been called and thus, preview has + // not been bound to the lifecycle of the camera. + camera.previewInitiallyBound = false; - expect( - () => camera.buildPreview(cameraId), - throwsA(isA()), - ); - }, - ); + expect(() => camera.buildPreview(cameraId), throwsA(isA())); + }); group('video recording', () { test( @@ -2667,27 +2206,18 @@ void main() { ({required void Function(Observer, T) onChanged}) { return Observer.detached(onChanged: onChanged); }; - PigeonOverrides.camera2CameraInfo_from = - ({required dynamic cameraInfo}) => mockCamera2CameraInfo; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) => + mockCamera2CameraInfo; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) - onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { final mockSystemServicesManager = MockSystemServicesManager(); when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), + mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'), ).thenAnswer((_) async => outputPath); return mockSystemServicesManager; }; PigeonOverrides.videoRecordEventListener_new = - ({ - required void Function(VideoRecordEventListener, VideoRecordEvent) - onEvent, - }) { + ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) { return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); }; PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = @@ -2705,25 +2235,18 @@ void main() { when( mockPendingRecording.asPersistentRecording(), ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecordingWithAudio.start(any), - ).thenAnswer((_) async => mockRecording); + when(mockPendingRecordingWithAudio.start(any)).thenAnswer((_) async => mockRecording); when( camera.processCameraProvider!.isBound(camera.videoCapture!), ).thenAnswer((_) async => false); when( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [camera.videoCapture!], - ), + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + camera.videoCapture!, + ]), ).thenAnswer((_) async => newMockCamera); - when( - newMockCamera.getCameraInfo(), - ).thenAnswer((_) async => mockCameraInfo); + when(newMockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); when(newMockCamera.cameraControl).thenReturn(mockCameraControl); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => newMockLiveCameraState); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => newMockLiveCameraState); when( mockCamera2CameraInfo.getCameraCharacteristic(any), ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); @@ -2738,10 +2261,9 @@ void main() { // Verify VideoCapture UseCase is bound and camera & its properties // are updated. verify( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [camera.videoCapture!], - ), + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + camera.videoCapture!, + ]), ); expect(camera.camera, equals(newMockCamera)); expect(camera.cameraInfo, equals(mockCameraInfo)); @@ -2751,8 +2273,7 @@ void main() { await testCameraClosingObserver( camera, cameraId, - verify(newMockLiveCameraState.observe(captureAny)).captured.single - as Observer, + verify(newMockLiveCameraState.observe(captureAny)).captured.single as Observer, ), isTrue, ); @@ -2763,240 +2284,201 @@ void main() { }, ); - test( - 'startVideoCapturing binds video capture use case and starts the recording' - ' on first call, and does nothing on second call', - () async { - // Set up mocks and constants. - final camera = AndroidCameraCameraX(); - final mockPendingRecording = MockPendingRecording(); - final mockRecording = MockRecording(); - final mockCamera = MockCamera(); - final mockCameraInfo = MockCameraInfo(); - final mockCamera2CameraInfo = MockCamera2CameraInfo(); - - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); - camera.enableRecordingAudio = false; + test('startVideoCapturing binds video capture use case and starts the recording' + ' on first call, and does nothing on second call', () async { + // Set up mocks and constants. + final camera = AndroidCameraCameraX(); + final mockPendingRecording = MockPendingRecording(); + final mockRecording = MockRecording(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + camera.enableRecordingAudio = false; - // Tell plugin to create detached Observer when camera info updated. - const outputPath = '/temp/REC123.mp4'; - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; - PigeonOverrides.camera2CameraInfo_from = - ({required dynamic cameraInfo}) => mockCamera2CameraInfo; - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) - onCameraError, - }) { - final mockSystemServicesManager = MockSystemServicesManager(); - when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), - ).thenAnswer((_) async => outputPath); - return mockSystemServicesManager; - }; - PigeonOverrides.videoRecordEventListener_new = - ({ - required void Function(VideoRecordEventListener, VideoRecordEvent) - onEvent, - }) { - return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); - }; - PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = - MockCameraCharacteristicsKey(); + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - const cameraId = 17; + // Tell plugin to create detached Observer when camera info updated. + const outputPath = '/temp/REC123.mp4'; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) => + mockCamera2CameraInfo; + PigeonOverrides.systemServicesManager_new = + ({required void Function(SystemServicesManager, String) onCameraError}) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = + MockCameraCharacteristicsKey(); - // Mock method calls. - when( - camera.recorder!.prepareRecording(outputPath), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.asPersistentRecording(), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.start(any), - ).thenAnswer((_) async => mockRecording); - when( - camera.processCameraProvider!.isBound(camera.videoCapture!), - ).thenAnswer((_) async => false); - when( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [camera.videoCapture!], - ), - ).thenAnswer((_) async => mockCamera); - when( - mockCamera.getCameraInfo(), - ).thenAnswer((_) => Future.value(mockCameraInfo)); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - when( - mockCamera2CameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); + const cameraId = 17; - // Simulate video recording being started so startVideoRecording completes. - AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached(), - ); + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.asPersistentRecording(), + ).thenAnswer((_) async => mockPendingRecording); + when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + camera.videoCapture!, + ]), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) => Future.value(mockCameraInfo)); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached(), + ); - verify( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [camera.videoCapture!], - ), - ); - expect(camera.pendingRecording, equals(mockPendingRecording)); - expect(camera.recording, mockRecording); + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - // Verify that each of these calls happened only once. - verify( - camera.systemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), - ).called(1); - verifyNoMoreInteractions(camera.systemServicesManager); - verify(camera.recorder!.prepareRecording(outputPath)).called(1); - verifyNoMoreInteractions(camera.recorder); - verify(mockPendingRecording.start(any)).called(1); - verify(mockPendingRecording.withAudioEnabled(any)).called(1); - verify(mockPendingRecording.asPersistentRecording()).called(1); - verifyNoMoreInteractions(mockPendingRecording); - }, - ); + verify( + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + camera.videoCapture!, + ]), + ); + expect(camera.pendingRecording, equals(mockPendingRecording)); + expect(camera.recording, mockRecording); - test( - 'startVideoCapturing called with stream options starts image streaming', - () async { - // Set up mocks and constants. - final camera = AndroidCameraCameraX(); - final mockProcessCameraProvider = MockProcessCameraProvider(); - final Recorder mockRecorder = MockRecorder(); - final mockPendingRecording = MockPendingRecording(); - final initialCameraInfo = MockCameraInfo(); - final mockCamera2CameraInfo = MockCamera2CameraInfo(); + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + // Verify that each of these calls happened only once. + verify(camera.systemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4')).called(1); + verifyNoMoreInteractions(camera.systemServicesManager); + verify(camera.recorder!.prepareRecording(outputPath)).called(1); + verifyNoMoreInteractions(camera.recorder); + verify(mockPendingRecording.start(any)).called(1); + verify(mockPendingRecording.withAudioEnabled(any)).called(1); + verify(mockPendingRecording.asPersistentRecording()).called(1); + verifyNoMoreInteractions(mockPendingRecording); + }); - // Set directly for test versus calling createCamera. + test('startVideoCapturing called with stream options starts image streaming', () async { + // Set up mocks and constants. + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final Recorder mockRecorder = MockRecorder(); + final mockPendingRecording = MockPendingRecording(); + final initialCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); - camera.videoCapture = MockVideoCapture(); - camera.imageAnalysis = MockImageAnalysis(); - camera.camera = MockCamera(); - camera.recorder = mockRecorder; - camera.cameraInfo = initialCameraInfo; - camera.imageCapture = MockImageCapture(); - camera.enableRecordingAudio = true; + // Set directly for test versus calling createCamera. - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); + camera.videoCapture = MockVideoCapture(); + camera.imageAnalysis = MockImageAnalysis(); + camera.camera = MockCamera(); + camera.recorder = mockRecorder; + camera.cameraInfo = initialCameraInfo; + camera.imageCapture = MockImageCapture(); + camera.enableRecordingAudio = true; - // Tell plugin to create detached Analyzer for testing. - const outputPath = '/temp/REC123.mp4'; - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; - PigeonOverrides.camera2CameraInfo_from = - ({required dynamic cameraInfo}) => mockCamera2CameraInfo; - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) - onCameraError, - }) { - final mockSystemServicesManager = MockSystemServicesManager(); - when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), - ).thenAnswer((_) async => outputPath); - return mockSystemServicesManager; - }; - PigeonOverrides.videoRecordEventListener_new = - ({ - required void Function(VideoRecordEventListener, VideoRecordEvent) - onEvent, - }) { - return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); - }; - PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = - MockCameraCharacteristicsKey(); - PigeonOverrides.analyzer_new = - ({required void Function(Analyzer, ImageProxy) analyze}) { - return MockAnalyzer(); - }; + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - const cameraId = 17; - final imageDataCompleter = Completer(); - final videoCaptureOptions = VideoCaptureOptions( - cameraId, - streamCallback: (CameraImageData imageData) => - imageDataCompleter.complete(imageData), - ); + // Tell plugin to create detached Analyzer for testing. + const outputPath = '/temp/REC123.mp4'; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) => + mockCamera2CameraInfo; + PigeonOverrides.systemServicesManager_new = + ({required void Function(SystemServicesManager, String) onCameraError}) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = + MockCameraCharacteristicsKey(); + PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) { + return MockAnalyzer(); + }; - // Mock method calls. - when( - camera.processCameraProvider!.isBound(camera.videoCapture!), - ).thenAnswer((_) async => true); - when( - camera.processCameraProvider!.isBound(camera.imageAnalysis!), - ).thenAnswer((_) async => true); - when( - camera.recorder!.prepareRecording(outputPath), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.asPersistentRecording(), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) => Future.value(camera.camera)); - when( - camera.camera!.getCameraInfo(), - ).thenAnswer((_) => Future.value(MockCameraInfo())); - when( - mockCamera2CameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3); + const cameraId = 17; + final imageDataCompleter = Completer(); + final videoCaptureOptions = VideoCaptureOptions( + cameraId, + streamCallback: (CameraImageData imageData) => imageDataCompleter.complete(imageData), + ); - // Simulate video recording being started so startVideoRecording completes. - AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached(), - ); + // Mock method calls. + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => true); + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.withAudioEnabled(!camera.enableRecordingAudio), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.asPersistentRecording(), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) => Future.value(camera.camera)); + when( + camera.camera!.getCameraInfo(), + ).thenAnswer((_) => Future.value(MockCameraInfo())); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3); - await camera.startVideoCapturing(videoCaptureOptions); + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached(), + ); - final CameraImageData mockCameraImageData = MockCameraImageData(); - camera.cameraImageDataStreamController!.add(mockCameraImageData); + await camera.startVideoCapturing(videoCaptureOptions); - expect(imageDataCompleter.future, isNotNull); - await camera.cameraImageDataStreamController!.close(); - }, - ); + final CameraImageData mockCameraImageData = MockCameraImageData(); + camera.cameraImageDataStreamController!.add(mockCameraImageData); + + expect(imageDataCompleter.future, isNotNull); + await camera.cameraImageDataStreamController!.close(); + }); test( 'startVideoCapturing sets VideoCapture target rotation to current video orientation if orientation unlocked', @@ -3026,41 +2508,28 @@ void main() { ({required void Function(Observer, T) onChanged}) { return Observer.detached(onChanged: onChanged); }; - PigeonOverrides.camera2CameraInfo_from = - ({required dynamic cameraInfo}) => cameraInfo == initialCameraInfo - ? mockCamera2CameraInfo - : MockCamera2CameraInfo(); + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) => + cameraInfo == initialCameraInfo ? mockCamera2CameraInfo : MockCamera2CameraInfo(); PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) - onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { final mockSystemServicesManager = MockSystemServicesManager(); when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), + mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'), ).thenAnswer((_) async => outputPath); return mockSystemServicesManager; }; PigeonOverrides.deviceOrientationManager_new = ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, + required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged, }) { - final mockDeviceOrientationManager = - MockDeviceOrientationManager(); + final mockDeviceOrientationManager = MockDeviceOrientationManager(); when( mockDeviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) async => defaultTargetRotation); return mockDeviceOrientationManager; }; PigeonOverrides.videoRecordEventListener_new = - ({ - required void Function(VideoRecordEventListener, VideoRecordEvent) - onEvent, - }) { + ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) { return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); }; PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = @@ -3078,9 +2547,7 @@ void main() { when( mockPendingRecording.asPersistentRecording(), ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.start(any), - ).thenAnswer((_) async => mockRecording); + when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording); when( camera.processCameraProvider!.isBound(camera.videoCapture!), ).thenAnswer((_) async => true); @@ -3180,9 +2647,7 @@ void main() { camera.videoOutputPath = videoOutputPath; // Tell plugin that videoCapture use case was bound to start recording. - when( - camera.processCameraProvider!.isBound(videoCapture), - ).thenAnswer((_) async => true); + when(camera.processCameraProvider!.isBound(videoCapture)).thenAnswer((_) async => true); // Simulate video recording being finalized so stopVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( @@ -3224,9 +2689,7 @@ void main() { camera.videoCapture = mockVideoCapture; // Tell plugin that videoCapture use case was bound to start recording. - when( - camera.processCameraProvider!.isBound(mockVideoCapture), - ).thenAnswer((_) async => true); + when(camera.processCameraProvider!.isBound(mockVideoCapture)).thenAnswer((_) async => true); await expectLater(() async { // Simulate video recording being finalized so stopVideoRecording completes. @@ -3265,39 +2728,34 @@ void main() { }, throwsA(isA())); }); - test( - 'VideoCapture use case is unbound from lifecycle when video recording stops', - () async { - final camera = AndroidCameraCameraX(); - final recording = MockRecording(); - final processCameraProvider = MockProcessCameraProvider(); - final videoCapture = MockVideoCapture(); - const videoOutputPath = '/test/output/path'; - - // Set directly for test versus calling createCamera and startVideoCapturing. - camera.processCameraProvider = processCameraProvider; - camera.recording = recording; - camera.videoCapture = videoCapture; - camera.videoOutputPath = videoOutputPath; - - // Tell plugin that videoCapture use case was bound to start recording. - when( - camera.processCameraProvider!.isBound(videoCapture), - ).thenAnswer((_) async => true); + test('VideoCapture use case is unbound from lifecycle when video recording stops', () async { + final camera = AndroidCameraCameraX(); + final recording = MockRecording(); + final processCameraProvider = MockProcessCameraProvider(); + final videoCapture = MockVideoCapture(); + const videoOutputPath = '/test/output/path'; - // Simulate video recording being finalized so stopVideoRecording completes. - AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventFinalize.pigeon_detached(), - ); + // Set directly for test versus calling createCamera and startVideoCapturing. + camera.processCameraProvider = processCameraProvider; + camera.recording = recording; + camera.videoCapture = videoCapture; + camera.videoOutputPath = videoOutputPath; - await camera.stopVideoRecording(90); - verify(processCameraProvider.unbind([videoCapture])); + // Tell plugin that videoCapture use case was bound to start recording. + when(camera.processCameraProvider!.isBound(videoCapture)).thenAnswer((_) async => true); - // Verify that recording stops. - verify(recording.close()); - verifyNoMoreInteractions(recording); - }, - ); + // Simulate video recording being finalized so stopVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventFinalize.pigeon_detached(), + ); + + await camera.stopVideoRecording(90); + verify(processCameraProvider.unbind([videoCapture])); + + // Verify that recording stops. + verify(recording.close()); + verifyNoMoreInteractions(recording); + }); test('setDescriptionWhileRecording changes the camera description', () async { final camera = AndroidCameraCameraX(); @@ -3344,19 +2802,13 @@ void main() { int? targetRotation, CameraIntegerRange? targetFpsRange, }) { - when( - mockPreview.setSurfaceProvider(any), - ).thenAnswer((_) async => 19); - final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: MockCameraSize(), - ); + when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => 19); + final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); when( mockPreview.surfaceProducerHandlesCropAndRotation(), ).thenAnswer((_) async => false); when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); return mockPreview; }; PigeonOverrides.imageCapture_new = @@ -3368,21 +2820,14 @@ void main() { return mockImageCapture; }; PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - QualitySelector? qualitySelector, - int? targetVideoEncodingBitRate, - }) { + ({int? aspectRatio, QualitySelector? qualitySelector, int? targetVideoEncodingBitRate}) { when( mockRecorder.prepareRecording(outputPath), ).thenAnswer((_) async => mockPendingRecording); return mockRecorder; }; PigeonOverrides.videoCapture_withOutput = - ({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - }) { + ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) { return mockVideoCapture; }; PigeonOverrides.imageAnalysis_new = @@ -3402,10 +2847,7 @@ void main() { return mockBackCameraSelector; }; PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final manager = MockDeviceOrientationManager(); when(manager.getUiOrientation()).thenAnswer((_) async { return 'PORTRAIT_UP'; @@ -3426,42 +2868,31 @@ void main() { ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); return camera2cameraInfo; }; - PigeonOverrides.cameraCharacteristics_sensorOrientation = - mockCameraCharacteristicsKey; + PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey; GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { return Observer.detached(onChanged: onChanged); }; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { final mockSystemServicesManager = MockSystemServicesManager(); when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), + mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'), ).thenAnswer((_) async => outputPath); return mockSystemServicesManager; }; PigeonOverrides.videoRecordEventListener_new = - ({ - required void Function(VideoRecordEventListener, VideoRecordEvent) - onEvent, - }) { + ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) { return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); }; PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = MockCameraCharacteristicsKey(); // mock functions - when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( - (_) async => [mockBackCameraInfo, mockFrontCameraInfo], - ); when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + mockProcessCameraProvider.getAvailableCameraInfos(), + ).thenAnswer((_) async => [mockBackCameraInfo, mockFrontCameraInfo]); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); camera.processCameraProvider = mockProcessCameraProvider; camera.liveCameraState = mockLiveCameraState; @@ -3472,35 +2903,22 @@ void main() { when( mockPendingRecording.asPersistentRecording(), ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.start(any), - ).thenAnswer((_) async => mockRecording); - when( - camera.processCameraProvider!.isBound(mockImageCapture), - ).thenAnswer((_) async => true); - when( - camera.processCameraProvider!.isBound(mockImageAnalysis), - ).thenAnswer((_) async => true); + when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording); + when(camera.processCameraProvider!.isBound(mockImageCapture)).thenAnswer((_) async => true); + when(camera.processCameraProvider!.isBound(mockImageAnalysis)).thenAnswer((_) async => true); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl); when( - camera.processCameraProvider?.bindToLifecycle( - mockFrontCameraSelector, - [ - mockVideoCapture, - mockPreview, - mockImageCapture, - mockImageAnalysis, - ], - ), + camera.processCameraProvider?.bindToLifecycle(mockFrontCameraSelector, [ + mockVideoCapture, + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), ).thenAnswer((_) async => newMockCamera); - when( - newMockCamera.getCameraInfo(), - ).thenAnswer((_) async => mockCameraInfo); + when(newMockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); when(newMockCamera.cameraControl).thenReturn(mockCameraControl); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => newMockLiveCameraState); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => newMockLiveCameraState); // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( @@ -3515,31 +2933,24 @@ void main() { ); await camera.initializeCamera(flutterSurfaceTextureId); - await camera.startVideoCapturing( - VideoCaptureOptions(flutterSurfaceTextureId), - ); + await camera.startVideoCapturing(VideoCaptureOptions(flutterSurfaceTextureId)); await camera.setDescriptionWhileRecording(testFrontCameraDescription); //verify front camera selected and camera properties updated verify(camera.processCameraProvider?.unbindAll()).called(2); verify( - camera.processCameraProvider?.bindToLifecycle( - mockFrontCameraSelector, - [ - mockVideoCapture, - mockPreview, - mockImageCapture, - mockImageAnalysis, - ], - ), + camera.processCameraProvider?.bindToLifecycle(mockFrontCameraSelector, [ + mockVideoCapture, + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), ).called(1); expect(camera.camera, equals(newMockCamera)); expect(camera.cameraInfo, equals(mockCameraInfo)); expect(camera.cameraControl, equals(mockCameraControl)); verify(mockLiveCameraState.removeObservers()); - for (final Object? observer in verify( - newMockLiveCameraState.observe(captureAny), - ).captured) { + for (final Object? observer in verify(newMockLiveCameraState.observe(captureAny)).captured) { expect( await testCameraClosingObserver( camera, @@ -3553,15 +2964,12 @@ void main() { //verify back camera selected await camera.setDescriptionWhileRecording(testBackCameraDescription); verify( - camera.processCameraProvider?.bindToLifecycle( - mockBackCameraSelector, - [ - mockVideoCapture, - mockPreview, - mockImageCapture, - mockImageAnalysis, - ], - ), + camera.processCameraProvider?.bindToLifecycle(mockBackCameraSelector, [ + mockVideoCapture, + mockPreview, + mockImageCapture, + mockImageAnalysis, + ]), ).called(1); }); @@ -3607,19 +3015,13 @@ void main() { int? targetRotation, CameraIntegerRange? targetFpsRange, }) { - when( - mockPreview.setSurfaceProvider(any), - ).thenAnswer((_) async => 19); - final testResolutionInfo = ResolutionInfo.pigeon_detached( - resolution: MockCameraSize(), - ); + when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => 19); + final testResolutionInfo = ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); when( mockPreview.surfaceProducerHandlesCropAndRotation(), ).thenAnswer((_) async => false); when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); + when(mockPreview.getResolutionInfo()).thenAnswer((_) async => testResolutionInfo); return mockPreview; }; PigeonOverrides.imageCapture_new = @@ -3631,21 +3033,14 @@ void main() { return mockImageCapture; }; PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - QualitySelector? qualitySelector, - int? targetVideoEncodingBitRate, - }) { + ({int? aspectRatio, QualitySelector? qualitySelector, int? targetVideoEncodingBitRate}) { when( mockRecorder.prepareRecording(outputPath), ).thenAnswer((_) async => mockPendingRecording); return mockRecorder; }; PigeonOverrides.videoCapture_withOutput = - ({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - }) { + ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) { return mockVideoCapture; }; PigeonOverrides.imageAnalysis_new = @@ -3665,10 +3060,7 @@ void main() { return mockBackCameraSelector; }; PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final manager = MockDeviceOrientationManager(); when(manager.getUiOrientation()).thenAnswer((_) async { return 'PORTRAIT_UP'; @@ -3689,42 +3081,31 @@ void main() { ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); return camera2cameraInfo; }; - PigeonOverrides.cameraCharacteristics_sensorOrientation = - mockCameraCharacteristicsKey; + PigeonOverrides.cameraCharacteristics_sensorOrientation = mockCameraCharacteristicsKey; GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { return Observer.detached(onChanged: onChanged); }; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { final mockSystemServicesManager = MockSystemServicesManager(); when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), + mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'), ).thenAnswer((_) async => outputPath); return mockSystemServicesManager; }; PigeonOverrides.videoRecordEventListener_new = - ({ - required void Function(VideoRecordEventListener, VideoRecordEvent) - onEvent, - }) { + ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) { return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); }; PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = MockCameraCharacteristicsKey(); // mock functions - when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( - (_) async => [mockBackCameraInfo, mockFrontCameraInfo], - ); when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + mockProcessCameraProvider.getAvailableCameraInfos(), + ).thenAnswer((_) async => [mockBackCameraInfo, mockFrontCameraInfo]); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); camera.processCameraProvider = mockProcessCameraProvider; camera.enableRecordingAudio = false; @@ -3734,22 +3115,12 @@ void main() { when( mockPendingRecording.asPersistentRecording(), ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.start(any), - ).thenAnswer((_) async => mockRecording); - when( - camera.processCameraProvider!.isBound(mockImageCapture), - ).thenAnswer((_) async => true); - when( - camera.processCameraProvider!.isBound(mockImageAnalysis), - ).thenAnswer((_) async => true); + when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording); + when(camera.processCameraProvider!.isBound(mockImageCapture)).thenAnswer((_) async => true); + when(camera.processCameraProvider!.isBound(mockImageAnalysis)).thenAnswer((_) async => true); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl); // Simulate video recording being started so startVideoRecording completes. @@ -3765,9 +3136,7 @@ void main() { ); await camera.initializeCamera(flutterSurfaceTextureId); - await camera.startVideoCapturing( - VideoCaptureOptions(flutterSurfaceTextureId), - ); + await camera.startVideoCapturing(VideoCaptureOptions(flutterSurfaceTextureId)); // pause the preview await camera.pausePreview(flutterSurfaceTextureId); @@ -3777,66 +3146,56 @@ void main() { // verify preview not bound to lifecycle verify(camera.processCameraProvider?.unbindAll()).called(2); verify( - camera.processCameraProvider?.bindToLifecycle( - mockFrontCameraSelector, - [mockVideoCapture, mockImageCapture, mockImageAnalysis], - ), + camera.processCameraProvider?.bindToLifecycle(mockFrontCameraSelector, [ + mockVideoCapture, + mockImageCapture, + mockImageAnalysis, + ]), ).called(1); }); }); - test( - 'takePicture binds ImageCapture to lifecycle and makes call to take a picture', - () async { - final camera = AndroidCameraCameraX(); - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockCamera = MockCamera(); - final mockCameraInfo = MockCameraInfo(); - final mockImageCapture = MockImageCapture(); - const testPicturePath = 'test/absolute/path/to/picture'; + test('takePicture binds ImageCapture to lifecycle and makes call to take a picture', () async { + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockImageCapture = MockImageCapture(); + const testPicturePath = 'test/absolute/path/to/picture'; - // Set directly for test versus calling createCamera. - camera.imageCapture = mockImageCapture; - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); + // Set directly for test versus calling createCamera. + camera.imageCapture = mockImageCapture; + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - // Tell plugin to create detached camera state observers and mock systemServicesManager. - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { - return MockSystemServicesManager(); - }; + // Tell plugin to create detached camera state observers and mock systemServicesManager. + GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({required void Function(SystemServicesManager, String) onCameraError}) { + return MockSystemServicesManager(); + }; - when( - mockProcessCameraProvider.isBound(camera.imageCapture), - ).thenAnswer((_) async => false); - when( - mockProcessCameraProvider.bindToLifecycle( - camera.cameraSelector, - [camera.imageCapture!], - ), - ).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); - when( - mockImageCapture.takePicture(argThat(isA())), - ).thenAnswer((_) async => testPicturePath); + when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => false); + when( + mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, [ + camera.imageCapture!, + ]), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); + when( + mockImageCapture.takePicture(argThat(isA())), + ).thenAnswer((_) async => testPicturePath); - final XFile imageFile = await camera.takePicture(3); + final XFile imageFile = await camera.takePicture(3); - expect(imageFile.path, equals(testPicturePath)); - }, - ); + expect(imageFile.path, equals(testPicturePath)); + }); test( 'takePicture sets ImageCapture target rotation as expected when orientation locked or unlocked', @@ -3854,10 +3213,7 @@ void main() { // Tell plugin to mock call to get current photo orientation and systemServicesManager. PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final mockDeviceOrientationManager = MockDeviceOrientationManager(); when( mockDeviceOrientationManager.getDefaultDisplayRotation(), @@ -3865,15 +3221,11 @@ void main() { return mockDeviceOrientationManager; }; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { return MockSystemServicesManager(); }; - when( - mockProcessCameraProvider.isBound(camera.imageCapture), - ).thenAnswer((_) async => true); + when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => true); when( mockImageCapture.takePicture(argThat(isA())), ).thenAnswer((_) async => 'test/absolute/path/to/picture'); @@ -3905,94 +3257,80 @@ void main() { }, ); - test( - 'takePicture turns non-torch flash mode off when torch mode enabled', - () async { - final camera = AndroidCameraCameraX(); - final mockProcessCameraProvider = MockProcessCameraProvider(); - const cameraId = 77; - - // Set directly for test versus calling createCamera. - camera.imageCapture = MockImageCapture(); - camera.cameraControl = MockCameraControl(); - camera.processCameraProvider = mockProcessCameraProvider; - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + test('takePicture turns non-torch flash mode off when torch mode enabled', () async { + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + const cameraId = 77; - // Tell plugin to mock call to get systemServicesManager. - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { - return MockSystemServicesManager(); - }; + // Set directly for test versus calling createCamera. + camera.imageCapture = MockImageCapture(); + camera.cameraControl = MockCameraControl(); + camera.processCameraProvider = mockProcessCameraProvider; - when( - mockProcessCameraProvider.isBound(camera.imageCapture), - ).thenAnswer((_) async => true); + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - await camera.setFlashMode(cameraId, FlashMode.torch); - await camera.takePicture(cameraId); - verify(camera.imageCapture!.setFlashMode(CameraXFlashMode.off)); - }, - ); + // Tell plugin to mock call to get systemServicesManager. + PigeonOverrides.systemServicesManager_new = + ({required void Function(SystemServicesManager, String) onCameraError}) { + return MockSystemServicesManager(); + }; - test( - 'setFlashMode configures ImageCapture with expected non-torch flash mode', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 22; - final mockCameraControl = MockCameraControl(); - final mockProcessCameraProvider = MockProcessCameraProvider(); + when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => true); - // Set directly for test versus calling createCamera. - camera.imageCapture = MockImageCapture(); - camera.cameraControl = mockCameraControl; + await camera.setFlashMode(cameraId, FlashMode.torch); + await camera.takePicture(cameraId); + verify(camera.imageCapture!.setFlashMode(CameraXFlashMode.off)); + }); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - camera.processCameraProvider = mockProcessCameraProvider; + test('setFlashMode configures ImageCapture with expected non-torch flash mode', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 22; + final mockCameraControl = MockCameraControl(); + final mockProcessCameraProvider = MockProcessCameraProvider(); - // Tell plugin to mock call to get current photo orientation and systemServicesManager. - PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { - return MockSystemServicesManager(); - }; + // Set directly for test versus calling createCamera. + camera.imageCapture = MockImageCapture(); + camera.cameraControl = mockCameraControl; - when( - mockProcessCameraProvider.isBound(camera.imageCapture), - ).thenAnswer((_) async => true); + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + camera.processCameraProvider = mockProcessCameraProvider; - for (final FlashMode flashMode in FlashMode.values) { - await camera.setFlashMode(cameraId, flashMode); - - CameraXFlashMode? expectedFlashMode; - switch (flashMode) { - case FlashMode.off: - expectedFlashMode = CameraXFlashMode.off; - case FlashMode.auto: - expectedFlashMode = CameraXFlashMode.auto; - case FlashMode.always: - expectedFlashMode = CameraXFlashMode.on; - case FlashMode.torch: - expectedFlashMode = null; - } + // Tell plugin to mock call to get current photo orientation and systemServicesManager. + PigeonOverrides.systemServicesManager_new = + ({required void Function(SystemServicesManager, String) onCameraError}) { + return MockSystemServicesManager(); + }; - if (expectedFlashMode == null) { - // Torch mode enabled and won't be used for configuring image capture. - continue; - } + when(mockProcessCameraProvider.isBound(camera.imageCapture)).thenAnswer((_) async => true); + + for (final FlashMode flashMode in FlashMode.values) { + await camera.setFlashMode(cameraId, flashMode); + + CameraXFlashMode? expectedFlashMode; + switch (flashMode) { + case FlashMode.off: + expectedFlashMode = CameraXFlashMode.off; + case FlashMode.auto: + expectedFlashMode = CameraXFlashMode.auto; + case FlashMode.always: + expectedFlashMode = CameraXFlashMode.on; + case FlashMode.torch: + expectedFlashMode = null; + } - verifyNever(mockCameraControl.enableTorch(true)); - expect(camera.torchEnabled, isFalse); - await camera.takePicture(cameraId); - verify(camera.imageCapture!.setFlashMode(expectedFlashMode)); + if (expectedFlashMode == null) { + // Torch mode enabled and won't be used for configuring image capture. + continue; } - }, - ); + + verifyNever(mockCameraControl.enableTorch(true)); + expect(camera.torchEnabled, isFalse); + await camera.takePicture(cameraId); + verify(camera.imageCapture!.setFlashMode(expectedFlashMode)); + } + }); test('setFlashMode turns on torch mode as expected', () async { final camera = AndroidCameraCameraX(); @@ -4008,43 +3346,37 @@ void main() { expect(camera.torchEnabled, isTrue); }); - test( - 'setFlashMode turns off torch mode when non-torch flash modes set', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 33; - final mockCameraControl = MockCameraControl(); + test('setFlashMode turns off torch mode when non-torch flash modes set', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 33; + final mockCameraControl = MockCameraControl(); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; - for (final FlashMode flashMode in FlashMode.values) { - camera.torchEnabled = true; - await camera.setFlashMode(cameraId, flashMode); - - switch (flashMode) { - case FlashMode.off: - case FlashMode.auto: - case FlashMode.always: - verify(mockCameraControl.enableTorch(false)); - expect(camera.torchEnabled, isFalse); - case FlashMode.torch: - verifyNever(mockCameraControl.enableTorch(true)); - expect(camera.torchEnabled, true); - } + for (final FlashMode flashMode in FlashMode.values) { + camera.torchEnabled = true; + await camera.setFlashMode(cameraId, flashMode); + + switch (flashMode) { + case FlashMode.off: + case FlashMode.auto: + case FlashMode.always: + verify(mockCameraControl.enableTorch(false)); + expect(camera.torchEnabled, isFalse); + case FlashMode.torch: + verifyNever(mockCameraControl.enableTorch(true)); + expect(camera.torchEnabled, true); } - }, - ); + } + }); test('getMinExposureOffset returns expected exposure offset', () async { final camera = AndroidCameraCameraX(); final mockCameraInfo = MockCameraInfo(); final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 3, - upper: 4, - ), + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4), exposureCompensationStep: 0.2, ); @@ -4063,10 +3395,7 @@ void main() { final mockCameraInfo = MockCameraInfo(); final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 3, - upper: 4, - ), + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4), exposureCompensationStep: 0.2, ); @@ -4084,10 +3413,7 @@ void main() { final mockCameraInfo = MockCameraInfo(); final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 3, - upper: 4, - ), + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4), exposureCompensationStep: 0.2, ); @@ -4105,10 +3431,7 @@ void main() { final camera = AndroidCameraCameraX(); final mockCameraInfo = MockCameraInfo(); final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 0, - upper: 0, - ), + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 0, upper: 0), exposureCompensationStep: 0, ); @@ -4126,17 +3449,12 @@ void main() { final mockCameraInfo = MockCameraInfo(); const double maxZoomRatio = 1; final LiveData mockLiveZoomState = MockLiveZoomState(); - final zoomState = ZoomState.pigeon_detached( - maxZoomRatio: maxZoomRatio, - minZoomRatio: 0, - ); + final zoomState = ZoomState.pigeon_detached(maxZoomRatio: maxZoomRatio, minZoomRatio: 0); // Set directly for test versus calling createCamera. camera.cameraInfo = mockCameraInfo; - when( - mockCameraInfo.getZoomState(), - ).thenAnswer((_) async => mockLiveZoomState); + when(mockCameraInfo.getZoomState()).thenAnswer((_) async => mockLiveZoomState); when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState); expect(await camera.getMaxZoomLevel(55), maxZoomRatio); @@ -4147,17 +3465,12 @@ void main() { final mockCameraInfo = MockCameraInfo(); const double minZoomRatio = 0; final LiveData mockLiveZoomState = MockLiveZoomState(); - final zoomState = ZoomState.pigeon_detached( - maxZoomRatio: 1, - minZoomRatio: minZoomRatio, - ); + final zoomState = ZoomState.pigeon_detached(maxZoomRatio: 1, minZoomRatio: minZoomRatio); // Set directly for test versus calling createCamera. camera.cameraInfo = mockCameraInfo; - when( - mockCameraInfo.getZoomState(), - ).thenAnswer((_) async => mockLiveZoomState); + when(mockCameraInfo.getZoomState()).thenAnswer((_) async => mockLiveZoomState); when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState); expect(await camera.getMinZoomLevel(55), minZoomRatio); @@ -4192,25 +3505,20 @@ void main() { // Tell plugin to create detached Camera2CameraControl and // CaptureRequestOptions instances for testing. - final controlVideoStabilizationModeKey = - CaptureRequestKey.pigeon_detached(); - PigeonOverrides.camera2CameraControl_from = - ({required CameraControl cameraControl}) => - cameraControl == mockCameraControl - ? mockCamera2CameraControl - : Camera2CameraControl.pigeon_detached(); - PigeonOverrides.captureRequestOptions_new = - ({required Map options}) { - final mockCaptureRequestOptions = MockCaptureRequestOptions(); - options.forEach((CaptureRequestKey key, Object? value) { - when( - mockCaptureRequestOptions.getCaptureRequestOption(key), - ).thenAnswer((_) async => value); - }); - return mockCaptureRequestOptions; - }; - PigeonOverrides.captureRequest_controlVideoStabilizationMode = - controlVideoStabilizationModeKey; + final controlVideoStabilizationModeKey = CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides + .captureRequestOptions_new = ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlVideoStabilizationMode = controlVideoStabilizationModeKey; PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { when( @@ -4218,186 +3526,124 @@ void main() { ).thenAnswer((_) async => [0, 1, 2]); return mockCamera2CameraInfo; }; - PigeonOverrides - .cameraCharacteristics_controlAvailableVideoStabilizationModes = + PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes = MockCameraCharacteristicsKey(); // Test off. - await camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.off, - ); + await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.off); VerificationResult verificationResult = verify( mockCamera2CameraControl.addCaptureRequestOptions(captureAny), ); - var capturedCaptureRequestOptions = - verificationResult.captured.single as CaptureRequestOptions; + var capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions; expect( - await capturedCaptureRequestOptions.getCaptureRequestOption( - controlVideoStabilizationModeKey, - ), + await capturedCaptureRequestOptions.getCaptureRequestOption(controlVideoStabilizationModeKey), equals(0), ); clearInteractions(mockCamera2CameraControl); // Test level1. - await camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level1, - ); + await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1); - verificationResult = verify( - mockCamera2CameraControl.addCaptureRequestOptions(captureAny), - ); - capturedCaptureRequestOptions = - verificationResult.captured.single as CaptureRequestOptions; + verificationResult = verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny)); + capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions; expect( - await capturedCaptureRequestOptions.getCaptureRequestOption( - controlVideoStabilizationModeKey, - ), + await capturedCaptureRequestOptions.getCaptureRequestOption(controlVideoStabilizationModeKey), equals(1), ); }); - test( - 'setVideoStabilizationMode throws ArgumentError when mode not available', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 102; - final mockCameraControl = MockCameraControl(); - final mockCamera2CameraControl = MockCamera2CameraControl(); - final mockCameraInfo = MockCameraInfo(); - final mockCamera2CameraInfo = MockCamera2CameraInfo(); + test('setVideoStabilizationMode throws ArgumentError when mode not available', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 102; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); - // Set directly for test versus calling createCamera. - camera.camera = MockCamera(); - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; + // Set directly for test versus calling createCamera. + camera.camera = MockCamera(); + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; - // Tell plugin to create detached Camera2CameraControl and - // CaptureRequestOptions instances for testing. - final controlVideoStabilizationModeKey = - CaptureRequestKey.pigeon_detached(); - PigeonOverrides.camera2CameraControl_from = - ({required CameraControl cameraControl}) => - cameraControl == mockCameraControl - ? mockCamera2CameraControl - : Camera2CameraControl.pigeon_detached(); - PigeonOverrides.captureRequestOptions_new = - ({required Map options}) { - final mockCaptureRequestOptions = MockCaptureRequestOptions(); - options.forEach((CaptureRequestKey key, Object? value) { - when( - mockCaptureRequestOptions.getCaptureRequestOption(key), - ).thenAnswer((_) async => value); - }); - return mockCaptureRequestOptions; - }; - PigeonOverrides.captureRequest_controlVideoStabilizationMode = - controlVideoStabilizationModeKey; + // Tell plugin to create detached Camera2CameraControl and + // CaptureRequestOptions instances for testing. + final controlVideoStabilizationModeKey = CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides + .captureRequestOptions_new = ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlVideoStabilizationMode = controlVideoStabilizationModeKey; - PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { - when( - mockCamera2CameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => [0]); - return mockCamera2CameraInfo; - }; - PigeonOverrides - .cameraCharacteristics_controlAvailableVideoStabilizationModes = - MockCameraCharacteristicsKey(); - expect( - () => camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level1, - ), - throwsA( - isA().having( - (ArgumentError e) => e.name, - 'name', - 'mode', - ), - ), - ); - }, - ); + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when(mockCamera2CameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => [0]); + return mockCamera2CameraInfo; + }; + PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes = + MockCameraCharacteristicsKey(); + expect( + () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1), + throwsA(isA().having((ArgumentError e) => e.name, 'name', 'mode')), + ); + }); - test( - 'setVideoStabilizationMode throws ArgumentError when mode not mapped', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 102; - final mockCameraControl = MockCameraControl(); - final mockCamera2CameraControl = MockCamera2CameraControl(); - final mockCameraInfo = MockCameraInfo(); - final mockCamera2CameraInfo = MockCamera2CameraInfo(); + test('setVideoStabilizationMode throws ArgumentError when mode not mapped', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 102; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); - // Set directly for test versus calling createCamera. - camera.camera = MockCamera(); - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; + // Set directly for test versus calling createCamera. + camera.camera = MockCamera(); + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; - // Tell plugin to create detached Camera2CameraControl and - // CaptureRequestOptions instances for testing. - final controlVideoStabilizationModeKey = - CaptureRequestKey.pigeon_detached(); - PigeonOverrides.camera2CameraControl_from = - ({required CameraControl cameraControl}) => - cameraControl == mockCameraControl - ? mockCamera2CameraControl - : Camera2CameraControl.pigeon_detached(); - PigeonOverrides.captureRequestOptions_new = - ({required Map options}) { - final mockCaptureRequestOptions = MockCaptureRequestOptions(); - options.forEach((CaptureRequestKey key, Object? value) { - when( - mockCaptureRequestOptions.getCaptureRequestOption(key), - ).thenAnswer((_) async => value); - }); - return mockCaptureRequestOptions; - }; - PigeonOverrides.captureRequest_controlVideoStabilizationMode = - controlVideoStabilizationModeKey; + // Tell plugin to create detached Camera2CameraControl and + // CaptureRequestOptions instances for testing. + final controlVideoStabilizationModeKey = CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides + .captureRequestOptions_new = ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlVideoStabilizationMode = controlVideoStabilizationModeKey; - PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { - when( - mockCamera2CameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => [0, 1, 2]); - return mockCamera2CameraInfo; - }; - PigeonOverrides - .cameraCharacteristics_controlAvailableVideoStabilizationModes = - MockCameraCharacteristicsKey(); + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => [0, 1, 2]); + return mockCamera2CameraInfo; + }; + PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes = + MockCameraCharacteristicsKey(); - expect( - () => camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level2, - ), - throwsA( - isA().having( - (ArgumentError e) => e.name, - 'name', - 'mode', - ), - ), - ); - expect( - () => camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level3, - ), - throwsA( - isA().having( - (ArgumentError e) => e.name, - 'name', - 'mode', - ), - ), - ); - }, - ); + expect( + () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level2), + throwsA(isA().having((ArgumentError e) => e.name, 'name', 'mode')), + ); + expect( + () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level3), + throwsA(isA().having((ArgumentError e) => e.name, 'name', 'mode')), + ); + }); test('getVideoStabilizationMode returns no available mode', () async { // Set up mocks and constants. @@ -4409,19 +3655,17 @@ void main() { camera.cameraInfo = mockCameraInfo; PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { - when( - mockCamera2cameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => []); + when(mockCamera2cameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => []); return mockCamera2cameraInfo; }; - PigeonOverrides - .cameraCharacteristics_controlAvailableVideoStabilizationModes = + PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes = MockCameraCharacteristicsKey(); const cameraId = 103; - final Iterable modes = await camera - .getSupportedVideoStabilizationModes(cameraId); + final Iterable modes = await camera.getSupportedVideoStabilizationModes( + cameraId, + ); expect(modes, orderedEquals([])); }); @@ -4442,12 +3686,12 @@ void main() { ).thenAnswer((_) async => [0, 1, 2]); return mockCamera2CameraInfo; }; - PigeonOverrides - .cameraCharacteristics_controlAvailableVideoStabilizationModes = + PigeonOverrides.cameraCharacteristics_controlAvailableVideoStabilizationModes = MockCameraCharacteristicsKey(); - final Iterable modes = await camera - .getSupportedVideoStabilizationModes(cameraId); + final Iterable modes = await camera.getSupportedVideoStabilizationModes( + cameraId, + ); expect( modes, @@ -4473,10 +3717,9 @@ void main() { const cameraId = 22; // Tell plugin to create detached Analyzer for testing. - PigeonOverrides.analyzer_new = - ({required void Function(Analyzer, ImageProxy) analyze}) { - return Analyzer.pigeon_detached(analyze: analyze); - }; + PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) { + return Analyzer.pigeon_detached(analyze: analyze); + }; // Set directly for test versus calling createCamera. camera.processCameraProvider = mockProcessCameraProvider; @@ -4489,19 +3732,12 @@ void main() { when( mockProcessCameraProvider.bindToLifecycle(any, any), ).thenAnswer((_) => Future.value(mockCamera)); - when( - mockProcessCameraProvider.isBound(camera.imageAnalysis), - ).thenAnswer((_) async => true); - when( - mockCamera.getCameraInfo(), - ).thenAnswer((_) => Future.value(mockCameraInfo)); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockProcessCameraProvider.isBound(camera.imageAnalysis)).thenAnswer((_) async => true); + when(mockCamera.getCameraInfo()).thenAnswer((_) => Future.value(mockCameraInfo)); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); final CameraImageData mockCameraImageData = MockCameraImageData(); - final Stream imageStream = camera - .onStreamedFrameAvailable(cameraId); + final Stream imageStream = camera.onStreamedFrameAvailable(cameraId); final streamQueue = StreamQueue(imageStream); camera.cameraImageDataStreamController!.add(mockCameraImageData); @@ -4519,10 +3755,9 @@ void main() { const cameraId = 22; // Tell plugin to create detached Analyzer for testing. - PigeonOverrides.analyzer_new = - ({required void Function(Analyzer, ImageProxy) analyze}) { - return Analyzer.pigeon_detached(analyze: analyze); - }; + PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) { + return Analyzer.pigeon_detached(analyze: analyze); + }; // Set directly for test versus calling createCamera. camera.processCameraProvider = mockProcessCameraProvider; @@ -4532,22 +3767,19 @@ void main() { // Ignore setting target rotation for this test; tested seprately. camera.captureOrientationLocked = true; - when( - mockProcessCameraProvider.isBound(camera.imageAnalysis), - ).thenAnswer((_) async => true); + when(mockProcessCameraProvider.isBound(camera.imageAnalysis)).thenAnswer((_) async => true); final CameraImageData mockCameraImageData = MockCameraImageData(); - final Stream imageStream = camera - .onStreamedFrameAvailable(cameraId); + final Stream imageStream = camera.onStreamedFrameAvailable(cameraId); // Listen to image stream. - final StreamSubscription imageStreamSubscription = - imageStream.listen((CameraImageData data) {}); + final StreamSubscription imageStreamSubscription = imageStream.listen( + (CameraImageData data) {}, + ); // Cancel subscription to image stream. await imageStreamSubscription.cancel(); - final Stream imageStream2 = camera - .onStreamedFrameAvailable(cameraId); + final Stream imageStream2 = camera.onStreamedFrameAvailable(cameraId); // Listen to image stream again. final streamQueue = StreamQueue(imageStream2); @@ -4563,8 +3795,7 @@ void main() { () async { final camera = AndroidCameraCameraX(); const cameraId = 33; - final ProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); + final ProcessCameraProvider mockProcessCameraProvider = MockProcessCameraProvider(); final CameraSelector mockCameraSelector = MockCameraSelector(); final mockImageAnalysis = MockImageAnalysis(); final Camera mockCamera = MockCamera(); @@ -4580,10 +3811,9 @@ void main() { const imageWidth = 200; // Tell plugin to create detached Analyzer for testing. - PigeonOverrides.analyzer_new = - ({required void Function(Analyzer, ImageProxy) analyze}) { - return Analyzer.pigeon_detached(analyze: analyze); - }; + PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) { + return Analyzer.pigeon_detached(analyze: analyze); + }; GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { return Observer.detached(onChanged: onChanged); @@ -4597,18 +3827,12 @@ void main() { // Ignore setting target rotation for this test; tested seprately. camera.captureOrientationLocked = true; + when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => false); when( - mockProcessCameraProvider.isBound(mockImageAnalysis), - ).thenAnswer((_) async => false); - when( - mockProcessCameraProvider.bindToLifecycle(mockCameraSelector, [ - mockImageAnalysis, - ]), + mockProcessCameraProvider.bindToLifecycle(mockCameraSelector, [mockImageAnalysis]), ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); when( mockImageProxy.getPlanes(), ).thenAnswer((_) async => Future>.value(mockPlanes)); @@ -4620,8 +3844,7 @@ void main() { when(mockImageProxy.width).thenReturn(imageWidth); final imageDataCompleter = Completer(); - final StreamSubscription - onStreamedFrameAvailableSubscription = camera + final StreamSubscription onStreamedFrameAvailableSubscription = camera .onStreamedFrameAvailable(cameraId) .listen((CameraImageData imageData) { imageDataCompleter.complete(imageData); @@ -4630,8 +3853,7 @@ void main() { // Test ImageAnalysis use case is bound to ProcessCameraProvider. await untilCalled(mockImageAnalysis.setAnalyzer(any)); final capturedAnalyzer = - verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single - as Analyzer; + verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single as Analyzer; capturedAnalyzer.analyze(MockAnalyzer(), mockImageProxy); @@ -4664,13 +3886,9 @@ void main() { final testNv21Buffer = Uint8List(10); // Mock use case bindings and related Camera objects. - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); // Set up CameraXProxy with ImageAnalysis specifics needed for testing its Analyzer. setUpOverridesForTestingUseCaseConfiguration( @@ -4678,16 +3896,14 @@ void main() { newAnalyzer: ({required void Function(Analyzer, ImageProxy) analyze}) { return Analyzer.pigeon_detached(analyze: analyze); }, - newImageAnalysis: - ({ - int? outputImageFormat, - ResolutionSelector? resolutionSelector, - int? targetRotation, - CameraIntegerRange? targetFpsRange, - }) => mockImageAnalysis, - getNv21BufferImageProxyUtils: - (int imageWidth, int imageHeight, List planes) => - Future.value(testNv21Buffer), + newImageAnalysis: ({ + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + }) => mockImageAnalysis, + getNv21BufferImageProxyUtils: (int imageWidth, int imageHeight, List planes) => + Future.value(testNv21Buffer), ); // Create and initialize camera with NV21. @@ -4699,10 +3915,7 @@ void main() { ), ResolutionPreset.low, ); - await camera.initializeCamera( - cameraId, - imageFormatGroup: ImageFormatGroup.nv21, - ); + await camera.initializeCamera(cameraId, imageFormatGroup: ImageFormatGroup.nv21); // Create mock ImageProxy with theoretical underlying NV21 format but with three // planes still in YUV_420_888 format that should get transformed to testNv21Buffer. @@ -4718,8 +3931,7 @@ void main() { await untilCalled(mockImageAnalysis.setAnalyzer(any)); final capturedAnalyzer = - verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single - as Analyzer; + verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single as Analyzer; capturedAnalyzer.analyze(MockAnalyzer(), mockImageProxy); final CameraImageData imageData = await imageDataCompleter.future; @@ -4749,13 +3961,10 @@ void main() { camera.captureOrientationLocked = true; // Tell plugin to create a detached analyzer for testing purposes. - PigeonOverrides.analyzer_new = - ({required void Function(Analyzer, ImageProxy) analyze}) => - MockAnalyzer(); + PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) => + MockAnalyzer(); - when( - mockProcessCameraProvider.isBound(mockImageAnalysis), - ).thenAnswer((_) async => true); + when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => true); final StreamSubscription imageStreamSubscription = camera .onStreamedFrameAvailable(cameraId) @@ -4782,14 +3991,10 @@ void main() { // Tell plugin to create a detached analyzer for testing purposes and mock // call to get current photo orientation. - PigeonOverrides.analyzer_new = - ({required void Function(Analyzer, ImageProxy) analyze}) => - MockAnalyzer(); + PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) => + MockAnalyzer(); PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) { + ({required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged}) { final manager = MockDeviceOrientationManager(); when(manager.getDefaultDisplayRotation()).thenAnswer((_) async { return defaultTargetRotation; @@ -4797,9 +4002,7 @@ void main() { return manager; }; - when( - mockProcessCameraProvider.isBound(mockImageAnalysis), - ).thenAnswer((_) async => true); + when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => true); // Orientation is unlocked and plugin does not need to set default target // rotation manually. @@ -4838,9 +4041,7 @@ void main() { imageStreamSubscription = camera .onStreamedFrameAvailable(cameraId) .listen((CameraImageData data) {}); - await untilCalled( - mockImageAnalysis.setTargetRotation(defaultTargetRotation), - ); + await untilCalled(mockImageAnalysis.setTargetRotation(defaultTargetRotation)); await imageStreamSubscription.cancel(); }, ); @@ -4873,190 +4074,161 @@ void main() { expectedTargetRotation = Surface.rotation270; } - await camera.lockCaptureOrientation(cameraId, orientation); - - verify(mockImageAnalysis.setTargetRotation(expectedTargetRotation)); - verify(mockImageCapture.setTargetRotation(expectedTargetRotation)); - verify(mockVideoCapture.setTargetRotation(expectedTargetRotation)); - expect(camera.captureOrientationLocked, isTrue); - expect(camera.shouldSetDefaultRotation, isTrue); - - // Reset flags for testing. - camera.captureOrientationLocked = false; - camera.shouldSetDefaultRotation = false; - } - }, - ); - - test( - 'unlockCaptureOrientation sets capture-related use case target rotations to current photo/video orientation', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 57; - - camera.captureOrientationLocked = true; - await camera.unlockCaptureOrientation(cameraId); - expect(camera.captureOrientationLocked, isFalse); - }, - ); - - test( - 'setExposureMode sets expected controlAeLock value via Camera2 interop', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 78; - final mockCameraControl = MockCameraControl(); - final mockCamera2CameraControl = MockCamera2CameraControl(); - - // Set directly for test versus calling createCamera. - camera.camera = MockCamera(); - camera.cameraControl = mockCameraControl; - - // Tell plugin to create detached Camera2CameraControl and - // CaptureRequestOptions instances for testing. - final controlAELockKey = CaptureRequestKey.pigeon_detached(); - PigeonOverrides.camera2CameraControl_from = - ({required CameraControl cameraControl}) => - cameraControl == mockCameraControl - ? mockCamera2CameraControl - : Camera2CameraControl.pigeon_detached(); - PigeonOverrides.captureRequestOptions_new = - ({required Map options}) { - final mockCaptureRequestOptions = MockCaptureRequestOptions(); - options.forEach((CaptureRequestKey key, Object? value) { - when( - mockCaptureRequestOptions.getCaptureRequestOption(key), - ).thenAnswer((_) async => value); - }); - return mockCaptureRequestOptions; - }; - PigeonOverrides.captureRequest_controlAELock = controlAELockKey; - - // Test auto mode. - await camera.setExposureMode(cameraId, ExposureMode.auto); - - VerificationResult verificationResult = verify( - mockCamera2CameraControl.addCaptureRequestOptions(captureAny), - ); - var capturedCaptureRequestOptions = - verificationResult.captured.single as CaptureRequestOptions; - expect( - await capturedCaptureRequestOptions.getCaptureRequestOption( - controlAELockKey, - ), - isFalse, - ); + await camera.lockCaptureOrientation(cameraId, orientation); - // Test locked mode. - clearInteractions(mockCamera2CameraControl); - await camera.setExposureMode(cameraId, ExposureMode.locked); + verify(mockImageAnalysis.setTargetRotation(expectedTargetRotation)); + verify(mockImageCapture.setTargetRotation(expectedTargetRotation)); + verify(mockVideoCapture.setTargetRotation(expectedTargetRotation)); + expect(camera.captureOrientationLocked, isTrue); + expect(camera.shouldSetDefaultRotation, isTrue); - verificationResult = verify( - mockCamera2CameraControl.addCaptureRequestOptions(captureAny), - ); - capturedCaptureRequestOptions = - verificationResult.captured.single as CaptureRequestOptions; - expect( - await capturedCaptureRequestOptions.getCaptureRequestOption( - controlAELockKey, - ), - isTrue, - ); + // Reset flags for testing. + camera.captureOrientationLocked = false; + camera.shouldSetDefaultRotation = false; + } }, ); test( - 'setExposurePoint clears current auto-exposure metering point as expected', + 'unlockCaptureOrientation sets capture-related use case target rotations to current photo/video orientation', () async { final camera = AndroidCameraCameraX(); - const cameraId = 93; - final mockCameraControl = MockCameraControl(); - final mockCameraInfo = MockCameraInfo(); + const cameraId = 57; - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; + camera.captureOrientationLocked = true; + await camera.unlockCaptureOrientation(cameraId); + expect(camera.captureOrientationLocked, isFalse); + }, + ); - final mockActionBuilder = MockFocusMeteringActionBuilder(); - when(mockActionBuilder.build()).thenAnswer( - (_) async => FocusMeteringAction.pigeon_detached( - meteringPointsAe: const [], - meteringPointsAf: const [], - meteringPointsAwb: const [], - isAutoCancelEnabled: false, - ), - ); - MeteringMode? actionBuilderMeteringMode; - MeteringPoint? actionBuilderMeteringPoint; - setUpOverridesForExposureAndFocus( - withModeFocusMeteringActionBuilder: - ({required MeteringMode mode, required MeteringPoint point}) { - actionBuilderMeteringMode = mode; - actionBuilderMeteringPoint = point; - return mockActionBuilder; - }, - ); + test('setExposureMode sets expected controlAeLock value via Camera2 interop', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 78; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); - // Verify nothing happens if no current focus and metering action has been - // enabled. - await camera.setExposurePoint(cameraId, null); - verifyNever(mockCameraControl.startFocusAndMetering(any)); - verifyNever(mockCameraControl.cancelFocusAndMetering()); + // Set directly for test versus calling createCamera. + camera.camera = MockCamera(); + camera.cameraControl = mockCameraControl; - // Verify current auto-exposure metering point is removed if previously set. - final originalMeteringAction = FocusMeteringAction.pigeon_detached( - meteringPointsAe: [MeteringPoint.pigeon_detached()], - meteringPointsAf: [MeteringPoint.pigeon_detached()], - meteringPointsAwb: const [], - isAutoCancelEnabled: false, - ); - camera.currentFocusMeteringAction = originalMeteringAction; + // Tell plugin to create detached Camera2CameraControl and + // CaptureRequestOptions instances for testing. + final controlAELockKey = CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides + .captureRequestOptions_new = ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when(mockCaptureRequestOptions.getCaptureRequestOption(key)).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlAELock = controlAELockKey; - await camera.setExposurePoint(cameraId, null); + // Test auto mode. + await camera.setExposureMode(cameraId, ExposureMode.auto); - expect(actionBuilderMeteringMode, MeteringMode.af); - expect( - actionBuilderMeteringPoint, - originalMeteringAction.meteringPointsAf.single, - ); - verifyNever(mockActionBuilder.addPoint(any)); - verifyNever(mockActionBuilder.addPointWithMode(any, any)); + VerificationResult verificationResult = verify( + mockCamera2CameraControl.addCaptureRequestOptions(captureAny), + ); + var capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions; + expect(await capturedCaptureRequestOptions.getCaptureRequestOption(controlAELockKey), isFalse); - // Verify current focus and metering action is cleared if only previously - // set metering point was for auto-exposure. - camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached( - meteringPointsAe: [MeteringPoint.pigeon_detached()], + // Test locked mode. + clearInteractions(mockCamera2CameraControl); + await camera.setExposureMode(cameraId, ExposureMode.locked); + + verificationResult = verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny)); + capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions; + expect(await capturedCaptureRequestOptions.getCaptureRequestOption(controlAELockKey), isTrue); + }); + + test('setExposurePoint clears current auto-exposure metering point as expected', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 93; + final mockCameraControl = MockCameraControl(); + final mockCameraInfo = MockCameraInfo(); + + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; + + final mockActionBuilder = MockFocusMeteringActionBuilder(); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - ); + ), + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + setUpOverridesForExposureAndFocus( + withModeFocusMeteringActionBuilder: + ({required MeteringMode mode, required MeteringPoint point}) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); - await camera.setExposurePoint(cameraId, null); + // Verify nothing happens if no current focus and metering action has been + // enabled. + await camera.setExposurePoint(cameraId, null); + verifyNever(mockCameraControl.startFocusAndMetering(any)); + verifyNever(mockCameraControl.cancelFocusAndMetering()); + + // Verify current auto-exposure metering point is removed if previously set. + final originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [MeteringPoint.pigeon_detached()], + meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); + camera.currentFocusMeteringAction = originalMeteringAction; + + await camera.setExposurePoint(cameraId, null); + + expect(actionBuilderMeteringMode, MeteringMode.af); + expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAf.single); + verifyNever(mockActionBuilder.addPoint(any)); + verifyNever(mockActionBuilder.addPointWithMode(any, any)); + + // Verify current focus and metering action is cleared if only previously + // set metering point was for auto-exposure. + camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [MeteringPoint.pigeon_detached()], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); - verify(mockCameraControl.cancelFocusAndMetering()); - }, - ); + await camera.setExposurePoint(cameraId, null); - test( - 'setExposurePoint throws CameraException if invalid point specified', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 23; - final mockCameraControl = MockCameraControl(); - const invalidExposurePoint = Point(3, -1); + verify(mockCameraControl.cancelFocusAndMetering()); + }); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); + test('setExposurePoint throws CameraException if invalid point specified', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 23; + final mockCameraControl = MockCameraControl(); + const invalidExposurePoint = Point(3, -1); - setUpOverridesForExposureAndFocus(); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - expect( - () => camera.setExposurePoint(cameraId, invalidExposurePoint), - throwsA(isA()), - ); - }, - ); + setUpOverridesForExposureAndFocus(); + + expect( + () => camera.setExposurePoint(cameraId, invalidExposurePoint), + throwsA(isA()), + ); + }); test( 'setExposurePoint adds new exposure point to focus metering action to start as expected when previous metering points have been set', @@ -5086,11 +4258,7 @@ void main() { ); setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: - ({ - required dynamic cameraInfo, - required double width, - required double height, - }) { + ({required dynamic cameraInfo, required double width, required double height}) { final mockFactory = MockDisplayOrientedMeteringPointFactory(); when( mockFactory.createPoint(exposurePointX, exposurePointY), @@ -5117,17 +4285,9 @@ void main() { await camera.setExposurePoint(cameraId, exposurePoint); - expect( - actionBuilderMeteringPoint, - originalMeteringAction.meteringPointsAf.single, - ); + expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAf.single); expect(actionBuilderMeteringMode, MeteringMode.af); - verify( - mockActionBuilder.addPointWithMode( - createdMeteringPoint, - MeteringMode.ae, - ), - ); + verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.ae)); // Verify exposure point is set when no auto-exposure metering point // previously set, but an auto-focus point metering point has been. @@ -5144,17 +4304,9 @@ void main() { await camera.setExposurePoint(cameraId, exposurePoint); - expect( - actionBuilderMeteringPoint, - originalMeteringAction.meteringPointsAf.single, - ); + expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAf.single); expect(actionBuilderMeteringMode, MeteringMode.af); - verify( - mockActionBuilder.addPointWithMode( - createdMeteringPoint, - MeteringMode.ae, - ), - ); + verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.ae)); }, ); @@ -5187,11 +4339,7 @@ void main() { ); setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: - ({ - required dynamic cameraInfo, - required double width, - required double height, - }) { + ({required dynamic cameraInfo, required double width, required double height}) { final mockFactory = MockDisplayOrientedMeteringPointFactory(); when( mockFactory.createPoint(exposurePointX, exposurePointY), @@ -5213,83 +4361,63 @@ void main() { }, ); - test( - 'setExposurePoint disables auto-cancel for focus and metering as expected', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 2; - final mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - const exposurePoint = Point(0.1, 0.2); - - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - MockCamera2CameraControl(), - ); + test('setExposurePoint disables auto-cancel for focus and metering as expected', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 2; + final mockCameraControl = MockCameraControl(); + final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); + const exposurePoint = Point(0.1, 0.2); - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - // Test not disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.auto); - clearInteractions(mockCameraControl); - await camera.setExposurePoint(cameraId, exposurePoint); - VerificationResult verificationResult = verify( - mockCameraControl.startFocusAndMetering(captureAny), - ); - var capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.isAutoCancelEnabled, isTrue); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl()); - clearInteractions(mockCameraControl); + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); - // Test disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); - await camera.setExposurePoint(cameraId, exposurePoint); - verificationResult = verify( - mockCameraControl.startFocusAndMetering(captureAny), - ); - capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.isAutoCancelEnabled, isFalse); - }, - ); + // Test not disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.auto); + clearInteractions(mockCameraControl); + await camera.setExposurePoint(cameraId, exposurePoint); + VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + var capturedAction = verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); + + clearInteractions(mockCameraControl); + + // Test disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + await camera.setExposurePoint(cameraId, exposurePoint); + verificationResult = verify(mockCameraControl.startFocusAndMetering(captureAny)); + capturedAction = verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + }); - test( - 'setExposureOffset throws exception if exposure compensation not supported', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 6; - const double offset = 2; - final mockCameraInfo = MockCameraInfo(); - final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 3, - upper: 4, - ), - exposureCompensationStep: 0, - ); + test('setExposureOffset throws exception if exposure compensation not supported', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 6; + const double offset = 2; + final mockCameraInfo = MockCameraInfo(); + final exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4), + exposureCompensationStep: 0, + ); - // Set directly for test versus calling createCamera. - camera.cameraInfo = mockCameraInfo; + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; - when(mockCameraInfo.exposureState).thenReturn(exposureState); + when(mockCameraInfo.exposureState).thenReturn(exposureState); - expect( - () => camera.setExposureOffset(cameraId, offset), - throwsA(isA()), - ); - }, - ); + expect(() => camera.setExposureOffset(cameraId, offset), throwsA(isA())); + }); test( 'setExposureOffset throws exception if exposure compensation could not be set for unknown reason', @@ -5300,10 +4428,7 @@ void main() { final mockCameraInfo = MockCameraInfo(); final CameraControl mockCameraControl = MockCameraControl(); final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 3, - upper: 4, - ), + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4), exposureCompensationStep: 0.2, ); @@ -5315,15 +4440,11 @@ void main() { when(mockCameraControl.setExposureCompensationIndex(15)).thenThrow( PlatformException( code: 'TEST_ERROR', - message: - 'This is a test error message indicating exposure offset could not be set.', + message: 'This is a test error message indicating exposure offset could not be set.', ), ); - expect( - () => camera.setExposureOffset(cameraId, offset), - throwsA(isA()), - ); + expect(() => camera.setExposureOffset(cameraId, offset), throwsA(isA())); }, ); @@ -5336,10 +4457,7 @@ void main() { final mockCameraInfo = MockCameraInfo(); final CameraControl mockCameraControl = MockCameraControl(); final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 3, - upper: 4, - ), + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4), exposureCompensationStep: 0.1, ); final int expectedExposureCompensationIndex = @@ -5351,15 +4469,10 @@ void main() { when(mockCameraInfo.exposureState).thenReturn(exposureState); when( - mockCameraControl.setExposureCompensationIndex( - expectedExposureCompensationIndex, - ), + mockCameraControl.setExposureCompensationIndex(expectedExposureCompensationIndex), ).thenAnswer((_) async => Future.value()); - expect( - () => camera.setExposureOffset(cameraId, offset), - throwsA(isA()), - ); + expect(() => camera.setExposureOffset(cameraId, offset), throwsA(isA())); }, ); @@ -5369,132 +4482,116 @@ void main() { final camera = AndroidCameraCameraX(); const cameraId = 11; const double offset = 3; - final mockCameraInfo = MockCameraInfo(); - final CameraControl mockCameraControl = MockCameraControl(); - final exposureState = ExposureState.pigeon_detached( - exposureCompensationRange: CameraIntegerRange.pigeon_detached( - lower: 3, - upper: 4, - ), - exposureCompensationStep: 0.2, - ); - final int expectedExposureCompensationIndex = - (offset / exposureState.exposureCompensationStep).round(); - - // Set directly for test versus calling createCamera. - camera.cameraInfo = mockCameraInfo; - camera.cameraControl = mockCameraControl; - - when(mockCameraInfo.exposureState).thenReturn(exposureState); - when( - mockCameraControl.setExposureCompensationIndex( - expectedExposureCompensationIndex, - ), - ).thenAnswer( - (_) async => Future.value( - (expectedExposureCompensationIndex * - exposureState.exposureCompensationStep) - .round(), - ), - ); - - // Exposure index * exposure offset step size = exposure offset, i.e. - // 15 * 0.2 = 3. - expect(await camera.setExposureOffset(cameraId, offset), equals(3)); - }, - ); - - test( - 'setFocusPoint clears current auto-exposure metering point as expected', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 93; - final mockCameraControl = MockCameraControl(); - final mockCameraInfo = MockCameraInfo(); - - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; - - final mockActionBuilder = MockFocusMeteringActionBuilder(); - when(mockActionBuilder.build()).thenAnswer( - (_) async => FocusMeteringAction.pigeon_detached( - meteringPointsAe: const [], - meteringPointsAf: const [], - meteringPointsAwb: const [], - isAutoCancelEnabled: false, - ), - ); - MeteringMode? actionBuilderMeteringMode; - MeteringPoint? actionBuilderMeteringPoint; - setUpOverridesForExposureAndFocus( - withModeFocusMeteringActionBuilder: - ({required MeteringMode mode, required MeteringPoint point}) { - actionBuilderMeteringMode = mode; - actionBuilderMeteringPoint = point; - return mockActionBuilder; - }, + final mockCameraInfo = MockCameraInfo(); + final CameraControl mockCameraControl = MockCameraControl(); + final exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached(lower: 3, upper: 4), + exposureCompensationStep: 0.2, ); + final int expectedExposureCompensationIndex = + (offset / exposureState.exposureCompensationStep).round(); - // Verify nothing happens if no current focus and metering action has been - // enabled. - await camera.setFocusPoint(cameraId, null); - verifyNever(mockCameraControl.startFocusAndMetering(any)); - verifyNever(mockCameraControl.cancelFocusAndMetering()); + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; + camera.cameraControl = mockCameraControl; - final originalMeteringAction = FocusMeteringAction.pigeon_detached( - meteringPointsAe: [MeteringPoint.pigeon_detached()], - meteringPointsAf: [MeteringPoint.pigeon_detached()], - meteringPointsAwb: const [], - isAutoCancelEnabled: false, + when(mockCameraInfo.exposureState).thenReturn(exposureState); + when( + mockCameraControl.setExposureCompensationIndex(expectedExposureCompensationIndex), + ).thenAnswer( + (_) async => Future.value( + (expectedExposureCompensationIndex * exposureState.exposureCompensationStep).round(), + ), ); - camera.currentFocusMeteringAction = originalMeteringAction; - await camera.setFocusPoint(cameraId, null); + // Exposure index * exposure offset step size = exposure offset, i.e. + // 15 * 0.2 = 3. + expect(await camera.setExposureOffset(cameraId, offset), equals(3)); + }, + ); + + test('setFocusPoint clears current auto-exposure metering point as expected', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 93; + final mockCameraControl = MockCameraControl(); + final mockCameraInfo = MockCameraInfo(); - expect(actionBuilderMeteringMode, MeteringMode.ae); - expect( - actionBuilderMeteringPoint, - originalMeteringAction.meteringPointsAe.single, - ); - verifyNever(mockActionBuilder.addPoint(any)); - verifyNever(mockActionBuilder.addPointWithMode(any, any)); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; - // Verify current focus and metering action is cleared if only previously - // set metering point was for auto-exposure. - camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached( + final mockActionBuilder = MockFocusMeteringActionBuilder(); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( meteringPointsAe: const [], - meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - ); + ), + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + setUpOverridesForExposureAndFocus( + withModeFocusMeteringActionBuilder: + ({required MeteringMode mode, required MeteringPoint point}) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); - await camera.setFocusPoint(cameraId, null); + // Verify nothing happens if no current focus and metering action has been + // enabled. + await camera.setFocusPoint(cameraId, null); + verifyNever(mockCameraControl.startFocusAndMetering(any)); + verifyNever(mockCameraControl.cancelFocusAndMetering()); + + final originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [MeteringPoint.pigeon_detached()], + meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); + camera.currentFocusMeteringAction = originalMeteringAction; + + await camera.setFocusPoint(cameraId, null); + + expect(actionBuilderMeteringMode, MeteringMode.ae); + expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAe.single); + verifyNever(mockActionBuilder.addPoint(any)); + verifyNever(mockActionBuilder.addPointWithMode(any, any)); + + // Verify current focus and metering action is cleared if only previously + // set metering point was for auto-exposure. + camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); - verify(mockCameraControl.cancelFocusAndMetering()); - }, - ); + await camera.setFocusPoint(cameraId, null); - test( - 'setFocusPoint throws CameraException if invalid point specified', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 23; - final mockCameraControl = MockCameraControl(); - const invalidFocusPoint = Point(-3, 1); + verify(mockCameraControl.cancelFocusAndMetering()); + }); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); + test('setFocusPoint throws CameraException if invalid point specified', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 23; + final mockCameraControl = MockCameraControl(); + const invalidFocusPoint = Point(-3, 1); + + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - setUpOverridesForExposureAndFocus(); + setUpOverridesForExposureAndFocus(); - expect( - () => camera.setFocusPoint(cameraId, invalidFocusPoint), - throwsA(isA()), - ); - }, - ); + expect( + () => camera.setFocusPoint(cameraId, invalidFocusPoint), + throwsA(isA()), + ); + }); test( 'setFocusPoint adds new focus point to focus metering action to start as expected when previous metering points have been set', @@ -5525,11 +4622,7 @@ void main() { ); setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: - ({ - required dynamic cameraInfo, - required double width, - required double height, - }) { + ({required dynamic cameraInfo, required double width, required double height}) { final mockFactory = MockDisplayOrientedMeteringPointFactory(); when( mockFactory.createPoint(focusPointX, focusPointY), @@ -5555,17 +4648,9 @@ void main() { await camera.setFocusPoint(cameraId, focusPoint); - expect( - actionBuilderMeteringPoint, - originalMeteringAction.meteringPointsAe.single, - ); + expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAe.single); expect(actionBuilderMeteringMode, MeteringMode.ae); - verify( - mockActionBuilder.addPointWithMode( - createdMeteringPoint, - MeteringMode.af, - ), - ); + verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.af)); // Verify exposure point is set when no auto-focus metering point // previously set, but an auto-exposure point metering point has been. @@ -5582,17 +4667,9 @@ void main() { await camera.setFocusPoint(cameraId, focusPoint); - expect( - actionBuilderMeteringPoint, - originalMeteringAction.meteringPointsAe.single, - ); + expect(actionBuilderMeteringPoint, originalMeteringAction.meteringPointsAe.single); expect(actionBuilderMeteringMode, MeteringMode.ae); - verify( - mockActionBuilder.addPointWithMode( - createdMeteringPoint, - MeteringMode.af, - ), - ); + verify(mockActionBuilder.addPointWithMode(createdMeteringPoint, MeteringMode.af)); }, ); @@ -5625,11 +4702,7 @@ void main() { ); setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: - ({ - required dynamic cameraInfo, - required double width, - required double height, - }) { + ({required dynamic cameraInfo, required double width, required double height}) { final mockFactory = MockDisplayOrientedMeteringPointFactory(); when( mockFactory.createPoint(focusPointX, focusPointY), @@ -5651,57 +4724,47 @@ void main() { }, ); - test( - 'setFocusPoint disables auto-cancel for focus and metering as expected', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 2; - final mockCameraControl = MockCameraControl(); - final mockFocusMeteringResult = MockFocusMeteringResult(); - const exposurePoint = Point(0.1, 0.2); + test('setFocusPoint disables auto-cancel for focus and metering as expected', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 2; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); + const exposurePoint = Point(0.1, 0.2); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - MockCamera2CameraControl(), - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl()); - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); - // Test not disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.auto); - clearInteractions(mockCameraControl); + // Test not disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.auto); + clearInteractions(mockCameraControl); - await camera.setFocusPoint(cameraId, exposurePoint); - VerificationResult verificationResult = verify( - mockCameraControl.startFocusAndMetering(captureAny), - ); - var capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.isAutoCancelEnabled, isTrue); + await camera.setFocusPoint(cameraId, exposurePoint); + VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + var capturedAction = verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); - clearInteractions(mockCameraControl); + clearInteractions(mockCameraControl); - // Test disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); + // Test disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); - await camera.setFocusPoint(cameraId, exposurePoint); - verificationResult = verify( - mockCameraControl.startFocusAndMetering(captureAny), - ); - capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.isAutoCancelEnabled, isFalse); - }, - ); + await camera.setFocusPoint(cameraId, exposurePoint); + verificationResult = verify(mockCameraControl.startFocusAndMetering(captureAny)); + capturedAction = verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + }); test( 'setFocusMode does nothing if setting auto-focus mode and is already using auto-focus mode', @@ -5715,16 +4778,13 @@ void main() { camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - MockCamera2CameraControl(), - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl()); // Make setting focus and metering action successful for test. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Set locked focus mode and then try to re-set it. await camera.setFocusMode(cameraId, FocusMode.locked); @@ -5773,22 +4833,14 @@ void main() { mockCameraControl, mockCamera2CameraControl, newDisplayOrientedMeteringPointFactory: - ({ - required dynamic cameraInfo, - required double width, - required double height, - }) { + ({required dynamic cameraInfo, required double width, required double height}) { final mockFactory = MockDisplayOrientedMeteringPointFactory(); - when( - mockFactory.createPoint(exposurePointX, exposurePointY), - ).thenAnswer((_) async { + when(mockFactory.createPoint(exposurePointX, exposurePointY)).thenAnswer((_) async { final createdMeteringPoint = MeteringPoint.pigeon_detached(); createdMeteringPoints.add(createdMeteringPoint); return createdMeteringPoint; }); - when(mockFactory.createPointWithSize(0.5, 0.5, 1)).thenAnswer(( - _, - ) async { + when(mockFactory.createPointWithSize(0.5, 0.5, 1)).thenAnswer((_) async { final createdMeteringPoint = MeteringPoint.pigeon_detached(); createdMeteringPoints.add(createdMeteringPoint); return createdMeteringPoint; @@ -5799,15 +4851,12 @@ void main() { // Make setting focus and metering action successful for test. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Set exposure points. - await camera.setExposurePoint( - cameraId, - const Point(exposurePointX, exposurePointY), - ); + await camera.setExposurePoint(cameraId, const Point(exposurePointX, exposurePointY)); // Lock focus default focus point. await camera.setFocusMode(cameraId, FocusMode.locked); @@ -5820,8 +4869,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); // We expect only the previously set exposure point to be re-set. @@ -5837,8 +4885,7 @@ void main() { final camera = AndroidCameraCameraX(); const cameraId = 5; final mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); + final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); final mockCamera2CameraControl = MockCamera2CameraControl(); // Set directly for test versus calling createCamera. @@ -5849,16 +4896,13 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - mockCamera2CameraControl, - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl); // Make setting focus and metering action successful for test. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Lock focus default focus point. await camera.setFocusMode(cameraId, FocusMode.locked); @@ -5876,8 +4920,7 @@ void main() { final camera = AndroidCameraCameraX(); const cameraId = 6; final mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); + final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); final mockCamera2CameraControl = MockCamera2CameraControl(); const focusPointX = 0.1; const focusPointY = 0.2; @@ -5890,22 +4933,16 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - mockCamera2CameraControl, - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl); // Make setting focus and metering action successful for test. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Lock a focus point. - await camera.setFocusPoint( - cameraId, - const Point(focusPointX, focusPointY), - ); + await camera.setFocusPoint(cameraId, const Point(focusPointX, focusPointY)); await camera.setFocusMode(cameraId, FocusMode.locked); clearInteractions(mockCameraControl); @@ -5916,14 +4953,12 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); expect(capturedAction.meteringPointsAe.length, equals(0)); expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final focusPoint = - capturedAction.meteringPointsAf.single as TestMeteringPoint; + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(focusPointX)); expect(focusPoint.y, equals(focusPointY)); expect(focusPoint.size, isNull); @@ -5948,16 +4983,10 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - mockCamera2CameraControl, - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl); // Set a focus point. - await camera.setFocusPoint( - cameraId, - const Point(focusPointX, focusPointY), - ); + await camera.setFocusPoint(cameraId, const Point(focusPointX, focusPointY)); clearInteractions(mockCameraControl); // Lock focus point. @@ -5966,8 +4995,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); // We expect the set focus point to be locked. @@ -5975,8 +5003,7 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final focusPoint = - capturedAction.meteringPointsAf.single as TestMeteringPoint; + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(focusPointX)); expect(focusPoint.y, equals(focusPointY)); expect(focusPoint.size, isNull); @@ -6003,20 +5030,11 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - mockCamera2CameraControl, - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl); // Set focus and exposure points. - await camera.setFocusPoint( - cameraId, - const Point(focusPointX, focusPointY), - ); - await camera.setExposurePoint( - cameraId, - const Point(exposurePointX, exposurePointY), - ); + await camera.setFocusPoint(cameraId, const Point(focusPointX, focusPointY)); + await camera.setExposurePoint(cameraId, const Point(exposurePointX, exposurePointY)); clearInteractions(mockCameraControl); // Lock focus point. @@ -6025,8 +5043,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); // We expect two MeteringPoints, the set focus point and the set exposure @@ -6035,14 +5052,12 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final focusPoint = - capturedAction.meteringPointsAf.single as TestMeteringPoint; + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(focusPointX)); expect(focusPoint.y, equals(focusPointY)); expect(focusPoint.size, isNull); - final exposurePoint = - capturedAction.meteringPointsAe.single as TestMeteringPoint; + final exposurePoint = capturedAction.meteringPointsAe.single as TestMeteringPoint; expect(exposurePoint.x, equals(exposurePointX)); expect(exposurePoint.y, equals(exposurePointY)); expect(exposurePoint.size, isNull); @@ -6070,17 +5085,11 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - mockCamera2CameraControl, - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl); // Set an exposure point (creates a current focus and metering action // without a focus point). - await camera.setExposurePoint( - cameraId, - const Point(exposurePointX, exposurePointY), - ); + await camera.setExposurePoint(cameraId, const Point(exposurePointX, exposurePointY)); clearInteractions(mockCameraControl); // Lock focus point. @@ -6089,8 +5098,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); // We expect two MeteringPoints, the default focus point and the set @@ -6099,14 +5107,12 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final focusPoint = - capturedAction.meteringPointsAf.single as TestMeteringPoint; + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(defaultFocusPointX)); expect(focusPoint.y, equals(defaultFocusPointY)); expect(focusPoint.size, equals(defaultFocusPointSize)); - final exposurePoint = - capturedAction.meteringPointsAe.single as TestMeteringPoint; + final exposurePoint = capturedAction.meteringPointsAe.single as TestMeteringPoint; expect(exposurePoint.x, equals(exposurePointX)); expect(exposurePoint.y, equals(exposurePointY)); expect(exposurePoint.size, isNull); @@ -6132,10 +5138,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - mockCamera2CameraControl, - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl); // Lock focus point. await camera.setFocusMode(cameraId, FocusMode.locked); @@ -6143,8 +5146,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); // We expect only the default focus point to be set. @@ -6152,8 +5154,7 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final focusPoint = - capturedAction.meteringPointsAf.single as TestMeteringPoint; + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(defaultFocusPointX)); expect(focusPoint.y, equals(defaultFocusPointY)); expect(focusPoint.size, equals(defaultFocusPointSize)); @@ -6166,8 +5167,7 @@ void main() { final camera = AndroidCameraCameraX(); const cameraId = 11; final mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); + final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); final mockCamera2CameraControl = MockCamera2CameraControl(); // Set directly for test versus calling createCamera. @@ -6178,16 +5178,13 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - mockCamera2CameraControl, - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, mockCamera2CameraControl); // Make setting focus and metering action successful for test. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Set auto exposure mode. await camera.setExposureMode(cameraId, ExposureMode.auto); @@ -6202,9 +5199,7 @@ void main() { final capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions; expect( - await capturedCaptureRequestOptions.getCaptureRequestOption( - CaptureRequest.controlAELock, - ), + await capturedCaptureRequestOptions.getCaptureRequestOption(CaptureRequest.controlAELock), isFalse, ); }, @@ -6223,17 +5218,14 @@ void main() { camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - MockCamera2CameraControl(), - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl()); // Make setting focus and metering action successful to set locked focus // mode. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Set exposure point to later mock failed call to set an exposure point ( // otherwise, focus and metering will be canceled altogether, which is @@ -6258,8 +5250,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); }, ); @@ -6277,17 +5268,14 @@ void main() { camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - MockCamera2CameraControl(), - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl()); // Make setting focus and metering action successful to set locked focus // mode. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Set exposure point to later mock failed call to set an exposure point ( // otherwise, focus and metering will be canceled altogether, which is @@ -6311,8 +5299,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); }, ); @@ -6330,17 +5317,14 @@ void main() { camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - MockCamera2CameraControl(), - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl()); // Make setting focus and metering action fail to test auto-cancel is not // disabled. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Set exposure point to later mock failed call to set an exposure point. await camera.setExposurePoint(cameraId, const Point(0.43, 0.34)); @@ -6353,8 +5337,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); }, ); @@ -6372,17 +5355,14 @@ void main() { camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - setUpOverridesForSettingFocusandExposurePoints( - mockCameraControl, - MockCamera2CameraControl(), - ); + setUpOverridesForSettingFocusandExposurePoints(mockCameraControl, MockCamera2CameraControl()); // Make setting focus and metering action fail to test auto-cancel is not // disabled. when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( - (_) async => Future.value(mockFocusMeteringResult), - ); + when( + mockCameraControl.startFocusAndMetering(any), + ).thenAnswer((_) async => Future.value(mockFocusMeteringResult)); // Set exposure point to later mock failed call to set an exposure point. await camera.setExposurePoint(cameraId, const Point(0.5, 0.2)); @@ -6395,67 +5375,54 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final capturedAction = - verificationResult.captured.single as FocusMeteringAction; + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); }, ); - test( - 'onStreamedFrameAvailable binds ImageAnalysis use case when not already bound', - () async { - final camera = AndroidCameraCameraX(); - const cameraId = 22; - final mockImageAnalysis = MockImageAnalysis(); - final mockProcessCameraProvider = MockProcessCameraProvider(); - final mockCamera = MockCamera(); - final mockCameraInfo = MockCameraInfo(); + test('onStreamedFrameAvailable binds ImageAnalysis use case when not already bound', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 22; + final mockImageAnalysis = MockImageAnalysis(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); - // Set directly for test versus calling createCamera. - camera.imageAnalysis = mockImageAnalysis; - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); + // Set directly for test versus calling createCamera. + camera.imageAnalysis = mockImageAnalysis; + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - // Tell plugin to create a detached analyzer for testing purposes. - PigeonOverrides.analyzer_new = - ({required void Function(Analyzer, ImageProxy) analyze}) => - MockAnalyzer(); - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; + // Tell plugin to create a detached analyzer for testing purposes. + PigeonOverrides.analyzer_new = ({required void Function(Analyzer, ImageProxy) analyze}) => + MockAnalyzer(); + GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; - when( - mockProcessCameraProvider.isBound(mockImageAnalysis), - ).thenAnswer((_) async => false); - when( - mockProcessCameraProvider.bindToLifecycle(any, [ - mockImageAnalysis, - ]), - ).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockProcessCameraProvider.isBound(mockImageAnalysis)).thenAnswer((_) async => false); + when( + mockProcessCameraProvider.bindToLifecycle(any, [mockImageAnalysis]), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); - final StreamSubscription imageStreamSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData data) {}); + final StreamSubscription imageStreamSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData data) {}); - await untilCalled(mockImageAnalysis.setAnalyzer(any)); - verify( - mockProcessCameraProvider.bindToLifecycle( - camera.cameraSelector, - [mockImageAnalysis], - ), - ); + await untilCalled(mockImageAnalysis.setAnalyzer(any)); + verify( + mockProcessCameraProvider.bindToLifecycle(camera.cameraSelector, [ + mockImageAnalysis, + ]), + ); - await imageStreamSubscription.cancel(); - }, - ); + await imageStreamSubscription.cancel(); + }); test( 'startVideoCapturing unbinds ImageAnalysis use case when image streaming callback not specified', @@ -6486,26 +5453,18 @@ void main() { ({required void Function(Observer, T) onChanged}) { return Observer.detached(onChanged: onChanged); }; - PigeonOverrides.camera2CameraInfo_from = - ({required dynamic cameraInfo}) => mockCamera2CameraInfo; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) => + mockCamera2CameraInfo; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { final mockSystemServicesManager = MockSystemServicesManager(); when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), + mockSystemServicesManager.getTempFilePath(camera.videoPrefix, '.mp4'), ).thenAnswer((_) async => outputPath); return mockSystemServicesManager; }; PigeonOverrides.videoRecordEventListener_new = - ({ - required void Function(VideoRecordEventListener, VideoRecordEvent) - onEvent, - }) { + ({required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent}) { return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); }; PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = @@ -6523,9 +5482,7 @@ void main() { when( mockPendingRecording.asPersistentRecording(), ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.start(any), - ).thenAnswer((_) async => mockRecording); + when(mockPendingRecording.start(any)).thenAnswer((_) async => mockRecording); when( camera.processCameraProvider!.isBound(camera.videoCapture!), ).thenAnswer((_) async => false); @@ -6533,17 +5490,12 @@ void main() { camera.processCameraProvider!.isBound(camera.imageAnalysis!), ).thenAnswer((_) async => true); when( - camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, - [camera.videoCapture!], - ), + camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, [ + camera.videoCapture!, + ]), ).thenAnswer((_) async => mockCamera); - when( - mockCamera.getCameraInfo(), - ).thenAnswer((_) => Future.value(mockCameraInfo)); - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCamera.getCameraInfo()).thenAnswer((_) => Future.value(mockCameraInfo)); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); when( mockCamera2CameraInfo.getCameraCharacteristic(any), ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3); @@ -6555,9 +5507,7 @@ void main() { await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - verify( - camera.processCameraProvider!.unbind([camera.imageAnalysis!]), - ); + verify(camera.processCameraProvider!.unbind([camera.imageAnalysis!])); }, ); diff --git a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart index aa997efe8d05..db06a67ab232 100644 --- a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart +++ b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart @@ -8,8 +8,7 @@ import 'dart:typed_data' as _i7; import 'package:camera_android_camerax/src/camerax_library.dart' as _i3; import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2; -import 'package:camera_platform_interface/camera_platform_interface.dart' - as _i4; +import 'package:camera_platform_interface/camera_platform_interface.dart' as _i4; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i6; @@ -28,19 +27,16 @@ import 'package:mockito/src/dummies.dart' as _i6; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAnalyzer_1 extends _i1.SmartFake implements _i2.Analyzer { - _FakeAnalyzer_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAnalyzer_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAspectRatioStrategy_2 extends _i1.SmartFake - implements _i2.AspectRatioStrategy { +class _FakeAspectRatioStrategy_2 extends _i1.SmartFake implements _i2.AspectRatioStrategy { _FakeAspectRatioStrategy_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -51,13 +47,11 @@ class _FakeCameraControl_3 extends _i1.SmartFake implements _i2.CameraControl { } class _FakeCameraInfo_4 extends _i1.SmartFake implements _i2.CameraInfo { - _FakeCameraInfo_4(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeCameraInfo_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeCamera_5 extends _i1.SmartFake implements _i2.Camera { - _FakeCamera_5(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeCamera_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeExposureState_6 extends _i1.SmartFake implements _i2.ExposureState { @@ -66,13 +60,11 @@ class _FakeExposureState_6 extends _i1.SmartFake implements _i2.ExposureState { } class _FakeLiveData_7 extends _i1.SmartFake implements _i3.LiveData { - _FakeLiveData_7(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeLiveData_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeCameraInfo_8 extends _i1.SmartFake implements _i3.CameraInfo { - _FakeCameraInfo_8(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeCameraInfo_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeCameraCharacteristicsKey_9 extends _i1.SmartFake @@ -82,36 +74,30 @@ class _FakeCameraCharacteristicsKey_9 extends _i1.SmartFake } class _FakeCameraSize_10 extends _i1.SmartFake implements _i2.CameraSize { - _FakeCameraSize_10(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeCameraSize_10(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCamera2CameraControl_11 extends _i1.SmartFake - implements _i2.Camera2CameraControl { +class _FakeCamera2CameraControl_11 extends _i1.SmartFake implements _i2.Camera2CameraControl { _FakeCamera2CameraControl_11(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCamera2CameraInfo_12 extends _i1.SmartFake - implements _i2.Camera2CameraInfo { +class _FakeCamera2CameraInfo_12 extends _i1.SmartFake implements _i2.Camera2CameraInfo { _FakeCamera2CameraInfo_12(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCameraImageFormat_13 extends _i1.SmartFake - implements _i4.CameraImageFormat { +class _FakeCameraImageFormat_13 extends _i1.SmartFake implements _i4.CameraImageFormat { _FakeCameraImageFormat_13(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCameraSelector_14 extends _i1.SmartFake - implements _i2.CameraSelector { +class _FakeCameraSelector_14 extends _i1.SmartFake implements _i2.CameraSelector { _FakeCameraSelector_14(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCaptureRequestOptions_15 extends _i1.SmartFake - implements _i2.CaptureRequestOptions { +class _FakeCaptureRequestOptions_15 extends _i1.SmartFake implements _i2.CaptureRequestOptions { _FakeCaptureRequestOptions_15(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -124,10 +110,8 @@ class _FakeDeviceOrientationManager_16 extends _i1.SmartFake class _FakeDisplayOrientedMeteringPointFactory_17 extends _i1.SmartFake implements _i2.DisplayOrientedMeteringPointFactory { - _FakeDisplayOrientedMeteringPointFactory_17( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeDisplayOrientedMeteringPointFactory_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeMeteringPoint_18 extends _i1.SmartFake implements _i2.MeteringPoint { @@ -135,20 +119,17 @@ class _FakeMeteringPoint_18 extends _i1.SmartFake implements _i2.MeteringPoint { : super(parent, parentInvocation); } -class _FakeCameraIntegerRange_19 extends _i1.SmartFake - implements _i2.CameraIntegerRange { +class _FakeCameraIntegerRange_19 extends _i1.SmartFake implements _i2.CameraIntegerRange { _FakeCameraIntegerRange_19(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeFallbackStrategy_20 extends _i1.SmartFake - implements _i2.FallbackStrategy { +class _FakeFallbackStrategy_20 extends _i1.SmartFake implements _i2.FallbackStrategy { _FakeFallbackStrategy_20(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeFocusMeteringAction_21 extends _i1.SmartFake - implements _i2.FocusMeteringAction { +class _FakeFocusMeteringAction_21 extends _i1.SmartFake implements _i2.FocusMeteringAction { _FakeFocusMeteringAction_21(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -159,8 +140,7 @@ class _FakeFocusMeteringActionBuilder_22 extends _i1.SmartFake : super(parent, parentInvocation); } -class _FakeFocusMeteringResult_23 extends _i1.SmartFake - implements _i2.FocusMeteringResult { +class _FakeFocusMeteringResult_23 extends _i1.SmartFake implements _i2.FocusMeteringResult { _FakeFocusMeteringResult_23(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -176,80 +156,66 @@ class _FakeImageCapture_25 extends _i1.SmartFake implements _i2.ImageCapture { } class _FakeImageProxy_26 extends _i1.SmartFake implements _i2.ImageProxy { - _FakeImageProxy_26(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeImageProxy_26(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeObserver_27 extends _i1.SmartFake implements _i3.Observer { - _FakeObserver_27(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeObserver_27(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePendingRecording_28 extends _i1.SmartFake - implements _i2.PendingRecording { +class _FakePendingRecording_28 extends _i1.SmartFake implements _i2.PendingRecording { _FakePendingRecording_28(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeRecording_29 extends _i1.SmartFake implements _i2.Recording { - _FakeRecording_29(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeRecording_29(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakePlaneProxy_30 extends _i1.SmartFake implements _i2.PlaneProxy { - _FakePlaneProxy_30(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakePlaneProxy_30(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakePreview_31 extends _i1.SmartFake implements _i2.Preview { - _FakePreview_31(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakePreview_31(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeProcessCameraProvider_32 extends _i1.SmartFake - implements _i2.ProcessCameraProvider { +class _FakeProcessCameraProvider_32 extends _i1.SmartFake implements _i2.ProcessCameraProvider { _FakeProcessCameraProvider_32(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeQualitySelector_33 extends _i1.SmartFake - implements _i2.QualitySelector { +class _FakeQualitySelector_33 extends _i1.SmartFake implements _i2.QualitySelector { _FakeQualitySelector_33(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeRecorder_34 extends _i1.SmartFake implements _i2.Recorder { - _FakeRecorder_34(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeRecorder_34(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResolutionFilter_35 extends _i1.SmartFake - implements _i2.ResolutionFilter { +class _FakeResolutionFilter_35 extends _i1.SmartFake implements _i2.ResolutionFilter { _FakeResolutionFilter_35(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResolutionSelector_36 extends _i1.SmartFake - implements _i2.ResolutionSelector { +class _FakeResolutionSelector_36 extends _i1.SmartFake implements _i2.ResolutionSelector { _FakeResolutionSelector_36(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResolutionStrategy_37 extends _i1.SmartFake - implements _i2.ResolutionStrategy { +class _FakeResolutionStrategy_37 extends _i1.SmartFake implements _i2.ResolutionStrategy { _FakeResolutionStrategy_37(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeSystemServicesManager_38 extends _i1.SmartFake - implements _i2.SystemServicesManager { +class _FakeSystemServicesManager_38 extends _i1.SmartFake implements _i2.SystemServicesManager { _FakeSystemServicesManager_38(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeVideoOutput_39 extends _i1.SmartFake implements _i2.VideoOutput { - _FakeVideoOutput_39(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeVideoOutput_39(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeVideoCapture_40 extends _i1.SmartFake implements _i2.VideoCapture { @@ -258,8 +224,7 @@ class _FakeVideoCapture_40 extends _i1.SmartFake implements _i2.VideoCapture { } class _FakeZoomState_41 extends _i1.SmartFake implements _i2.ZoomState { - _FakeZoomState_41(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeZoomState_41(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [Analyzer]. @@ -267,108 +232,71 @@ class _FakeZoomState_41 extends _i1.SmartFake implements _i2.ZoomState { /// See the documentation for Mockito's code generation for more information. class MockAnalyzer extends _i1.Mock implements _i2.Analyzer { @override - void Function(_i2.Analyzer, _i2.ImageProxy) get analyze => - (super.noSuchMethod( - Invocation.getter(#analyze), - returnValue: - (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {}, - returnValueForMissingStub: - (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {}, - ) - as void Function(_i2.Analyzer, _i2.ImageProxy)); + void Function(_i2.Analyzer, _i2.ImageProxy) get analyze => (super.noSuchMethod( + Invocation.getter(#analyze), + returnValue: (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {}, + returnValueForMissingStub: (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {}, + ) as void Function(_i2.Analyzer, _i2.ImageProxy)); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.Analyzer pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAnalyzer_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAnalyzer_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.Analyzer); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.Analyzer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAnalyzer_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAnalyzer_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.Analyzer); } /// A class which mocks [AspectRatioStrategy]. /// /// See the documentation for Mockito's code generation for more information. -class MockAspectRatioStrategy extends _i1.Mock - implements _i2.AspectRatioStrategy { - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.AspectRatioStrategyFallbackRule> getFallbackRule() => - (super.noSuchMethod( - Invocation.method(#getFallbackRule, []), - returnValue: _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value( - _i2.AspectRatioStrategyFallbackRule.auto, - ), - returnValueForMissingStub: - _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value( - _i2.AspectRatioStrategyFallbackRule.auto, - ), - ) - as _i5.Future<_i2.AspectRatioStrategyFallbackRule>); - - @override - _i5.Future<_i2.AspectRatio> getPreferredAspectRatio() => - (super.noSuchMethod( - Invocation.method(#getPreferredAspectRatio, []), - returnValue: _i5.Future<_i2.AspectRatio>.value( - _i2.AspectRatio.ratio16To9, - ), - returnValueForMissingStub: _i5.Future<_i2.AspectRatio>.value( - _i2.AspectRatio.ratio16To9, - ), - ) - as _i5.Future<_i2.AspectRatio>); - - @override - _i2.AspectRatioStrategy pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAspectRatioStrategy_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAspectRatioStrategy_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AspectRatioStrategy); +class MockAspectRatioStrategy extends _i1.Mock implements _i2.AspectRatioStrategy { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.AspectRatioStrategyFallbackRule> getFallbackRule() => (super.noSuchMethod( + Invocation.method(#getFallbackRule, []), + returnValue: _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value( + _i2.AspectRatioStrategyFallbackRule.auto, + ), + returnValueForMissingStub: _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value( + _i2.AspectRatioStrategyFallbackRule.auto, + ), + ) as _i5.Future<_i2.AspectRatioStrategyFallbackRule>); + + @override + _i5.Future<_i2.AspectRatio> getPreferredAspectRatio() => (super.noSuchMethod( + Invocation.method(#getPreferredAspectRatio, []), + returnValue: _i5.Future<_i2.AspectRatio>.value(_i2.AspectRatio.ratio16To9), + returnValueForMissingStub: _i5.Future<_i2.AspectRatio>.value(_i2.AspectRatio.ratio16To9), + ) as _i5.Future<_i2.AspectRatio>); + + @override + _i2.AspectRatioStrategy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAspectRatioStrategy_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAspectRatioStrategy_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.AspectRatioStrategy); } /// A class which mocks [Camera]. @@ -376,62 +304,39 @@ class MockAspectRatioStrategy extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockCamera extends _i1.Mock implements _i2.Camera { @override - _i2.CameraControl get cameraControl => - (super.noSuchMethod( - Invocation.getter(#cameraControl), - returnValue: _FakeCameraControl_3( - this, - Invocation.getter(#cameraControl), - ), - returnValueForMissingStub: _FakeCameraControl_3( - this, - Invocation.getter(#cameraControl), - ), - ) - as _i2.CameraControl); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.CameraInfo> getCameraInfo() => - (super.noSuchMethod( - Invocation.method(#getCameraInfo, []), - returnValue: _i5.Future<_i2.CameraInfo>.value( - _FakeCameraInfo_4(this, Invocation.method(#getCameraInfo, [])), - ), - returnValueForMissingStub: _i5.Future<_i2.CameraInfo>.value( - _FakeCameraInfo_4(this, Invocation.method(#getCameraInfo, [])), - ), - ) - as _i5.Future<_i2.CameraInfo>); - - @override - _i2.Camera pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCamera_5( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCamera_5( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.Camera); + _i2.CameraControl get cameraControl => (super.noSuchMethod( + Invocation.getter(#cameraControl), + returnValue: _FakeCameraControl_3(this, Invocation.getter(#cameraControl)), + returnValueForMissingStub: _FakeCameraControl_3(this, Invocation.getter(#cameraControl)), + ) as _i2.CameraControl); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.CameraInfo> getCameraInfo() => (super.noSuchMethod( + Invocation.method(#getCameraInfo, []), + returnValue: _i5.Future<_i2.CameraInfo>.value( + _FakeCameraInfo_4(this, Invocation.method(#getCameraInfo, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.CameraInfo>.value( + _FakeCameraInfo_4(this, Invocation.method(#getCameraInfo, [])), + ), + ) as _i5.Future<_i2.CameraInfo>); + + @override + _i2.Camera pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCamera_5(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCamera_5(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.Camera); } /// A class which mocks [CameraInfo]. @@ -439,143 +344,89 @@ class MockCamera extends _i1.Mock implements _i2.Camera { /// See the documentation for Mockito's code generation for more information. class MockCameraInfo extends _i1.Mock implements _i3.CameraInfo { @override - int get sensorRotationDegrees => - (super.noSuchMethod( - Invocation.getter(#sensorRotationDegrees), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get sensorRotationDegrees => (super.noSuchMethod( + Invocation.getter(#sensorRotationDegrees), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - _i2.LensFacing get lensFacing => - (super.noSuchMethod( - Invocation.getter(#lensFacing), - returnValue: _i2.LensFacing.front, - returnValueForMissingStub: _i2.LensFacing.front, - ) - as _i2.LensFacing); + _i2.LensFacing get lensFacing => (super.noSuchMethod( + Invocation.getter(#lensFacing), + returnValue: _i2.LensFacing.front, + returnValueForMissingStub: _i2.LensFacing.front, + ) as _i2.LensFacing); @override - _i2.ExposureState get exposureState => - (super.noSuchMethod( - Invocation.getter(#exposureState), - returnValue: _FakeExposureState_6( - this, - Invocation.getter(#exposureState), - ), - returnValueForMissingStub: _FakeExposureState_6( - this, - Invocation.getter(#exposureState), - ), - ) - as _i2.ExposureState); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i3.LiveData<_i2.CameraState>> getCameraState() => - (super.noSuchMethod( - Invocation.method(#getCameraState, []), - returnValue: _i5.Future<_i3.LiveData<_i2.CameraState>>.value( - _FakeLiveData_7<_i2.CameraState>( - this, - Invocation.method(#getCameraState, []), - ), - ), - returnValueForMissingStub: - _i5.Future<_i3.LiveData<_i2.CameraState>>.value( - _FakeLiveData_7<_i2.CameraState>( - this, - Invocation.method(#getCameraState, []), - ), - ), - ) - as _i5.Future<_i3.LiveData<_i2.CameraState>>); - - @override - _i5.Future<_i3.LiveData<_i2.ZoomState>> getZoomState() => - (super.noSuchMethod( - Invocation.method(#getZoomState, []), - returnValue: _i5.Future<_i3.LiveData<_i2.ZoomState>>.value( - _FakeLiveData_7<_i2.ZoomState>( - this, - Invocation.method(#getZoomState, []), - ), - ), - returnValueForMissingStub: - _i5.Future<_i3.LiveData<_i2.ZoomState>>.value( - _FakeLiveData_7<_i2.ZoomState>( - this, - Invocation.method(#getZoomState, []), - ), - ), - ) - as _i5.Future<_i3.LiveData<_i2.ZoomState>>); - - @override - _i3.CameraInfo pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCameraInfo_8( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCameraInfo_8( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i3.CameraInfo); + _i2.ExposureState get exposureState => (super.noSuchMethod( + Invocation.getter(#exposureState), + returnValue: _FakeExposureState_6(this, Invocation.getter(#exposureState)), + returnValueForMissingStub: _FakeExposureState_6(this, Invocation.getter(#exposureState)), + ) as _i2.ExposureState); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i3.LiveData<_i2.CameraState>> getCameraState() => (super.noSuchMethod( + Invocation.method(#getCameraState, []), + returnValue: _i5.Future<_i3.LiveData<_i2.CameraState>>.value( + _FakeLiveData_7<_i2.CameraState>(this, Invocation.method(#getCameraState, [])), + ), + returnValueForMissingStub: _i5.Future<_i3.LiveData<_i2.CameraState>>.value( + _FakeLiveData_7<_i2.CameraState>(this, Invocation.method(#getCameraState, [])), + ), + ) as _i5.Future<_i3.LiveData<_i2.CameraState>>); + + @override + _i5.Future<_i3.LiveData<_i2.ZoomState>> getZoomState() => (super.noSuchMethod( + Invocation.method(#getZoomState, []), + returnValue: _i5.Future<_i3.LiveData<_i2.ZoomState>>.value( + _FakeLiveData_7<_i2.ZoomState>(this, Invocation.method(#getZoomState, [])), + ), + returnValueForMissingStub: _i5.Future<_i3.LiveData<_i2.ZoomState>>.value( + _FakeLiveData_7<_i2.ZoomState>(this, Invocation.method(#getZoomState, [])), + ), + ) as _i5.Future<_i3.LiveData<_i2.ZoomState>>); + + @override + _i3.CameraInfo pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraInfo_8(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCameraInfo_8(this, Invocation.method(#pigeon_copy, [])), + ) as _i3.CameraInfo); } /// A class which mocks [CameraCharacteristicsKey]. /// /// See the documentation for Mockito's code generation for more information. -class MockCameraCharacteristicsKey extends _i1.Mock - implements _i2.CameraCharacteristicsKey { +class MockCameraCharacteristicsKey extends _i1.Mock implements _i2.CameraCharacteristicsKey { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.CameraCharacteristicsKey pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCameraCharacteristicsKey_9( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCameraCharacteristicsKey_9( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.CameraCharacteristicsKey); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.CameraCharacteristicsKey pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraCharacteristicsKey_9(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCameraCharacteristicsKey_9( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.CameraCharacteristicsKey); } /// A class which mocks [CameraControl]. @@ -583,82 +434,57 @@ class MockCameraCharacteristicsKey extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockCameraControl extends _i1.Mock implements _i2.CameraControl { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future enableTorch(bool? torch) => - (super.noSuchMethod( - Invocation.method(#enableTorch, [torch]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future setZoomRatio(double? ratio) => - (super.noSuchMethod( - Invocation.method(#setZoomRatio, [ratio]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future enableTorch(bool? torch) => (super.noSuchMethod( + Invocation.method(#enableTorch, [torch]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i2.FocusMeteringResult?> startFocusAndMetering( - _i2.FocusMeteringAction? action, - ) => - (super.noSuchMethod( - Invocation.method(#startFocusAndMetering, [action]), - returnValue: _i5.Future<_i2.FocusMeteringResult?>.value(), - returnValueForMissingStub: - _i5.Future<_i2.FocusMeteringResult?>.value(), - ) - as _i5.Future<_i2.FocusMeteringResult?>); + _i5.Future setZoomRatio(double? ratio) => (super.noSuchMethod( + Invocation.method(#setZoomRatio, [ratio]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future cancelFocusAndMetering() => + _i5.Future<_i2.FocusMeteringResult?> startFocusAndMetering(_i2.FocusMeteringAction? action) => (super.noSuchMethod( - Invocation.method(#cancelFocusAndMetering, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#startFocusAndMetering, [action]), + returnValue: _i5.Future<_i2.FocusMeteringResult?>.value(), + returnValueForMissingStub: _i5.Future<_i2.FocusMeteringResult?>.value(), + ) as _i5.Future<_i2.FocusMeteringResult?>); @override - _i5.Future setExposureCompensationIndex(int? index) => - (super.noSuchMethod( - Invocation.method(#setExposureCompensationIndex, [index]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future cancelFocusAndMetering() => (super.noSuchMethod( + Invocation.method(#cancelFocusAndMetering, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.CameraControl pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCameraControl_3( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCameraControl_3( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.CameraControl); + _i5.Future setExposureCompensationIndex(int? index) => (super.noSuchMethod( + Invocation.method(#setExposureCompensationIndex, [index]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.CameraControl pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraControl_3(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCameraControl_3(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.CameraControl); } /// A class which mocks [CameraSize]. @@ -667,98 +493,63 @@ class MockCameraControl extends _i1.Mock implements _i2.CameraControl { class MockCameraSize extends _i1.Mock implements _i2.CameraSize { @override int get width => - (super.noSuchMethod( - Invocation.getter(#width), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0) as int); @override int get height => - (super.noSuchMethod( - Invocation.getter(#height), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0) as int); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.CameraSize pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCameraSize_10( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCameraSize_10( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.CameraSize); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.CameraSize pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraSize_10(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCameraSize_10(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.CameraSize); } /// A class which mocks [Camera2CameraControl]. /// /// See the documentation for Mockito's code generation for more information. -class MockCamera2CameraControl extends _i1.Mock - implements _i2.Camera2CameraControl { +class MockCamera2CameraControl extends _i1.Mock implements _i2.Camera2CameraControl { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future addCaptureRequestOptions( - _i2.CaptureRequestOptions? bundle, - ) => - (super.noSuchMethod( - Invocation.method(#addCaptureRequestOptions, [bundle]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.Camera2CameraControl pigeon_copy() => + _i5.Future addCaptureRequestOptions(_i2.CaptureRequestOptions? bundle) => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCamera2CameraControl_11( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCamera2CameraControl_11( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.Camera2CameraControl); + Invocation.method(#addCaptureRequestOptions, [bundle]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.Camera2CameraControl pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCamera2CameraControl_11(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCamera2CameraControl_11( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Camera2CameraControl); } /// A class which mocks [Camera2CameraInfo]. @@ -766,58 +557,40 @@ class MockCamera2CameraControl extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockCamera2CameraInfo extends _i1.Mock implements _i2.Camera2CameraInfo { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future getCameraId() => - (super.noSuchMethod( - Invocation.method(#getCameraId, []), - returnValue: _i5.Future.value( - _i6.dummyValue(this, Invocation.method(#getCameraId, [])), - ), - returnValueForMissingStub: _i5.Future.value( - _i6.dummyValue(this, Invocation.method(#getCameraId, [])), - ), - ) - as _i5.Future); - - @override - _i5.Future getCameraCharacteristic( - _i2.CameraCharacteristicsKey? key, - ) => - (super.noSuchMethod( - Invocation.method(#getCameraCharacteristic, [key]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future getCameraId() => (super.noSuchMethod( + Invocation.method(#getCameraId, []), + returnValue: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getCameraId, [])), + ), + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getCameraId, [])), + ), + ) as _i5.Future); @override - _i2.Camera2CameraInfo pigeon_copy() => + _i5.Future getCameraCharacteristic(_i2.CameraCharacteristicsKey? key) => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCamera2CameraInfo_12( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCamera2CameraInfo_12( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.Camera2CameraInfo); + Invocation.method(#getCameraCharacteristic, [key]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.Camera2CameraInfo pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCamera2CameraInfo_12(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCamera2CameraInfo_12(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.Camera2CameraInfo); } /// A class which mocks [CameraImageData]. @@ -826,46 +599,28 @@ class MockCamera2CameraInfo extends _i1.Mock implements _i2.Camera2CameraInfo { // ignore: must_be_immutable class MockCameraImageData extends _i1.Mock implements _i4.CameraImageData { @override - _i4.CameraImageFormat get format => - (super.noSuchMethod( - Invocation.getter(#format), - returnValue: _FakeCameraImageFormat_13( - this, - Invocation.getter(#format), - ), - returnValueForMissingStub: _FakeCameraImageFormat_13( - this, - Invocation.getter(#format), - ), - ) - as _i4.CameraImageFormat); + _i4.CameraImageFormat get format => (super.noSuchMethod( + Invocation.getter(#format), + returnValue: _FakeCameraImageFormat_13(this, Invocation.getter(#format)), + returnValueForMissingStub: _FakeCameraImageFormat_13(this, Invocation.getter(#format)), + ) as _i4.CameraImageFormat); @override int get height => - (super.noSuchMethod( - Invocation.getter(#height), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0) as int); @override int get width => - (super.noSuchMethod( - Invocation.getter(#width), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0) as int); @override - List<_i4.CameraImagePlane> get planes => - (super.noSuchMethod( - Invocation.getter(#planes), - returnValue: <_i4.CameraImagePlane>[], - returnValueForMissingStub: <_i4.CameraImagePlane>[], - ) - as List<_i4.CameraImagePlane>); + List<_i4.CameraImagePlane> get planes => (super.noSuchMethod( + Invocation.getter(#planes), + returnValue: <_i4.CameraImagePlane>[], + returnValueForMissingStub: <_i4.CameraImagePlane>[], + ) as List<_i4.CameraImagePlane>); } /// A class which mocks [CameraSelector]. @@ -873,192 +628,128 @@ class MockCameraImageData extends _i1.Mock implements _i4.CameraImageData { /// See the documentation for Mockito's code generation for more information. class MockCameraSelector extends _i1.Mock implements _i2.CameraSelector { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future> filter(List<_i2.CameraInfo>? cameraInfos) => - (super.noSuchMethod( - Invocation.method(#filter, [cameraInfos]), - returnValue: _i5.Future>.value( - <_i2.CameraInfo>[], - ), - returnValueForMissingStub: _i5.Future>.value( - <_i2.CameraInfo>[], - ), - ) - as _i5.Future>); - - @override - _i2.CameraSelector pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCameraSelector_14( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCameraSelector_14( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.CameraSelector); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future> filter(List<_i2.CameraInfo>? cameraInfos) => (super.noSuchMethod( + Invocation.method(#filter, [cameraInfos]), + returnValue: _i5.Future>.value(<_i2.CameraInfo>[]), + returnValueForMissingStub: _i5.Future>.value(<_i2.CameraInfo>[]), + ) as _i5.Future>); + + @override + _i2.CameraSelector pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraSelector_14(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCameraSelector_14(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.CameraSelector); } /// A class which mocks [CaptureRequestOptions]. /// /// See the documentation for Mockito's code generation for more information. -class MockCaptureRequestOptions extends _i1.Mock - implements _i2.CaptureRequestOptions { +class MockCaptureRequestOptions extends _i1.Mock implements _i2.CaptureRequestOptions { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future getCaptureRequestOption(_i2.CaptureRequestKey? key) => - (super.noSuchMethod( - Invocation.method(#getCaptureRequestOption, [key]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.CaptureRequestOptions pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCaptureRequestOptions_15( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCaptureRequestOptions_15( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.CaptureRequestOptions); + _i5.Future getCaptureRequestOption(_i2.CaptureRequestKey? key) => (super.noSuchMethod( + Invocation.method(#getCaptureRequestOption, [key]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.CaptureRequestOptions pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCaptureRequestOptions_15(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCaptureRequestOptions_15( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.CaptureRequestOptions); } /// A class which mocks [DeviceOrientationManager]. /// /// See the documentation for Mockito's code generation for more information. -class MockDeviceOrientationManager extends _i1.Mock - implements _i2.DeviceOrientationManager { +class MockDeviceOrientationManager extends _i1.Mock implements _i2.DeviceOrientationManager { @override - void Function(_i2.DeviceOrientationManager, String) - get onDeviceOrientationChanged => - (super.noSuchMethod( - Invocation.getter(#onDeviceOrientationChanged), - returnValue: - ( - _i2.DeviceOrientationManager pigeon_instance, - String orientation, - ) {}, - returnValueForMissingStub: - ( - _i2.DeviceOrientationManager pigeon_instance, - String orientation, - ) {}, - ) - as void Function(_i2.DeviceOrientationManager, String)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => + void Function(_i2.DeviceOrientationManager, String) get onDeviceOrientationChanged => (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future startListeningForDeviceOrientationChange() => - (super.noSuchMethod( - Invocation.method(#startListeningForDeviceOrientationChange, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.getter(#onDeviceOrientationChanged), + returnValue: (_i2.DeviceOrientationManager pigeon_instance, String orientation) {}, + returnValueForMissingStub: ( + _i2.DeviceOrientationManager pigeon_instance, + String orientation, + ) {}, + ) as void Function(_i2.DeviceOrientationManager, String)); @override - _i5.Future stopListeningForDeviceOrientationChange() => - (super.noSuchMethod( - Invocation.method(#stopListeningForDeviceOrientationChange, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future getDefaultDisplayRotation() => - (super.noSuchMethod( - Invocation.method(#getDefaultDisplayRotation, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i5.Future startListeningForDeviceOrientationChange() => (super.noSuchMethod( + Invocation.method(#startListeningForDeviceOrientationChange, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future getUiOrientation() => - (super.noSuchMethod( - Invocation.method(#getUiOrientation, []), - returnValue: _i5.Future.value( - _i6.dummyValue( - this, - Invocation.method(#getUiOrientation, []), - ), - ), - returnValueForMissingStub: _i5.Future.value( - _i6.dummyValue( - this, - Invocation.method(#getUiOrientation, []), - ), - ), - ) - as _i5.Future); - - @override - _i2.DeviceOrientationManager pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeDeviceOrientationManager_16( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeDeviceOrientationManager_16( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.DeviceOrientationManager); + _i5.Future stopListeningForDeviceOrientationChange() => (super.noSuchMethod( + Invocation.method(#stopListeningForDeviceOrientationChange, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future getDefaultDisplayRotation() => (super.noSuchMethod( + Invocation.method(#getDefaultDisplayRotation, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); + + @override + _i5.Future getUiOrientation() => (super.noSuchMethod( + Invocation.method(#getUiOrientation, []), + returnValue: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getUiOrientation, [])), + ), + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getUiOrientation, [])), + ), + ) as _i5.Future); + + @override + _i2.DeviceOrientationManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeDeviceOrientationManager_16(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeDeviceOrientationManager_16( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.DeviceOrientationManager); } /// A class which mocks [DisplayOrientedMeteringPointFactory]. @@ -1067,77 +758,50 @@ class MockDeviceOrientationManager extends _i1.Mock class MockDisplayOrientedMeteringPointFactory extends _i1.Mock implements _i2.DisplayOrientedMeteringPointFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.DisplayOrientedMeteringPointFactory pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeDisplayOrientedMeteringPointFactory_17( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: - _FakeDisplayOrientedMeteringPointFactory_17( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.DisplayOrientedMeteringPointFactory); - - @override - _i5.Future<_i2.MeteringPoint> createPoint(double? x, double? y) => - (super.noSuchMethod( - Invocation.method(#createPoint, [x, y]), - returnValue: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_18( - this, - Invocation.method(#createPoint, [x, y]), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_18( - this, - Invocation.method(#createPoint, [x, y]), - ), - ), - ) - as _i5.Future<_i2.MeteringPoint>); - - @override - _i5.Future<_i2.MeteringPoint> createPointWithSize( - double? x, - double? y, - double? size, - ) => - (super.noSuchMethod( - Invocation.method(#createPointWithSize, [x, y, size]), - returnValue: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_18( - this, - Invocation.method(#createPointWithSize, [x, y, size]), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_18( - this, - Invocation.method(#createPointWithSize, [x, y, size]), - ), - ), - ) - as _i5.Future<_i2.MeteringPoint>); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.DisplayOrientedMeteringPointFactory pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeDisplayOrientedMeteringPointFactory_17( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeDisplayOrientedMeteringPointFactory_17( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.DisplayOrientedMeteringPointFactory); + + @override + _i5.Future<_i2.MeteringPoint> createPoint(double? x, double? y) => (super.noSuchMethod( + Invocation.method(#createPoint, [x, y]), + returnValue: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_18(this, Invocation.method(#createPoint, [x, y])), + ), + returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_18(this, Invocation.method(#createPoint, [x, y])), + ), + ) as _i5.Future<_i2.MeteringPoint>); + + @override + _i5.Future<_i2.MeteringPoint> createPointWithSize(double? x, double? y, double? size) => + (super.noSuchMethod( + Invocation.method(#createPointWithSize, [x, y, size]), + returnValue: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_18(this, Invocation.method(#createPointWithSize, [x, y, size])), + ), + returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_18(this, Invocation.method(#createPointWithSize, [x, y, size])), + ), + ) as _i5.Future<_i2.MeteringPoint>); } /// A class which mocks [ExposureState]. @@ -1145,58 +809,38 @@ class MockDisplayOrientedMeteringPointFactory extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockExposureState extends _i1.Mock implements _i2.ExposureState { @override - _i2.CameraIntegerRange get exposureCompensationRange => - (super.noSuchMethod( - Invocation.getter(#exposureCompensationRange), - returnValue: _FakeCameraIntegerRange_19( - this, - Invocation.getter(#exposureCompensationRange), - ), - returnValueForMissingStub: _FakeCameraIntegerRange_19( - this, - Invocation.getter(#exposureCompensationRange), - ), - ) - as _i2.CameraIntegerRange); - - @override - double get exposureCompensationStep => - (super.noSuchMethod( - Invocation.getter(#exposureCompensationStep), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) - as double); + _i2.CameraIntegerRange get exposureCompensationRange => (super.noSuchMethod( + Invocation.getter(#exposureCompensationRange), + returnValue: _FakeCameraIntegerRange_19(this, Invocation.getter(#exposureCompensationRange)), + returnValueForMissingStub: _FakeCameraIntegerRange_19( + this, + Invocation.getter(#exposureCompensationRange), + ), + ) as _i2.CameraIntegerRange); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.ExposureState pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeExposureState_6( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeExposureState_6( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ExposureState); + double get exposureCompensationStep => (super.noSuchMethod( + Invocation.getter(#exposureCompensationStep), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.ExposureState pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeExposureState_6(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeExposureState_6(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ExposureState); } /// A class which mocks [FallbackStrategy]. @@ -1204,162 +848,111 @@ class MockExposureState extends _i1.Mock implements _i2.ExposureState { /// See the documentation for Mockito's code generation for more information. class MockFallbackStrategy extends _i1.Mock implements _i2.FallbackStrategy { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.FallbackStrategy pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeFallbackStrategy_20( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeFallbackStrategy_20( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.FallbackStrategy); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.FallbackStrategy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFallbackStrategy_20(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeFallbackStrategy_20(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.FallbackStrategy); } /// A class which mocks [FocusMeteringActionBuilder]. /// /// See the documentation for Mockito's code generation for more information. -class MockFocusMeteringActionBuilder extends _i1.Mock - implements _i2.FocusMeteringActionBuilder { +class MockFocusMeteringActionBuilder extends _i1.Mock implements _i2.FocusMeteringActionBuilder { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future addPoint(_i2.MeteringPoint? point) => - (super.noSuchMethod( - Invocation.method(#addPoint, [point]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future addPointWithMode( - _i2.MeteringPoint? point, - _i2.MeteringMode? mode, - ) => - (super.noSuchMethod( - Invocation.method(#addPointWithMode, [point, mode]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future addPoint(_i2.MeteringPoint? point) => (super.noSuchMethod( + Invocation.method(#addPoint, [point]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future disableAutoCancel() => + _i5.Future addPointWithMode(_i2.MeteringPoint? point, _i2.MeteringMode? mode) => (super.noSuchMethod( - Invocation.method(#disableAutoCancel, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#addPointWithMode, [point, mode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i2.FocusMeteringAction> build() => - (super.noSuchMethod( - Invocation.method(#build, []), - returnValue: _i5.Future<_i2.FocusMeteringAction>.value( - _FakeFocusMeteringAction_21(this, Invocation.method(#build, [])), - ), - returnValueForMissingStub: - _i5.Future<_i2.FocusMeteringAction>.value( - _FakeFocusMeteringAction_21( - this, - Invocation.method(#build, []), - ), - ), - ) - as _i5.Future<_i2.FocusMeteringAction>); - - @override - _i2.FocusMeteringActionBuilder pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeFocusMeteringActionBuilder_22( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeFocusMeteringActionBuilder_22( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.FocusMeteringActionBuilder); + _i5.Future disableAutoCancel() => (super.noSuchMethod( + Invocation.method(#disableAutoCancel, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future<_i2.FocusMeteringAction> build() => (super.noSuchMethod( + Invocation.method(#build, []), + returnValue: _i5.Future<_i2.FocusMeteringAction>.value( + _FakeFocusMeteringAction_21(this, Invocation.method(#build, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.FocusMeteringAction>.value( + _FakeFocusMeteringAction_21(this, Invocation.method(#build, [])), + ), + ) as _i5.Future<_i2.FocusMeteringAction>); + + @override + _i2.FocusMeteringActionBuilder pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFocusMeteringActionBuilder_22(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeFocusMeteringActionBuilder_22( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.FocusMeteringActionBuilder); } /// A class which mocks [FocusMeteringResult]. /// /// See the documentation for Mockito's code generation for more information. -class MockFocusMeteringResult extends _i1.Mock - implements _i2.FocusMeteringResult { +class MockFocusMeteringResult extends _i1.Mock implements _i2.FocusMeteringResult { @override - bool get isFocusSuccessful => - (super.noSuchMethod( - Invocation.getter(#isFocusSuccessful), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isFocusSuccessful => (super.noSuchMethod( + Invocation.getter(#isFocusSuccessful), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.FocusMeteringResult pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeFocusMeteringResult_23( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeFocusMeteringResult_23( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.FocusMeteringResult); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.FocusMeteringResult pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFocusMeteringResult_23(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeFocusMeteringResult_23( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.FocusMeteringResult); } /// A class which mocks [ImageAnalysis]. @@ -1367,61 +960,42 @@ class MockFocusMeteringResult extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockImageAnalysis extends _i1.Mock implements _i2.ImageAnalysis { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setAnalyzer(_i2.Analyzer? analyzer) => - (super.noSuchMethod( - Invocation.method(#setAnalyzer, [analyzer]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future clearAnalyzer() => - (super.noSuchMethod( - Invocation.method(#clearAnalyzer, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setAnalyzer(_i2.Analyzer? analyzer) => (super.noSuchMethod( + Invocation.method(#setAnalyzer, [analyzer]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setTargetRotation(int? rotation) => - (super.noSuchMethod( - Invocation.method(#setTargetRotation, [rotation]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future clearAnalyzer() => (super.noSuchMethod( + Invocation.method(#clearAnalyzer, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.ImageAnalysis pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImageAnalysis_24( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImageAnalysis_24( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImageAnalysis); + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.ImageAnalysis pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImageAnalysis_24(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImageAnalysis_24(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImageAnalysis); } /// A class which mocks [ImageCapture]. @@ -1429,73 +1003,47 @@ class MockImageAnalysis extends _i1.Mock implements _i2.ImageAnalysis { /// See the documentation for Mockito's code generation for more information. class MockImageCapture extends _i1.Mock implements _i2.ImageCapture { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setFlashMode(_i2.CameraXFlashMode? flashMode) => - (super.noSuchMethod( - Invocation.method(#setFlashMode, [flashMode]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future takePicture( - _i2.SystemServicesManager? systemServicesManager, - ) => - (super.noSuchMethod( - Invocation.method(#takePicture, [systemServicesManager]), - returnValue: _i5.Future.value( - _i6.dummyValue( - this, - Invocation.method(#takePicture, [systemServicesManager]), - ), - ), - returnValueForMissingStub: _i5.Future.value( - _i6.dummyValue( - this, - Invocation.method(#takePicture, [systemServicesManager]), - ), - ), - ) - as _i5.Future); - - @override - _i5.Future setTargetRotation(int? rotation) => - (super.noSuchMethod( - Invocation.method(#setTargetRotation, [rotation]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setFlashMode(_i2.CameraXFlashMode? flashMode) => (super.noSuchMethod( + Invocation.method(#setFlashMode, [flashMode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.ImageCapture pigeon_copy() => + _i5.Future takePicture(_i2.SystemServicesManager? systemServicesManager) => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImageCapture_25( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImageCapture_25( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImageCapture); + Invocation.method(#takePicture, [systemServicesManager]), + returnValue: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#takePicture, [systemServicesManager])), + ), + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#takePicture, [systemServicesManager])), + ), + ) as _i5.Future); + + @override + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.ImageCapture pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImageCapture_25(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImageCapture_25(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImageCapture); } /// A class which mocks [ImageProxy]. @@ -1504,82 +1052,49 @@ class MockImageCapture extends _i1.Mock implements _i2.ImageCapture { class MockImageProxy extends _i1.Mock implements _i2.ImageProxy { @override int get format => - (super.noSuchMethod( - Invocation.getter(#format), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#format), returnValue: 0, returnValueForMissingStub: 0) as int); @override int get width => - (super.noSuchMethod( - Invocation.getter(#width), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0) as int); @override int get height => - (super.noSuchMethod( - Invocation.getter(#height), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0) as int); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future> getPlanes() => - (super.noSuchMethod( - Invocation.method(#getPlanes, []), - returnValue: _i5.Future>.value( - <_i2.PlaneProxy>[], - ), - returnValueForMissingStub: _i5.Future>.value( - <_i2.PlaneProxy>[], - ), - ) - as _i5.Future>); - - @override - _i5.Future close() => - (super.noSuchMethod( - Invocation.method(#close, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.ImageProxy pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImageProxy_26( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImageProxy_26( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImageProxy); + _i5.Future> getPlanes() => (super.noSuchMethod( + Invocation.method(#getPlanes, []), + returnValue: _i5.Future>.value(<_i2.PlaneProxy>[]), + returnValueForMissingStub: _i5.Future>.value(<_i2.PlaneProxy>[]), + ) as _i5.Future>); + + @override + _i5.Future close() => (super.noSuchMethod( + Invocation.method(#close, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.ImageProxy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImageProxy_26(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImageProxy_26(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImageProxy); } /// A class which mocks [Observer]. @@ -1587,44 +1102,31 @@ class MockImageProxy extends _i1.Mock implements _i2.ImageProxy { /// See the documentation for Mockito's code generation for more information. class MockObserver extends _i1.Mock implements _i3.Observer<_i2.CameraState> { @override - void Function(_i2.Observer, Object) get onChanged => - (super.noSuchMethod( - Invocation.getter(#onChanged), - returnValue: (_i2.Observer pigeon_instance, Object value) {}, - returnValueForMissingStub: - (_i2.Observer pigeon_instance, Object value) {}, - ) - as void Function(_i2.Observer, Object)); + void Function(_i2.Observer, Object) get onChanged => (super.noSuchMethod( + Invocation.getter(#onChanged), + returnValue: (_i2.Observer pigeon_instance, Object value) {}, + returnValueForMissingStub: (_i2.Observer pigeon_instance, Object value) {}, + ) as void Function(_i2.Observer, Object)); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i3.Observer<_i2.CameraState> pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeObserver_27<_i2.CameraState>( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeObserver_27<_i2.CameraState>( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i3.Observer<_i2.CameraState>); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i3.Observer<_i2.CameraState> pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeObserver_27<_i2.CameraState>(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeObserver_27<_i2.CameraState>( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i3.Observer<_i2.CameraState>); } /// A class which mocks [PendingRecording]. @@ -1632,85 +1134,54 @@ class MockObserver extends _i1.Mock implements _i3.Observer<_i2.CameraState> { /// See the documentation for Mockito's code generation for more information. class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.PendingRecording> withAudioEnabled(bool? initialMuted) => - (super.noSuchMethod( - Invocation.method(#withAudioEnabled, [initialMuted]), - returnValue: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_28( - this, - Invocation.method(#withAudioEnabled, [initialMuted]), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_28( - this, - Invocation.method(#withAudioEnabled, [initialMuted]), - ), - ), - ) - as _i5.Future<_i2.PendingRecording>); - - @override - _i5.Future<_i2.PendingRecording> asPersistentRecording() => - (super.noSuchMethod( - Invocation.method(#asPersistentRecording, []), - returnValue: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_28( - this, - Invocation.method(#asPersistentRecording, []), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_28( - this, - Invocation.method(#asPersistentRecording, []), - ), - ), - ) - as _i5.Future<_i2.PendingRecording>); - - @override - _i5.Future<_i2.Recording> start(_i2.VideoRecordEventListener? listener) => - (super.noSuchMethod( - Invocation.method(#start, [listener]), - returnValue: _i5.Future<_i2.Recording>.value( - _FakeRecording_29(this, Invocation.method(#start, [listener])), - ), - returnValueForMissingStub: _i5.Future<_i2.Recording>.value( - _FakeRecording_29(this, Invocation.method(#start, [listener])), - ), - ) - as _i5.Future<_i2.Recording>); - - @override - _i2.PendingRecording pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakePendingRecording_28( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakePendingRecording_28( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.PendingRecording); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.PendingRecording> withAudioEnabled(bool? initialMuted) => (super.noSuchMethod( + Invocation.method(#withAudioEnabled, [initialMuted]), + returnValue: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_28(this, Invocation.method(#withAudioEnabled, [initialMuted])), + ), + returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_28(this, Invocation.method(#withAudioEnabled, [initialMuted])), + ), + ) as _i5.Future<_i2.PendingRecording>); + + @override + _i5.Future<_i2.PendingRecording> asPersistentRecording() => (super.noSuchMethod( + Invocation.method(#asPersistentRecording, []), + returnValue: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_28(this, Invocation.method(#asPersistentRecording, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_28(this, Invocation.method(#asPersistentRecording, [])), + ), + ) as _i5.Future<_i2.PendingRecording>); + + @override + _i5.Future<_i2.Recording> start(_i2.VideoRecordEventListener? listener) => (super.noSuchMethod( + Invocation.method(#start, [listener]), + returnValue: _i5.Future<_i2.Recording>.value( + _FakeRecording_29(this, Invocation.method(#start, [listener])), + ), + returnValueForMissingStub: _i5.Future<_i2.Recording>.value( + _FakeRecording_29(this, Invocation.method(#start, [listener])), + ), + ) as _i5.Future<_i2.Recording>); + + @override + _i2.PendingRecording pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakePendingRecording_28(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakePendingRecording_28(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.PendingRecording); } /// A class which mocks [PlaneProxy]. @@ -1718,61 +1189,42 @@ class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { /// See the documentation for Mockito's code generation for more information. class MockPlaneProxy extends _i1.Mock implements _i2.PlaneProxy { @override - _i7.Uint8List get buffer => - (super.noSuchMethod( - Invocation.getter(#buffer), - returnValue: _i7.Uint8List(0), - returnValueForMissingStub: _i7.Uint8List(0), - ) - as _i7.Uint8List); + _i7.Uint8List get buffer => (super.noSuchMethod( + Invocation.getter(#buffer), + returnValue: _i7.Uint8List(0), + returnValueForMissingStub: _i7.Uint8List(0), + ) as _i7.Uint8List); @override - int get pixelStride => - (super.noSuchMethod( - Invocation.getter(#pixelStride), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get pixelStride => (super.noSuchMethod( + Invocation.getter(#pixelStride), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - int get rowStride => - (super.noSuchMethod( - Invocation.getter(#rowStride), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get rowStride => (super.noSuchMethod( + Invocation.getter(#rowStride), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.PlaneProxy pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakePlaneProxy_30( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakePlaneProxy_30( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.PlaneProxy); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.PlaneProxy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakePlaneProxy_30(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakePlaneProxy_30(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.PlaneProxy); } /// A class which mocks [Preview]. @@ -1780,179 +1232,124 @@ class MockPlaneProxy extends _i1.Mock implements _i2.PlaneProxy { /// See the documentation for Mockito's code generation for more information. class MockPreview extends _i1.Mock implements _i2.Preview { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setSurfaceProvider( - _i2.SystemServicesManager? systemServicesManager, - ) => - (super.noSuchMethod( - Invocation.method(#setSurfaceProvider, [systemServicesManager]), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future releaseSurfaceProvider() => + _i5.Future setSurfaceProvider(_i2.SystemServicesManager? systemServicesManager) => (super.noSuchMethod( - Invocation.method(#releaseSurfaceProvider, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#setSurfaceProvider, [systemServicesManager]), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); @override - _i5.Future<_i2.ResolutionInfo?> getResolutionInfo() => - (super.noSuchMethod( - Invocation.method(#getResolutionInfo, []), - returnValue: _i5.Future<_i2.ResolutionInfo?>.value(), - returnValueForMissingStub: _i5.Future<_i2.ResolutionInfo?>.value(), - ) - as _i5.Future<_i2.ResolutionInfo?>); + _i5.Future releaseSurfaceProvider() => (super.noSuchMethod( + Invocation.method(#releaseSurfaceProvider, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setTargetRotation(int? rotation) => - (super.noSuchMethod( - Invocation.method(#setTargetRotation, [rotation]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future<_i2.ResolutionInfo?> getResolutionInfo() => (super.noSuchMethod( + Invocation.method(#getResolutionInfo, []), + returnValue: _i5.Future<_i2.ResolutionInfo?>.value(), + returnValueForMissingStub: _i5.Future<_i2.ResolutionInfo?>.value(), + ) as _i5.Future<_i2.ResolutionInfo?>); @override - _i5.Future surfaceProducerHandlesCropAndRotation() => - (super.noSuchMethod( - Invocation.method(#surfaceProducerHandlesCropAndRotation, []), - returnValue: _i5.Future.value(false), - returnValueForMissingStub: _i5.Future.value(false), - ) - as _i5.Future); + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.Preview pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakePreview_31( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakePreview_31( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.Preview); + _i5.Future surfaceProducerHandlesCropAndRotation() => (super.noSuchMethod( + Invocation.method(#surfaceProducerHandlesCropAndRotation, []), + returnValue: _i5.Future.value(false), + returnValueForMissingStub: _i5.Future.value(false), + ) as _i5.Future); + + @override + _i2.Preview pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakePreview_31(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakePreview_31(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.Preview); } /// A class which mocks [ProcessCameraProvider]. /// /// See the documentation for Mockito's code generation for more information. -class MockProcessCameraProvider extends _i1.Mock - implements _i2.ProcessCameraProvider { +class MockProcessCameraProvider extends _i1.Mock implements _i2.ProcessCameraProvider { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future> getAvailableCameraInfos() => - (super.noSuchMethod( - Invocation.method(#getAvailableCameraInfos, []), - returnValue: _i5.Future>.value( - <_i2.CameraInfo>[], - ), - returnValueForMissingStub: _i5.Future>.value( - <_i2.CameraInfo>[], - ), - ) - as _i5.Future>); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future> getAvailableCameraInfos() => (super.noSuchMethod( + Invocation.method(#getAvailableCameraInfos, []), + returnValue: _i5.Future>.value(<_i2.CameraInfo>[]), + returnValueForMissingStub: _i5.Future>.value(<_i2.CameraInfo>[]), + ) as _i5.Future>); @override _i5.Future<_i2.Camera> bindToLifecycle( _i2.CameraSelector? cameraSelector, List<_i2.UseCase>? useCases, - ) => - (super.noSuchMethod( - Invocation.method(#bindToLifecycle, [cameraSelector, useCases]), - returnValue: _i5.Future<_i2.Camera>.value( - _FakeCamera_5( - this, - Invocation.method(#bindToLifecycle, [cameraSelector, useCases]), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.Camera>.value( - _FakeCamera_5( - this, - Invocation.method(#bindToLifecycle, [cameraSelector, useCases]), - ), - ), - ) - as _i5.Future<_i2.Camera>); - - @override - _i5.Future isBound(_i2.UseCase? useCase) => - (super.noSuchMethod( - Invocation.method(#isBound, [useCase]), - returnValue: _i5.Future.value(false), - returnValueForMissingStub: _i5.Future.value(false), - ) - as _i5.Future); + ) => (super.noSuchMethod( + Invocation.method(#bindToLifecycle, [cameraSelector, useCases]), + returnValue: _i5.Future<_i2.Camera>.value( + _FakeCamera_5(this, Invocation.method(#bindToLifecycle, [cameraSelector, useCases])), + ), + returnValueForMissingStub: _i5.Future<_i2.Camera>.value( + _FakeCamera_5(this, Invocation.method(#bindToLifecycle, [cameraSelector, useCases])), + ), + ) as _i5.Future<_i2.Camera>); @override - _i5.Future unbind(List<_i2.UseCase>? useCases) => - (super.noSuchMethod( - Invocation.method(#unbind, [useCases]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future isBound(_i2.UseCase? useCase) => (super.noSuchMethod( + Invocation.method(#isBound, [useCase]), + returnValue: _i5.Future.value(false), + returnValueForMissingStub: _i5.Future.value(false), + ) as _i5.Future); @override - _i5.Future unbindAll() => - (super.noSuchMethod( - Invocation.method(#unbindAll, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future unbind(List<_i2.UseCase>? useCases) => (super.noSuchMethod( + Invocation.method(#unbind, [useCases]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.ProcessCameraProvider pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeProcessCameraProvider_32( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeProcessCameraProvider_32( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ProcessCameraProvider); + _i5.Future unbindAll() => (super.noSuchMethod( + Invocation.method(#unbindAll, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.ProcessCameraProvider pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeProcessCameraProvider_32(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeProcessCameraProvider_32( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ProcessCameraProvider); } /// A class which mocks [QualitySelector]. @@ -1960,34 +1357,21 @@ class MockProcessCameraProvider extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockQualitySelector extends _i1.Mock implements _i2.QualitySelector { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.QualitySelector pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeQualitySelector_33( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeQualitySelector_33( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.QualitySelector); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.QualitySelector pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeQualitySelector_33(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeQualitySelector_33(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.QualitySelector); } /// A class which mocks [Recorder]. @@ -1995,90 +1379,57 @@ class MockQualitySelector extends _i1.Mock implements _i2.QualitySelector { /// See the documentation for Mockito's code generation for more information. class MockRecorder extends _i1.Mock implements _i2.Recorder { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future getAspectRatio() => - (super.noSuchMethod( - Invocation.method(#getAspectRatio, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future getTargetVideoEncodingBitRate() => - (super.noSuchMethod( - Invocation.method(#getTargetVideoEncodingBitRate, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i5.Future getAspectRatio() => (super.noSuchMethod( + Invocation.method(#getAspectRatio, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); @override - _i5.Future<_i2.QualitySelector> getQualitySelector() => - (super.noSuchMethod( - Invocation.method(#getQualitySelector, []), - returnValue: _i5.Future<_i2.QualitySelector>.value( - _FakeQualitySelector_33( - this, - Invocation.method(#getQualitySelector, []), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.QualitySelector>.value( - _FakeQualitySelector_33( - this, - Invocation.method(#getQualitySelector, []), - ), - ), - ) - as _i5.Future<_i2.QualitySelector>); - - @override - _i5.Future<_i2.PendingRecording> prepareRecording(String? path) => - (super.noSuchMethod( - Invocation.method(#prepareRecording, [path]), - returnValue: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_28( - this, - Invocation.method(#prepareRecording, [path]), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_28( - this, - Invocation.method(#prepareRecording, [path]), - ), - ), - ) - as _i5.Future<_i2.PendingRecording>); - - @override - _i2.Recorder pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeRecorder_34( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeRecorder_34( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.Recorder); + _i5.Future getTargetVideoEncodingBitRate() => (super.noSuchMethod( + Invocation.method(#getTargetVideoEncodingBitRate, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); + + @override + _i5.Future<_i2.QualitySelector> getQualitySelector() => (super.noSuchMethod( + Invocation.method(#getQualitySelector, []), + returnValue: _i5.Future<_i2.QualitySelector>.value( + _FakeQualitySelector_33(this, Invocation.method(#getQualitySelector, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.QualitySelector>.value( + _FakeQualitySelector_33(this, Invocation.method(#getQualitySelector, [])), + ), + ) as _i5.Future<_i2.QualitySelector>); + + @override + _i5.Future<_i2.PendingRecording> prepareRecording(String? path) => (super.noSuchMethod( + Invocation.method(#prepareRecording, [path]), + returnValue: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_28(this, Invocation.method(#prepareRecording, [path])), + ), + returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_28(this, Invocation.method(#prepareRecording, [path])), + ), + ) as _i5.Future<_i2.PendingRecording>); + + @override + _i2.Recorder pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeRecorder_34(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeRecorder_34(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.Recorder); } /// A class which mocks [ResolutionFilter]. @@ -2086,149 +1437,100 @@ class MockRecorder extends _i1.Mock implements _i2.Recorder { /// See the documentation for Mockito's code generation for more information. class MockResolutionFilter extends _i1.Mock implements _i2.ResolutionFilter { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.ResolutionFilter pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeResolutionFilter_35( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeResolutionFilter_35( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ResolutionFilter); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.ResolutionFilter pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeResolutionFilter_35(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeResolutionFilter_35(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ResolutionFilter); } /// A class which mocks [ResolutionSelector]. /// /// See the documentation for Mockito's code generation for more information. -class MockResolutionSelector extends _i1.Mock - implements _i2.ResolutionSelector { - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.AspectRatioStrategy> getAspectRatioStrategy() => - (super.noSuchMethod( - Invocation.method(#getAspectRatioStrategy, []), - returnValue: _i5.Future<_i2.AspectRatioStrategy>.value( - _FakeAspectRatioStrategy_2( - this, - Invocation.method(#getAspectRatioStrategy, []), - ), - ), - returnValueForMissingStub: - _i5.Future<_i2.AspectRatioStrategy>.value( - _FakeAspectRatioStrategy_2( - this, - Invocation.method(#getAspectRatioStrategy, []), - ), - ), - ) - as _i5.Future<_i2.AspectRatioStrategy>); - - @override - _i2.ResolutionSelector pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeResolutionSelector_36( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeResolutionSelector_36( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ResolutionSelector); +class MockResolutionSelector extends _i1.Mock implements _i2.ResolutionSelector { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.AspectRatioStrategy> getAspectRatioStrategy() => (super.noSuchMethod( + Invocation.method(#getAspectRatioStrategy, []), + returnValue: _i5.Future<_i2.AspectRatioStrategy>.value( + _FakeAspectRatioStrategy_2(this, Invocation.method(#getAspectRatioStrategy, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.AspectRatioStrategy>.value( + _FakeAspectRatioStrategy_2(this, Invocation.method(#getAspectRatioStrategy, [])), + ), + ) as _i5.Future<_i2.AspectRatioStrategy>); + + @override + _i2.ResolutionSelector pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeResolutionSelector_36(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeResolutionSelector_36( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ResolutionSelector); } /// A class which mocks [ResolutionStrategy]. /// /// See the documentation for Mockito's code generation for more information. -class MockResolutionStrategy extends _i1.Mock - implements _i2.ResolutionStrategy { - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.CameraSize?> getBoundSize() => - (super.noSuchMethod( - Invocation.method(#getBoundSize, []), - returnValue: _i5.Future<_i2.CameraSize?>.value(), - returnValueForMissingStub: _i5.Future<_i2.CameraSize?>.value(), - ) - as _i5.Future<_i2.CameraSize?>); - - @override - _i5.Future<_i2.ResolutionStrategyFallbackRule> getFallbackRule() => - (super.noSuchMethod( - Invocation.method(#getFallbackRule, []), - returnValue: _i5.Future<_i2.ResolutionStrategyFallbackRule>.value( - _i2.ResolutionStrategyFallbackRule.closestHigher, - ), - returnValueForMissingStub: - _i5.Future<_i2.ResolutionStrategyFallbackRule>.value( - _i2.ResolutionStrategyFallbackRule.closestHigher, - ), - ) - as _i5.Future<_i2.ResolutionStrategyFallbackRule>); - - @override - _i2.ResolutionStrategy pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeResolutionStrategy_37( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeResolutionStrategy_37( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ResolutionStrategy); +class MockResolutionStrategy extends _i1.Mock implements _i2.ResolutionStrategy { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.CameraSize?> getBoundSize() => (super.noSuchMethod( + Invocation.method(#getBoundSize, []), + returnValue: _i5.Future<_i2.CameraSize?>.value(), + returnValueForMissingStub: _i5.Future<_i2.CameraSize?>.value(), + ) as _i5.Future<_i2.CameraSize?>); + + @override + _i5.Future<_i2.ResolutionStrategyFallbackRule> getFallbackRule() => (super.noSuchMethod( + Invocation.method(#getFallbackRule, []), + returnValue: _i5.Future<_i2.ResolutionStrategyFallbackRule>.value( + _i2.ResolutionStrategyFallbackRule.closestHigher, + ), + returnValueForMissingStub: _i5.Future<_i2.ResolutionStrategyFallbackRule>.value( + _i2.ResolutionStrategyFallbackRule.closestHigher, + ), + ) as _i5.Future<_i2.ResolutionStrategyFallbackRule>); + + @override + _i2.ResolutionStrategy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeResolutionStrategy_37(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeResolutionStrategy_37( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ResolutionStrategy); } /// A class which mocks [Recording]. @@ -2236,154 +1538,103 @@ class MockResolutionStrategy extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockRecording extends _i1.Mock implements _i2.Recording { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future close() => - (super.noSuchMethod( - Invocation.method(#close, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future pause() => - (super.noSuchMethod( - Invocation.method(#pause, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future close() => (super.noSuchMethod( + Invocation.method(#close, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future resume() => - (super.noSuchMethod( - Invocation.method(#resume, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future stop() => - (super.noSuchMethod( - Invocation.method(#stop, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future resume() => (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.Recording pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeRecording_29( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeRecording_29( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.Recording); + _i5.Future stop() => (super.noSuchMethod( + Invocation.method(#stop, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.Recording pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeRecording_29(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeRecording_29(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.Recording); } /// A class which mocks [SystemServicesManager]. /// /// See the documentation for Mockito's code generation for more information. -class MockSystemServicesManager extends _i1.Mock - implements _i2.SystemServicesManager { +class MockSystemServicesManager extends _i1.Mock implements _i2.SystemServicesManager { @override - void Function(_i2.SystemServicesManager, String) get onCameraError => - (super.noSuchMethod( - Invocation.getter(#onCameraError), - returnValue: - ( - _i2.SystemServicesManager pigeon_instance, - String errorDescription, - ) {}, - returnValueForMissingStub: - ( - _i2.SystemServicesManager pigeon_instance, - String errorDescription, - ) {}, - ) - as void Function(_i2.SystemServicesManager, String)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.CameraPermissionsError?> requestCameraPermissions( - bool? enableAudio, - ) => - (super.noSuchMethod( - Invocation.method(#requestCameraPermissions, [enableAudio]), - returnValue: _i5.Future<_i2.CameraPermissionsError?>.value(), - returnValueForMissingStub: - _i5.Future<_i2.CameraPermissionsError?>.value(), - ) - as _i5.Future<_i2.CameraPermissionsError?>); + void Function(_i2.SystemServicesManager, String) get onCameraError => (super.noSuchMethod( + Invocation.getter(#onCameraError), + returnValue: (_i2.SystemServicesManager pigeon_instance, String errorDescription) {}, + returnValueForMissingStub: ( + _i2.SystemServicesManager pigeon_instance, + String errorDescription, + ) {}, + ) as void Function(_i2.SystemServicesManager, String)); @override - _i5.Future getTempFilePath(String? prefix, String? suffix) => - (super.noSuchMethod( - Invocation.method(#getTempFilePath, [prefix, suffix]), - returnValue: _i5.Future.value( - _i6.dummyValue( - this, - Invocation.method(#getTempFilePath, [prefix, suffix]), - ), - ), - returnValueForMissingStub: _i5.Future.value( - _i6.dummyValue( - this, - Invocation.method(#getTempFilePath, [prefix, suffix]), - ), - ), - ) - as _i5.Future); - - @override - _i2.SystemServicesManager pigeon_copy() => + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.CameraPermissionsError?> requestCameraPermissions(bool? enableAudio) => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeSystemServicesManager_38( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeSystemServicesManager_38( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.SystemServicesManager); + Invocation.method(#requestCameraPermissions, [enableAudio]), + returnValue: _i5.Future<_i2.CameraPermissionsError?>.value(), + returnValueForMissingStub: _i5.Future<_i2.CameraPermissionsError?>.value(), + ) as _i5.Future<_i2.CameraPermissionsError?>); + + @override + _i5.Future getTempFilePath(String? prefix, String? suffix) => (super.noSuchMethod( + Invocation.method(#getTempFilePath, [prefix, suffix]), + returnValue: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getTempFilePath, [prefix, suffix])), + ), + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getTempFilePath, [prefix, suffix])), + ), + ) as _i5.Future); + + @override + _i2.SystemServicesManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeSystemServicesManager_38(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeSystemServicesManager_38( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.SystemServicesManager); } /// A class which mocks [VideoCapture]. @@ -2391,56 +1642,39 @@ class MockSystemServicesManager extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockVideoCapture extends _i1.Mock implements _i2.VideoCapture { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.VideoOutput> getOutput() => - (super.noSuchMethod( - Invocation.method(#getOutput, []), - returnValue: _i5.Future<_i2.VideoOutput>.value( - _FakeVideoOutput_39(this, Invocation.method(#getOutput, [])), - ), - returnValueForMissingStub: _i5.Future<_i2.VideoOutput>.value( - _FakeVideoOutput_39(this, Invocation.method(#getOutput, [])), - ), - ) - as _i5.Future<_i2.VideoOutput>); - - @override - _i5.Future setTargetRotation(int? rotation) => - (super.noSuchMethod( - Invocation.method(#setTargetRotation, [rotation]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.VideoCapture pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoCapture_40( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoCapture_40( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoCapture); + _i5.Future<_i2.VideoOutput> getOutput() => (super.noSuchMethod( + Invocation.method(#getOutput, []), + returnValue: _i5.Future<_i2.VideoOutput>.value( + _FakeVideoOutput_39(this, Invocation.method(#getOutput, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.VideoOutput>.value( + _FakeVideoOutput_39(this, Invocation.method(#getOutput, [])), + ), + ) as _i5.Future<_i2.VideoOutput>); + + @override + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.VideoCapture pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoCapture_40(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoCapture_40(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.VideoCapture); } /// A class which mocks [ZoomState]. @@ -2448,182 +1682,127 @@ class MockVideoCapture extends _i1.Mock implements _i2.VideoCapture { /// See the documentation for Mockito's code generation for more information. class MockZoomState extends _i1.Mock implements _i2.ZoomState { @override - double get minZoomRatio => - (super.noSuchMethod( - Invocation.getter(#minZoomRatio), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) - as double); + double get minZoomRatio => (super.noSuchMethod( + Invocation.getter(#minZoomRatio), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); @override - double get maxZoomRatio => - (super.noSuchMethod( - Invocation.getter(#maxZoomRatio), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) - as double); + double get maxZoomRatio => (super.noSuchMethod( + Invocation.getter(#maxZoomRatio), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.ZoomState pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeZoomState_41( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeZoomState_41( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ZoomState); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.ZoomState pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeZoomState_41(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeZoomState_41(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ZoomState); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. -class MockLiveCameraState extends _i1.Mock - implements _i3.LiveData<_i2.CameraState> { +class MockLiveCameraState extends _i1.Mock implements _i3.LiveData<_i2.CameraState> { MockLiveCameraState() { _i1.throwOnMissingStub(this); } @override - _i2.LiveDataSupportedType get type => - (super.noSuchMethod( - Invocation.getter(#type), - returnValue: _i2.LiveDataSupportedType.cameraState, - ) - as _i2.LiveDataSupportedType); + _i2.LiveDataSupportedType get type => (super.noSuchMethod( + Invocation.getter(#type), + returnValue: _i2.LiveDataSupportedType.cameraState, + ) as _i2.LiveDataSupportedType); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + ) as _i2.PigeonInstanceManager); @override - _i5.Future observe(_i2.Observer? observer) => - (super.noSuchMethod( - Invocation.method(#observe, [observer]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future observe(_i2.Observer? observer) => (super.noSuchMethod( + Invocation.method(#observe, [observer]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i2.CameraState?> getValue() => - (super.noSuchMethod( - Invocation.method(#getValue, []), - returnValue: _i5.Future<_i2.CameraState?>.value(), - ) - as _i5.Future<_i2.CameraState?>); + _i5.Future<_i2.CameraState?> getValue() => (super.noSuchMethod( + Invocation.method(#getValue, []), + returnValue: _i5.Future<_i2.CameraState?>.value(), + ) as _i5.Future<_i2.CameraState?>); @override - _i3.LiveData<_i2.CameraState> pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeLiveData_7<_i2.CameraState>( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i3.LiveData<_i2.CameraState>); + _i3.LiveData<_i2.CameraState> pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeLiveData_7<_i2.CameraState>(this, Invocation.method(#pigeon_copy, [])), + ) as _i3.LiveData<_i2.CameraState>); @override - _i5.Future removeObservers() => - (super.noSuchMethod( - Invocation.method(#removeObservers, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future removeObservers() => (super.noSuchMethod( + Invocation.method(#removeObservers, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. -class MockLiveZoomState extends _i1.Mock - implements _i3.LiveData<_i2.ZoomState> { +class MockLiveZoomState extends _i1.Mock implements _i3.LiveData<_i2.ZoomState> { MockLiveZoomState() { _i1.throwOnMissingStub(this); } @override - _i2.LiveDataSupportedType get type => - (super.noSuchMethod( - Invocation.getter(#type), - returnValue: _i2.LiveDataSupportedType.cameraState, - ) - as _i2.LiveDataSupportedType); + _i2.LiveDataSupportedType get type => (super.noSuchMethod( + Invocation.getter(#type), + returnValue: _i2.LiveDataSupportedType.cameraState, + ) as _i2.LiveDataSupportedType); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + ) as _i2.PigeonInstanceManager); @override - _i5.Future observe(_i2.Observer? observer) => - (super.noSuchMethod( - Invocation.method(#observe, [observer]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future observe(_i2.Observer? observer) => (super.noSuchMethod( + Invocation.method(#observe, [observer]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i2.ZoomState?> getValue() => - (super.noSuchMethod( - Invocation.method(#getValue, []), - returnValue: _i5.Future<_i2.ZoomState?>.value(), - ) - as _i5.Future<_i2.ZoomState?>); + _i5.Future<_i2.ZoomState?> getValue() => (super.noSuchMethod( + Invocation.method(#getValue, []), + returnValue: _i5.Future<_i2.ZoomState?>.value(), + ) as _i5.Future<_i2.ZoomState?>); @override - _i3.LiveData<_i2.ZoomState> pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeLiveData_7<_i2.ZoomState>( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i3.LiveData<_i2.ZoomState>); + _i3.LiveData<_i2.ZoomState> pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeLiveData_7<_i2.ZoomState>(this, Invocation.method(#pigeon_copy, [])), + ) as _i3.LiveData<_i2.ZoomState>); @override - _i5.Future removeObservers() => - (super.noSuchMethod( - Invocation.method(#removeObservers, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future removeObservers() => (super.noSuchMethod( + Invocation.method(#removeObservers, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } diff --git a/packages/camera/camera_android_camerax/test/preview_rotation_test.dart b/packages/camera/camera_android_camerax/test/preview_rotation_test.dart index cfc6b2db103b..6bcb5ff9c7b2 100644 --- a/packages/camera/camera_android_camerax/test/preview_rotation_test.dart +++ b/packages/camera/camera_android_camerax/test/preview_rotation_test.dart @@ -6,8 +6,7 @@ import 'package:camera_android_camerax/camera_android_camerax.dart'; import 'package:camera_android_camerax/src/camerax_library.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart' - show MatrixUtils, RotatedBox, Texture, Transform; +import 'package:flutter/widgets.dart' show MatrixUtils, RotatedBox, Texture, Transform; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; @@ -61,9 +60,7 @@ void main() { final mockCamera = MockCamera(); // Mock retrieving available test camera. - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); + when(mockProcessCameraProvider.bindToLifecycle(any, any)).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); when( mockProcessCameraProvider.getAvailableCameraInfos(), @@ -71,15 +68,11 @@ void main() { when( mockCameraInfo.lensFacing, ).thenReturn(isCameraFrontFacing ? LensFacing.front : LensFacing.back); - when( - mockCameraInfo.sensorRotationDegrees, - ).thenReturn(sensorRotationDegrees); + when(mockCameraInfo.sensorRotationDegrees).thenReturn(sensorRotationDegrees); // Mock additional ProcessCameraProvider operation that is irrelevant // for the tests in this file. - when( - mockCameraInfo.getCameraState(), - ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCameraInfo.getCameraState()).thenAnswer((_) async => MockLiveCameraState()); return mockProcessCameraProvider; } @@ -92,15 +85,11 @@ void main() { void setUpOverridesForCreatingTestCameraWithDeviceOrientationManager( DeviceOrientationManager deviceOrientationManager, { required MockProcessCameraProvider mockProcessCameraProvider, - required CameraSelector Function({ - LensFacing? requireLensFacing, - dynamic cameraInfoForFilter, - }) + required CameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) createCameraSelector, required bool handlesCropAndRotation, }) { - PigeonOverrides.processCameraProvider_getInstance = () async => - mockProcessCameraProvider; + PigeonOverrides.processCameraProvider_getInstance = () async => mockProcessCameraProvider; PigeonOverrides.cameraSelector_new = createCameraSelector; PigeonOverrides.preview_new = ({ @@ -112,29 +101,23 @@ void main() { when( preview.surfaceProducerHandlesCropAndRotation(), ).thenAnswer((_) async => handlesCropAndRotation); - when(preview.getResolutionInfo()).thenAnswer( - (_) async => - ResolutionInfo.pigeon_detached(resolution: MockCameraSize()), - ); + when( + preview.getResolutionInfo(), + ).thenAnswer((_) async => ResolutionInfo.pigeon_detached(resolution: MockCameraSize())); return preview; }; - PigeonOverrides.imageCapture_new = - ({ - int? targetRotation, - CameraXFlashMode? flashMode, - ResolutionSelector? resolutionSelector, - }) => MockImageCapture(); - PigeonOverrides.recorder_new = - ({ - int? aspectRatio, - int? targetVideoEncodingBitRate, - QualitySelector? qualitySelector, - }) => MockRecorder(); + PigeonOverrides.imageCapture_new = ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) => MockImageCapture(); + PigeonOverrides.recorder_new = ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) => MockRecorder(); PigeonOverrides.videoCapture_withOutput = - ({ - required VideoOutput videoOutput, - CameraIntegerRange? targetFpsRange, - }) { + ({required VideoOutput videoOutput, CameraIntegerRange? targetFpsRange}) { return MockVideoCapture(); }; PigeonOverrides.imageAnalysis_new = @@ -147,10 +130,7 @@ void main() { return MockImageAnalysis(); }; PigeonOverrides.resolutionStrategy_new = - ({ - required CameraSize boundSize, - required ResolutionStrategyFallbackRule fallbackRule, - }) { + ({required CameraSize boundSize, required ResolutionStrategyFallbackRule fallbackRule}) { return MockResolutionStrategy(); }; PigeonOverrides.resolutionSelector_new = @@ -161,49 +141,38 @@ void main() { }) { return MockResolutionSelector(); }; - PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = - ({required VideoQuality quality}) { - return MockFallbackStrategy(); - }; - PigeonOverrides.fallbackStrategy_lowerQualityThan = - ({required VideoQuality quality}) { - return MockFallbackStrategy(); - }; + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; + PigeonOverrides.fallbackStrategy_lowerQualityThan = ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { final camera2cameraInfo = MockCamera2CameraInfo(); - when( - camera2cameraInfo.getCameraCharacteristic(any), - ).thenAnswer((_) async => 90); + when(camera2cameraInfo.getCameraCharacteristic(any)).thenAnswer((_) async => 90); return camera2cameraInfo; }; PigeonOverrides.qualitySelector_from = ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { return MockQualitySelector(); }; - GenericsPigeonOverrides.observerNew = - ({required void Function(Observer, T) onChanged}) { - return Observer.detached(onChanged: onChanged); - }; + GenericsPigeonOverrides.observerNew = ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; PigeonOverrides.systemServicesManager_new = - ({ - required void Function(SystemServicesManager, String) onCameraError, - }) { + ({required void Function(SystemServicesManager, String) onCameraError}) { return MockSystemServicesManager(); }; - PigeonOverrides.deviceOrientationManager_new = - ({ - required void Function(DeviceOrientationManager, String) - onDeviceOrientationChanged, - }) => deviceOrientationManager; + PigeonOverrides.deviceOrientationManager_new = ({ + required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged, + }) => deviceOrientationManager; PigeonOverrides.aspectRatioStrategy_new = ({ required AspectRatio preferredAspectRatio, required AspectRatioStrategyFallbackRule fallbackRule, }) { final mockAspectRatioStrategy = MockAspectRatioStrategy(); - when( - mockAspectRatioStrategy.getFallbackRule(), - ).thenAnswer((_) async => fallbackRule); + when(mockAspectRatioStrategy.getFallbackRule()).thenAnswer((_) async => fallbackRule); when( mockAspectRatioStrategy.getPreferredAspectRatio(), ).thenAnswer((_) async => preferredAspectRatio); @@ -223,19 +192,14 @@ void main() { /// Useful for tests that do not need a reference to a DeviceOrientationManager. void setUpOverridesForCreatingTestCamera({ required MockProcessCameraProvider mockProcessCameraProvider, - required CameraSelector Function({ - LensFacing? requireLensFacing, - dynamic cameraInfoForFilter, - }) + required CameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) createCameraSelector, required bool handlesCropAndRotation, required Future Function() getUiOrientation, required Future Function() getDefaultDisplayRotation, }) { final deviceOrientationManager = MockDeviceOrientationManager(); - when( - deviceOrientationManager.getUiOrientation(), - ).thenAnswer((_) => getUiOrientation()); + when(deviceOrientationManager.getUiOrientation()).thenAnswer((_) => getUiOrientation()); when( deviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) => getDefaultDisplayRotation()); @@ -248,10 +212,7 @@ void main() { } /// Returns function that a CameraXProxy can use to select the front camera. - MockCameraSelector Function({ - LensFacing? requireLensFacing, - dynamic cameraInfoForFilter, - }) + MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) createCameraSelectorForFrontCamera(MockCameraSelector mockCameraSelector) { return ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { switch (requireLensFacing) { @@ -267,10 +228,7 @@ void main() { } /// Returns function that a CameraXProxy can use to select the back camera. - MockCameraSelector Function({ - LensFacing? requireLensFacing, - dynamic cameraInfoForFilter, - }) + MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) createCameraSelectorForBackCamera(MockCameraSelector mockCameraSelector) { return ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { switch (requireLensFacing) { @@ -286,10 +244,7 @@ void main() { } /// Error message for detecting an incorrect preview rotation. - String getExpectedRotationTestFailureReason( - int expectedQuarterTurns, - int actualQuarterTurns, - ) => + String getExpectedRotationTestFailureReason(int expectedQuarterTurns, int actualQuarterTurns) => 'Expected the preview to be rotated by $expectedQuarterTurns quarter turns (which is ${expectedQuarterTurns * 90} degrees clockwise) but instead was rotated $actualQuarterTurns quarter turns.'; /// Checks that the transform matrix (Matrix4) mirrors across the x-axis by @@ -318,10 +273,7 @@ void main() { 1.0, ); - expect( - MatrixUtils.matrixEquals(mirrorAcrossXMatrix, transformationMatrix), - isTrue, - ); + expect(MatrixUtils.matrixEquals(mirrorAcrossXMatrix, transformationMatrix), isTrue); } /// Checks that the transform matrix (Matrix4) mirrors across the y-axis by @@ -350,10 +302,7 @@ void main() { 1.0, ); - expect( - MatrixUtils.matrixEquals(mirrorAcrossYMatrix, transformationMatrix), - isTrue, - ); + expect(MatrixUtils.matrixEquals(mirrorAcrossYMatrix, transformationMatrix), isTrue); } group('when handlesCropAndRotation is true', () { @@ -364,10 +313,7 @@ void main() { late int cameraId; late DeviceOrientation testInitialDeviceOrientation; late MockProcessCameraProvider mockProcessCameraProvider; - late MockCameraSelector Function({ - LensFacing? requireLensFacing, - dynamic cameraInfoForFilter, - }) + late MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) fakeCreateCameraSelector; late MediaSettings testMediaSettings; @@ -385,9 +331,7 @@ void main() { sensorRotationDegrees: /* irrelevant for test */ 90, isCameraFrontFacing: false, ); - fakeCreateCameraSelector = createCameraSelectorForBackCamera( - mockCameraSelector, - ); + fakeCreateCameraSelector = createCameraSelectorForBackCamera(mockCameraSelector); // Media settings to create camera; irrelevant for test. testMediaSettings = const MediaSettings(); @@ -402,21 +346,17 @@ void main() { mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, - getUiOrientation: () async => - _serializeDeviceOrientation(testInitialDeviceOrientation), - getDefaultDisplayRotation: () => - Future.value(Surface.rotation0), + getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation), + getDefaultDisplayRotation: () => Future.value(Surface.rotation0), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -430,9 +370,7 @@ void main() { // Verify Texture is rotated by 0 - 90 = -90 degrees clockwise = 270 degrees clockwise. const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; expect(rotatedBox.child, isA()); @@ -457,21 +395,17 @@ void main() { mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, - getUiOrientation: () async => - _serializeDeviceOrientation(testInitialDeviceOrientation), - getDefaultDisplayRotation: () => - Future.value(Surface.rotation90), + getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation), + getDefaultDisplayRotation: () => Future.value(Surface.rotation90), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -485,9 +419,7 @@ void main() { // Verify Texture is rotated by 270 - 90 = 180 degrees clockwise. const int expectedQuarterTurns = _180DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -510,21 +442,17 @@ void main() { mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, - getUiOrientation: () async => - _serializeDeviceOrientation(testInitialDeviceOrientation), - getDefaultDisplayRotation: () => - Future.value(Surface.rotation180), + getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation), + getDefaultDisplayRotation: () => Future.value(Surface.rotation180), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -538,9 +466,7 @@ void main() { // Verify Texture is rotated by 180 - 90 = 90 degrees clockwise. const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -563,21 +489,17 @@ void main() { mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, - getUiOrientation: () async => - _serializeDeviceOrientation(testInitialDeviceOrientation), - getDefaultDisplayRotation: () => - Future.value(Surface.rotation270), + getUiOrientation: () async => _serializeDeviceOrientation(testInitialDeviceOrientation), + getDefaultDisplayRotation: () => Future.value(Surface.rotation270), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -591,9 +513,7 @@ void main() { // Verify Texture is rotated by 90 - 90 = 0 degrees. const int expectedQuarterTurns = _0DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -616,10 +536,7 @@ void main() { late int cameraId; late int testInitialDefaultDisplayRotation; late MockProcessCameraProvider mockProcessCameraProvider; - late MockCameraSelector Function({ - LensFacing? requireLensFacing, - dynamic cameraInfoForFilter, - }) + late MockCameraSelector Function({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) fakeCreateCameraSelector; late MediaSettings testMediaSettings; @@ -637,9 +554,7 @@ void main() { sensorRotationDegrees: /* irrelevant for test */ 90, isCameraFrontFacing: false, ); - fakeCreateCameraSelector = createCameraSelectorForBackCamera( - mockCameraSelector, - ); + fakeCreateCameraSelector = createCameraSelectorForBackCamera(mockCameraSelector); // Media settings to create camera; irrelevant for test. testMediaSettings = const MediaSettings(); @@ -654,21 +569,17 @@ void main() { mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, - getUiOrientation: () async => - _serializeDeviceOrientation(DeviceOrientation.portraitUp), - getDefaultDisplayRotation: () => - Future.value(testInitialDefaultDisplayRotation), + getUiOrientation: () async => _serializeDeviceOrientation(DeviceOrientation.portraitUp), + getDefaultDisplayRotation: () => Future.value(testInitialDefaultDisplayRotation), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -682,9 +593,7 @@ void main() { // Verify Texture is rotated by 270 - 0 = 270 degrees clockwise. const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -709,19 +618,16 @@ void main() { handlesCropAndRotation: true, getUiOrientation: () async => _serializeDeviceOrientation(DeviceOrientation.landscapeLeft), - getDefaultDisplayRotation: () => - Future.value(testInitialDefaultDisplayRotation), + getDefaultDisplayRotation: () => Future.value(testInitialDefaultDisplayRotation), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -735,9 +641,7 @@ void main() { // Verify Texture is rotated by 270 - 270 = 0 degrees. const int expectedQuarterTurns = _0DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -762,19 +666,16 @@ void main() { handlesCropAndRotation: true, getUiOrientation: () async => _serializeDeviceOrientation(DeviceOrientation.portraitDown), - getDefaultDisplayRotation: () => - Future.value(testInitialDefaultDisplayRotation), + getDefaultDisplayRotation: () => Future.value(testInitialDefaultDisplayRotation), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -788,9 +689,7 @@ void main() { // Verify Texture is rotated by 270 - 180 = 90 degrees clockwise. const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -815,19 +714,16 @@ void main() { handlesCropAndRotation: true, getUiOrientation: () async => _serializeDeviceOrientation(DeviceOrientation.landscapeRight), - getDefaultDisplayRotation: () => - Future.value(testInitialDefaultDisplayRotation), + getDefaultDisplayRotation: () => Future.value(testInitialDefaultDisplayRotation), ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -841,9 +737,7 @@ void main() { // Verify Texture is rotated by 270 - 90 = 180 degrees clockwise. const int expectedQuarterTurns = _180DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -865,8 +759,7 @@ void main() { (WidgetTester tester) async { final camera = AndroidCameraCameraX(); const cameraId = 11; - const DeviceOrientation testDeviceOrientation = - DeviceOrientation.portraitDown; + const DeviceOrientation testDeviceOrientation = DeviceOrientation.portraitDown; // Create and set up mock CameraSelector, mock ProcessCameraProvider, and media settings for test front camera. // These settings do not matter for this test. @@ -875,10 +768,10 @@ void main() { LensFacing? requireLensFacing, dynamic cameraInfoForFilter, }) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); - final MockProcessCameraProvider - mockProcessCameraProviderForFrontCamera = + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera( + mockFrontCameraSelector, + ); + final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, @@ -890,9 +783,7 @@ void main() { // to portrait down, set initial default display rotation to 0 degrees clockwise. final mockDeviceOrientationManager = MockDeviceOrientationManager(); when(mockDeviceOrientationManager.getUiOrientation()).thenAnswer( - (_) => Future.value( - _serializeDeviceOrientation(testDeviceOrientation), - ), + (_) => Future.value(_serializeDeviceOrientation(testDeviceOrientation)), ); when( mockDeviceOrientationManager.getDefaultDisplayRotation(), @@ -906,14 +797,12 @@ void main() { ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Calculated according to: counterClockwiseCurrentDefaultDisplayRotation - cameraPreviewPreAppliedRotation, @@ -936,21 +825,15 @@ void main() { mockDeviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) => Future.value(currentDefaultDisplayRotation)); - const testEvent = DeviceOrientationChangedEvent( - testDeviceOrientation, - ); - AndroidCameraCameraX.deviceOrientationChangedStreamController.add( - testEvent, - ); + const testEvent = DeviceOrientationChangedEvent(testDeviceOrientation); + AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent); await tester.pumpAndSettle(); // Verify Texture is rotated by expected clockwise degrees. final int expectedQuarterTurns = expectedRotationPerDefaultDisplayRotation[currentDefaultDisplayRotation]!; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); final int clockwiseQuarterTurns = rotatedBox.quarterTurns < 0 ? rotatedBox.quarterTurns + 4 : rotatedBox.quarterTurns; @@ -981,10 +864,10 @@ void main() { LensFacing? requireLensFacing, dynamic cameraInfoForFilter, }) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); - final MockProcessCameraProvider - mockProcessCameraProviderForFrontCamera = + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera( + mockFrontCameraSelector, + ); + final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, @@ -998,22 +881,18 @@ void main() { mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: true, - getUiOrientation: /* initial device orientation is irrelevant */ - () async => - _serializeDeviceOrientation(DeviceOrientation.portraitUp), - getDefaultDisplayRotation: () => - Future.value(testInitialDefaultDisplayRotation), + getUiOrientation: /* initial device orientation is irrelevant */ () async => + _serializeDeviceOrientation(DeviceOrientation.portraitUp), + getDefaultDisplayRotation: () => Future.value(testInitialDefaultDisplayRotation), ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Calculated according to: counterClockwiseCurrentDefaultDisplayRotation - cameraPreviewPreAppliedRotation, @@ -1032,21 +911,15 @@ void main() { for (final DeviceOrientation currentDeviceOrientation in expectedRotationPerDeviceOrientation.keys) { - final testEvent = DeviceOrientationChangedEvent( - currentDeviceOrientation, - ); - AndroidCameraCameraX.deviceOrientationChangedStreamController.add( - testEvent, - ); + final testEvent = DeviceOrientationChangedEvent(currentDeviceOrientation); + AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent); await tester.pumpAndSettle(); // Verify Texture is rotated by expected clockwise degrees. final int expectedQuarterTurns = expectedRotationPerDeviceOrientation[currentDeviceOrientation]!; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); final int clockwiseQuarterTurns = rotatedBox.quarterTurns < 0 ? rotatedBox.quarterTurns + 4 : rotatedBox.quarterTurns; @@ -1088,16 +961,16 @@ void main() { // with sensor orientation degrees 270. Also, set up function to mock initial default display // of 0. mockFrontCameraSelector = MockCameraSelector(); - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera( + mockFrontCameraSelector, + ); mockProcessCameraProviderForFrontCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, isCameraFrontFacing: true, ); - proxyGetDefaultDisplayRotation = () => - Future.value(Surface.rotation0); + proxyGetDefaultDisplayRotation = () => Future.value(Surface.rotation0); // Media settings to create camera; irrelevant for test. testMediaSettings = const MediaSettings(); @@ -1109,8 +982,7 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial device orientation to portrait up. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, handlesCropAndRotation: false, @@ -1119,14 +991,12 @@ void main() { ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1136,9 +1006,7 @@ void main() { // Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 0 = 270 degrees. const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1146,8 +1014,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in portrait mode, we expect the camera // preview to be mirrored across the y-axis. @@ -1170,8 +1037,7 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial device orientation to landscape right. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, handlesCropAndRotation: false, @@ -1180,14 +1046,12 @@ void main() { ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1197,9 +1061,7 @@ void main() { // Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 90 = 180 degrees. const int expectedQuarterTurns = _180DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1207,8 +1069,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera // preview to be mirrored across the x-axis. @@ -1231,8 +1092,7 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial device orientation to portrait down. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, handlesCropAndRotation: false, @@ -1241,14 +1101,12 @@ void main() { ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1258,9 +1116,7 @@ void main() { // Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 180 = 90 degrees clockwise. const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1268,8 +1124,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in portrait mode, we expect the camera // preview to be mirrored across the y-axis. @@ -1292,8 +1147,7 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial device orientation to landscape left. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, handlesCropAndRotation: false, @@ -1302,14 +1156,12 @@ void main() { ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1319,9 +1171,7 @@ void main() { // Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 270 = 0 degrees clockwise. const int expectedQuarterTurns = _0DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1329,8 +1179,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera // preview to be mirrored across the x-axis. @@ -1373,8 +1222,9 @@ void main() { // with sensor orientation degrees 270. Also, set up function to mock initial default display // of 0. mockFrontCameraSelector = MockCameraSelector(); - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera( + mockFrontCameraSelector, + ); mockProcessCameraProviderForFrontCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, @@ -1394,24 +1244,20 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, - getDefaultDisplayRotation: () => - Future.value(Surface.rotation0), + getDefaultDisplayRotation: () => Future.value(Surface.rotation0), handlesCropAndRotation: false, getUiOrientation: proxyGetUiOrientation, ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1421,9 +1267,7 @@ void main() { // Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 270 = 0 degrees. const int expectedQuarterTurns = _0DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1431,8 +1275,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera // preview to be mirrored across the x-axis. @@ -1455,24 +1298,20 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, - getDefaultDisplayRotation: () => - Future.value(Surface.rotation90), + getDefaultDisplayRotation: () => Future.value(Surface.rotation90), handlesCropAndRotation: false, getUiOrientation: proxyGetUiOrientation, ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1484,9 +1323,7 @@ void main() { // 270 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the // default display rotation. const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1494,8 +1331,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera // preview to be mirrored across the x-axis. @@ -1520,24 +1356,20 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, - getDefaultDisplayRotation: () => - Future.value(Surface.rotation180), + getDefaultDisplayRotation: () => Future.value(Surface.rotation180), handlesCropAndRotation: false, getUiOrientation: proxyGetUiOrientation, ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1547,9 +1379,7 @@ void main() { // Verify Texture is rotated by ((270 - 180 * 1 + 360) % 360) - 270 = -180 degrees clockwise = 180 degrees clockwise. const int expectedQuarterTurns = _180DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1557,8 +1387,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera // preview to be mirrored across the x-axis. @@ -1583,24 +1412,20 @@ void main() { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. setUpOverridesForCreatingTestCamera( - mockProcessCameraProvider: - mockProcessCameraProviderForFrontCamera, + mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, - getDefaultDisplayRotation: () => - Future.value(Surface.rotation270), + getDefaultDisplayRotation: () => Future.value(Surface.rotation270), handlesCropAndRotation: false, getUiOrientation: proxyGetUiOrientation, ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1612,9 +1437,7 @@ void main() { // 90 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the // default display rotation. const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1622,8 +1445,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera // preview to be mirrored across the x-axis. @@ -1650,8 +1472,7 @@ void main() { (WidgetTester tester) async { final camera = AndroidCameraCameraX(); const cameraId = 11; - const DeviceOrientation testDeviceOrientation = - DeviceOrientation.landscapeRight; + const DeviceOrientation testDeviceOrientation = DeviceOrientation.landscapeRight; // Create and set up mock front camera CameraSelector, mock ProcessCameraProvider, 270 degree sensor orientation, // media settings for test front camera. @@ -1660,10 +1481,10 @@ void main() { LensFacing? requireLensFacing, dynamic cameraInfoForFilter, }) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); - final MockProcessCameraProvider - mockProcessCameraProviderForFrontCamera = + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera( + mockFrontCameraSelector, + ); + final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, @@ -1675,9 +1496,7 @@ void main() { // to portrait down, set initial default display rotation to 0 degrees clockwise. final mockDeviceOrientationManager = MockDeviceOrientationManager(); when(mockDeviceOrientationManager.getUiOrientation()).thenAnswer( - (_) => Future.value( - _serializeDeviceOrientation(testDeviceOrientation), - ), + (_) => Future.value(_serializeDeviceOrientation(testDeviceOrientation)), ); when( mockDeviceOrientationManager.getDefaultDisplayRotation(), @@ -1690,14 +1509,12 @@ void main() { ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Calculated according to: ((270 - counterClockwiseDefaultDisplayRotation * 1 + 360) % 360) - 90. @@ -1720,21 +1537,15 @@ void main() { mockDeviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) async => currentDefaultDisplayRotation); - const testEvent = DeviceOrientationChangedEvent( - testDeviceOrientation, - ); - AndroidCameraCameraX.deviceOrientationChangedStreamController.add( - testEvent, - ); + const testEvent = DeviceOrientationChangedEvent(testDeviceOrientation); + AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent); await tester.pumpAndSettle(); // Verify Texture is rotated by expected clockwise degrees. final int expectedQuarterTurns = expectedRotationPerDefaultDisplayRotation[currentDefaultDisplayRotation]!; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1776,10 +1587,10 @@ void main() { LensFacing? requireLensFacing, dynamic cameraInfoForFilter, }) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); - final MockProcessCameraProvider - mockProcessCameraProviderForFrontCamera = + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera( + mockFrontCameraSelector, + ); + final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 90, @@ -1796,22 +1607,18 @@ void main() { mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: false, - getUiOrientation: /* initial device orientation irrelevant for test */ - () async => - _serializeDeviceOrientation(DeviceOrientation.landscapeLeft), - getDefaultDisplayRotation: () => - Future.value(Surface.rotation90), + getUiOrientation: /* initial device orientation irrelevant for test */ () async => + _serializeDeviceOrientation(DeviceOrientation.landscapeLeft), + getDefaultDisplayRotation: () => Future.value(Surface.rotation90), ); // Get and create test front camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Calculated according to: ((90 - 270 * 1 + 360) % 360) - cameraPreviewPreAppliedRotation. @@ -1829,21 +1636,15 @@ void main() { for (final DeviceOrientation currentDeviceOrientation in expectedRotationPerDeviceOrientation.keys) { - final testEvent = DeviceOrientationChangedEvent( - currentDeviceOrientation, - ); - AndroidCameraCameraX.deviceOrientationChangedStreamController.add( - testEvent, - ); + final testEvent = DeviceOrientationChangedEvent(currentDeviceOrientation); + AndroidCameraCameraX.deviceOrientationChangedStreamController.add(testEvent); await tester.pumpAndSettle(); // Verify Texture is rotated by expected clockwise degrees. final int expectedQuarterTurns = expectedRotationPerDeviceOrientation[currentDeviceOrientation]!; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -1904,10 +1705,10 @@ void main() { // Create and set up mock CameraSelector and mock ProcessCameraProvider for test back camera // with sensor orientation degrees 270. mockBackCameraSelector = MockCameraSelector(); - proxyCreateCameraSelectorForBackCamera = - createCameraSelectorForBackCamera(mockBackCameraSelector); - proxyGetDefaultDisplayRotation = () => - Future.value(Surface.rotation270); + proxyCreateCameraSelectorForBackCamera = createCameraSelectorForBackCamera( + mockBackCameraSelector, + ); + proxyGetDefaultDisplayRotation = () => Future.value(Surface.rotation270); testMediaSettings = const MediaSettings(); }); @@ -1917,8 +1718,7 @@ void main() { (WidgetTester tester) async { // Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees // 90 is available. - final MockProcessCameraProvider - mockProcessCameraProviderForBackCamera = + final MockProcessCameraProvider mockProcessCameraProviderForBackCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockBackCameraSelector, sensorRotationDegrees: 90, @@ -1937,14 +1737,12 @@ void main() { ); // Get and create test back camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -1956,9 +1754,7 @@ void main() { // 90 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the // default display rotation. const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -1978,8 +1774,7 @@ void main() { (WidgetTester tester) async { // Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees // 270 is available. - final MockProcessCameraProvider - mockProcessCameraProviderForBackCamera = + final MockProcessCameraProvider mockProcessCameraProviderForBackCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockBackCameraSelector, sensorRotationDegrees: 270, @@ -1998,14 +1793,12 @@ void main() { ); // Get and create test back camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -2017,9 +1810,7 @@ void main() { // 90 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the // default display rotation. const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); @@ -2056,8 +1847,7 @@ void main() { testSensorOrientation = 90; // Create mock for seting initial default display rotation to 180 degrees. - proxyGetDefaultDisplayRotation = () => - Future.value(Surface.rotation90); + proxyGetDefaultDisplayRotation = () => Future.value(Surface.rotation90); // Media settings to create camera; irrelevant for test. testMediaSettings = const MediaSettings(); @@ -2079,8 +1869,9 @@ void main() { LensFacing? requireLensFacing, dynamic cameraInfoForFilter, }) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera( + mockFrontCameraSelector, + ); setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -2091,14 +1882,12 @@ void main() { ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -2110,9 +1899,7 @@ void main() { // 270 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the // default display rotation. const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); // We expect a Transform widget to wrap the RotatedBox with the camera // preview to mirror the preview, since the front camera is being @@ -2120,8 +1907,7 @@ void main() { expect(rotatedBox.child, isA()); final transformedPreview = rotatedBox.child! as Transform; - final Matrix4 transformedPreviewMatrix = - transformedPreview.transform; + final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera // preview to be mirrored across the x-axis. @@ -2155,8 +1941,9 @@ void main() { LensFacing? requireLensFacing, dynamic cameraInfoForFilter, }) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForBackCamera(mockBackCameraSelector); + proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForBackCamera( + mockBackCameraSelector, + ); setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -2167,14 +1954,12 @@ void main() { ); // Get and create test camera. - final List availableCameras = await camera - .availableCameras(); + final List availableCameras = await camera.availableCameras(); expect(availableCameras.length, 1); - final int flutterSurfaceTextureId = await camera - .createCameraWithSettings( - availableCameras.first, - testMediaSettings, - ); + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); await camera.initializeCamera(flutterSurfaceTextureId); // Put camera preview in widget tree and pump one frame so that Future to retrieve @@ -2186,9 +1971,7 @@ void main() { // 270 is used in this calculation for the device orientation because it is the counter-clockwise degrees of the // default display rotation. const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = tester.widget( - find.byType(RotatedBox), - ); + final RotatedBox rotatedBox = tester.widget(find.byType(RotatedBox)); final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; expect(rotatedBox.child, isA()); expect((rotatedBox.child! as Texture).textureId, cameraId); diff --git a/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart b/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart index bb48c3a01ca1..5c7fbaf69fae 100644 --- a/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart +++ b/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart @@ -73,18 +73,14 @@ void main() { ); } - testWidgets('Capture specific image resolutions', ( - WidgetTester tester, - ) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + testWidgets('Capture specific image resolutions', (WidgetTester tester) async { + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final cameraDescription in cameras) { var previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { + for (final MapEntry preset in presetExpectedSizes.entries) { final controller = CameraController(cameraDescription, preset.key); await controller.initialize(); final bool presetExactlySupported = await testCaptureImageResolution( @@ -123,24 +119,17 @@ void main() { // Verify image dimensions are as expected expect(video, isNotNull); - return assertExpectedDimensions( - expectedSize, - Size(video.height, video.width), - ); + return assertExpectedDimensions(expectedSize, Size(video.height, video.width)); } - testWidgets('Capture specific video resolutions', ( - WidgetTester tester, - ) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + testWidgets('Capture specific video resolutions', (WidgetTester tester) async { + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final cameraDescription in cameras) { var previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { + for (final MapEntry preset in presetExpectedSizes.entries) { final controller = CameraController(cameraDescription, preset.key); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -159,17 +148,12 @@ void main() { }); testWidgets('Pause and resume video recording', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -198,8 +182,7 @@ void main() { sleep(const Duration(milliseconds: 500)); final XFile file = await controller.stopVideoRecording(); - final int recordingTime = - DateTime.now().millisecondsSinceEpoch - recordingStart; + final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; final videoFile = File(file.path); final videoController = VideoPlayerController.file(videoFile); @@ -211,17 +194,12 @@ void main() { }); testWidgets('Set description while recording', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.length < 2) { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -233,17 +211,12 @@ void main() { }); testWidgets('Set description', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.length < 2) { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); await controller.setDescription(cameras[1]); @@ -279,11 +252,8 @@ void main() { return completer.future; } - testWidgets('image streaming with imageFormatGroup', ( - WidgetTester tester, - ) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + testWidgets('image streaming with imageFormatGroup', (WidgetTester tester) async { + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } @@ -305,17 +275,12 @@ void main() { }); testWidgets('Recording with video streaming', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } - final controller = CameraController( - cameras[0], - ResolutionPreset.low, - enableAudio: false, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low, enableAudio: false); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -335,20 +300,14 @@ void main() { }); // Test fileFormat is respected when taking a picture. - testWidgets('Capture specific image output formats', ( - WidgetTester tester, - ) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + testWidgets('Capture specific image output formats', (WidgetTester tester) async { + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } for (final cameraDescription in cameras) { for (final ImageFileFormat fileFormat in ImageFileFormat.values) { - final controller = CameraController( - cameraDescription, - ResolutionPreset.low, - ); + final controller = CameraController(cameraDescription, ResolutionPreset.low); await controller.initialize(); await controller.setImageFileFormat(fileFormat); final XFile file = await controller.takePicture(); @@ -360,8 +319,7 @@ void main() { group('Camera settings', () { testWidgets('Control FPS', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } @@ -370,10 +328,7 @@ void main() { for (final fps in [10, 30]) { final controller = CameraController.withSettings( cameras.first, - mediaSettings: MediaSettings( - resolutionPreset: ResolutionPreset.medium, - fps: fps, - ), + mediaSettings: MediaSettings(resolutionPreset: ResolutionPreset.medium, fps: fps), ); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -401,8 +356,7 @@ void main() { }); testWidgets('Control video bitrate', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } @@ -443,8 +397,7 @@ void main() { }); testWidgets('Control audio bitrate', (WidgetTester tester) async { - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { return; } diff --git a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart index ed3a8e5a953d..662f5bf9d8fa 100644 --- a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart +++ b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart @@ -178,10 +178,7 @@ class CameraController extends ValueNotifier { ImageFormatGroup? imageFormatGroup, }) => CameraController.withSettings( cameraDescription, - mediaSettings: MediaSettings( - resolutionPreset: resolutionPreset, - enableAudio: enableAudio, - ), + mediaSettings: MediaSettings(resolutionPreset: resolutionPreset, enableAudio: enableAudio), imageFormatGroup: imageFormatGroup, ); @@ -212,8 +209,7 @@ class CameraController extends ValueNotifier { bool _isDisposed = false; StreamSubscription? _imageStreamSubscription; FutureOr? _initCalled; - StreamSubscription? - _deviceOrientationSubscription; + StreamSubscription? _deviceOrientationSubscription; /// The camera identifier with which the controller is associated. int get cameraId => _cameraId; @@ -224,16 +220,13 @@ class CameraController extends ValueNotifier { Future _initializeWithDescription(CameraDescription description) async { final initializeCompleter = Completer(); - _deviceOrientationSubscription = CameraPlatform.instance - .onDeviceOrientationChanged() - .listen((DeviceOrientationChangedEvent event) { - value = value.copyWith(deviceOrientation: event.orientation); - }); + _deviceOrientationSubscription = CameraPlatform.instance.onDeviceOrientationChanged().listen(( + DeviceOrientationChangedEvent event, + ) { + value = value.copyWith(deviceOrientation: event.orientation); + }); - _cameraId = await CameraPlatform.instance.createCameraWithSettings( - description, - mediaSettings, - ); + _cameraId = await CameraPlatform.instance.createCameraWithSettings(description, mediaSettings); unawaited( CameraPlatform.instance.onCameraInitialized(_cameraId).first.then(( @@ -252,8 +245,7 @@ class CameraController extends ValueNotifier { isInitialized: true, description: description, previewSize: await initializeCompleter.future.then( - (CameraInitializedEvent event) => - Size(event.previewWidth, event.previewHeight), + (CameraInitializedEvent event) => Size(event.previewWidth, event.previewHeight), ), exposureMode: await initializeCompleter.future.then( (CameraInitializedEvent event) => event.exposureMode, @@ -318,14 +310,12 @@ class CameraController extends ValueNotifier { } /// Start streaming images from platform camera. - Future startImageStream( - void Function(CameraImageData image) onAvailable, - ) async { - _imageStreamSubscription = CameraPlatform.instance - .onStreamedFrameAvailable(_cameraId) - .listen((CameraImageData imageData) { - onAvailable(imageData); - }); + Future startImageStream(void Function(CameraImageData image) onAvailable) async { + _imageStreamSubscription = CameraPlatform.instance.onStreamedFrameAvailable(_cameraId).listen(( + CameraImageData imageData, + ) { + onAvailable(imageData); + }); value = value.copyWith(isStreamingImages: true); } @@ -340,9 +330,7 @@ class CameraController extends ValueNotifier { /// /// The video is returned as a [XFile] after calling [stopVideoRecording]. /// Throws a [CameraException] if the capture fails. - Future startVideoRecording({ - void Function(CameraImageData image)? streamCallback, - }) async { + Future startVideoRecording({void Function(CameraImageData image)? streamCallback}) async { await CameraPlatform.instance.startVideoCapturing( VideoCaptureOptions(_cameraId, streamCallback: streamCallback), ); @@ -364,9 +352,7 @@ class CameraController extends ValueNotifier { await stopImageStream(); } - final XFile file = await CameraPlatform.instance.stopVideoRecording( - _cameraId, - ); + final XFile file = await CameraPlatform.instance.stopVideoRecording(_cameraId); value = value.copyWith( isRecordingVideo: false, recordingOrientation: const Optional.absent(), @@ -416,8 +402,7 @@ class CameraController extends ValueNotifier { ]); // Round to the closest step if needed - final double stepSize = await CameraPlatform.instance - .getExposureOffsetStepSize(_cameraId); + final double stepSize = await CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); if (stepSize > 0) { final double inv = 1.0 / stepSize; double roundedOffset = (offset * inv).roundToDouble() / inv; @@ -436,23 +421,16 @@ class CameraController extends ValueNotifier { /// /// If [orientation] is omitted, the current device orientation is used. Future lockCaptureOrientation() async { - await CameraPlatform.instance.lockCaptureOrientation( - _cameraId, - value.deviceOrientation, - ); + await CameraPlatform.instance.lockCaptureOrientation(_cameraId, value.deviceOrientation); value = value.copyWith( - lockedCaptureOrientation: Optional.of( - value.deviceOrientation, - ), + lockedCaptureOrientation: Optional.of(value.deviceOrientation), ); } /// Unlocks the capture orientation. Future unlockCaptureOrientation() async { await CameraPlatform.instance.unlockCaptureOrientation(_cameraId); - value = value.copyWith( - lockedCaptureOrientation: const Optional.absent(), - ); + value = value.copyWith(lockedCaptureOrientation: const Optional.absent()); } /// Sets the focus mode for taking pictures. @@ -559,9 +537,7 @@ class Optional extends IterableBase { /// /// The transformer must not return `null`. If it does, an [ArgumentError] is thrown. Optional transform(S Function(T? value) transformer) { - return _value == null - ? Optional.absent() - : Optional.of(transformer(_value)); + return _value == null ? Optional.absent() : Optional.of(transformer(_value)); } /// Transforms the Optional value. @@ -570,14 +546,11 @@ class Optional extends IterableBase { /// /// Returns [absent()] if the transformer returns `null`. Optional transformNullable(S? Function(T? value) transformer) { - return _value == null - ? Optional.absent() - : Optional.fromNullable(transformer(_value)); + return _value == null ? Optional.absent() : Optional.fromNullable(transformer(_value)); } @override - Iterator get iterator => - isPresent ? [_value as T].iterator : Iterable.empty().iterator; + Iterator get iterator => isPresent ? [_value as T].iterator : Iterable.empty().iterator; /// Delegates to the underlying [value] hashCode. @override @@ -589,8 +562,6 @@ class Optional extends IterableBase { @override String toString() { - return _value == null - ? 'Optional { absent }' - : 'Optional { value: $_value }'; + return _value == null ? 'Optional { absent }' : 'Optional { value: $_value }'; } } diff --git a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart index 0a768b340639..7e8d6438ff65 100644 --- a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart +++ b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart @@ -26,12 +26,9 @@ class CameraPreview extends StatelessWidget { valueListenable: controller, builder: (BuildContext context, Object? value, Widget? child) { final double cameraAspectRatio = - controller.value.previewSize!.width / - controller.value.previewSize!.height; + controller.value.previewSize!.width / controller.value.previewSize!.height; return AspectRatio( - aspectRatio: _isLandscape() - ? cameraAspectRatio - : (1 / cameraAspectRatio), + aspectRatio: _isLandscape() ? cameraAspectRatio : (1 / cameraAspectRatio), child: Stack( fit: StackFit.expand, children: [ diff --git a/packages/camera/camera_avfoundation/example/lib/main.dart b/packages/camera/camera_avfoundation/example/lib/main.dart index f9576b96398f..4268285101c9 100644 --- a/packages/camera/camera_avfoundation/example/lib/main.dart +++ b/packages/camera/camera_avfoundation/example/lib/main.dart @@ -138,8 +138,7 @@ class _CameraExampleHomeState extends State decoration: BoxDecoration( color: Colors.black, border: Border.all( - color: - controller != null && controller!.value.isRecordingVideo + color: controller != null && controller!.value.isRecordingVideo ? Colors.redAccent : Colors.grey, width: 3.0, @@ -155,9 +154,7 @@ class _CameraExampleHomeState extends State _modeControlRowWidget(), Padding( padding: const EdgeInsets.all(5.0), - child: Row( - children: [_cameraTogglesRowWidget(), _thumbnailWidget()], - ), + child: Row(children: [_cameraTogglesRowWidget(), _thumbnailWidget()]), ), ], ), @@ -171,11 +168,7 @@ class _CameraExampleHomeState extends State if (cameraController == null || !cameraController.value.isInitialized) { return const Text( 'Tap a camera', - style: TextStyle( - color: Colors.white, - fontSize: 24.0, - fontWeight: FontWeight.w900, - ), + style: TextStyle(color: Colors.white, fontSize: 24.0, fontWeight: FontWeight.w900), ); } else { return Listener( @@ -189,8 +182,7 @@ class _CameraExampleHomeState extends State behavior: HitTestBehavior.opaque, onScaleStart: _handleScaleStart, onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), + onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints), ); }, ), @@ -209,15 +201,9 @@ class _CameraExampleHomeState extends State return; } - _currentScale = (_baseScale * details.scale).clamp( - _minAvailableZoom, - _maxAvailableZoom, - ); + _currentScale = (_baseScale * details.scale).clamp(_minAvailableZoom, _maxAvailableZoom); - await CameraPlatform.instance.setZoomLevel( - controller!.cameraId, - _currentScale, - ); + await CameraPlatform.instance.setZoomLevel(controller!.cameraId, _currentScale); } /// Display the thumbnail of the captured image or video. @@ -242,13 +228,9 @@ class _CameraExampleHomeState extends State // pointing to a location within the browser. It may be displayed // either with Image.network or Image.memory after loading the image // bytes to memory. - kIsWeb - ? Image.network(imageFile!.path) - : Image.file(File(imageFile!.path))) + kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path))) : Container( - decoration: BoxDecoration( - border: Border.all(color: Colors.pink), - ), + decoration: BoxDecoration(border: Border.all(color: Colors.pink)), child: Center( child: AspectRatio( aspectRatio: localVideoController.value.aspectRatio, @@ -281,16 +263,12 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.exposure), color: Colors.blue, - onPressed: controller != null - ? onExposureModeButtonPressed - : null, + onPressed: controller != null ? onExposureModeButtonPressed : null, ), IconButton( icon: const Icon(Icons.filter_center_focus), color: Colors.blue, - onPressed: controller != null - ? onFocusModeButtonPressed - : null, + onPressed: controller != null ? onFocusModeButtonPressed : null, ), ] : [], @@ -306,9 +284,7 @@ class _CameraExampleHomeState extends State : Icons.screen_rotation, ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null, ), ], ), @@ -328,36 +304,28 @@ class _CameraExampleHomeState extends State children: [ IconButton( icon: const Icon(Icons.flash_off), - color: controller?.value.flashMode == FlashMode.off - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.off ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.off) : null, ), IconButton( icon: const Icon(Icons.flash_auto), - color: controller?.value.flashMode == FlashMode.auto - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.auto ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.auto) : null, ), IconButton( icon: const Icon(Icons.flash_on), - color: controller?.value.flashMode == FlashMode.always - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.always ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.always) : null, ), IconButton( icon: const Icon(Icons.highlight), - color: controller?.value.flashMode == FlashMode.torch - ? Colors.orange - : Colors.blue, + color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue, onPressed: controller != null ? () => onSetFlashModeButtonPressed(FlashMode.torch) : null, @@ -394,15 +362,11 @@ class _CameraExampleHomeState extends State TextButton( style: styleAuto, onPressed: controller != null - ? () => - onSetExposureModeButtonPressed(ExposureMode.auto) + ? () => onSetExposureModeButtonPressed(ExposureMode.auto) : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance.setExposurePoint( - controller!.cameraId, - null, - ); + CameraPlatform.instance.setExposurePoint(controller!.cameraId, null); showInSnackBar('Resetting exposure point'); } }, @@ -411,17 +375,13 @@ class _CameraExampleHomeState extends State TextButton( style: styleLocked, onPressed: controller != null - ? () => onSetExposureModeButtonPressed( - ExposureMode.locked, - ) + ? () => onSetExposureModeButtonPressed(ExposureMode.locked) : null, child: const Text('LOCKED'), ), TextButton( style: styleLocked, - onPressed: controller != null - ? () => controller!.setExposureOffset(0.0) - : null, + onPressed: controller != null ? () => controller!.setExposureOffset(0.0) : null, child: const Text('RESET OFFSET'), ), ], @@ -436,9 +396,7 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: - _minAvailableExposureOffset == - _maxAvailableExposureOffset + onChanged: _minAvailableExposureOffset == _maxAvailableExposureOffset ? null : setExposureOffset, ), @@ -454,9 +412,7 @@ class _CameraExampleHomeState extends State Widget _focusModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - foregroundColor: controller?.value.focusMode == FocusMode.auto - ? Colors.orange - : Colors.blue, + foregroundColor: controller?.value.focusMode == FocusMode.auto ? Colors.orange : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( foregroundColor: controller?.value.focusMode == FocusMode.locked @@ -482,10 +438,7 @@ class _CameraExampleHomeState extends State : null, onLongPress: () { if (controller != null) { - CameraPlatform.instance.setFocusPoint( - controller!.cameraId, - null, - ); + CameraPlatform.instance.setFocusPoint(controller!.cameraId, null); } showInSnackBar('Resetting focus point'); }, @@ -563,13 +516,10 @@ class _CameraExampleHomeState extends State ), IconButton( icon: const Icon(Icons.pause_presentation), - color: - cameraController != null && cameraController.value.isPreviewPaused + color: cameraController != null && cameraController.value.isPreviewPaused ? Colors.red : Colors.blue, - onPressed: cameraController == null - ? null - : onPausePreviewButtonPressed, + onPressed: cameraController == null ? null : onPausePreviewButtonPressed, ), ], ); @@ -615,9 +565,7 @@ class _CameraExampleHomeState extends State String timestamp() => DateTime.now().millisecondsSinceEpoch.toString(); void showInSnackBar(String message) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message))); } void onViewFinderTap(TapDownDetails details, BoxConstraints constraints) { @@ -643,9 +591,7 @@ class _CameraExampleHomeState extends State } } - Future _initializeCameraController( - CameraDescription cameraDescription, - ) async { + Future _initializeCameraController(CameraDescription cameraDescription) async { final cameraController = CameraController( cameraDescription, kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, @@ -670,14 +616,10 @@ class _CameraExampleHomeState extends State ? >[ CameraPlatform.instance .getMinExposureOffset(cameraController.cameraId) - .then( - (double value) => _minAvailableExposureOffset = value, - ), + .then((double value) => _minAvailableExposureOffset = value), CameraPlatform.instance .getMaxExposureOffset(cameraController.cameraId) - .then( - (double value) => _maxAvailableExposureOffset = value, - ), + .then((double value) => _maxAvailableExposureOffset = value), ] : >[], CameraPlatform.instance diff --git a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart index 3907ed89219b..aea36cd4c2d0 100644 --- a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart +++ b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart @@ -18,8 +18,7 @@ import 'utils.dart'; /// An iOS implementation of [CameraPlatform] based on AVFoundation. class AVFoundationCamera extends CameraPlatform { /// Creates a new AVFoundation-based [CameraPlatform] implementation instance. - AVFoundationCamera({@visibleForTesting CameraApi? api}) - : _hostApi = api ?? CameraApi(); + AVFoundationCamera({@visibleForTesting CameraApi? api}) : _hostApi = api ?? CameraApi(); /// Registers this class as the default instance of [CameraPlatform]. static void registerWith() { @@ -51,8 +50,7 @@ class AVFoundationCamera extends CameraPlatform { /// The per-camera handlers for messages that should be rebroadcast to /// clients as [CameraEvent]s. @visibleForTesting - final Map hostCameraHandlers = - {}; + final Map hostCameraHandlers = {}; // The stream to receive frames from the native code. StreamSubscription? _platformImageStreamSubscription; @@ -60,16 +58,13 @@ class AVFoundationCamera extends CameraPlatform { // The stream for vending frames to platform interface clients. StreamController? _frameStreamController; - Stream _cameraEvents(int cameraId) => cameraEventStreamController - .stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => + cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { try { - return (await _hostApi.getAvailableCameras()) - .map(cameraDescriptionFromPlatform) - .toList(); + return (await _hostApi.getAvailableCameras()).map(cameraDescriptionFromPlatform).toList(); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -94,9 +89,7 @@ class AVFoundationCamera extends CameraPlatform { return await _hostApi.create( cameraDescription.name, PlatformMediaSettings( - resolutionPreset: _pigeonResolutionPreset( - mediaSettings?.resolutionPreset, - ), + resolutionPreset: _pigeonResolutionPreset(mediaSettings?.resolutionPreset), framesPerSecond: mediaSettings?.fps, videoBitrate: mediaSettings?.videoBitrate, audioBitrate: mediaSettings?.audioBitrate, @@ -137,9 +130,7 @@ class AVFoundationCamera extends CameraPlatform { @override Future dispose(int cameraId) async { - final HostCameraMessageHandler? handler = hostCameraHandlers.remove( - cameraId, - ); + final HostCameraMessageHandler? handler = hostCameraHandlers.remove(cameraId); handler?.dispose(); await _hostApi.dispose(cameraId); @@ -177,13 +168,8 @@ class AVFoundationCamera extends CameraPlatform { } @override - Future lockCaptureOrientation( - int cameraId, - DeviceOrientation orientation, - ) async { - await _hostApi.lockCaptureOrientation( - serializeDeviceOrientation(orientation), - ); + Future lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async { + await _hostApi.lockCaptureOrientation(serializeDeviceOrientation(orientation)); } @override @@ -203,10 +189,7 @@ class AVFoundationCamera extends CameraPlatform { } @override - Future startVideoRecording( - int cameraId, { - Duration? maxVideoDuration, - }) async { + Future startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -247,15 +230,11 @@ class AVFoundationCamera extends CameraPlatform { int cameraId, { CameraImageStreamOptions? options, }) { - _frameStreamController = _createStreamController( - onListen: _onFrameStreamListen, - ); + _frameStreamController = _createStreamController(onListen: _onFrameStreamListen); return _frameStreamController!.stream; } - StreamController _createStreamController({ - void Function()? onListen, - }) { + StreamController _createStreamController({void Function()? onListen}) { return StreamController( onListen: onListen ?? () {}, onPause: _onFrameStreamPauseResume, @@ -376,13 +355,10 @@ class AVFoundationCamera extends CameraPlatform { } @override - Future setVideoStabilizationMode( - int cameraId, - VideoStabilizationMode mode, - ) async { + Future setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) async { try { - final Map - availableModes = await _getSupportedVideoStabilizationModeMap(cameraId); + final Map availableModes = + await _getSupportedVideoStabilizationModeMap(cameraId); final PlatformVideoStabilizationMode? platformMode = availableModes[mode]; if (platformMode == null) { @@ -395,9 +371,7 @@ class AVFoundationCamera extends CameraPlatform { } @override - Future> getSupportedVideoStabilizationModes( - int cameraId, - ) async { + Future> getSupportedVideoStabilizationModes(int cameraId) async { return (await _getSupportedVideoStabilizationModeMap(cameraId)).keys; } @@ -406,11 +380,9 @@ class AVFoundationCamera extends CameraPlatform { final ret = {}; for (final VideoStabilizationMode mode in VideoStabilizationMode.values) { - final PlatformVideoStabilizationMode? platformMode = - _pigeonVideoStabilizationMode(mode); + final PlatformVideoStabilizationMode? platformMode = _pigeonVideoStabilizationMode(mode); if (platformMode != null) { - final bool isSupported = await _hostApi - .isVideoStabilizationModeSupported(platformMode); + final bool isSupported = await _hostApi.isVideoStabilizationModeSupported(platformMode); if (isSupported) { ret[mode] = platformMode; } @@ -431,9 +403,7 @@ class AVFoundationCamera extends CameraPlatform { } @override - Future setDescriptionWhileRecording( - CameraDescription description, - ) async { + Future setDescriptionWhileRecording(CameraDescription description) async { await _hostApi.updateDescriptionWhileRecording(description.name); } @@ -503,9 +473,7 @@ class AVFoundationCamera extends CameraPlatform { } /// Returns a [ResolutionPreset]'s Pigeon representation. - PlatformResolutionPreset _pigeonResolutionPreset( - ResolutionPreset? resolutionPreset, - ) { + PlatformResolutionPreset _pigeonResolutionPreset(ResolutionPreset? resolutionPreset) { if (resolutionPreset == null) { // Provide a default if one isn't provided, since the native side needs // to set something. diff --git a/packages/camera/camera_avfoundation/lib/src/messages.g.dart b/packages/camera/camera_avfoundation/lib/src/messages.g.dart index 46c94d58f8a1..348ae53566a2 100644 --- a/packages/camera/camera_avfoundation/lib/src/messages.g.dart +++ b/packages/camera/camera_avfoundation/lib/src/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -75,12 +69,7 @@ enum PlatformCameraLensType { unknown, } -enum PlatformDeviceOrientation { - portraitUp, - landscapeLeft, - portraitDown, - landscapeRight, -} +enum PlatformDeviceOrientation { portraitUp, landscapeLeft, portraitDown, landscapeRight } enum PlatformExposureMode { auto, locked } @@ -95,12 +84,7 @@ enum PlatformImageFormatGroup { bgra8888, yuv420 } enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } -enum PlatformVideoStabilizationMode { - off, - standard, - cinematic, - cinematicExtended, -} +enum PlatformVideoStabilizationMode { off, standard, cinematic, cinematicExtended } class PlatformCameraDescription { PlatformCameraDescription({ @@ -138,8 +122,7 @@ class PlatformCameraDescription { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraDescription || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraDescription || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -328,8 +311,7 @@ class PlatformCameraImagePlane { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraImagePlane || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraImagePlane || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -363,13 +345,7 @@ class PlatformMediaSettings { bool enableAudio; List _toList() { - return [ - resolutionPreset, - framesPerSecond, - videoBitrate, - audioBitrate, - enableAudio, - ]; + return [resolutionPreset, framesPerSecond, videoBitrate, audioBitrate, enableAudio]; } Object encode() { @@ -458,10 +434,7 @@ class PlatformSize { static PlatformSize decode(Object result) { result as List; - return PlatformSize( - width: result[0]! as double, - height: result[1]! as double, - ); + return PlatformSize(width: result[0]! as double, height: result[1]! as double); } @override @@ -576,9 +549,7 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PlatformResolutionPreset.values[value]; case 138: final value = readValue(buffer) as int?; - return value == null - ? null - : PlatformVideoStabilizationMode.values[value]; + return value == null ? null : PlatformVideoStabilizationMode.values[value]; case 139: return PlatformCameraDescription.decode(readValue(buffer)!); case 140: @@ -599,21 +570,17 @@ class _PigeonCodec extends StandardMessageCodec { } } -const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( - _PigeonCodec(), -); +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec(_PigeonCodec()); class CameraApi { /// Constructor for [CameraApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - CameraApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + CameraApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -645,8 +612,7 @@ class CameraApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } @@ -659,9 +625,10 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraName, settings], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraName, + settings, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -682,10 +649,7 @@ class CameraApi { } /// Initializes the camera with the given ID. - Future initialize( - int cameraId, - PlatformImageFormatGroup imageFormat, - ) async { + Future initialize(int cameraId, PlatformImageFormatGroup imageFormat) async { final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.initialize$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -693,9 +657,10 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId, imageFormat], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraId, + imageFormat, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -795,9 +760,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -813,9 +776,7 @@ class CameraApi { } /// Locks the camera capture to the current device orientation. - Future lockCaptureOrientation( - PlatformDeviceOrientation orientation, - ) async { + Future lockCaptureOrientation(PlatformDeviceOrientation orientation) async { final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.lockCaptureOrientation$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -823,9 +784,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [orientation], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([orientation]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -929,9 +888,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enableStream], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enableStream]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1032,9 +989,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [mode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([mode]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1058,9 +1013,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [mode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([mode]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1086,9 +1039,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [point], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([point]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1170,9 +1121,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [offset], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([offset]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1196,9 +1145,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [mode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([mode]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1224,9 +1171,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [point], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([point]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1308,9 +1253,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [zoom], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([zoom]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1326,9 +1269,7 @@ class CameraApi { } /// Sets the video stabilization mode. - Future setVideoStabilizationMode( - PlatformVideoStabilizationMode mode, - ) async { + Future setVideoStabilizationMode(PlatformVideoStabilizationMode mode) async { final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setVideoStabilizationMode$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1336,9 +1277,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [mode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([mode]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1354,9 +1293,7 @@ class CameraApi { } /// Gets if the given video stabilization mode is supported. - Future isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode mode, - ) async { + Future isVideoStabilizationModeSupported(PlatformVideoStabilizationMode mode) async { final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.isVideoStabilizationModeSupported$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1364,9 +1301,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [mode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([mode]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1445,9 +1380,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraName], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraName]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1471,9 +1404,7 @@ class CameraApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [format], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([format]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1514,9 +1445,7 @@ abstract class CameraGlobalEventApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix', @@ -1574,9 +1503,7 @@ abstract class CameraEventApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized$messageChannelSuffix', @@ -1592,8 +1519,7 @@ abstract class CameraEventApi { 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized was null.', ); final List args = (message as List?)!; - final PlatformCameraState? arg_initialState = - (args[0] as PlatformCameraState?); + final PlatformCameraState? arg_initialState = (args[0] as PlatformCameraState?); assert( arg_initialState != null, 'Argument for dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized was null, expected non-null PlatformCameraState.', diff --git a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart index 7753f054b007..213b35508c09 100644 --- a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart +++ b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart @@ -18,18 +18,14 @@ CameraImageData cameraImageFromPlatformData(PlatformCameraImageData data) { sensorSensitivity: data.sensorSensitivity, planes: List.unmodifiable( data.planes.map( - (PlatformCameraImagePlane planeData) => - _cameraImagePlaneFromPlatformData(planeData), + (PlatformCameraImagePlane planeData) => _cameraImagePlaneFromPlatformData(planeData), ), ), ); } CameraImageFormat _cameraImageFormatFromPlatformImageFormat(int data) { - return CameraImageFormat( - _imageFormatGroupFromPlatformImageFormat(data), - raw: data, - ); + return CameraImageFormat(_imageFormatGroupFromPlatformImageFormat(data), raw: data); } ImageFormatGroup _imageFormatGroupFromPlatformImageFormat(int data) { @@ -44,9 +40,7 @@ ImageFormatGroup _imageFormatGroupFromPlatformImageFormat(int data) { return ImageFormatGroup.unknown; } -CameraImagePlane _cameraImagePlaneFromPlatformData( - PlatformCameraImagePlane data, -) { +CameraImagePlane _cameraImagePlaneFromPlatformData(PlatformCameraImagePlane data) { return CameraImagePlane( bytes: data.bytes, bytesPerRow: data.bytesPerRow, diff --git a/packages/camera/camera_avfoundation/lib/src/utils.dart b/packages/camera/camera_avfoundation/lib/src/utils.dart index 3308bcc6fd52..4e883cde84a8 100644 --- a/packages/camera/camera_avfoundation/lib/src/utils.dart +++ b/packages/camera/camera_avfoundation/lib/src/utils.dart @@ -8,9 +8,7 @@ import 'package:flutter/services.dart'; import 'messages.g.dart'; /// Creates a [CameraDescription] from a Pigeon [PlatformCameraDescription]. -CameraDescription cameraDescriptionFromPlatform( - PlatformCameraDescription camera, -) { +CameraDescription cameraDescriptionFromPlatform(PlatformCameraDescription camera) { return CameraDescription( name: camera.name, lensDirection: cameraLensDirectionFromPlatform(camera.lensDirection), @@ -20,9 +18,7 @@ CameraDescription cameraDescriptionFromPlatform( } /// Converts a Pigeon [PlatformCameraLensDirection] to a [CameraLensDirection]. -CameraLensDirection cameraLensDirectionFromPlatform( - PlatformCameraLensDirection direction, -) { +CameraLensDirection cameraLensDirectionFromPlatform(PlatformCameraLensDirection direction) { return switch (direction) { PlatformCameraLensDirection.front => CameraLensDirection.front, PlatformCameraLensDirection.back => CameraLensDirection.back, @@ -41,9 +37,7 @@ CameraLensType cameraLensTypeFromPlatform(PlatformCameraLensType type) { } /// Convents the given device orientation to Pigeon. -PlatformDeviceOrientation serializeDeviceOrientation( - DeviceOrientation orientation, -) { +PlatformDeviceOrientation serializeDeviceOrientation(DeviceOrientation orientation) { switch (orientation) { case DeviceOrientation.portraitUp: return PlatformDeviceOrientation.portraitUp; @@ -64,15 +58,12 @@ PlatformDeviceOrientation serializeDeviceOrientation( } /// Converts a Pigeon [PlatformDeviceOrientation] to a [DeviceOrientation]. -DeviceOrientation deviceOrientationFromPlatform( - PlatformDeviceOrientation orientation, -) { +DeviceOrientation deviceOrientationFromPlatform(PlatformDeviceOrientation orientation) { return switch (orientation) { PlatformDeviceOrientation.portraitUp => DeviceOrientation.portraitUp, PlatformDeviceOrientation.portraitDown => DeviceOrientation.portraitDown, PlatformDeviceOrientation.landscapeLeft => DeviceOrientation.landscapeLeft, - PlatformDeviceOrientation.landscapeRight => - DeviceOrientation.landscapeRight, + PlatformDeviceOrientation.landscapeRight => DeviceOrientation.landscapeRight, }; } diff --git a/packages/camera/camera_avfoundation/pigeons/messages.dart b/packages/camera/camera_avfoundation/pigeons/messages.dart index b4976758cf47..1a1208d2b10e 100644 --- a/packages/camera/camera_avfoundation/pigeons/messages.dart +++ b/packages/camera/camera_avfoundation/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - swiftOut: - 'ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift', + swiftOut: 'ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift', copyrightHeader: 'pigeons/copyright.txt', ), ) @@ -40,12 +39,7 @@ enum PlatformCameraLensType { } // Pigeon version of DeviceOrientation. -enum PlatformDeviceOrientation { - portraitUp, - landscapeLeft, - portraitDown, - landscapeRight, -} +enum PlatformDeviceOrientation { portraitUp, landscapeLeft, portraitDown, landscapeRight } // Pigeon version of ExposureMode. enum PlatformExposureMode { auto, locked } @@ -65,12 +59,7 @@ enum PlatformImageFormatGroup { bgra8888, yuv420 } // Pigeon version of ResolutionPreset. enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } -enum PlatformVideoStabilizationMode { - off, - standard, - cinematic, - cinematicExtended, -} +enum PlatformVideoStabilizationMode { off, standard, cinematic, cinematicExtended } // Pigeon version of CameraDescription. class PlatformCameraDescription { diff --git a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart index 53d7965c6bac..f9a844cfa184 100644 --- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart +++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart @@ -46,9 +46,7 @@ void main() { ); // Assert - final VerificationResult verification = verify( - mockApi.create(captureAny, captureAny), - ); + final VerificationResult verification = verify(mockApi.create(captureAny, captureAny)); expect(verification.captured[0], cameraName); final settings = verification.captured[1] as PlatformMediaSettings?; expect(settings, isNotNull); @@ -85,9 +83,7 @@ void main() { ); // Assert - final VerificationResult verification = verify( - mockApi.create(captureAny, captureAny), - ); + final VerificationResult verification = verify(mockApi.create(captureAny, captureAny)); expect(verification.captured[0], cameraName); final settings = verification.captured[1] as PlatformMediaSettings?; expect(settings, isNotNull); @@ -100,78 +96,58 @@ void main() { }, ); - test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - const exceptionCode = 'TESTING_ERROR_CODE'; - const exceptionMessage = 'Mock error message used during testing.'; - final mockApi = MockCameraApi(); - when(mockApi.create(any, any)).thenAnswer((_) async { - throw PlatformException( - code: exceptionCode, - message: exceptionMessage, - ); - }); - final camera = AVFoundationCamera(api: mockApi); + test('Should throw CameraException when create throws a PlatformException', () { + // Arrange + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); + when(mockApi.create(any, any)).thenAnswer((_) async { + throw PlatformException(code: exceptionCode, message: exceptionMessage); + }); + final camera = AVFoundationCamera(api: mockApi); - // Act - expect( - () => camera.createCamera( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ), - ResolutionPreset.high, - ), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', exceptionCode) - .having( - (CameraException e) => e.description, - 'description', - exceptionMessage, - ), + // Act + expect( + () => camera.createCamera( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, ), - ); - }, - ); + ResolutionPreset.high, + ), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', exceptionCode) + .having((CameraException e) => e.description, 'description', exceptionMessage), + ), + ); + }); - test( - 'Should throw CameraException when initialize throws a PlatformException', - () { - // Arrange - const exceptionCode = 'TESTING_ERROR_CODE'; - const exceptionMessage = 'Mock error message used during testing.'; - final mockApi = MockCameraApi(); - when(mockApi.initialize(any, any)).thenAnswer((_) async { - throw PlatformException( - code: exceptionCode, - message: exceptionMessage, - ); - }); - final camera = AVFoundationCamera(api: mockApi); + test('Should throw CameraException when initialize throws a PlatformException', () { + // Arrange + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); + when(mockApi.initialize(any, any)).thenAnswer((_) async { + throw PlatformException(code: exceptionCode, message: exceptionMessage); + }); + final camera = AVFoundationCamera(api: mockApi); - // Act - expect( - () => camera.initializeCamera(0), - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), - ), - ); - }, - ); + // Act + expect( + () => camera.initializeCamera(0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); test('Should send initialization data', () async { // Arrange @@ -189,22 +165,12 @@ void main() { // Act final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; // Assert - final VerificationResult verification = verify( - mockApi.initialize(captureAny, captureAny), - ); + final VerificationResult verification = verify(mockApi.initialize(captureAny, captureAny)); expect(verification.captured[0], cameraId); // The default when unspecified should be bgra8888. expect(verification.captured[1], PlatformImageFormatGroup.bgra8888); @@ -224,15 +190,7 @@ void main() { ); final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; @@ -240,9 +198,7 @@ void main() { await camera.dispose(cameraId); // Assert - final VerificationResult verification = verify( - mockApi.dispose(captureAny), - ); + final VerificationResult verification = verify(mockApi.dispose(captureAny)); expect(verification.captured[0], cameraId); }); }); @@ -264,23 +220,14 @@ void main() { ); final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; }); test('Should receive initialized event', () async { // Act - final Stream eventStream = camera - .onCameraInitialized(cameraId); + final Stream eventStream = camera.onCameraInitialized(cameraId); final streamQueue = StreamQueue(eventStream); final previewSize = PlatformSize(width: 3840, height: 2160); @@ -313,9 +260,7 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = camera.onCameraError( - cameraId, - ); + final Stream errorStream = camera.onCameraError(cameraId); final streamQueue = StreamQueue(errorStream); // Emit test events @@ -336,18 +281,13 @@ void main() { test('Should receive device orientation change events', () async { // Act - final Stream eventStream = camera - .onDeviceOrientationChanged(); - final streamQueue = StreamQueue( - eventStream, - ); + final Stream eventStream = camera.onDeviceOrientationChanged(); + final streamQueue = StreamQueue(eventStream); // Emit test events const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); for (var i = 0; i < 3; i++) { - camera.hostHandler.deviceOrientationChanged( - PlatformDeviceOrientation.portraitUp, - ); + camera.hostHandler.deviceOrientationChanged(PlatformDeviceOrientation.portraitUp); } // Assert @@ -379,78 +319,57 @@ void main() { ); final Future initializeFuture = camera.initializeCamera(cameraId); camera.cameraEventStreamController.add( - CameraInitializedEvent( - cameraId, - 1920, - 1080, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ), + CameraInitializedEvent(cameraId, 1920, 1080, ExposureMode.auto, true, FocusMode.auto, true), ); await initializeFuture; }); - test( - 'Should fetch CameraDescription instances for available cameras', - () async { - final returnData = [ - PlatformCameraDescription( - name: 'Test 1', - lensDirection: PlatformCameraLensDirection.front, - lensType: PlatformCameraLensType.ultraWide, - ), - PlatformCameraDescription( - name: 'Test 2', - lensDirection: PlatformCameraLensDirection.back, - lensType: PlatformCameraLensType.telephoto, - ), - ]; - when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData); - - final List cameras = await camera.availableCameras(); - - expect(cameras.length, returnData.length); - for (var i = 0; i < returnData.length; i++) { - expect(cameras[i].name, returnData[i].name); - expect( - cameras[i].lensDirection, - cameraLensDirectionFromPlatform(returnData[i].lensDirection), - ); - expect( - cameras[i].lensType, - cameraLensTypeFromPlatform(returnData[i].lensType), - ); - // This value isn't provided by the platform, so is hard-coded to 90. - expect(cameras[i].sensorOrientation, 90); - } - }, - ); + test('Should fetch CameraDescription instances for available cameras', () async { + final returnData = [ + PlatformCameraDescription( + name: 'Test 1', + lensDirection: PlatformCameraLensDirection.front, + lensType: PlatformCameraLensType.ultraWide, + ), + PlatformCameraDescription( + name: 'Test 2', + lensDirection: PlatformCameraLensDirection.back, + lensType: PlatformCameraLensType.telephoto, + ), + ]; + when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData); - test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - const code = 'TESTING_ERROR_CODE'; - const message = 'Mock error message used during testing.'; - when(mockApi.getAvailableCameras()).thenAnswer( - (_) async => throw PlatformException(code: code, message: message), - ); + final List cameras = await camera.availableCameras(); + expect(cameras.length, returnData.length); + for (var i = 0; i < returnData.length; i++) { + expect(cameras[i].name, returnData[i].name); expect( - camera.availableCameras, - throwsA( - isA() - .having((CameraException e) => e.code, 'code', code) - .having( - (CameraException e) => e.description, - 'description', - message, - ), - ), + cameras[i].lensDirection, + cameraLensDirectionFromPlatform(returnData[i].lensDirection), ); - }, - ); + expect(cameras[i].lensType, cameraLensTypeFromPlatform(returnData[i].lensType)); + // This value isn't provided by the platform, so is hard-coded to 90. + expect(cameras[i].sensorOrientation, 90); + } + }); + + test('Should throw CameraException when availableCameras throws a PlatformException', () { + const code = 'TESTING_ERROR_CODE'; + const message = 'Mock error message used during testing.'; + when( + mockApi.getAvailableCameras(), + ).thenAnswer((_) async => throw PlatformException(code: code, message: message)); + + expect( + camera.availableCameras, + throwsA( + isA() + .having((CameraException e) => e.code, 'code', code) + .having((CameraException e) => e.description, 'description', message), + ), + ); + }); test('Should take a picture and return an XFile instance', () async { const stubPath = '/test/path.jpg'; @@ -477,10 +396,7 @@ void main() { 'Should pass enableStream if callback is passed when starting recording a video', () async { await camera.startVideoCapturing( - VideoCaptureOptions( - cameraId, - streamCallback: (CameraImageData imageData) {}, - ), + VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}), ); verify(mockApi.startVideoRecording(true)); @@ -560,9 +476,7 @@ void main() { const point = Point(0.4, 0.6); await camera.setExposurePoint(cameraId, point); - final VerificationResult verification = verify( - mockApi.setExposurePoint(captureAny), - ); + final VerificationResult verification = verify(mockApi.setExposurePoint(captureAny)); final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint?.x, point.x); expect(passedPoint?.y, point.y); @@ -571,35 +485,25 @@ void main() { test('Should set the exposure point to null for reset', () async { await camera.setExposurePoint(cameraId, null); - final VerificationResult verification = verify( - mockApi.setExposurePoint(captureAny), - ); + final VerificationResult verification = verify(mockApi.setExposurePoint(captureAny)); final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint, null); }); test('Should get the min exposure offset', () async { const stubMinOffset = 2.0; - when( - mockApi.getMinExposureOffset(), - ).thenAnswer((_) async => stubMinOffset); + when(mockApi.getMinExposureOffset()).thenAnswer((_) async => stubMinOffset); - final double minExposureOffset = await camera.getMinExposureOffset( - cameraId, - ); + final double minExposureOffset = await camera.getMinExposureOffset(cameraId); expect(minExposureOffset, stubMinOffset); }); test('Should get the max exposure offset', () async { const stubMaxOffset = 2.0; - when( - mockApi.getMaxExposureOffset(), - ).thenAnswer((_) async => stubMaxOffset); + when(mockApi.getMaxExposureOffset()).thenAnswer((_) async => stubMaxOffset); - final double maxExposureOffset = await camera.getMaxExposureOffset( - cameraId, - ); + final double maxExposureOffset = await camera.getMaxExposureOffset(cameraId); expect(maxExposureOffset, stubMaxOffset); }); @@ -635,9 +539,7 @@ void main() { const point = Point(0.4, 0.6); await camera.setFocusPoint(cameraId, point); - final VerificationResult verification = verify( - mockApi.setFocusPoint(captureAny), - ); + final VerificationResult verification = verify(mockApi.setFocusPoint(captureAny)); final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint?.x, point.x); expect(passedPoint?.y, point.y); @@ -646,9 +548,7 @@ void main() { test('Should set the focus point to null for reset', () async { await camera.setFocusPoint(cameraId, null); - final VerificationResult verification = verify( - mockApi.setFocusPoint(captureAny), - ); + final VerificationResult verification = verify(mockApi.setFocusPoint(captureAny)); final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint, null); }); @@ -686,108 +586,65 @@ void main() { verify(mockApi.setZoomLevel(zoom)); }); - test( - 'Should throw CameraException when illegal zoom level is supplied', - () async { - const code = 'ZOOM_ERROR'; - const message = 'Illegal zoom error'; - when(mockApi.setZoomLevel(any)).thenAnswer( - (_) async => throw PlatformException(code: code, message: message), - ); - - expect( - () => camera.setZoomLevel(cameraId, -1.0), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', code) - .having( - (CameraException e) => e.description, - 'description', - message, - ), - ), - ); - }, - ); + test('Should throw CameraException when illegal zoom level is supplied', () async { + const code = 'ZOOM_ERROR'; + const message = 'Illegal zoom error'; + when( + mockApi.setZoomLevel(any), + ).thenAnswer((_) async => throw PlatformException(code: code, message: message)); + + expect( + () => camera.setZoomLevel(cameraId, -1.0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', code) + .having((CameraException e) => e.description, 'description', message), + ), + ); + }); test('Should set video stabilization mode to off', () async { when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.off, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.off), ).thenAnswer((_) async => true); - await camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.off, - ); + await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.off); - verify( - mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.off), - ); + verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.off)); }); test('Should set video stabilization mode to level1', () async { when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.standard, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.standard), ).thenAnswer((_) async => true); - await camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level1, - ); + await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1); - verify( - mockApi.setVideoStabilizationMode( - PlatformVideoStabilizationMode.standard, - ), - ); + verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.standard)); }); test('Should set video stabilization mode to cinematic', () async { when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.cinematic, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematic), ).thenAnswer((_) async => true); - await camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level2, - ); + await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level2); - verify( - mockApi.setVideoStabilizationMode( - PlatformVideoStabilizationMode.cinematic, - ), - ); + verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.cinematic)); }); test('Should set video stabilization mode to cinematicExtended', () async { when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.cinematicExtended, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematicExtended), ).thenAnswer((_) async => true); - await camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level3, - ); + await camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level3); - verify( - mockApi.setVideoStabilizationMode( - PlatformVideoStabilizationMode.cinematicExtended, - ), - ); + verify(mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.cinematicExtended)); }); test('Should get no video stabilization mode', () async { - when( - mockApi.isVideoStabilizationModeSupported(any), - ).thenAnswer((_) async => false); + when(mockApi.isVideoStabilizationModeSupported(any)).thenAnswer((_) async => false); final Iterable modes = await camera .getSupportedVideoStabilizationModes(cameraId); @@ -797,28 +654,21 @@ void main() { test('Should get off and standard video stabilization modes', () async { when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.off, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.off), ).thenAnswer((_) async => true); when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.standard, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.standard), ).thenAnswer((_) async => true); when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.cinematic, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematic), ).thenAnswer((_) async => false); when( - mockApi.isVideoStabilizationModeSupported( - PlatformVideoStabilizationMode.cinematicExtended, - ), + mockApi.isVideoStabilizationModeSupported(PlatformVideoStabilizationMode.cinematicExtended), ).thenAnswer((_) async => false); - final List modes = - (await camera.getSupportedVideoStabilizationModes(cameraId)).toList(); + final List modes = (await camera.getSupportedVideoStabilizationModes( + cameraId, + )).toList(); expect(modes, [ VideoStabilizationMode.off, @@ -827,12 +677,11 @@ void main() { }); test('Should get all video stabilization modes', () async { - when( - mockApi.isVideoStabilizationModeSupported(any), - ).thenAnswer((_) async => true); + when(mockApi.isVideoStabilizationModeSupported(any)).thenAnswer((_) async => true); - final List modes = - (await camera.getSupportedVideoStabilizationModes(cameraId)).toList(); + final List modes = (await camera.getSupportedVideoStabilizationModes( + cameraId, + )).toList(); expect(modes, [ VideoStabilizationMode.off, @@ -842,101 +691,48 @@ void main() { ]); }); - test( - 'Should throw ArgumentError when unavailable video stabilization mode is set', - () async { - when( - mockApi.isVideoStabilizationModeSupported(any), - ).thenAnswer((_) async => false); - - expect( - () => camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.off, - ), - throwsA( - isA().having( - (ArgumentError e) => e.name, - 'name', - 'mode', - ), - ), - ); - expect( - () => camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level1, - ), - throwsA( - isA().having( - (ArgumentError e) => e.name, - 'name', - 'mode', - ), - ), - ); - expect( - () => camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level2, - ), - throwsA( - isA().having( - (ArgumentError e) => e.name, - 'name', - 'mode', - ), - ), - ); - expect( - () => camera.setVideoStabilizationMode( - cameraId, - VideoStabilizationMode.level3, - ), - throwsA( - isA().having( - (ArgumentError e) => e.name, - 'name', - 'mode', - ), - ), - ); - }, - ); + test('Should throw ArgumentError when unavailable video stabilization mode is set', () async { + when(mockApi.isVideoStabilizationModeSupported(any)).thenAnswer((_) async => false); - test( - 'Should throw CameraException when illegal zoom level is supplied', - () async { - const code = 'ZOOM_ERROR'; - const message = 'Illegal zoom error'; - when(mockApi.setZoomLevel(any)).thenAnswer( - (_) async => throw PlatformException(code: code, message: message), - ); + expect( + () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.off), + throwsA(isA().having((ArgumentError e) => e.name, 'name', 'mode')), + ); + expect( + () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level1), + throwsA(isA().having((ArgumentError e) => e.name, 'name', 'mode')), + ); + expect( + () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level2), + throwsA(isA().having((ArgumentError e) => e.name, 'name', 'mode')), + ); + expect( + () => camera.setVideoStabilizationMode(cameraId, VideoStabilizationMode.level3), + throwsA(isA().having((ArgumentError e) => e.name, 'name', 'mode')), + ); + }); - expect( - () => camera.setZoomLevel(cameraId, -1.0), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', code) - .having( - (CameraException e) => e.description, - 'description', - message, - ), - ), - ); - }, - ); + test('Should throw CameraException when illegal zoom level is supplied', () async { + const code = 'ZOOM_ERROR'; + const message = 'Illegal zoom error'; + when( + mockApi.setZoomLevel(any), + ).thenAnswer((_) async => throw PlatformException(code: code, message: message)); + + expect( + () => camera.setZoomLevel(cameraId, -1.0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', code) + .having((CameraException e) => e.description, 'description', message), + ), + ); + }); test('Should lock the capture orientation', () async { - await camera.lockCaptureOrientation( - cameraId, - DeviceOrientation.portraitUp, - ); + await camera.lockCaptureOrientation(cameraId, DeviceOrientation.portraitUp); - verify( - mockApi.lockCaptureOrientation(PlatformDeviceOrientation.portraitUp), - ); + verify(mockApi.lockCaptureOrientation(PlatformDeviceOrientation.portraitUp)); }); test('Should unlock the capture orientation', () async { diff --git a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart index 225eac9931c6..33838fbfb9c1 100644 --- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart +++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart @@ -28,336 +28,253 @@ import 'package:mockito/src/dummies.dart' as _i3; /// See the documentation for Mockito's code generation for more information. class MockCameraApi extends _i1.Mock implements _i2.CameraApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); - - @override - _i4.Future> getAvailableCameras() => - (super.noSuchMethod( - Invocation.method(#getAvailableCameras, []), - returnValue: _i4.Future>.value( - <_i2.PlatformCameraDescription>[], - ), - returnValueForMissingStub: - _i4.Future>.value( - <_i2.PlatformCameraDescription>[], - ), - ) - as _i4.Future>); - - @override - _i4.Future create( - String? cameraName, - _i2.PlatformMediaSettings? settings, - ) => - (super.noSuchMethod( - Invocation.method(#create, [cameraName, settings]), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) - as _i4.Future); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future initialize( - int? cameraId, - _i2.PlatformImageFormatGroup? imageFormat, - ) => - (super.noSuchMethod( - Invocation.method(#initialize, [cameraId, imageFormat]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future> getAvailableCameras() => (super.noSuchMethod( + Invocation.method(#getAvailableCameras, []), + returnValue: _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + returnValueForMissingStub: _i4.Future>.value( + <_i2.PlatformCameraDescription>[], + ), + ) as _i4.Future>); @override - _i4.Future startImageStream() => + _i4.Future create(String? cameraName, _i2.PlatformMediaSettings? settings) => (super.noSuchMethod( - Invocation.method(#startImageStream, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#create, [cameraName, settings]), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) as _i4.Future); @override - _i4.Future stopImageStream() => + _i4.Future initialize(int? cameraId, _i2.PlatformImageFormatGroup? imageFormat) => (super.noSuchMethod( - Invocation.method(#stopImageStream, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#initialize, [cameraId, imageFormat]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future receivedImageStreamData() => - (super.noSuchMethod( - Invocation.method(#receivedImageStreamData, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future startImageStream() => (super.noSuchMethod( + Invocation.method(#startImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future dispose(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#dispose, [cameraId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future stopImageStream() => (super.noSuchMethod( + Invocation.method(#stopImageStream, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future lockCaptureOrientation( - _i2.PlatformDeviceOrientation? orientation, - ) => - (super.noSuchMethod( - Invocation.method(#lockCaptureOrientation, [orientation]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future receivedImageStreamData() => (super.noSuchMethod( + Invocation.method(#receivedImageStreamData, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future unlockCaptureOrientation() => - (super.noSuchMethod( - Invocation.method(#unlockCaptureOrientation, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future dispose(int? cameraId) => (super.noSuchMethod( + Invocation.method(#dispose, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future takePicture() => - (super.noSuchMethod( - Invocation.method(#takePicture, []), - returnValue: _i4.Future.value( - _i3.dummyValue(this, Invocation.method(#takePicture, [])), - ), - returnValueForMissingStub: _i4.Future.value( - _i3.dummyValue(this, Invocation.method(#takePicture, [])), - ), - ) - as _i4.Future); - - @override - _i4.Future prepareForVideoRecording() => + _i4.Future lockCaptureOrientation(_i2.PlatformDeviceOrientation? orientation) => (super.noSuchMethod( - Invocation.method(#prepareForVideoRecording, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#lockCaptureOrientation, [orientation]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future startVideoRecording(bool? enableStream) => - (super.noSuchMethod( - Invocation.method(#startVideoRecording, [enableStream]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future unlockCaptureOrientation() => (super.noSuchMethod( + Invocation.method(#unlockCaptureOrientation, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future stopVideoRecording() => - (super.noSuchMethod( - Invocation.method(#stopVideoRecording, []), - returnValue: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#stopVideoRecording, []), - ), - ), - returnValueForMissingStub: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#stopVideoRecording, []), - ), - ), - ) - as _i4.Future); - - @override - _i4.Future pauseVideoRecording() => - (super.noSuchMethod( - Invocation.method(#pauseVideoRecording, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future takePicture() => (super.noSuchMethod( + Invocation.method(#takePicture, []), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [])), + ), + ) as _i4.Future); @override - _i4.Future resumeVideoRecording() => - (super.noSuchMethod( - Invocation.method(#resumeVideoRecording, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future prepareForVideoRecording() => (super.noSuchMethod( + Invocation.method(#prepareForVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setFlashMode(_i2.PlatformFlashMode? mode) => - (super.noSuchMethod( - Invocation.method(#setFlashMode, [mode]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future startVideoRecording(bool? enableStream) => (super.noSuchMethod( + Invocation.method(#startVideoRecording, [enableStream]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setExposureMode(_i2.PlatformExposureMode? mode) => - (super.noSuchMethod( - Invocation.method(#setExposureMode, [mode]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future stopVideoRecording() => (super.noSuchMethod( + Invocation.method(#stopVideoRecording, []), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#stopVideoRecording, [])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#stopVideoRecording, [])), + ), + ) as _i4.Future); @override - _i4.Future setExposurePoint(_i2.PlatformPoint? point) => - (super.noSuchMethod( - Invocation.method(#setExposurePoint, [point]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future pauseVideoRecording() => (super.noSuchMethod( + Invocation.method(#pauseVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getMinExposureOffset() => - (super.noSuchMethod( - Invocation.method(#getMinExposureOffset, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future resumeVideoRecording() => (super.noSuchMethod( + Invocation.method(#resumeVideoRecording, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getMaxExposureOffset() => - (super.noSuchMethod( - Invocation.method(#getMaxExposureOffset, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future setFlashMode(_i2.PlatformFlashMode? mode) => (super.noSuchMethod( + Invocation.method(#setFlashMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setExposureOffset(double? offset) => - (super.noSuchMethod( - Invocation.method(#setExposureOffset, [offset]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setExposureMode(_i2.PlatformExposureMode? mode) => (super.noSuchMethod( + Invocation.method(#setExposureMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setFocusMode(_i2.PlatformFocusMode? mode) => - (super.noSuchMethod( - Invocation.method(#setFocusMode, [mode]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setExposurePoint(_i2.PlatformPoint? point) => (super.noSuchMethod( + Invocation.method(#setExposurePoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setFocusPoint(_i2.PlatformPoint? point) => - (super.noSuchMethod( - Invocation.method(#setFocusPoint, [point]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getMinExposureOffset() => (super.noSuchMethod( + Invocation.method(#getMinExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future getMinZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getMinZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getMaxExposureOffset() => (super.noSuchMethod( + Invocation.method(#getMaxExposureOffset, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future getMaxZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getMaxZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future setExposureOffset(double? offset) => (super.noSuchMethod( + Invocation.method(#setExposureOffset, [offset]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setZoomLevel(double? zoom) => - (super.noSuchMethod( - Invocation.method(#setZoomLevel, [zoom]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setFocusMode(_i2.PlatformFocusMode? mode) => (super.noSuchMethod( + Invocation.method(#setFocusMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setVideoStabilizationMode( - _i2.PlatformVideoStabilizationMode? mode, - ) => - (super.noSuchMethod( - Invocation.method(#setVideoStabilizationMode, [mode]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setFocusPoint(_i2.PlatformPoint? point) => (super.noSuchMethod( + Invocation.method(#setFocusPoint, [point]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future isVideoStabilizationModeSupported( - _i2.PlatformVideoStabilizationMode? mode, - ) => - (super.noSuchMethod( - Invocation.method(#isVideoStabilizationModeSupported, [mode]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future getMinZoomLevel() => (super.noSuchMethod( + Invocation.method(#getMinZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future pausePreview() => - (super.noSuchMethod( - Invocation.method(#pausePreview, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getMaxZoomLevel() => (super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future resumePreview() => - (super.noSuchMethod( - Invocation.method(#resumePreview, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setZoomLevel(double? zoom) => (super.noSuchMethod( + Invocation.method(#setZoomLevel, [zoom]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future updateDescriptionWhileRecording(String? cameraName) => + _i4.Future setVideoStabilizationMode(_i2.PlatformVideoStabilizationMode? mode) => (super.noSuchMethod( - Invocation.method(#updateDescriptionWhileRecording, [cameraName]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#setVideoStabilizationMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setImageFileFormat(_i2.PlatformImageFileFormat? format) => + _i4.Future isVideoStabilizationModeSupported(_i2.PlatformVideoStabilizationMode? mode) => (super.noSuchMethod( - Invocation.method(#setImageFileFormat, [format]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#isVideoStabilizationModeSupported, [mode]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); + + @override + _i4.Future pausePreview() => (super.noSuchMethod( + Invocation.method(#pausePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); + + @override + _i4.Future resumePreview() => (super.noSuchMethod( + Invocation.method(#resumePreview, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); + + @override + _i4.Future updateDescriptionWhileRecording(String? cameraName) => (super.noSuchMethod( + Invocation.method(#updateDescriptionWhileRecording, [cameraName]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); + + @override + _i4.Future setImageFileFormat(_i2.PlatformImageFileFormat? format) => (super.noSuchMethod( + Invocation.method(#setImageFileFormat, [format]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart b/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart index 78cd0ac4fd4e..06cbdafff3b2 100644 --- a/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart +++ b/packages/camera/camera_platform_interface/lib/src/events/camera_event.dart @@ -35,9 +35,7 @@ abstract class CameraEvent { @override bool operator ==(Object other) => identical(this, other) || - other is CameraEvent && - runtimeType == other.runtimeType && - cameraId == other.cameraId; + other is CameraEvent && runtimeType == other.runtimeType && cameraId == other.cameraId; @override int get hashCode => cameraId.hashCode; @@ -66,8 +64,7 @@ class CameraInitializedEvent extends CameraEvent { : previewWidth = json['previewWidth']! as double, previewHeight = json['previewHeight']! as double, exposureMode = deserializeExposureMode(json['exposureMode']! as String), - exposurePointSupported = - (json['exposurePointSupported'] as bool?) ?? false, + exposurePointSupported = (json['exposurePointSupported'] as bool?) ?? false, focusMode = deserializeFocusMode(json['focusMode']! as String), focusPointSupported = (json['focusPointSupported'] as bool?) ?? false, super(json['cameraId']! as int); @@ -134,11 +131,7 @@ class CameraResolutionChangedEvent extends CameraEvent { /// /// The `captureWidth` represents the width of the resulting image in pixels. /// The `captureHeight` represents the height of the resulting image in pixels. - const CameraResolutionChangedEvent( - super.cameraId, - this.captureWidth, - this.captureHeight, - ); + const CameraResolutionChangedEvent(super.cameraId, this.captureWidth, this.captureHeight); /// Converts the supplied [Map] to an instance of the /// [CameraResolutionChangedEvent] class. @@ -182,8 +175,7 @@ class CameraClosingEvent extends CameraEvent { /// Converts the supplied [Map] to an instance of the [CameraClosingEvent] /// class. - CameraClosingEvent.fromJson(Map json) - : super(json['cameraId']! as int); + CameraClosingEvent.fromJson(Map json) : super(json['cameraId']! as int); /// Converts the [CameraClosingEvent] instance into a [Map] instance that can /// be serialized to JSON. @@ -192,9 +184,7 @@ class CameraClosingEvent extends CameraEvent { @override bool operator ==(Object other) => identical(this, other) || - super == other && - other is CameraClosingEvent && - runtimeType == other.runtimeType; + super == other && other is CameraClosingEvent && runtimeType == other.runtimeType; @override // This is here even though it just calls super to make it less likely that diff --git a/packages/camera/camera_platform_interface/lib/src/events/device_event.dart b/packages/camera/camera_platform_interface/lib/src/events/device_event.dart index 1751363f469d..7b3975e35335 100644 --- a/packages/camera/camera_platform_interface/lib/src/events/device_event.dart +++ b/packages/camera/camera_platform_interface/lib/src/events/device_event.dart @@ -34,9 +34,7 @@ class DeviceOrientationChangedEvent extends DeviceEvent { /// Converts the supplied [Map] to an instance of the [DeviceOrientationChangedEvent] /// class. DeviceOrientationChangedEvent.fromJson(Map json) - : orientation = deserializeDeviceOrientation( - json['orientation']! as String, - ); + : orientation = deserializeDeviceOrientation(json['orientation']! as String); /// The new orientation of the device final DeviceOrientation orientation; diff --git a/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart b/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart index 97c4107668f5..7423ebb1c83e 100644 --- a/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart +++ b/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart @@ -21,9 +21,7 @@ class MethodChannelCamera extends CameraPlatform { /// Construct a new method channel camera instance. MethodChannelCamera() { const channel = MethodChannel('flutter.io/cameraPlugin/device'); - channel.setMethodCallHandler( - (MethodCall call) => handleDeviceMethodCall(call), - ); + channel.setMethodCallHandler((MethodCall call) => handleDeviceMethodCall(call)); } final Map _channels = {}; @@ -56,9 +54,8 @@ class MethodChannelCamera extends CameraPlatform { // The stream for vending frames to platform interface clients. StreamController? _frameStreamController; - Stream _cameraEvents(int cameraId) => cameraEventStreamController - .stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => + cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { @@ -73,9 +70,7 @@ class MethodChannelCamera extends CameraPlatform { return cameras.map((Map camera) { return CameraDescription( name: camera['name']! as String, - lensDirection: parseCameraLensDirection( - camera['lensFacing']! as String, - ), + lensDirection: parseCameraLensDirection(camera['lensFacing']! as String), sensorOrientation: camera['sensorOrientation']! as int, ); }).toList(); @@ -126,9 +121,7 @@ class MethodChannelCamera extends CameraPlatform { }) { _channels.putIfAbsent(cameraId, () { final channel = MethodChannel('flutter.io/cameraPlugin/camera$cameraId'); - channel.setMethodCallHandler( - (MethodCall call) => handleCameraMethodCall(call, cameraId), - ); + channel.setMethodCallHandler((MethodCall call) => handleCameraMethodCall(call, cameraId)); return channel; }); @@ -153,10 +146,7 @@ class MethodChannelCamera extends CameraPlatform { // ignore: only_throw_errors throw error; } - completer.completeError( - CameraException(error.code, error.message), - stackTrace, - ); + completer.completeError(CameraException(error.code, error.message), stackTrace); }, ); @@ -171,9 +161,7 @@ class MethodChannelCamera extends CameraPlatform { _channels.remove(cameraId); } - await _channel.invokeMethod('dispose', { - 'cameraId': cameraId, - }); + await _channel.invokeMethod('dispose', {'cameraId': cameraId}); } @override @@ -203,38 +191,29 @@ class MethodChannelCamera extends CameraPlatform { @override Stream onDeviceOrientationChanged() { - return deviceEventStreamController.stream - .whereType(); + return deviceEventStreamController.stream.whereType(); } @override - Future lockCaptureOrientation( - int cameraId, - DeviceOrientation orientation, - ) async { - await _channel.invokeMethod( - 'lockCaptureOrientation', - { - 'cameraId': cameraId, - 'orientation': serializeDeviceOrientation(orientation), - }, - ); + Future lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async { + await _channel.invokeMethod('lockCaptureOrientation', { + 'cameraId': cameraId, + 'orientation': serializeDeviceOrientation(orientation), + }); } @override Future unlockCaptureOrientation(int cameraId) async { - await _channel.invokeMethod( - 'unlockCaptureOrientation', - {'cameraId': cameraId}, - ); + await _channel.invokeMethod('unlockCaptureOrientation', { + 'cameraId': cameraId, + }); } @override Future takePicture(int cameraId) async { - final String? path = await _channel.invokeMethod( - 'takePicture', - {'cameraId': cameraId}, - ); + final String? path = await _channel.invokeMethod('takePicture', { + 'cameraId': cameraId, + }); if (path == null) { throw CameraException( @@ -251,13 +230,8 @@ class MethodChannelCamera extends CameraPlatform { _channel.invokeMethod('prepareForVideoRecording'); @override - Future startVideoRecording( - int cameraId, { - Duration? maxVideoDuration, - }) async { - return startVideoCapturing( - VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration), - ); + Future startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async { + return startVideoCapturing(VideoCaptureOptions(cameraId, maxDuration: maxVideoDuration)); } @override @@ -292,16 +266,12 @@ class MethodChannelCamera extends CameraPlatform { } @override - Future pauseVideoRecording(int cameraId) => _channel.invokeMethod( - 'pauseVideoRecording', - {'cameraId': cameraId}, - ); + Future pauseVideoRecording(int cameraId) => + _channel.invokeMethod('pauseVideoRecording', {'cameraId': cameraId}); @override Future resumeVideoRecording(int cameraId) => - _channel.invokeMethod('resumeVideoRecording', { - 'cameraId': cameraId, - }); + _channel.invokeMethod('resumeVideoRecording', {'cameraId': cameraId}); @override Stream onStreamedFrameAvailable( @@ -312,9 +282,7 @@ class MethodChannelCamera extends CameraPlatform { return _frameStreamController!.stream; } - StreamController _installStreamController({ - void Function()? onListen, - }) { + StreamController _installStreamController({void Function()? onListen}) { _frameStreamController = StreamController( onListen: onListen ?? () {}, onPause: _onFrameStreamPauseResume, @@ -334,23 +302,19 @@ class MethodChannelCamera extends CameraPlatform { } void _startStreamListener() { - const cameraEventChannel = EventChannel( - 'plugins.flutter.io/camera/imageStream', - ); - _platformImageStreamSubscription = cameraEventChannel - .receiveBroadcastStream() - .listen((dynamic imageData) { - if (defaultTargetPlatform == TargetPlatform.iOS) { - try { - _channel.invokeMethod('receivedImageStreamData'); - } on PlatformException catch (e) { - throw CameraException(e.code, e.message); - } - } - _frameStreamController!.add( - cameraImageFromPlatformData(imageData as Map), - ); - }); + const cameraEventChannel = EventChannel('plugins.flutter.io/camera/imageStream'); + _platformImageStreamSubscription = cameraEventChannel.receiveBroadcastStream().listen(( + dynamic imageData, + ) { + if (defaultTargetPlatform == TargetPlatform.iOS) { + try { + _channel.invokeMethod('receivedImageStreamData'); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + _frameStreamController!.add(cameraImageFromPlatformData(imageData as Map)); + }); } FutureOr _onFrameStreamCancel() async { @@ -368,18 +332,16 @@ class MethodChannelCamera extends CameraPlatform { } @override - Future setFlashMode(int cameraId, FlashMode mode) => - _channel.invokeMethod('setFlashMode', { - 'cameraId': cameraId, - 'mode': _serializeFlashMode(mode), - }); + Future setFlashMode(int cameraId, FlashMode mode) => _channel.invokeMethod( + 'setFlashMode', + {'cameraId': cameraId, 'mode': _serializeFlashMode(mode)}, + ); @override - Future setExposureMode(int cameraId, ExposureMode mode) => - _channel.invokeMethod('setExposureMode', { - 'cameraId': cameraId, - 'mode': serializeExposureMode(mode), - }); + Future setExposureMode(int cameraId, ExposureMode mode) => _channel.invokeMethod( + 'setExposureMode', + {'cameraId': cameraId, 'mode': serializeExposureMode(mode)}, + ); @override Future setExposurePoint(int cameraId, Point? point) { @@ -435,11 +397,10 @@ class MethodChannelCamera extends CameraPlatform { } @override - Future setFocusMode(int cameraId, FocusMode mode) => - _channel.invokeMethod('setFocusMode', { - 'cameraId': cameraId, - 'mode': serializeFocusMode(mode), - }); + Future setFocusMode(int cameraId, FocusMode mode) => _channel.invokeMethod( + 'setFocusMode', + {'cameraId': cameraId, 'mode': serializeFocusMode(mode)}, + ); @override Future setFocusPoint(int cameraId, Point? point) { @@ -488,26 +449,19 @@ class MethodChannelCamera extends CameraPlatform { @override Future pausePreview(int cameraId) async { - await _channel.invokeMethod('pausePreview', { - 'cameraId': cameraId, - }); + await _channel.invokeMethod('pausePreview', {'cameraId': cameraId}); } @override Future resumePreview(int cameraId) async { - await _channel.invokeMethod('resumePreview', { - 'cameraId': cameraId, - }); + await _channel.invokeMethod('resumePreview', {'cameraId': cameraId}); } @override - Future setDescriptionWhileRecording( - CameraDescription description, - ) async { - await _channel.invokeMethod( - 'setDescriptionWhileRecording', - {'cameraName': description.name}, - ); + Future setDescriptionWhileRecording(CameraDescription description) async { + await _channel.invokeMethod('setDescriptionWhileRecording', { + 'cameraName': description.name, + }); } @override diff --git a/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart b/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart index 457d7d00ccb4..b7eaa0b02994 100644 --- a/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart +++ b/packages/camera/camera_platform_interface/lib/src/method_channel/type_conversion.dart @@ -18,9 +18,8 @@ CameraImageData cameraImageFromPlatformData(Map data) { sensorSensitivity: data['sensorSensitivity'] as double?, planes: List.unmodifiable( (data['planes'] as List).map( - (dynamic planeData) => _cameraImagePlaneFromPlatformData( - planeData as Map, - ), + (dynamic planeData) => + _cameraImagePlaneFromPlatformData(planeData as Map), ), ), ); diff --git a/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart b/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart index 192bce8b0134..efb1576cee82 100644 --- a/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart +++ b/packages/camera/camera_platform_interface/lib/src/platform_interface/camera_platform.dart @@ -113,16 +113,11 @@ abstract class CameraPlatform extends PlatformInterface { /// Implementations for this: /// - Should support all 4 orientations. Stream onDeviceOrientationChanged() { - throw UnimplementedError( - 'onDeviceOrientationChanged() is not implemented.', - ); + throw UnimplementedError('onDeviceOrientationChanged() is not implemented.'); } /// Locks the capture orientation. - Future lockCaptureOrientation( - int cameraId, - DeviceOrientation orientation, - ) { + Future lockCaptureOrientation(int cameraId, DeviceOrientation orientation) { throw UnimplementedError('lockCaptureOrientation() is not implemented.'); } @@ -146,9 +141,7 @@ abstract class CameraPlatform extends PlatformInterface { /// This method is deprecated in favour of [startVideoCapturing]. Future startVideoRecording( int cameraId, { - @Deprecated( - 'This parameter is unused, and will be ignored on all platforms', - ) + @Deprecated('This parameter is unused, and will be ignored on all platforms') Duration? maxVideoDuration, }) { throw UnimplementedError('startVideoRecording() is not implemented.'); @@ -282,15 +275,11 @@ abstract class CameraPlatform extends PlatformInterface { } /// Gets a list of video stabilization modes that are supported for the selected camera. - Future> getSupportedVideoStabilizationModes( - int cameraId, - ) => Future>.value([]); + Future> getSupportedVideoStabilizationModes(int cameraId) => + Future>.value([]); /// Sets the video stabilization mode for the selected camera. - Future setVideoStabilizationMode( - int cameraId, - VideoStabilizationMode mode, - ) { + Future setVideoStabilizationMode(int cameraId, VideoStabilizationMode mode) { throw UnimplementedError('setVideoStabilizationMode() is not implemented.'); } @@ -298,9 +287,7 @@ abstract class CameraPlatform extends PlatformInterface { /// /// This method returns the video stabilization mode that [setVideoStabilizationMode] /// should set when the device does not support the given [mode]. - static VideoStabilizationMode? getFallbackVideoStabilizationMode( - VideoStabilizationMode mode, - ) { + static VideoStabilizationMode? getFallbackVideoStabilizationMode(VideoStabilizationMode mode) { return switch (mode) { VideoStabilizationMode.off => null, VideoStabilizationMode.level1 => VideoStabilizationMode.off, @@ -325,9 +312,7 @@ abstract class CameraPlatform extends PlatformInterface { /// with `enablePersistentRecording` set to `true` /// to avoid cancelling any active recording. Future setDescriptionWhileRecording(CameraDescription description) { - throw UnimplementedError( - 'setDescriptionWhileRecording() is not implemented.', - ); + throw UnimplementedError('setDescriptionWhileRecording() is not implemented.'); } /// Returns a widget showing a live camera preview. diff --git a/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart b/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart index 579f7b8867c3..8f84e8fd2284 100644 --- a/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart +++ b/packages/camera/camera_platform_interface/lib/src/types/media_settings.dart @@ -61,13 +61,7 @@ class MediaSettings { } @override - int get hashCode => Object.hash( - resolutionPreset, - fps, - videoBitrate, - audioBitrate, - enableAudio, - ); + int get hashCode => Object.hash(resolutionPreset, fps, videoBitrate, audioBitrate, enableAudio); @override String toString() { diff --git a/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart b/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart index dda06fb4ce84..d5e38e8cc49a 100644 --- a/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart +++ b/packages/camera/camera_platform_interface/lib/src/types/video_capture_options.dart @@ -12,10 +12,7 @@ class VideoCaptureOptions { /// Constructs a new instance. const VideoCaptureOptions( this.cameraId, { - @Deprecated( - 'This parameter is unused, and will be ignored on all platforms', - ) - this.maxDuration, + @Deprecated('This parameter is unused, and will be ignored on all platforms') this.maxDuration, this.streamCallback, this.streamOptions, this.enablePersistentRecording = true, @@ -67,11 +64,6 @@ class VideoCaptureOptions { enablePersistentRecording == other.enablePersistentRecording; @override - int get hashCode => Object.hash( - cameraId, - maxDuration, - streamCallback, - streamOptions, - enablePersistentRecording, - ); + int get hashCode => + Object.hash(cameraId, maxDuration, streamCallback, streamOptions, enablePersistentRecording); } diff --git a/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart b/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart index 8453772f2441..787122cf316b 100644 --- a/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart +++ b/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart @@ -32,72 +32,45 @@ void main() { CameraPlatform.instance = ExtendsCameraPlatform(); }); - test( - 'Default implementation of availableCameras() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of availableCameras() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.availableCameras(), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.availableCameras(), throwsUnimplementedError); + }); - test( - 'Default implementation of onCameraInitialized() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of onCameraInitialized() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onCameraInitialized(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.onCameraInitialized(1), throwsUnimplementedError); + }); - test( - 'Default implementation of onResolutionChanged() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of onResolutionChanged() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onCameraResolutionChanged(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.onCameraResolutionChanged(1), throwsUnimplementedError); + }); - test( - 'Default implementation of onCameraClosing() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of onCameraClosing() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.onCameraClosing(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.onCameraClosing(1), throwsUnimplementedError); + }); - test( - 'Default implementation of onCameraError() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of onCameraError() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect(() => cameraPlatform.onCameraError(1), throwsUnimplementedError); - }, - ); + // Act & Assert + expect(() => cameraPlatform.onCameraError(1), throwsUnimplementedError); + }); test( 'Default implementation of onDeviceOrientationChanged() should throw unimplemented error', @@ -106,29 +79,20 @@ void main() { final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert - expect( - () => cameraPlatform.onDeviceOrientationChanged(), - throwsUnimplementedError, - ); + expect(() => cameraPlatform.onDeviceOrientationChanged(), throwsUnimplementedError); }, ); - test( - 'Default implementation of lockCaptureOrientation() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of lockCaptureOrientation() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.lockCaptureOrientation( - 1, - DeviceOrientation.portraitUp, - ), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect( + () => cameraPlatform.lockCaptureOrientation(1, DeviceOrientation.portraitUp), + throwsUnimplementedError, + ); + }); test( 'Default implementation of unlockCaptureOrientation() should throw unimplemented error', @@ -137,44 +101,35 @@ void main() { final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert - expect( - () => cameraPlatform.unlockCaptureOrientation(1), - throwsUnimplementedError, - ); + expect(() => cameraPlatform.unlockCaptureOrientation(1), throwsUnimplementedError); }, ); - test( - 'Default implementation of dispose() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of dispose() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect(() => cameraPlatform.dispose(1), throwsUnimplementedError); - }, - ); - - test( - 'Default implementation of createCamera() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + // Act & Assert + expect(() => cameraPlatform.dispose(1), throwsUnimplementedError); + }); - // Act & Assert - expect( - () => cameraPlatform.createCamera( - const CameraDescription( - name: 'back', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ), - ResolutionPreset.low, + test('Default implementation of createCamera() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); + + // Act & Assert + expect( + () => cameraPlatform.createCamera( + const CameraDescription( + name: 'back', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, ), - throwsUnimplementedError, - ); - }, - ); + ResolutionPreset.low, + ), + throwsUnimplementedError, + ); + }); test( 'Default implementation of createCameraWithSettings() should call createCamera() passing parameters', @@ -201,30 +156,19 @@ void main() { ResolutionPreset? resolutionPresetArg, bool enableAudioArg, ) { - expect( - cameraDescriptionArg, - cameraDescription, - reason: 'should pass camera description', - ); + expect(cameraDescriptionArg, cameraDescription, reason: 'should pass camera description'); expect( resolutionPresetArg, mediaSettings.resolutionPreset, reason: 'should pass resolution preset', ); - expect( - enableAudioArg, - mediaSettings.enableAudio, - reason: 'should pass enableAudio', - ); + expect(enableAudioArg, mediaSettings.enableAudio, reason: 'should pass enableAudio'); createCameraCalled = true; }); // Act & Assert - cameraPlatform.createCameraWithSettings( - cameraDescription, - mediaSettings, - ); + cameraPlatform.createCameraWithSettings(cameraDescription, mediaSettings); expect( createCameraCalled, @@ -235,33 +179,21 @@ void main() { }, ); - test( - 'Default implementation of initializeCamera() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of initializeCamera() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.initializeCamera(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.initializeCamera(1), throwsUnimplementedError); + }); - test( - 'Default implementation of pauseVideoRecording() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of pauseVideoRecording() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.pauseVideoRecording(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.pauseVideoRecording(1), throwsUnimplementedError); + }); test( 'Default implementation of prepareForVideoRecording() should throw unimplemented error', @@ -270,96 +202,57 @@ void main() { final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert - expect( - () => cameraPlatform.prepareForVideoRecording(), - throwsUnimplementedError, - ); + expect(() => cameraPlatform.prepareForVideoRecording(), throwsUnimplementedError); }, ); - test( - 'Default implementation of resumeVideoRecording() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of resumeVideoRecording() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.resumeVideoRecording(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.resumeVideoRecording(1), throwsUnimplementedError); + }); - test( - 'Default implementation of setFlashMode() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setFlashMode() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setFlashMode(1, FlashMode.auto), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setFlashMode(1, FlashMode.auto), throwsUnimplementedError); + }); - test( - 'Default implementation of setExposureMode() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setExposureMode() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setExposureMode(1, ExposureMode.auto), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setExposureMode(1, ExposureMode.auto), throwsUnimplementedError); + }); - test( - 'Default implementation of setExposurePoint() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setExposurePoint() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setExposurePoint(1, null), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setExposurePoint(1, null), throwsUnimplementedError); + }); - test( - 'Default implementation of getMinExposureOffset() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of getMinExposureOffset() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMinExposureOffset(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.getMinExposureOffset(1), throwsUnimplementedError); + }); - test( - 'Default implementation of getMaxExposureOffset() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of getMaxExposureOffset() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMaxExposureOffset(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.getMaxExposureOffset(1), throwsUnimplementedError); + }); test( 'Default implementation of getExposureOffsetStepSize() should throw unimplemented error', @@ -368,221 +261,142 @@ void main() { final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert - expect( - () => cameraPlatform.getExposureOffsetStepSize(1), - throwsUnimplementedError, - ); + expect(() => cameraPlatform.getExposureOffsetStepSize(1), throwsUnimplementedError); }, ); - test( - 'Default implementation of setExposureOffset() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setExposureOffset() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setExposureOffset(1, 2.0), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setExposureOffset(1, 2.0), throwsUnimplementedError); + }); - test( - 'Default implementation of setFocusMode() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setFocusMode() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setFocusMode(1, FocusMode.auto), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setFocusMode(1, FocusMode.auto), throwsUnimplementedError); + }); - test( - 'Default implementation of setFocusPoint() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setFocusPoint() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setFocusPoint(1, null), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setFocusPoint(1, null), throwsUnimplementedError); + }); - test( - 'Default implementation of startVideoRecording() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of startVideoRecording() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.startVideoRecording(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.startVideoRecording(1), throwsUnimplementedError); + }); - test( - 'Default implementation of stopVideoRecording() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of stopVideoRecording() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.stopVideoRecording(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.stopVideoRecording(1), throwsUnimplementedError); + }); - test( - 'Default implementation of takePicture() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of takePicture() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect(() => cameraPlatform.takePicture(1), throwsUnimplementedError); - }, - ); + // Act & Assert + expect(() => cameraPlatform.takePicture(1), throwsUnimplementedError); + }); - test( - 'Default implementation of getMaxZoomLevel() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of getMaxZoomLevel() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMaxZoomLevel(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.getMaxZoomLevel(1), throwsUnimplementedError); + }); - test( - 'Default implementation of getMinZoomLevel() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of getMinZoomLevel() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.getMinZoomLevel(1), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.getMinZoomLevel(1), throwsUnimplementedError); + }); - test( - 'Default implementation of setZoomLevel() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setZoomLevel() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setZoomLevel(1, 1.0), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setZoomLevel(1, 1.0), throwsUnimplementedError); + }); - test( - 'Default implementation of pausePreview() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of pausePreview() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect(() => cameraPlatform.pausePreview(1), throwsUnimplementedError); - }, - ); + // Act & Assert + expect(() => cameraPlatform.pausePreview(1), throwsUnimplementedError); + }); - test( - 'Default implementation of resumePreview() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of resumePreview() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect(() => cameraPlatform.resumePreview(1), throwsUnimplementedError); - }, - ); + // Act & Assert + expect(() => cameraPlatform.resumePreview(1), throwsUnimplementedError); + }); - test( - 'Default implementation of setJpegImageQuality() should throw unimplemented error', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of setJpegImageQuality() should throw unimplemented error', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect( - () => cameraPlatform.setJpegImageQuality(1, 50), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => cameraPlatform.setJpegImageQuality(1, 50), throwsUnimplementedError); + }); - test( - 'Default implementation of supportsImageStreaming() should return false', - () { - // Arrange - final cameraPlatform = ExtendsCameraPlatform(); + test('Default implementation of supportsImageStreaming() should return false', () { + // Arrange + final cameraPlatform = ExtendsCameraPlatform(); - // Act & Assert - expect(cameraPlatform.supportsImageStreaming(), false); - }, - ); + // Act & Assert + expect(cameraPlatform.supportsImageStreaming(), false); + }); - test( - 'getFallbackVideoStabilizationMode returns level2 for mode level3', - () { - final VideoStabilizationMode? fallbackMode = - CameraPlatform.getFallbackVideoStabilizationMode( - VideoStabilizationMode.level3, - ); + test('getFallbackVideoStabilizationMode returns level2 for mode level3', () { + final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode( + VideoStabilizationMode.level3, + ); - expect(fallbackMode, VideoStabilizationMode.level2); - }, - ); + expect(fallbackMode, VideoStabilizationMode.level2); + }); - test( - 'getFallbackVideoStabilizationMode returns level1 for mode level2', - () { - final VideoStabilizationMode? fallbackMode = - CameraPlatform.getFallbackVideoStabilizationMode( - VideoStabilizationMode.level2, - ); + test('getFallbackVideoStabilizationMode returns level1 for mode level2', () { + final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode( + VideoStabilizationMode.level2, + ); - expect(fallbackMode, VideoStabilizationMode.level1); - }, - ); + expect(fallbackMode, VideoStabilizationMode.level1); + }); test('getFallbackVideoStabilizationMode returns off for mode level1', () { - final VideoStabilizationMode? fallbackMode = - CameraPlatform.getFallbackVideoStabilizationMode( - VideoStabilizationMode.level1, - ); + final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode( + VideoStabilizationMode.level1, + ); expect(fallbackMode, VideoStabilizationMode.off); }); test('getFallbackVideoStabilizationMode returns null for mode off', () { - final VideoStabilizationMode? fallbackMode = - CameraPlatform.getFallbackVideoStabilizationMode( - VideoStabilizationMode.off, - ); + final VideoStabilizationMode? fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode( + VideoStabilizationMode.off, + ); expect(fallbackMode, null); }); diff --git a/packages/camera/camera_platform_interface/test/events/camera_event_test.dart b/packages/camera/camera_platform_interface/test/events/camera_event_test.dart index 58ace30ce4bb..55cd34747fae 100644 --- a/packages/camera/camera_platform_interface/test/events/camera_event_test.dart +++ b/packages/camera/camera_platform_interface/test/events/camera_event_test.dart @@ -187,31 +187,28 @@ void main() { expect(firstEvent == secondEvent, false); }); - test( - 'equals should return false if exposurePointSupported is different', - () { - const firstEvent = CameraInitializedEvent( - 1, - 1024, - 640, - ExposureMode.auto, - true, - FocusMode.auto, - true, - ); - const secondEvent = CameraInitializedEvent( - 1, - 1024, - 640, - ExposureMode.auto, - false, - FocusMode.auto, - true, - ); - - expect(firstEvent == secondEvent, false); - }, - ); + test('equals should return false if exposurePointSupported is different', () { + const firstEvent = CameraInitializedEvent( + 1, + 1024, + 640, + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); + const secondEvent = CameraInitializedEvent( + 1, + 1024, + 640, + ExposureMode.auto, + false, + FocusMode.auto, + true, + ); + + expect(firstEvent == secondEvent, false); + }); test('equals should return false if focusMode is different', () { const firstEvent = CameraInitializedEvent( @@ -293,13 +290,11 @@ void main() { }); test('fromJson should initialize all properties', () { - final event = CameraResolutionChangedEvent.fromJson( - const { - 'cameraId': 1, - 'captureWidth': 1024.0, - 'captureHeight': 640.0, - }, - ); + final event = CameraResolutionChangedEvent.fromJson(const { + 'cameraId': 1, + 'captureWidth': 1024.0, + 'captureHeight': 640.0, + }); expect(event.cameraId, 1); expect(event.captureWidth, 1024); @@ -365,9 +360,7 @@ void main() { }); test('fromJson should initialize all properties', () { - final event = CameraClosingEvent.fromJson(const { - 'cameraId': 1, - }); + final event = CameraClosingEvent.fromJson(const {'cameraId': 1}); expect(event.cameraId, 1); }); @@ -454,10 +447,7 @@ void main() { test('hashCode should match hashCode of all properties', () { const event = CameraErrorEvent(1, 'Error'); - final int expectedHashCode = Object.hash( - event.cameraId.hashCode, - event.description, - ); + final int expectedHashCode = Object.hash(event.cameraId.hashCode, event.description); expect(event.hashCode, expectedHashCode); }); diff --git a/packages/camera/camera_platform_interface/test/events/device_event_test.dart b/packages/camera/camera_platform_interface/test/events/device_event_test.dart index 794a301f7523..59a0a3a8755c 100644 --- a/packages/camera/camera_platform_interface/test/events/device_event_test.dart +++ b/packages/camera/camera_platform_interface/test/events/device_event_test.dart @@ -17,9 +17,9 @@ void main() { }); test('fromJson should initialize all properties', () { - final event = DeviceOrientationChangedEvent.fromJson( - const {'orientation': 'portraitUp'}, - ); + final event = DeviceOrientationChangedEvent.fromJson(const { + 'orientation': 'portraitUp', + }); expect(event.orientation, DeviceOrientation.portraitUp); }); @@ -34,23 +34,15 @@ void main() { }); test('equals should return true if objects are the same', () { - const firstEvent = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); - const secondEvent = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); + const firstEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const secondEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); expect(firstEvent == secondEvent, true); }); test('equals should return false if orientation is different', () { - const firstEvent = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); - const secondEvent = DeviceOrientationChangedEvent( - DeviceOrientation.landscapeLeft, - ); + const firstEvent = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const secondEvent = DeviceOrientationChangedEvent(DeviceOrientation.landscapeLeft); expect(firstEvent == secondEvent, false); }); diff --git a/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart b/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart index a52d725cf442..cd592fc86730 100644 --- a/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart +++ b/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart @@ -25,10 +25,7 @@ void main() { final cameraMockChannel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { - 'create': { - 'cameraId': 1, - 'imageFormatGroup': 'unknown', - }, + 'create': {'cameraId': 1, 'imageFormatGroup': 'unknown'}, }, ); final camera = MethodChannelCamera(); @@ -65,146 +62,122 @@ void main() { expect(cameraId, 1); }); - test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'create': PlatformException( - code: 'TESTING_ERROR_CODE', - message: 'Mock error message used during testing.', - ), - }, - ); - final camera = MethodChannelCamera(); - - // Act - expect( - () => camera.createCameraWithSettings( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ), - const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, - ), + test('Should throw CameraException when create throws a PlatformException', () { + // Arrange + MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: { + 'create': PlatformException( + code: 'TESTING_ERROR_CODE', + message: 'Mock error message used during testing.', ), - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), + }, + ); + final camera = MethodChannelCamera(); + + // Act + expect( + () => camera.createCameraWithSettings( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, ), - ); - }, - ); - - test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'create': PlatformException( - code: 'TESTING_ERROR_CODE', - message: 'Mock error message used during testing.', - ), - }, - ); - final camera = MethodChannelCamera(); - - // Act - expect( - () => camera.createCameraWithSettings( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ), - const MediaSettings( - resolutionPreset: ResolutionPreset.low, - fps: 15, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, - ), + const MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, ), - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), + ), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); + + test('Should throw CameraException when create throws a PlatformException', () { + // Arrange + MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: { + 'create': PlatformException( + code: 'TESTING_ERROR_CODE', + message: 'Mock error message used during testing.', ), - ); - }, - ); - - test( - 'Should throw CameraException when initialize throws a PlatformException', - () { - // Arrange - MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'initialize': PlatformException( - code: 'TESTING_ERROR_CODE', - message: 'Mock error message used during testing.', - ), - }, - ); - final camera = MethodChannelCamera(); - - // Act - expect( - () => camera.initializeCamera(0), - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), + }, + ); + final camera = MethodChannelCamera(); + + // Act + expect( + () => camera.createCameraWithSettings( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, ), - ); - }, - ); + const MediaSettings( + resolutionPreset: ResolutionPreset.low, + fps: 15, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ), + ), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); + + test('Should throw CameraException when initialize throws a PlatformException', () { + // Arrange + MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: { + 'initialize': PlatformException( + code: 'TESTING_ERROR_CODE', + message: 'Mock error message used during testing.', + ), + }, + ); + final camera = MethodChannelCamera(); + + // Act + expect( + () => camera.initializeCamera(0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); test('Should send initialization data', () async { // Arrange final cameraMockChannel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { - 'create': { - 'cameraId': 1, - 'imageFormatGroup': 'unknown', - }, + 'create': {'cameraId': 1, 'imageFormatGroup': 'unknown'}, 'initialize': null, }, ); @@ -245,10 +218,7 @@ void main() { anything, isMethodCall( 'initialize', - arguments: { - 'cameraId': 1, - 'imageFormatGroup': 'unknown', - }, + arguments: {'cameraId': 1, 'imageFormatGroup': 'unknown'}, ), ]); }); @@ -349,8 +319,7 @@ void main() { test('Should receive initialized event', () async { // Act - final Stream eventStream = camera - .onCameraInitialized(cameraId); + final Stream eventStream = camera.onCameraInitialized(cameraId); final streamQueue = StreamQueue(eventStream); // Emit test events @@ -363,10 +332,7 @@ void main() { FocusMode.auto, true, ); - await camera.handleCameraMethodCall( - MethodCall('initialized', event.toJson()), - cameraId, - ); + await camera.handleCameraMethodCall(MethodCall('initialized', event.toJson()), cameraId); // Assert expect(await streamQueue.next, event); @@ -379,9 +345,7 @@ void main() { // Act final Stream resolutionStream = camera .onCameraResolutionChanged(cameraId); - final streamQueue = StreamQueue( - resolutionStream, - ); + final streamQueue = StreamQueue(resolutionStream); // Emit test events final fhdEvent = CameraResolutionChangedEvent(cameraId, 1920, 1080); @@ -415,25 +379,14 @@ void main() { test('Should receive camera closing events', () async { // Act - final Stream eventStream = camera.onCameraClosing( - cameraId, - ); + final Stream eventStream = camera.onCameraClosing(cameraId); final streamQueue = StreamQueue(eventStream); // Emit test events final event = CameraClosingEvent(cameraId); - await camera.handleCameraMethodCall( - MethodCall('camera_closing', event.toJson()), - cameraId, - ); - await camera.handleCameraMethodCall( - MethodCall('camera_closing', event.toJson()), - cameraId, - ); - await camera.handleCameraMethodCall( - MethodCall('camera_closing', event.toJson()), - cameraId, - ); + await camera.handleCameraMethodCall(MethodCall('camera_closing', event.toJson()), cameraId); + await camera.handleCameraMethodCall(MethodCall('camera_closing', event.toJson()), cameraId); + await camera.handleCameraMethodCall(MethodCall('camera_closing', event.toJson()), cameraId); // Assert expect(await streamQueue.next, event); @@ -446,25 +399,14 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = camera.onCameraError( - cameraId, - ); + final Stream errorStream = camera.onCameraError(cameraId); final streamQueue = StreamQueue(errorStream); // Emit test events final event = CameraErrorEvent(cameraId, 'Error Description'); - await camera.handleCameraMethodCall( - MethodCall('error', event.toJson()), - cameraId, - ); - await camera.handleCameraMethodCall( - MethodCall('error', event.toJson()), - cameraId, - ); - await camera.handleCameraMethodCall( - MethodCall('error', event.toJson()), - cameraId, - ); + await camera.handleCameraMethodCall(MethodCall('error', event.toJson()), cameraId); + await camera.handleCameraMethodCall(MethodCall('error', event.toJson()), cameraId); + await camera.handleCameraMethodCall(MethodCall('error', event.toJson()), cameraId); // Assert expect(await streamQueue.next, event); @@ -479,23 +421,13 @@ void main() { // Act final Stream eventStream = camera .onDeviceOrientationChanged(); - final streamQueue = StreamQueue( - eventStream, - ); + final streamQueue = StreamQueue(eventStream); // Emit test events - const event = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); - await camera.handleDeviceMethodCall( - MethodCall('orientation_changed', event.toJson()), - ); - await camera.handleDeviceMethodCall( - MethodCall('orientation_changed', event.toJson()), - ); - await camera.handleDeviceMethodCall( - MethodCall('orientation_changed', event.toJson()), - ); + const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + await camera.handleDeviceMethodCall(MethodCall('orientation_changed', event.toJson())); + await camera.handleDeviceMethodCall(MethodCall('orientation_changed', event.toJson())); + await camera.handleDeviceMethodCall(MethodCall('orientation_changed', event.toJson())); // Assert expect(await streamQueue.next, event); @@ -549,85 +481,61 @@ void main() { await initializeFuture; }); - test( - 'Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final returnData = [ - { - 'name': 'Test 1', - 'lensFacing': 'front', - 'sensorOrientation': 1, - }, - { - 'name': 'Test 2', - 'lensFacing': 'back', - 'sensorOrientation': 2, - }, - ]; - final channel = MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: {'availableCameras': returnData}, - ); + test('Should fetch CameraDescription instances for available cameras', () async { + // Arrange + final returnData = [ + {'name': 'Test 1', 'lensFacing': 'front', 'sensorOrientation': 1}, + {'name': 'Test 2', 'lensFacing': 'back', 'sensorOrientation': 2}, + ]; + final channel = MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: {'availableCameras': returnData}, + ); - // Act - final List cameras = await camera - .availableCameras(); - - // Assert - expect(channel.log, [ - isMethodCall('availableCameras', arguments: null), - ]); - expect(cameras.length, returnData.length); - for (var i = 0; i < returnData.length; i++) { - final Map typedData = - (returnData[i] as Map) - .cast(); - final cameraDescription = CameraDescription( - name: typedData['name']! as String, - lensDirection: parseCameraLensDirection( - typedData['lensFacing']! as String, - ), - sensorOrientation: typedData['sensorOrientation']! as int, - ); - expect(cameras[i], cameraDescription); - } - }, - ); - - test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - // Arrange - MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'availableCameras': PlatformException( - code: 'TESTING_ERROR_CODE', - message: 'Mock error message used during testing.', - ), - }, + // Act + final List cameras = await camera.availableCameras(); + + // Assert + expect(channel.log, [isMethodCall('availableCameras', arguments: null)]); + expect(cameras.length, returnData.length); + for (var i = 0; i < returnData.length; i++) { + final Map typedData = (returnData[i] as Map) + .cast(); + final cameraDescription = CameraDescription( + name: typedData['name']! as String, + lensDirection: parseCameraLensDirection(typedData['lensFacing']! as String), + sensorOrientation: typedData['sensorOrientation']! as int, ); + expect(cameras[i], cameraDescription); + } + }); - // Act - expect( - camera.availableCameras, - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), + test('Should throw CameraException when availableCameras throws a PlatformException', () { + // Arrange + MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: { + 'availableCameras': PlatformException( + code: 'TESTING_ERROR_CODE', + message: 'Mock error message used during testing.', ), - ); - }, - ); + }, + ); + + // Act + expect( + camera.availableCameras, + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); test('Should take a picture and return an XFile instance', () async { // Arrange @@ -641,10 +549,7 @@ void main() { // Assert expect(channel.log, [ - isMethodCall( - 'takePicture', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('takePicture', arguments: {'cameraId': cameraId}), ]); expect(file.path, '/test/path.jpg'); }); @@ -660,9 +565,7 @@ void main() { await camera.prepareForVideoRecording(); // Assert - expect(channel.log, [ - isMethodCall('prepareForVideoRecording', arguments: null), - ]); + expect(channel.log, [isMethodCall('prepareForVideoRecording', arguments: null)]); }); test('Should start recording a video', () async { @@ -724,10 +627,7 @@ void main() { // Assert expect(channel.log, [ - isMethodCall( - 'stopVideoRecording', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('stopVideoRecording', arguments: {'cameraId': cameraId}), ]); expect(file.path, '/test/path.mp4'); }); @@ -744,10 +644,7 @@ void main() { // Assert expect(channel.log, [ - isMethodCall( - 'pauseVideoRecording', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('pauseVideoRecording', arguments: {'cameraId': cameraId}), ]); }); @@ -763,10 +660,7 @@ void main() { // Assert expect(channel.log, [ - isMethodCall( - 'resumeVideoRecording', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('resumeVideoRecording', arguments: {'cameraId': cameraId}), ]); }); @@ -791,10 +685,7 @@ void main() { ), isMethodCall( 'setFlashMode', - arguments: { - 'cameraId': cameraId, - 'mode': 'always', - }, + arguments: {'cameraId': cameraId, 'mode': 'always'}, ), isMethodCall( 'setFlashMode', @@ -826,10 +717,7 @@ void main() { ), isMethodCall( 'setExposureMode', - arguments: { - 'cameraId': cameraId, - 'mode': 'locked', - }, + arguments: {'cameraId': cameraId, 'mode': 'locked'}, ), ]); }); @@ -849,21 +737,11 @@ void main() { expect(channel.log, [ isMethodCall( 'setExposurePoint', - arguments: { - 'cameraId': cameraId, - 'x': 0.5, - 'y': 0.5, - 'reset': false, - }, + arguments: {'cameraId': cameraId, 'x': 0.5, 'y': 0.5, 'reset': false}, ), isMethodCall( 'setExposurePoint', - arguments: { - 'cameraId': cameraId, - 'x': null, - 'y': null, - 'reset': true, - }, + arguments: {'cameraId': cameraId, 'x': null, 'y': null, 'reset': true}, ), ]); }); @@ -876,17 +754,12 @@ void main() { ); // Act - final double minExposureOffset = await camera.getMinExposureOffset( - cameraId, - ); + final double minExposureOffset = await camera.getMinExposureOffset(cameraId); // Assert expect(minExposureOffset, 2.0); expect(channel.log, [ - isMethodCall( - 'getMinExposureOffset', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('getMinExposureOffset', arguments: {'cameraId': cameraId}), ]); }); @@ -898,17 +771,12 @@ void main() { ); // Act - final double maxExposureOffset = await camera.getMaxExposureOffset( - cameraId, - ); + final double maxExposureOffset = await camera.getMaxExposureOffset(cameraId); // Assert expect(maxExposureOffset, 2.0); expect(channel.log, [ - isMethodCall( - 'getMaxExposureOffset', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('getMaxExposureOffset', arguments: {'cameraId': cameraId}), ]); }); @@ -920,9 +788,7 @@ void main() { ); // Act - final double stepSize = await camera.getExposureOffsetStepSize( - cameraId, - ); + final double stepSize = await camera.getExposureOffsetStepSize(cameraId); // Assert expect(stepSize, 0.25); @@ -942,10 +808,7 @@ void main() { ); // Act - final double actualOffset = await camera.setExposureOffset( - cameraId, - 0.5, - ); + final double actualOffset = await camera.setExposureOffset(cameraId, 0.5); // Assert expect(actualOffset, 0.6); @@ -976,10 +839,7 @@ void main() { ), isMethodCall( 'setFocusMode', - arguments: { - 'cameraId': cameraId, - 'mode': 'locked', - }, + arguments: {'cameraId': cameraId, 'mode': 'locked'}, ), ]); }); @@ -999,21 +859,11 @@ void main() { expect(channel.log, [ isMethodCall( 'setFocusPoint', - arguments: { - 'cameraId': cameraId, - 'x': 0.5, - 'y': 0.5, - 'reset': false, - }, + arguments: {'cameraId': cameraId, 'x': 0.5, 'y': 0.5, 'reset': false}, ), isMethodCall( 'setFocusPoint', - arguments: { - 'cameraId': cameraId, - 'x': null, - 'y': null, - 'reset': true, - }, + arguments: {'cameraId': cameraId, 'x': null, 'y': null, 'reset': true}, ), ]); }); @@ -1027,20 +877,14 @@ void main() { expect((widget as Texture).textureId, cameraId); }); - test( - 'Should throw MissingPluginException when handling unknown method', - () { - final camera = MethodChannelCamera(); + test('Should throw MissingPluginException when handling unknown method', () { + final camera = MethodChannelCamera(); - expect( - () => camera.handleCameraMethodCall( - const MethodCall('unknown_method'), - 1, - ), - throwsA(isA()), - ); - }, - ); + expect( + () => camera.handleCameraMethodCall(const MethodCall('unknown_method'), 1), + throwsA(isA()), + ); + }); test('Should get the max zoom level', () async { // Arrange @@ -1055,10 +899,7 @@ void main() { // Assert expect(maxZoomLevel, 10.0); expect(channel.log, [ - isMethodCall( - 'getMaxZoomLevel', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('getMaxZoomLevel', arguments: {'cameraId': cameraId}), ]); }); @@ -1075,10 +916,7 @@ void main() { // Assert expect(maxZoomLevel, 1.0); expect(channel.log, [ - isMethodCall( - 'getMinZoomLevel', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('getMinZoomLevel', arguments: {'cameraId': cameraId}), ]); }); @@ -1101,35 +939,25 @@ void main() { ]); }); - test( - 'Should throw CameraException when illegal zoom level is supplied', - () async { - // Arrange - MethodChannelMock( - channelName: 'plugins.flutter.io/camera', - methods: { - 'setZoomLevel': PlatformException( - code: 'ZOOM_ERROR', - message: 'Illegal zoom error', - ), - }, - ); + test('Should throw CameraException when illegal zoom level is supplied', () async { + // Arrange + MethodChannelMock( + channelName: 'plugins.flutter.io/camera', + methods: { + 'setZoomLevel': PlatformException(code: 'ZOOM_ERROR', message: 'Illegal zoom error'), + }, + ); - // Act & assert - expect( - () => camera.setZoomLevel(cameraId, -1.0), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') - .having( - (CameraException e) => e.description, - 'description', - 'Illegal zoom error', - ), - ), - ); - }, - ); + // Act & assert + expect( + () => camera.setZoomLevel(cameraId, -1.0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'ZOOM_ERROR') + .having((CameraException e) => e.description, 'description', 'Illegal zoom error'), + ), + ); + }); test('Should lock the capture orientation', () async { // Arrange @@ -1139,19 +967,13 @@ void main() { ); // Act - await camera.lockCaptureOrientation( - cameraId, - DeviceOrientation.portraitUp, - ); + await camera.lockCaptureOrientation(cameraId, DeviceOrientation.portraitUp); // Assert expect(channel.log, [ isMethodCall( 'lockCaptureOrientation', - arguments: { - 'cameraId': cameraId, - 'orientation': 'portraitUp', - }, + arguments: {'cameraId': cameraId, 'orientation': 'portraitUp'}, ), ]); }); @@ -1187,10 +1009,7 @@ void main() { // Assert expect(channel.log, [ - isMethodCall( - 'pausePreview', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('pausePreview', arguments: {'cameraId': cameraId}), ]); }); @@ -1206,10 +1025,7 @@ void main() { // Assert expect(channel.log, [ - isMethodCall( - 'resumePreview', - arguments: {'cameraId': cameraId}, - ), + isMethodCall('resumePreview', arguments: {'cameraId': cameraId}), ]); }); @@ -1217,10 +1033,7 @@ void main() { // Arrange final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', - methods: { - 'startImageStream': null, - 'stopImageStream': null, - }, + methods: {'startImageStream': null, 'stopImageStream': null}, ); // Act @@ -1229,9 +1042,7 @@ void main() { .listen((CameraImageData imageData) {}); // Assert - expect(channel.log, [ - isMethodCall('startImageStream', arguments: null), - ]); + expect(channel.log, [isMethodCall('startImageStream', arguments: null)]); await subscription.cancel(); }); @@ -1240,10 +1051,7 @@ void main() { // Arrange final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', - methods: { - 'startImageStream': null, - 'stopImageStream': null, - }, + methods: {'startImageStream': null, 'stopImageStream': null}, ); // Act @@ -1273,10 +1081,7 @@ void main() { expect(channel.log, [ isMethodCall( 'setImageFileFormat', - arguments: { - 'cameraId': cameraId, - 'fileFormat': 'heif', - }, + arguments: {'cameraId': cameraId, 'fileFormat': 'heif'}, ), ]); }); @@ -1295,10 +1100,7 @@ void main() { expect(channel.log, [ isMethodCall( 'setImageFileFormat', - arguments: { - 'cameraId': cameraId, - 'fileFormat': 'jpeg', - }, + arguments: {'cameraId': cameraId, 'fileFormat': 'jpeg'}, ), ]); }); diff --git a/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart b/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart index 5e578b97b4e5..f3650bd9d4c4 100644 --- a/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart +++ b/packages/camera/camera_platform_interface/test/method_channel/type_conversion_test.dart @@ -9,25 +9,23 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('CameraImageData can be created', () { - final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final CameraImageData cameraImage = cameraImageFromPlatformData({ + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.height, 1); expect(cameraImage.width, 4); expect(cameraImage.format.group, ImageFormatGroup.yuv420); @@ -37,50 +35,46 @@ void main() { test('CameraImageData has ImageFormatGroup.yuv420 for iOS', () { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 875704438, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final CameraImageData cameraImage = cameraImageFromPlatformData({ + 'format': 875704438, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('CameraImageData has ImageFormatGroup.yuv420 for Android', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final CameraImageData cameraImage = cameraImageFromPlatformData({ + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); } diff --git a/packages/camera/camera_platform_interface/test/types/camera_description_test.dart b/packages/camera/camera_platform_interface/test/types/camera_description_test.dart index 6bf9ee3f2bcd..97cd240dcfee 100644 --- a/packages/camera/camera_platform_interface/test/types/camera_description_test.dart +++ b/packages/camera/camera_platform_interface/test/types/camera_description_test.dart @@ -107,24 +107,21 @@ void main() { expect(firstDescription == secondDescription, true); }); - test( - 'hashCode should match hashCode of all equality-tested properties', - () { - const description = CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.front, - sensorOrientation: 0, - lensType: CameraLensType.ultraWide, - ); - final int expectedHashCode = Object.hash( - description.name, - description.lensDirection, - description.lensType, - ); - - expect(description.hashCode, expectedHashCode); - }, - ); + test('hashCode should match hashCode of all equality-tested properties', () { + const description = CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.front, + sensorOrientation: 0, + lensType: CameraLensType.ultraWide, + ); + final int expectedHashCode = Object.hash( + description.name, + description.lensDirection, + description.lensType, + ); + + expect(description.hashCode, expectedHashCode); + }); test('toString should return correct string representation', () { const description = CameraDescription( diff --git a/packages/camera/camera_platform_interface/test/types/media_settings_test.dart b/packages/camera/camera_platform_interface/test/types/media_settings_test.dart index 65f619b1673d..19c44dff526e 100644 --- a/packages/camera/camera_platform_interface/test/types/media_settings_test.dart +++ b/packages/camera/camera_platform_interface/test/types/media_settings_test.dart @@ -8,46 +8,39 @@ import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - test( - 'MediaSettings non-parametrized constructor should have correct initial values', - () { - const settingsWithNoParameters = MediaSettings(); + test('MediaSettings non-parametrized constructor should have correct initial values', () { + const settingsWithNoParameters = MediaSettings(); - expect( - settingsWithNoParameters.resolutionPreset, - isNull, - reason: - 'MediaSettings constructor should have null default resolutionPreset', - ); + expect( + settingsWithNoParameters.resolutionPreset, + isNull, + reason: 'MediaSettings constructor should have null default resolutionPreset', + ); - expect( - settingsWithNoParameters.fps, - isNull, - reason: 'MediaSettings constructor should have null default fps', - ); + expect( + settingsWithNoParameters.fps, + isNull, + reason: 'MediaSettings constructor should have null default fps', + ); - expect( - settingsWithNoParameters.videoBitrate, - isNull, - reason: - 'MediaSettings constructor should have null default videoBitrate', - ); + expect( + settingsWithNoParameters.videoBitrate, + isNull, + reason: 'MediaSettings constructor should have null default videoBitrate', + ); - expect( - settingsWithNoParameters.audioBitrate, - isNull, - reason: - 'MediaSettings constructor should have null default audioBitrate', - ); + expect( + settingsWithNoParameters.audioBitrate, + isNull, + reason: 'MediaSettings constructor should have null default audioBitrate', + ); - expect( - settingsWithNoParameters.enableAudio, - isFalse, - reason: - 'MediaSettings constructor should have false default enableAudio', - ); - }, - ); + expect( + settingsWithNoParameters.enableAudio, + isFalse, + reason: 'MediaSettings constructor should have false default enableAudio', + ); + }); test('MediaSettings fps should hold parameters', () { const settings = MediaSettings( @@ -61,15 +54,10 @@ void main() { expect( settings.resolutionPreset, ResolutionPreset.low, - reason: - 'MediaSettings constructor should hold resolutionPreset parameter', + reason: 'MediaSettings constructor should hold resolutionPreset parameter', ); - expect( - settings.fps, - 20, - reason: 'MediaSettings constructor should hold fps parameter', - ); + expect(settings.fps, 20, reason: 'MediaSettings constructor should hold fps parameter'); expect( settings.videoBitrate, @@ -102,8 +90,7 @@ void main() { expect( settings.hashCode, Object.hash(ResolutionPreset.low, 20, 128000, 32000, true), - reason: - 'MediaSettings hash() should be equal to Object.hash of parameters', + reason: 'MediaSettings hash() should be equal to Object.hash of parameters', ); }); @@ -207,8 +194,7 @@ void main() { expect( settings1 == settingsIdentical, isTrue, - reason: - 'MediaSettings == operator should return true for identical objects', + reason: 'MediaSettings == operator should return true for identical objects', ); }); @@ -216,8 +202,7 @@ void main() { expect( settings1 == Object(), isFalse, - reason: - 'MediaSettings == operator should return false for objects of different types', + reason: 'MediaSettings == operator should return false for objects of different types', ); }); }); diff --git a/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart b/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart index 8c9f5d8a643d..a02b6287c359 100644 --- a/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart +++ b/packages/camera/camera_platform_interface/test/utils/method_channel_mock.dart @@ -6,13 +6,12 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class MethodChannelMock { - MethodChannelMock({ - required String channelName, - this.delay, - required this.methods, - }) : methodChannel = MethodChannel(channelName) { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(methodChannel, _handler); + MethodChannelMock({required String channelName, this.delay, required this.methods}) + : methodChannel = MethodChannel(channelName) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + methodChannel, + _handler, + ); } final Duration? delay; diff --git a/packages/camera/camera_platform_interface/test/utils/utils_test.dart b/packages/camera/camera_platform_interface/test/utils/utils_test.dart index 316a32935a4d..6d3a6c841eb5 100644 --- a/packages/camera/camera_platform_interface/test/utils/utils_test.dart +++ b/packages/camera/camera_platform_interface/test/utils/utils_test.dart @@ -14,59 +14,29 @@ void main() { () { expect(parseCameraLensDirection('back'), CameraLensDirection.back); expect(parseCameraLensDirection('front'), CameraLensDirection.front); - expect( - parseCameraLensDirection('external'), - CameraLensDirection.external, - ); + expect(parseCameraLensDirection('external'), CameraLensDirection.external); }, ); test( 'Should throw ArgumentException when invalid value is supplied when parsing camera lens direction', () { - expect( - () => parseCameraLensDirection('test'), - throwsA(isArgumentError), - ); + expect(() => parseCameraLensDirection('test'), throwsA(isArgumentError)); }, ); test('serializeDeviceOrientation() should serialize correctly', () { - expect( - serializeDeviceOrientation(DeviceOrientation.portraitUp), - 'portraitUp', - ); - expect( - serializeDeviceOrientation(DeviceOrientation.portraitDown), - 'portraitDown', - ); - expect( - serializeDeviceOrientation(DeviceOrientation.landscapeRight), - 'landscapeRight', - ); - expect( - serializeDeviceOrientation(DeviceOrientation.landscapeLeft), - 'landscapeLeft', - ); + expect(serializeDeviceOrientation(DeviceOrientation.portraitUp), 'portraitUp'); + expect(serializeDeviceOrientation(DeviceOrientation.portraitDown), 'portraitDown'); + expect(serializeDeviceOrientation(DeviceOrientation.landscapeRight), 'landscapeRight'); + expect(serializeDeviceOrientation(DeviceOrientation.landscapeLeft), 'landscapeLeft'); }); test('deserializeDeviceOrientation() should deserialize correctly', () { - expect( - deserializeDeviceOrientation('portraitUp'), - DeviceOrientation.portraitUp, - ); - expect( - deserializeDeviceOrientation('portraitDown'), - DeviceOrientation.portraitDown, - ); - expect( - deserializeDeviceOrientation('landscapeRight'), - DeviceOrientation.landscapeRight, - ); - expect( - deserializeDeviceOrientation('landscapeLeft'), - DeviceOrientation.landscapeLeft, - ); + expect(deserializeDeviceOrientation('portraitUp'), DeviceOrientation.portraitUp); + expect(deserializeDeviceOrientation('portraitDown'), DeviceOrientation.portraitDown); + expect(deserializeDeviceOrientation('landscapeRight'), DeviceOrientation.landscapeRight); + expect(deserializeDeviceOrientation('landscapeLeft'), DeviceOrientation.landscapeLeft); }); }); } diff --git a/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart b/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart index 371f23d341b1..412fdd084059 100644 --- a/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart @@ -45,9 +45,7 @@ void main() { } } - testWidgets('Camera allows to control video bitrate', ( - WidgetTester tester, - ) async { + testWidgets('Camera allows to control video bitrate', (WidgetTester tester) async { //const String supportedVideoType = 'video/webm'; const supportedVideoType = 'video/webm;codecs="vp9,opus"'; bool isVideoTypeSupported(String type) => type == supportedVideoType; @@ -59,8 +57,7 @@ void main() { final window = createJSInteropWrapper(mockWindow) as Window; final navigator = createJSInteropWrapper(mockNavigator) as Navigator; - final mediaDevices = - createJSInteropWrapper(mockMediaDevices) as MediaDevices; + final mediaDevices = createJSInteropWrapper(mockMediaDevices) as MediaDevices; mockWindow.navigator = navigator; mockNavigator.mediaDevices = mediaDevices; @@ -74,8 +71,7 @@ void main() { final cameraService = MockCameraService(); - CameraPlatform.instance = CameraPlugin(cameraService: cameraService) - ..window = window; + CameraPlatform.instance = CameraPlugin(cameraService: cameraService)..window = window; final options = CameraOptions( audio: const AudioConstraints(), diff --git a/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart b/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart index 8b80cbcbc160..4219616ad487 100644 --- a/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_error_code_test.dart @@ -18,10 +18,7 @@ void main() { group('CameraErrorCode', () { group('toString returns a correct type for', () { testWidgets('notSupported', (WidgetTester tester) async { - expect( - CameraErrorCode.notSupported.toString(), - equals('cameraNotSupported'), - ); + expect(CameraErrorCode.notSupported.toString(), equals('cameraNotSupported')); }); testWidgets('notFound', (WidgetTester tester) async { @@ -29,24 +26,15 @@ void main() { }); testWidgets('notReadable', (WidgetTester tester) async { - expect( - CameraErrorCode.notReadable.toString(), - equals('cameraNotReadable'), - ); + expect(CameraErrorCode.notReadable.toString(), equals('cameraNotReadable')); }); testWidgets('overconstrained', (WidgetTester tester) async { - expect( - CameraErrorCode.overconstrained.toString(), - equals('cameraOverconstrained'), - ); + expect(CameraErrorCode.overconstrained.toString(), equals('cameraOverconstrained')); }); testWidgets('permissionDenied', (WidgetTester tester) async { - expect( - CameraErrorCode.permissionDenied.toString(), - equals('CameraAccessDenied'), - ); + expect(CameraErrorCode.permissionDenied.toString(), equals('CameraAccessDenied')); }); testWidgets('type', (WidgetTester tester) async { @@ -62,10 +50,7 @@ void main() { }); testWidgets('missingMetadata', (WidgetTester tester) async { - expect( - CameraErrorCode.missingMetadata.toString(), - equals('cameraMissingMetadata'), - ); + expect(CameraErrorCode.missingMetadata.toString(), equals('cameraMissingMetadata')); }); testWidgets('orientationNotSupported', (WidgetTester tester) async { @@ -76,31 +61,19 @@ void main() { }); testWidgets('torchModeNotSupported', (WidgetTester tester) async { - expect( - CameraErrorCode.torchModeNotSupported.toString(), - equals('torchModeNotSupported'), - ); + expect(CameraErrorCode.torchModeNotSupported.toString(), equals('torchModeNotSupported')); }); testWidgets('zoomLevelNotSupported', (WidgetTester tester) async { - expect( - CameraErrorCode.zoomLevelNotSupported.toString(), - equals('zoomLevelNotSupported'), - ); + expect(CameraErrorCode.zoomLevelNotSupported.toString(), equals('zoomLevelNotSupported')); }); testWidgets('zoomLevelInvalid', (WidgetTester tester) async { - expect( - CameraErrorCode.zoomLevelInvalid.toString(), - equals('zoomLevelInvalid'), - ); + expect(CameraErrorCode.zoomLevelInvalid.toString(), equals('zoomLevelInvalid')); }); testWidgets('notStarted', (WidgetTester tester) async { - expect( - CameraErrorCode.notStarted.toString(), - equals('cameraNotStarted'), - ); + expect(CameraErrorCode.notStarted.toString(), equals('cameraNotStarted')); }); testWidgets('videoRecordingNotStarted', (WidgetTester tester) async { @@ -118,10 +91,7 @@ void main() { testWidgets('with aborted error code', (WidgetTester tester) async { expect( CameraErrorCode.fromMediaError( - createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_ABORTED), - ) - as MediaError, + createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_ABORTED)) as MediaError, ).toString(), equals('mediaErrorAborted'), ); @@ -130,10 +100,7 @@ void main() { testWidgets('with network error code', (WidgetTester tester) async { expect( CameraErrorCode.fromMediaError( - createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_NETWORK), - ) - as MediaError, + createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_NETWORK)) as MediaError, ).toString(), equals('mediaErrorNetwork'), ); @@ -142,23 +109,16 @@ void main() { testWidgets('with decode error code', (WidgetTester tester) async { expect( CameraErrorCode.fromMediaError( - createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_DECODE), - ) - as MediaError, + createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_DECODE)) as MediaError, ).toString(), equals('mediaErrorDecode'), ); }); - testWidgets('with source not supported error code', ( - WidgetTester tester, - ) async { + testWidgets('with source not supported error code', (WidgetTester tester) async { expect( CameraErrorCode.fromMediaError( - createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED), - ) + createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED)) as MediaError, ).toString(), equals('mediaErrorSourceNotSupported'), diff --git a/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart b/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart index a59518ceee86..c9383a5898f4 100644 --- a/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_metadata_test.dart @@ -14,9 +14,7 @@ void main() { testWidgets('supports value equality', (WidgetTester tester) async { expect( const CameraMetadata(deviceId: 'deviceId', facingMode: 'environment'), - equals( - const CameraMetadata(deviceId: 'deviceId', facingMode: 'environment'), - ), + equals(const CameraMetadata(deviceId: 'deviceId', facingMode: 'environment')), ); }); }); diff --git a/packages/camera/camera_web/example/integration_test/camera_options_test.dart b/packages/camera/camera_web/example/integration_test/camera_options_test.dart index 75d72107dd2b..fc7fb1642aac 100644 --- a/packages/camera/camera_web/example/integration_test/camera_options_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_options_test.dart @@ -16,9 +16,7 @@ void main() { testWidgets('serializes correctly', (WidgetTester tester) async { final cameraOptions = CameraOptions( audio: const AudioConstraints(enabled: true), - video: VideoConstraints( - facingMode: FacingModeConstraint.exact(CameraType.user), - ), + video: VideoConstraints(facingMode: FacingModeConstraint.exact(CameraType.user)), ); expect( @@ -36,16 +34,8 @@ void main() { audio: const AudioConstraints(), video: VideoConstraints( facingMode: FacingModeConstraint(CameraType.environment), - width: const VideoSizeConstraint( - minimum: 10, - ideal: 15, - maximum: 20, - ), - height: const VideoSizeConstraint( - minimum: 15, - ideal: 20, - maximum: 25, - ), + width: const VideoSizeConstraint(minimum: 10, ideal: 15, maximum: 20), + height: const VideoSizeConstraint(minimum: 15, ideal: 20, maximum: 25), deviceId: 'deviceId', ), ), @@ -54,16 +44,8 @@ void main() { audio: const AudioConstraints(), video: VideoConstraints( facingMode: FacingModeConstraint(CameraType.environment), - width: const VideoSizeConstraint( - minimum: 10, - ideal: 15, - maximum: 20, - ), - height: const VideoSizeConstraint( - minimum: 15, - ideal: 20, - maximum: 25, - ), + width: const VideoSizeConstraint(minimum: 10, ideal: 15, maximum: 20), + height: const VideoSizeConstraint(minimum: 15, ideal: 20, maximum: 25), deviceId: 'deviceId', ), ), @@ -74,17 +56,11 @@ void main() { group('AudioConstraints', () { testWidgets('serializes correctly', (WidgetTester tester) async { - expect( - const AudioConstraints(enabled: true).toMediaStreamConstraints(), - true.toJS, - ); + expect(const AudioConstraints(enabled: true).toMediaStreamConstraints(), true.toJS); }); testWidgets('supports value equality', (WidgetTester tester) async { - expect( - const AudioConstraints(enabled: true), - equals(const AudioConstraints(enabled: true)), - ); + expect(const AudioConstraints(enabled: true), equals(const AudioConstraints(enabled: true))); }); }); @@ -108,9 +84,7 @@ void main() { ); }); - testWidgets('serializes to true when no constraints are provided', ( - WidgetTester tester, - ) async { + testWidgets('serializes to true when no constraints are provided', (WidgetTester tester) async { const videoConstraints = VideoConstraints(); expect(videoConstraints.toMediaStreamConstraints().dartify(), isTrue); }); @@ -119,31 +93,15 @@ void main() { expect( VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.environment), - width: const VideoSizeConstraint( - minimum: 90, - ideal: 100, - maximum: 100, - ), - height: const VideoSizeConstraint( - minimum: 40, - ideal: 50, - maximum: 50, - ), + width: const VideoSizeConstraint(minimum: 90, ideal: 100, maximum: 100), + height: const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50), deviceId: 'deviceId', ), equals( VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.environment), - width: const VideoSizeConstraint( - minimum: 90, - ideal: 100, - maximum: 100, - ), - height: const VideoSizeConstraint( - minimum: 40, - ideal: 50, - maximum: 50, - ), + width: const VideoSizeConstraint(minimum: 90, ideal: 100, maximum: 100), + height: const VideoSizeConstraint(minimum: 40, ideal: 50, maximum: 50), deviceId: 'deviceId', ), ), @@ -206,11 +164,7 @@ void main() { group('VideoSizeConstraint ', () { testWidgets('serializes correctly', (WidgetTester tester) async { expect( - const VideoSizeConstraint( - minimum: 200, - ideal: 400, - maximum: 400, - ).toJson(), + const VideoSizeConstraint(minimum: 200, ideal: 400, maximum: 400).toJson(), equals({'min': 200, 'ideal': 400, 'max': 400}), ); }); @@ -218,9 +172,7 @@ void main() { testWidgets('supports value equality', (WidgetTester tester) async { expect( const VideoSizeConstraint(minimum: 100, ideal: 200, maximum: 300), - equals( - const VideoSizeConstraint(minimum: 100, ideal: 200, maximum: 300), - ), + equals(const VideoSizeConstraint(minimum: 100, ideal: 200, maximum: 300)), ); }); }); diff --git a/packages/camera/camera_web/example/integration_test/camera_service_test.dart b/packages/camera/camera_web/example/integration_test/camera_service_test.dart index 2805ae069350..26fe6a2fd745 100644 --- a/packages/camera/camera_web/example/integration_test/camera_service_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_service_test.dart @@ -44,8 +44,7 @@ void main() { window = createJSInteropWrapper(mockWindow) as web.Window; navigator = createJSInteropWrapper(mockNavigator) as web.Navigator; - mediaDevices = - createJSInteropWrapper(mockMediaDevices) as web.MediaDevices; + mediaDevices = createJSInteropWrapper(mockMediaDevices) as web.MediaDevices; mockWindow.navigator = navigator; mockNavigator.mediaDevices = mediaDevices; @@ -54,10 +53,9 @@ void main() { // Mock JsUtil to return the real getProperty from dart:js_util. when(jsUtil.getProperty(any, any)).thenAnswer( - (Invocation invocation) => - (invocation.positionalArguments[0] as JSObject).getProperty( - invocation.positionalArguments[1] as JSAny, - ), + (Invocation invocation) => (invocation.positionalArguments[0] as JSObject).getProperty( + invocation.positionalArguments[1] as JSAny, + ), ); cameraService = CameraService()..window = window; @@ -67,12 +65,10 @@ void main() { testWidgets('calls MediaDevices.getUserMedia ' 'with provided options', (WidgetTester tester) async { late final web.MediaStreamConstraints? capturedConstraints; - mockMediaDevices - .getUserMedia = ([web.MediaStreamConstraints? constraints]) { + mockMediaDevices.getUserMedia = ([web.MediaStreamConstraints? constraints]) { capturedConstraints = constraints; final stream = - createJSInteropWrapper(FakeMediaStream([])) - as web.MediaStream; + createJSInteropWrapper(FakeMediaStream([])) as web.MediaStream; return Future.value(stream).toJS; }.toJS; @@ -106,22 +102,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.notFound, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notFound), ), ); }); @@ -136,22 +121,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.notFound, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notFound), ), ); }); @@ -165,22 +139,11 @@ void main() { return Future.value(web.MediaStream()).toJS; }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.notReadable, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notReadable), ), ); }); @@ -195,22 +158,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.notReadable, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notReadable), ), ); }); @@ -225,17 +177,10 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) .having( (CameraWebException e) => e.code, 'code', @@ -255,17 +200,10 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) .having( (CameraWebException e) => e.code, 'code', @@ -285,17 +223,10 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) .having( (CameraWebException e) => e.code, 'code', @@ -315,17 +246,10 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) .having( (CameraWebException e) => e.code, 'code', @@ -345,22 +269,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.type, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.type), ), ); }); @@ -375,22 +288,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.abort, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.abort), ), ); }); @@ -405,22 +307,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.security, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.security), ), ); }); @@ -435,22 +326,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.unknown, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.unknown), ), ); }); @@ -466,22 +346,11 @@ void main() { }.toJS; expect( - () => cameraService.getMediaStreamForOptions( - const CameraOptions(), - cameraId: cameraId, - ), + () => cameraService.getMediaStreamForOptions(const CameraOptions(), cameraId: cameraId), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - cameraId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.unknown, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', cameraId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.unknown), ), ); }); @@ -498,15 +367,13 @@ void main() { mockVideoTrack = MockMediaStreamTrack(); videoTracks = [ createJSInteropWrapper(mockVideoTrack) as web.MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as web.MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) as web.MediaStreamTrack, ]; when(camera.textureId).thenReturn(0); - when(camera.stream).thenReturn( - createJSInteropWrapper(FakeMediaStream(videoTracks)) - as web.MediaStream, - ); + when( + camera.stream, + ).thenReturn(createJSInteropWrapper(FakeMediaStream(videoTracks)) as web.MediaStream); cameraService.jsUtil = jsUtil; }); @@ -549,11 +416,7 @@ void main() { () => cameraService.getZoomLevelCapabilityForCamera(camera), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - camera.textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', camera.textureId) .having( (CameraWebException e) => e.code, 'code', @@ -564,33 +427,22 @@ void main() { }); testWidgets('with notStarted error ' - 'when the camera stream has not been initialized', ( - WidgetTester tester, - ) async { + 'when the camera stream has not been initialized', (WidgetTester tester) async { mockMediaDevices.getSupportedConstraints = () { return web.MediaTrackSupportedConstraints(zoom: true); }.toJS; // Create a camera stream with no video tracks. when(camera.stream).thenReturn( - createJSInteropWrapper(FakeMediaStream([])) - as web.MediaStream, + createJSInteropWrapper(FakeMediaStream([])) as web.MediaStream, ); expect( () => cameraService.getZoomLevelCapabilityForCamera(camera), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - camera.textureId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.notStarted, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', camera.textureId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notStarted), ), ); }); @@ -609,8 +461,7 @@ void main() { }.toJS; final String? facingMode = cameraService.getFacingModeForVideoTrack( - createJSInteropWrapper(MockMediaStreamTrack()) - as web.MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) as web.MediaStreamTrack, ); expect(facingMode, isNull); @@ -622,12 +473,9 @@ void main() { setUp(() { mockVideoTrack = MockMediaStreamTrack(); - videoTrack = - createJSInteropWrapper(mockVideoTrack) as web.MediaStreamTrack; + videoTrack = createJSInteropWrapper(mockVideoTrack) as web.MediaStreamTrack; - when( - jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), - ).thenReturn(true); + when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)).thenReturn(true); mockMediaDevices.getSupportedConstraints = () { return web.MediaTrackSupportedConstraints(facingMode: true); @@ -640,18 +488,14 @@ void main() { return web.MediaTrackSettings(facingMode: 'user'); }.toJS; - final String? facingMode = cameraService.getFacingModeForVideoTrack( - videoTrack, - ); + final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, equals('user')); }); testWidgets('returns an appropriate facing mode ' 'based on the video track capabilities ' - 'when the facing mode setting is empty', ( - WidgetTester tester, - ) async { + 'when the facing mode setting is empty', (WidgetTester tester) async { mockVideoTrack.getSettings = () { return web.MediaTrackSettings(facingMode: ''); }.toJS; @@ -661,13 +505,9 @@ void main() { ); }.toJS; - when( - jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), - ).thenReturn(true); + when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)).thenReturn(true); - final String? facingMode = cameraService.getFacingModeForVideoTrack( - videoTrack, - ); + final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, equals('environment')); }); @@ -682,29 +522,21 @@ void main() { return web.MediaTrackCapabilities(facingMode: [].toJS); }.toJS; - final String? facingMode = cameraService.getFacingModeForVideoTrack( - videoTrack, - ); + final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, isNull); }); testWidgets('returns null ' 'when the facing mode setting is empty and ' - 'the video track capabilities are not supported', ( - WidgetTester tester, - ) async { + 'the video track capabilities are not supported', (WidgetTester tester) async { mockVideoTrack.getSettings = () { return web.MediaTrackSettings(facingMode: ''); }.toJS; - when( - jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), - ).thenReturn(false); + when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)).thenReturn(false); - final String? facingMode = cameraService.getFacingModeForVideoTrack( - videoTrack, - ); + final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, isNull); }); @@ -713,21 +545,16 @@ void main() { 'when the facing mode setting is empty and ' 'the facingMode capability is null', (WidgetTester tester) async { mockVideoTrack.getSettings = () { - return createJSInteropWrapper(FakeMediaTrackSettings()) - as web.MediaTrackSettings; + return createJSInteropWrapper(FakeMediaTrackSettings()) as web.MediaTrackSettings; }.toJS; mockVideoTrack.getCapabilities = () { return createJSInteropWrapper(FakeMediaTrackCapabilities()) as web.MediaTrackCapabilities; }.toJS; - when( - jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), - ).thenReturn(true); + when(jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS)).thenReturn(true); - final String? facingMode = cameraService.getFacingModeForVideoTrack( - videoTrack, - ); + final String? facingMode = cameraService.getFacingModeForVideoTrack(videoTrack); expect(facingMode, isNull); }); @@ -771,10 +598,7 @@ void main() { group('mapFacingModeToCameraType', () { testWidgets('returns user ' 'when the facing mode is user', (WidgetTester tester) async { - expect( - cameraService.mapFacingModeToCameraType('user'), - equals(CameraType.user), - ); + expect(cameraService.mapFacingModeToCameraType('user'), equals(CameraType.user)); }); testWidgets('returns environment ' @@ -787,18 +611,12 @@ void main() { testWidgets('returns user ' 'when the facing mode is left', (WidgetTester tester) async { - expect( - cameraService.mapFacingModeToCameraType('left'), - equals(CameraType.user), - ); + expect(cameraService.mapFacingModeToCameraType('left'), equals(CameraType.user)); }); testWidgets('returns user ' 'when the facing mode is right', (WidgetTester tester) async { - expect( - cameraService.mapFacingModeToCameraType('right'), - equals(CameraType.user), - ); + expect(cameraService.mapFacingModeToCameraType('right'), equals(CameraType.user)); }); }); @@ -812,9 +630,7 @@ void main() { }); testWidgets('returns 4096x2160 ' - 'when the resolution preset is ultraHigh', ( - WidgetTester tester, - ) async { + 'when the resolution preset is ultraHigh', (WidgetTester tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.ultraHigh), equals(const Size(4096, 2160)), @@ -822,9 +638,7 @@ void main() { }); testWidgets('returns 1920x1080 ' - 'when the resolution preset is veryHigh', ( - WidgetTester tester, - ) async { + 'when the resolution preset is veryHigh', (WidgetTester tester) async { expect( cameraService.mapResolutionPresetToSize(ResolutionPreset.veryHigh), equals(const Size(1920, 1080)), @@ -858,49 +672,33 @@ void main() { group('mapDeviceOrientationToOrientationType', () { testWidgets('returns portraitPrimary ' - 'when the device orientation is portraitUp', ( - WidgetTester tester, - ) async { + 'when the device orientation is portraitUp', (WidgetTester tester) async { expect( - cameraService.mapDeviceOrientationToOrientationType( - DeviceOrientation.portraitUp, - ), + cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.portraitUp), equals(OrientationType.portraitPrimary), ); }); testWidgets('returns landscapePrimary ' - 'when the device orientation is landscapeLeft', ( - WidgetTester tester, - ) async { + 'when the device orientation is landscapeLeft', (WidgetTester tester) async { expect( - cameraService.mapDeviceOrientationToOrientationType( - DeviceOrientation.landscapeLeft, - ), + cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeLeft), equals(OrientationType.landscapePrimary), ); }); testWidgets('returns portraitSecondary ' - 'when the device orientation is portraitDown', ( - WidgetTester tester, - ) async { + 'when the device orientation is portraitDown', (WidgetTester tester) async { expect( - cameraService.mapDeviceOrientationToOrientationType( - DeviceOrientation.portraitDown, - ), + cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.portraitDown), equals(OrientationType.portraitSecondary), ); }); testWidgets('returns landscapeSecondary ' - 'when the device orientation is landscapeRight', ( - WidgetTester tester, - ) async { + 'when the device orientation is landscapeRight', (WidgetTester tester) async { expect( - cameraService.mapDeviceOrientationToOrientationType( - DeviceOrientation.landscapeRight, - ), + cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeRight), equals(OrientationType.landscapeSecondary), ); }); @@ -908,61 +706,41 @@ void main() { group('mapOrientationTypeToDeviceOrientation', () { testWidgets('returns portraitUp ' - 'when the orientation type is portraitPrimary', ( - WidgetTester tester, - ) async { + 'when the orientation type is portraitPrimary', (WidgetTester tester) async { expect( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.portraitPrimary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitPrimary), equals(DeviceOrientation.portraitUp), ); }); testWidgets('returns landscapeLeft ' - 'when the orientation type is landscapePrimary', ( - WidgetTester tester, - ) async { + 'when the orientation type is landscapePrimary', (WidgetTester tester) async { expect( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.landscapePrimary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.landscapePrimary), equals(DeviceOrientation.landscapeLeft), ); }); testWidgets('returns portraitDown ' - 'when the orientation type is portraitSecondary', ( - WidgetTester tester, - ) async { + 'when the orientation type is portraitSecondary', (WidgetTester tester) async { expect( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.portraitSecondary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitSecondary), equals(DeviceOrientation.portraitDown), ); }); testWidgets('returns portraitDown ' - 'when the orientation type is portraitSecondary', ( - WidgetTester tester, - ) async { + 'when the orientation type is portraitSecondary', (WidgetTester tester) async { expect( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.portraitSecondary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitSecondary), equals(DeviceOrientation.portraitDown), ); }); testWidgets('returns landscapeRight ' - 'when the orientation type is landscapeSecondary', ( - WidgetTester tester, - ) async { + 'when the orientation type is landscapeSecondary', (WidgetTester tester) async { expect( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.landscapeSecondary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.landscapeSecondary), equals(DeviceOrientation.landscapeRight), ); }); diff --git a/packages/camera/camera_web/example/integration_test/camera_test.dart b/packages/camera/camera_web/example/integration_test/camera_test.dart index 29af6ceddbd9..254ca20d2907 100644 --- a/packages/camera/camera_web/example/integration_test/camera_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_test.dart @@ -50,16 +50,11 @@ void main() { cameraService = MockCameraService(); - final HTMLVideoElement videoElement = getVideoElementWithBlankStream( - const Size(10, 10), - ); + final HTMLVideoElement videoElement = getVideoElementWithBlankStream(const Size(10, 10)); mediaStream = videoElement.captureStream(); when( - cameraService.getMediaStreamForOptions( - any, - cameraId: anyNamed('cameraId'), - ), + cameraService.getMediaStreamForOptions(any, cameraId: anyNamed('cameraId')), ).thenAnswer((_) => Future.value(mediaStream)); }); @@ -73,17 +68,11 @@ void main() { ), ); - final camera = Camera( - textureId: textureId, - options: options, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, options: options, cameraService: cameraService); await camera.initialize(); - verify( - cameraService.getMediaStreamForOptions(options, cameraId: textureId), - ).called(1); + verify(cameraService.getMediaStreamForOptions(options, cameraId: textureId)).called(1); }); testWidgets('creates a video element ' @@ -95,10 +84,7 @@ void main() { final camera = Camera( textureId: textureId, - options: CameraOptions( - audio: audioConstraints, - video: videoConstraints, - ), + options: CameraOptions(audio: audioConstraints, video: videoConstraints), cameraService: cameraService, ); @@ -108,15 +94,9 @@ void main() { expect(camera.videoElement.autoplay, isFalse); expect(camera.videoElement.muted, isTrue); expect(camera.videoElement.srcObject, mediaStream); - expect( - camera.videoElement.attributes.getNamedItem('playsinline'), - isNotNull, - ); + expect(camera.videoElement.attributes.getNamedItem('playsinline'), isNotNull); - expect( - camera.videoElement.style.transformOrigin, - equals('center center'), - ); + expect(camera.videoElement.style.transformOrigin, equals('center center')); expect(camera.videoElement.style.pointerEvents, equals('none')); expect(camera.videoElement.style.width, equals('100%')); expect(camera.videoElement.style.height, equals('100%')); @@ -142,29 +122,21 @@ void main() { testWidgets('creates a wrapping div element ' 'with correct properties', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); expect(camera.divElement, isNotNull); expect(camera.divElement.style.objectFit, equals('cover')); - final array = - (globalContext['Array']! as JSObject).callMethod( - 'from'.toJS, - camera.divElement.children, - ) - as JSArray?; + final array = (globalContext['Array']! as JSObject).callMethod( + 'from'.toJS, + camera.divElement.children, + ) as JSArray?; expect(array?.toDart, contains(camera.videoElement)); }); testWidgets('initializes the camera stream', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); @@ -172,44 +144,30 @@ void main() { }); testWidgets('throws an exception ' - 'when CameraService.getMediaStreamForOptions throws', ( - WidgetTester tester, - ) async { + 'when CameraService.getMediaStreamForOptions throws', (WidgetTester tester) async { final exception = Exception('A media stream exception occured.'); when( - cameraService.getMediaStreamForOptions( - any, - cameraId: anyNamed('cameraId'), - ), + cameraService.getMediaStreamForOptions(any, cameraId: anyNamed('cameraId')), ).thenThrow(exception); - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); expect(camera.initialize, throwsA(exception)); }); }); group('play', () { - testWidgets('starts playing the video element', ( - WidgetTester tester, - ) async { + testWidgets('starts playing the video element', (WidgetTester tester) async { var startedPlaying = false; - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); - final StreamSubscription cameraPlaySubscription = camera - .videoElement - .onPlay - .listen((Event event) => startedPlaying = true); + final StreamSubscription cameraPlaySubscription = camera.videoElement.onPlay.listen( + (Event event) => startedPlaying = true, + ); await camera.play(); @@ -225,11 +183,7 @@ void main() { video: VideoConstraints(width: VideoSizeConstraint(ideal: 100)), ); - final camera = Camera( - textureId: textureId, - options: options, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, options: options, cameraService: cameraService); await camera.initialize(); @@ -240,9 +194,7 @@ void main() { await camera.play(); // Should be called twice: for initialize and play. - verify( - cameraService.getMediaStreamForOptions(options, cameraId: textureId), - ).called(2); + verify(cameraService.getMediaStreamForOptions(options, cameraId: textureId)).called(2); expect(camera.videoElement.srcObject, mediaStream); expect(camera.stream, mediaStream); @@ -251,10 +203,7 @@ void main() { group('pause', () { testWidgets('pauses the camera stream', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); await camera.play(); @@ -269,10 +218,7 @@ void main() { group('stop', () { testWidgets('resets the camera stream', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); await camera.play(); @@ -286,10 +232,7 @@ void main() { group('takePicture', () { testWidgets('returns a captured picture', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); await camera.play(); @@ -312,12 +255,9 @@ void main() { createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack, createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ]; - videoStream = - createJSInteropWrapper(FakeMediaStream(videoTracks)) - as MediaStream; + videoStream = createJSInteropWrapper(FakeMediaStream(videoTracks)) as MediaStream; - videoElement = getVideoElementWithBlankStream(const Size(100, 100)) - ..muted = true; + videoElement = getVideoElementWithBlankStream(const Size(100, 100))..muted = true; mockVideoTrack.getCapabilities = () { return MediaTrackCapabilities(torch: [true.toJS].toJS); @@ -325,23 +265,21 @@ void main() { }); testWidgets('if the flash mode is auto', (WidgetTester tester) async { - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..window = window - ..stream = videoStream - ..videoElement = videoElement - ..flashMode = FlashMode.auto; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream + ..videoElement = videoElement + ..flashMode = FlashMode.auto; await camera.play(); final capturedConstraints = []; - mockVideoTrack.applyConstraints = - ([MediaTrackConstraints? constraints]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; final XFile _ = await camera.takePicture(); @@ -351,23 +289,21 @@ void main() { }); testWidgets('if the flash mode is always', (WidgetTester tester) async { - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..window = window - ..stream = videoStream - ..videoElement = videoElement - ..flashMode = FlashMode.always; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream + ..videoElement = videoElement + ..flashMode = FlashMode.always; await camera.play(); final capturedConstraints = []; - mockVideoTrack.applyConstraints = - ([MediaTrackConstraints? constraints]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; final XFile _ = await camera.takePicture(); @@ -380,20 +316,13 @@ void main() { group('getVideoSize', () { testWidgets('returns a size ' - 'based on the first video track settings', ( - WidgetTester tester, - ) async { + 'based on the first video track settings', (WidgetTester tester) async { const videoSize = Size(1280, 720); - final HTMLVideoElement videoElement = getVideoElementWithBlankStream( - videoSize, - ); + final HTMLVideoElement videoElement = getVideoElementWithBlankStream(videoSize); mediaStream = videoElement.captureStream(); - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); @@ -406,10 +335,7 @@ void main() { final videoElement = HTMLVideoElement(); mediaStream = videoElement.captureStream(); - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); @@ -428,13 +354,11 @@ void main() { createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack, createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ]; - videoStream = - createJSInteropWrapper(FakeMediaStream(videoTracks)) as MediaStream; + videoStream = createJSInteropWrapper(FakeMediaStream(videoTracks)) as MediaStream; - mockVideoTrack.applyConstraints = - ([MediaTrackConstraints? constraints]) { - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { + return Future.value().toJS; + }.toJS; mockVideoTrack.getCapabilities = () { return MediaTrackCapabilities(); @@ -450,10 +374,9 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..window = window - ..stream = videoStream; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; const FlashMode flashMode = FlashMode.always; @@ -472,19 +395,17 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..window = window - ..stream = videoStream; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; final capturedConstraints = []; - mockVideoTrack.applyConstraints = - ([MediaTrackConstraints? constraints]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; camera.setFlashMode(FlashMode.torch); @@ -502,19 +423,17 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..window = window - ..stream = videoStream; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; final capturedConstraints = []; - mockVideoTrack.applyConstraints = - ([MediaTrackConstraints? constraints]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; camera.setFlashMode(FlashMode.auto); @@ -534,20 +453,15 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..window = window - ..stream = videoStream; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; expect( () => camera.setFlashMode(FlashMode.always), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) .having( (CameraWebException e) => e.code, 'code', @@ -568,20 +482,15 @@ void main() { return MediaTrackCapabilities(torch: [false.toJS].toJS); }.toJS; - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..window = window - ..stream = videoStream; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window + ..stream = videoStream; expect( () => camera.setFlashMode(FlashMode.always), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) .having( (CameraWebException e) => e.code, 'code', @@ -592,9 +501,7 @@ void main() { }); testWidgets('with notStarted error ' - 'when the camera stream has not been initialized', ( - WidgetTester tester, - ) async { + 'when the camera stream has not been initialized', (WidgetTester tester) async { mockMediaDevices.getSupportedConstraints = () { return MediaTrackSupportedConstraints(torch: true); }.toJS; @@ -603,25 +510,15 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - )..window = window; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..window = window; expect( () => camera.setFlashMode(FlashMode.always), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.notStarted, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notStarted), ), ); }); @@ -631,20 +528,13 @@ void main() { group('zoomLevel', () { group('getMaxZoomLevel', () { testWidgets('returns maximum ' - 'from CameraService.getZoomLevelCapabilityForCamera', ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + 'from CameraService.getZoomLevelCapabilityForCamera', (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ); when( @@ -653,9 +543,7 @@ void main() { final double maximumZoomLevel = camera.getMaxZoomLevel(); - verify( - cameraService.getZoomLevelCapabilityForCamera(camera), - ).called(1); + verify(cameraService.getZoomLevelCapabilityForCamera(camera)).called(1); expect(maximumZoomLevel, equals(zoomLevelCapability.maximum)); }); @@ -663,20 +551,13 @@ void main() { group('getMinZoomLevel', () { testWidgets('returns minimum ' - 'from CameraService.getZoomLevelCapabilityForCamera', ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + 'from CameraService.getZoomLevelCapabilityForCamera', (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ); when( @@ -685,9 +566,7 @@ void main() { final double minimumZoomLevel = camera.getMinZoomLevel(); - verify( - cameraService.getZoomLevelCapabilityForCamera(camera), - ).called(1); + verify(cameraService.getZoomLevelCapabilityForCamera(camera)).called(1); expect(minimumZoomLevel, equals(zoomLevelCapability.minimum)); }); @@ -695,17 +574,11 @@ void main() { group('setZoomLevel', () { testWidgets('applies zoom on the video track ' - 'from CameraService.getZoomLevelCapabilityForCamera', ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + 'from CameraService.getZoomLevelCapabilityForCamera', (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); final mockVideoTrack = MockMediaStreamTrack(); - final videoTrack = - createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; + final videoTrack = createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, @@ -714,13 +587,12 @@ void main() { ); final capturedConstraints = []; - mockVideoTrack.applyConstraints = - ([MediaTrackConstraints? constraints]) { - if (constraints != null) { - capturedConstraints.add(constraints); - } - return Future.value().toJS; - }.toJS; + mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { + if (constraints != null) { + capturedConstraints.add(constraints); + } + return Future.value().toJS; + }.toJS; when( cameraService.getZoomLevelCapabilityForCamera(camera), @@ -736,20 +608,13 @@ void main() { group('throws a CameraWebException', () { testWidgets('with zoomLevelInvalid error ' - 'when the provided zoom level is below minimum', ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + 'when the provided zoom level is below minimum', (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ); when( @@ -760,11 +625,7 @@ void main() { () => camera.setZoomLevel(45.0), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) .having( (CameraWebException e) => e.code, 'code', @@ -775,20 +636,13 @@ void main() { }); testWidgets('with zoomLevelInvalid error ' - 'when the provided zoom level is below minimum', ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + 'when the provided zoom level is below minimum', (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, - videoTrack: - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, + videoTrack: createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ); when( @@ -799,11 +653,7 @@ void main() { () => camera.setZoomLevel(105.0), throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) .having( (CameraWebException e) => e.code, 'code', @@ -818,29 +668,21 @@ void main() { group('getLensDirection', () { testWidgets('returns a lens direction ' - 'based on the first video track settings', ( - WidgetTester tester, - ) async { + 'based on the first video track settings', (WidgetTester tester) async { final mockVideoElement = MockVideoElement(); - final videoElement = - createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; + final videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - )..videoElement = videoElement; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..videoElement = videoElement; final firstVideoTrack = MockMediaStreamTrack(); - mockVideoElement.srcObject = - createJSInteropWrapper( - FakeMediaStream([ - createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ]), - ) - as MediaStream; + mockVideoElement.srcObject = createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + ]), + ) as MediaStream; firstVideoTrack.getSettings = () { return MediaTrackSettings(facingMode: 'environment'); @@ -854,29 +696,21 @@ void main() { }); testWidgets('returns null ' - 'if the first video track is missing the facing mode', ( - WidgetTester tester, - ) async { + 'if the first video track is missing the facing mode', (WidgetTester tester) async { final mockVideoElement = MockVideoElement(); - final videoElement = - createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; + final videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - )..videoElement = videoElement; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..videoElement = videoElement; final firstVideoTrack = MockMediaStreamTrack(); - videoElement.srcObject = - createJSInteropWrapper( - FakeMediaStream([ - createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ]), - ) - as MediaStream; + videoElement.srcObject = createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(firstVideoTrack) as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + ]), + ) as MediaStream; firstVideoTrack.getSettings = () { return MediaTrackSettings(); @@ -891,10 +725,7 @@ void main() { final videoElement = HTMLVideoElement(); mediaStream = videoElement.captureStream(); - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); @@ -904,17 +735,11 @@ void main() { group('getViewType', () { testWidgets('returns a correct view type', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); - expect( - camera.getViewType(), - equals('plugins.flutter.io/camera_$textureId'), - ); + expect(camera.getViewType(), equals('plugins.flutter.io/camera_$textureId')); }); }); @@ -928,8 +753,7 @@ void main() { setUp(() { mockMediaRecorder = MockMediaRecorder(); - mediaRecorder = - createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; + mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; }); group('startVideoRecording', () { @@ -950,9 +774,7 @@ void main() { expect(camera.mediaRecorder!.state, equals('recording')); }); - testWidgets('listens to the media recorder data events', ( - WidgetTester tester, - ) async { + testWidgets('listens to the media recorder data events', (WidgetTester tester) async { final camera = Camera(textureId: 1, cameraService: cameraService) ..mediaRecorder = mediaRecorder ..isVideoTypeSupported = isVideoTypeSupported; @@ -968,15 +790,10 @@ void main() { await camera.startVideoRecording(); - expect( - capturedEvents.where((String e) => e == 'dataavailable').length, - 1, - ); + expect(capturedEvents.where((String e) => e == 'dataavailable').length, 1); }); - testWidgets('listens to the media recorder stop events', ( - WidgetTester tester, - ) async { + testWidgets('listens to the media recorder stop events', (WidgetTester tester) async { final camera = Camera(textureId: 1, cameraService: cameraService) ..mediaRecorder = mediaRecorder ..isVideoTypeSupported = isVideoTypeSupported; @@ -1026,16 +843,8 @@ void main() { camera.startVideoRecording, throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) - .having( - (CameraWebException e) => e.code, - 'code', - CameraErrorCode.notSupported, - ), + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) + .having((CameraWebException e) => e.code, 'code', CameraErrorCode.notSupported), ), ); }); @@ -1059,20 +868,14 @@ void main() { testWidgets('throws a CameraWebException ' 'with videoRecordingNotStarted error ' - 'if the video recording was not started', ( - WidgetTester tester, - ) async { + 'if the video recording was not started', (WidgetTester tester) async { final camera = Camera(textureId: 1, cameraService: cameraService); expect( camera.pauseVideoRecording, throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) .having( (CameraWebException e) => e.code, 'code', @@ -1100,20 +903,14 @@ void main() { testWidgets('throws a CameraWebException ' 'with videoRecordingNotStarted error ' - 'if the video recording was not started', ( - WidgetTester tester, - ) async { + 'if the video recording was not started', (WidgetTester tester) async { final camera = Camera(textureId: 1, cameraService: cameraService); expect( camera.resumeVideoRecording, throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) .having( (CameraWebException e) => e.code, 'code', @@ -1167,20 +964,15 @@ void main() { final capturedVideoPartOne = Blob([].toJS); final capturedVideoPartTwo = Blob([].toJS); - final capturedVideoParts = [ - capturedVideoPartOne, - capturedVideoPartTwo, - ]; + final capturedVideoParts = [capturedVideoPartOne, capturedVideoPartTwo]; videoDataAvailableListener.callAsFunction( null, - createJSInteropWrapper(FakeBlobEvent(capturedVideoPartOne)) - as BlobEvent, + createJSInteropWrapper(FakeBlobEvent(capturedVideoPartOne)) as BlobEvent, ); videoDataAvailableListener.callAsFunction( null, - createJSInteropWrapper(FakeBlobEvent(capturedVideoPartTwo)) - as BlobEvent, + createJSInteropWrapper(FakeBlobEvent(capturedVideoPartTwo)) as BlobEvent, ); videoRecordingStoppedListener.callAsFunction(null, Event('stop')); @@ -1200,20 +992,14 @@ void main() { testWidgets('throws a CameraWebException ' 'with videoRecordingNotStarted error ' - 'if the video recording was not started', ( - WidgetTester tester, - ) async { + 'if the video recording was not started', (WidgetTester tester) async { final camera = Camera(textureId: 1, cameraService: cameraService); expect( camera.stopVideoRecording, throwsA( isA() - .having( - (CameraWebException e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((CameraWebException e) => e.cameraId, 'cameraId', textureId) .having( (CameraWebException e) => e.code, 'code', @@ -1258,10 +1044,7 @@ void main() { await Future.microtask(() {}); - expect( - capturedEvents.where((String e) => e == 'dataavailable').length, - 1, - ); + expect(capturedEvents.where((String e) => e == 'dataavailable').length, 1); }); testWidgets('stops listening to the media recorder stop events', ( @@ -1289,9 +1072,7 @@ void main() { expect(capturedEvents.where((String e) => e == 'stop').length, 1); }); - testWidgets('stops listening to the media recorder errors', ( - WidgetTester tester, - ) async { + testWidgets('stops listening to the media recorder errors', (WidgetTester tester) async { final onErrorStreamController = StreamController(); final provider = MockEventStreamProvider(); @@ -1300,9 +1081,7 @@ void main() { ..isVideoTypeSupported = isVideoTypeSupported ..mediaRecorderOnErrorProvider = provider; - when( - provider.forTarget(mediaRecorder), - ).thenAnswer((_) => onErrorStreamController.stream); + when(provider.forTarget(mediaRecorder)).thenAnswer((_) => onErrorStreamController.stream); await camera.initialize(); await camera.play(); @@ -1319,13 +1098,8 @@ void main() { }); group('dispose', () { - testWidgets("resets the video element's source", ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + testWidgets("resets the video element's source", (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); await camera.dispose(); @@ -1334,10 +1108,7 @@ void main() { }); testWidgets('closes the onEnded stream', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); await camera.dispose(); @@ -1345,13 +1116,8 @@ void main() { expect(camera.onEndedController.isClosed, isTrue); }); - testWidgets('closes the onVideoRecordedEvent stream', ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + testWidgets('closes the onVideoRecordedEvent stream', (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); await camera.dispose(); @@ -1359,13 +1125,8 @@ void main() { expect(camera.videoRecorderController.isClosed, isTrue); }); - testWidgets('closes the onVideoRecordingError stream', ( - WidgetTester tester, - ) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + testWidgets('closes the onVideoRecordingError stream', (WidgetTester tester) async { + final camera = Camera(textureId: textureId, cameraService: cameraService); await camera.initialize(); await camera.dispose(); @@ -1381,8 +1142,7 @@ void main() { const supportedVideoType = 'video/webm'; final mockMediaRecorder = MockMediaRecorder(); - final mediaRecorder = - createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; + final mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; final camera = Camera(textureId: 1, cameraService: cameraService) ..mediaRecorder = mediaRecorder @@ -1403,9 +1163,7 @@ void main() { } }.toJS; - final streamQueue = StreamQueue( - camera.onVideoRecordedEvent, - ); + final streamQueue = StreamQueue(camera.onVideoRecordedEvent); await camera.startVideoRecording(); @@ -1425,25 +1183,13 @@ void main() { await streamQueue.next, equals( isA() - .having( - (VideoRecordedEvent e) => e.cameraId, - 'cameraId', - textureId, - ) + .having((VideoRecordedEvent e) => e.cameraId, 'cameraId', textureId) .having( (VideoRecordedEvent e) => e.file, 'file', isA() - .having( - (XFile f) => f.mimeType, - 'mimeType', - supportedVideoType, - ) - .having( - (XFile f) => f.name, - 'name', - finalVideo.hashCode.toString(), - ), + .having((XFile f) => f.mimeType, 'mimeType', supportedVideoType) + .having((XFile f) => f.name, 'name', finalVideo.hashCode.toString()), ), ), ); @@ -1455,18 +1201,13 @@ void main() { group('onEnded', () { testWidgets('emits the default video track ' 'when it emits an ended event', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); final streamQueue = StreamQueue(camera.onEnded); await camera.initialize(); - final List videoTracks = camera.stream! - .getVideoTracks() - .toDart; + final List videoTracks = camera.stream!.getVideoTracks().toDart; final MediaStreamTrack defaultVideoTrack = videoTracks.first; defaultVideoTrack.dispatchEvent(Event('ended')); @@ -1478,18 +1219,13 @@ void main() { testWidgets('emits the default video track ' 'when the camera is stopped', (WidgetTester tester) async { - final camera = Camera( - textureId: textureId, - cameraService: cameraService, - ); + final camera = Camera(textureId: textureId, cameraService: cameraService); final streamQueue = StreamQueue(camera.onEnded); await camera.initialize(); - final List videoTracks = camera.stream! - .getVideoTracks() - .toDart; + final List videoTracks = camera.stream!.getVideoTracks().toDart; final MediaStreamTrack defaultVideoTrack = videoTracks.first; camera.stop(); @@ -1505,23 +1241,17 @@ void main() { 'when the media recorder fails ' 'when recording a video', (WidgetTester tester) async { final mockMediaRecorder = MockMediaRecorder(); - final mediaRecorder = - createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; + final mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; final errorController = StreamController(); final provider = MockEventStreamProvider(); - final camera = - Camera(textureId: textureId, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..mediaRecorderOnErrorProvider = provider; + final camera = Camera(textureId: textureId, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..mediaRecorderOnErrorProvider = provider; - when( - provider.forTarget(mediaRecorder), - ).thenAnswer((_) => errorController.stream); + when(provider.forTarget(mediaRecorder)).thenAnswer((_) => errorController.stream); - final streamQueue = StreamQueue( - camera.onVideoRecordingError, - ); + final streamQueue = StreamQueue(camera.onVideoRecordingError); await camera.initialize(); await camera.play(); diff --git a/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart b/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart index 8bc9469510b1..bf3f573226be 100644 --- a/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart @@ -23,19 +23,14 @@ void main() { expect(exception.description, equals(description)); }); - testWidgets('toString includes all properties', ( - WidgetTester tester, - ) async { + testWidgets('toString includes all properties', (WidgetTester tester) async { const cameraId = 2; const CameraErrorCode code = CameraErrorCode.notReadable; const description = 'The camera is not readable.'; final exception = CameraWebException(cameraId, code, description); - expect( - exception.toString(), - equals('CameraWebException($cameraId, $code, $description)'), - ); + expect(exception.toString(), equals('CameraWebException($cameraId, $code, $description)')); }); }); } diff --git a/packages/camera/camera_web/example/integration_test/camera_web_test.dart b/packages/camera/camera_web/example/integration_test/camera_web_test.dart index 5542bac34ec0..e772a9ebdc4e 100644 --- a/packages/camera/camera_web/example/integration_test/camera_web_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_web_test.dart @@ -71,8 +71,7 @@ void main() { mockScreenOrientation = MockScreenOrientation(); screen = createJSInteropWrapper(mockScreen) as Screen; - screenOrientation = - createJSInteropWrapper(mockScreenOrientation) as ScreenOrientation; + screenOrientation = createJSInteropWrapper(mockScreenOrientation) as ScreenOrientation; mockScreen.orientation = screenOrientation; mockWindow.screen = screen; @@ -89,19 +88,13 @@ void main() { cameraService = MockCameraService(); when( - cameraService.getMediaStreamForOptions( - any, - cameraId: anyNamed('cameraId'), - ), + cameraService.getMediaStreamForOptions(any, cameraId: anyNamed('cameraId')), ).thenAnswer((_) async => videoElement.captureStream()); - CameraPlatform.instance = CameraPlugin(cameraService: cameraService) - ..window = window; + CameraPlatform.instance = CameraPlugin(cameraService: cameraService)..window = window; }); - testWidgets('CameraPlugin is the live instance', ( - WidgetTester tester, - ) async { + testWidgets('CameraPlugin is the live instance', (WidgetTester tester) async { expect(CameraPlatform.instance, isA()); }); @@ -110,75 +103,52 @@ void main() { when(cameraService.getFacingModeForVideoTrack(any)).thenReturn(null); mockMediaDevices.enumerateDevices = () { - return Future>.value( - [].toJS, - ).toJS; + return Future>.value([].toJS).toJS; }.toJS; }); testWidgets('requests video permissions', (WidgetTester tester) async { - final List _ = await CameraPlatform.instance - .availableCameras(); + final List _ = await CameraPlatform.instance.availableCameras(); - verify( - cameraService.getMediaStreamForOptions(const CameraOptions()), - ).called(1); + verify(cameraService.getMediaStreamForOptions(const CameraOptions())).called(1); }); testWidgets('releases the camera stream ' 'used to request video permissions', (WidgetTester tester) async { final mockVideoTrack = MockMediaStreamTrack(); - final videoTrack = - createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; + final videoTrack = createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; var videoTrackStopped = false; mockVideoTrack.stop = () { videoTrackStopped = true; }.toJS; - when( - cameraService.getMediaStreamForOptions(const CameraOptions()), - ).thenAnswer( + when(cameraService.getMediaStreamForOptions(const CameraOptions())).thenAnswer( (_) => Future.value( - createJSInteropWrapper( - FakeMediaStream([videoTrack]), - ) - as MediaStream, + createJSInteropWrapper(FakeMediaStream([videoTrack])) as MediaStream, ), ); - final List _ = await CameraPlatform.instance - .availableCameras(); + final List _ = await CameraPlatform.instance.availableCameras(); expect(videoTrackStopped, isTrue); }); testWidgets('gets a video stream ' 'for a video input device', (WidgetTester tester) async { - final videoDevice = - createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) - as MediaDeviceInfo; + final videoDevice = createJSInteropWrapper( + FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput), + ) as MediaDeviceInfo; mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS, - ).toJS; + return Future>.value([videoDevice].toJS).toJS; }.toJS; - final List _ = await CameraPlatform.instance - .availableCameras(); + final List _ = await CameraPlatform.instance.availableCameras(); verify( cameraService.getMediaStreamForOptions( - CameraOptions( - video: VideoConstraints(deviceId: videoDevice.deviceId), - ), + CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)), ), ).called(1); }); @@ -186,30 +156,19 @@ void main() { testWidgets('does not get a video stream ' 'for the video input device ' 'with an empty device id', (WidgetTester tester) async { - final videoDevice = - createJSInteropWrapper( - FakeMediaDeviceInfo( - '', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) - as MediaDeviceInfo; + final videoDevice = createJSInteropWrapper( + FakeMediaDeviceInfo('', 'Camera 1', MediaDeviceKind.videoInput), + ) as MediaDeviceInfo; mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS, - ).toJS; + return Future>.value([videoDevice].toJS).toJS; }.toJS; - final List _ = await CameraPlatform.instance - .availableCameras(); + final List _ = await CameraPlatform.instance.availableCameras(); verifyNever( cameraService.getMediaStreamForOptions( - CameraOptions( - video: VideoConstraints(deviceId: videoDevice.deviceId), - ), + CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)), ), ); }); @@ -217,95 +176,59 @@ void main() { testWidgets('gets the facing mode ' 'from the first available video track ' 'of the video input device', (WidgetTester tester) async { - final videoDevice = - createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) - as MediaDeviceInfo; - - final videoStream = - createJSInteropWrapper( - FakeMediaStream([ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ]), - ) - as MediaStream; + final videoDevice = createJSInteropWrapper( + FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput), + ) as MediaDeviceInfo; + + final videoStream = createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + ]), + ) as MediaStream; when( cameraService.getMediaStreamForOptions( - CameraOptions( - video: VideoConstraints(deviceId: videoDevice.deviceId), - ), + CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)), ), ).thenAnswer((_) => Future.value(videoStream)); mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS, - ).toJS; + return Future>.value([videoDevice].toJS).toJS; }.toJS; - final List _ = await CameraPlatform.instance - .availableCameras(); + final List _ = await CameraPlatform.instance.availableCameras(); verify( - cameraService.getFacingModeForVideoTrack( - videoStream.getVideoTracks().toDart.first, - ), + cameraService.getFacingModeForVideoTrack(videoStream.getVideoTracks().toDart.first), ).called(1); }); testWidgets('returns appropriate camera descriptions ' 'for multiple video devices ' 'based on video streams', (WidgetTester tester) async { - final firstVideoDevice = - createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) - as MediaDeviceInfo; - - final secondVideoDevice = - createJSInteropWrapper( - FakeMediaDeviceInfo( - '4', - 'Camera 4', - MediaDeviceKind.videoInput, - ), - ) - as MediaDeviceInfo; + final firstVideoDevice = createJSInteropWrapper( + FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput), + ) as MediaDeviceInfo; + + final secondVideoDevice = createJSInteropWrapper( + FakeMediaDeviceInfo('4', 'Camera 4', MediaDeviceKind.videoInput), + ) as MediaDeviceInfo; // Create a video stream for the first video device. - final firstVideoStream = - createJSInteropWrapper( - FakeMediaStream([ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ]), - ) - as MediaStream; + final firstVideoStream = createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + ]), + ) as MediaStream; // Create a video stream for the second video device. - final secondVideoStream = - createJSInteropWrapper( - FakeMediaStream([ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ]), - ) - as MediaStream; + final secondVideoStream = createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + ]), + ) as MediaStream; // Mock media devices to return two video input devices // and two audio devices. @@ -314,21 +237,11 @@ void main() { [ firstVideoDevice, createJSInteropWrapper( - FakeMediaDeviceInfo( - '2', - 'Audio Input 2', - MediaDeviceKind.audioInput, - ), - ) - as MediaDeviceInfo, + FakeMediaDeviceInfo('2', 'Audio Input 2', MediaDeviceKind.audioInput), + ) as MediaDeviceInfo, createJSInteropWrapper( - FakeMediaDeviceInfo( - '3', - 'Audio Output 3', - MediaDeviceKind.audioOutput, - ), - ) - as MediaDeviceInfo, + FakeMediaDeviceInfo('3', 'Audio Output 3', MediaDeviceKind.audioOutput), + ) as MediaDeviceInfo, secondVideoDevice, ].toJS, ).toJS; @@ -338,9 +251,7 @@ void main() { // for the first video device. when( cameraService.getMediaStreamForOptions( - CameraOptions( - video: VideoConstraints(deviceId: firstVideoDevice.deviceId), - ), + CameraOptions(video: VideoConstraints(deviceId: firstVideoDevice.deviceId)), ), ).thenAnswer((_) => Future.value(firstVideoStream)); @@ -348,18 +259,14 @@ void main() { // for the second video device. when( cameraService.getMediaStreamForOptions( - CameraOptions( - video: VideoConstraints(deviceId: secondVideoDevice.deviceId), - ), + CameraOptions(video: VideoConstraints(deviceId: secondVideoDevice.deviceId)), ), ).thenAnswer((_) => Future.value(secondVideoStream)); // Mock camera service to return a user facing mode // for the first video stream. when( - cameraService.getFacingModeForVideoTrack( - firstVideoStream.getVideoTracks().toDart.first, - ), + cameraService.getFacingModeForVideoTrack(firstVideoStream.getVideoTracks().toDart.first), ).thenReturn('user'); when( @@ -369,17 +276,14 @@ void main() { // Mock camera service to return an environment facing mode // for the second video stream. when( - cameraService.getFacingModeForVideoTrack( - secondVideoStream.getVideoTracks().toDart.first, - ), + cameraService.getFacingModeForVideoTrack(secondVideoStream.getVideoTracks().toDart.first), ).thenReturn('environment'); when( cameraService.mapFacingModeToLensDirection('environment'), ).thenReturn(CameraLensDirection.back); - final List cameras = await CameraPlatform.instance - .availableCameras(); + final List cameras = await CameraPlatform.instance.availableCameras(); // Expect two cameras and ignore two audio devices. expect( @@ -401,76 +305,50 @@ void main() { testWidgets('sets camera metadata ' 'for the camera description', (WidgetTester tester) async { - final videoDevice = - createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) - as MediaDeviceInfo; - - final videoStream = - createJSInteropWrapper( - FakeMediaStream([ - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - createJSInteropWrapper(MockMediaStreamTrack()) - as MediaStreamTrack, - ]), - ) - as MediaStream; + final videoDevice = createJSInteropWrapper( + FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput), + ) as MediaDeviceInfo; + + final videoStream = createJSInteropWrapper( + FakeMediaStream([ + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, + ]), + ) as MediaStream; mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS, - ).toJS; + return Future>.value([videoDevice].toJS).toJS; }.toJS; when( cameraService.getMediaStreamForOptions( - CameraOptions( - video: VideoConstraints(deviceId: videoDevice.deviceId), - ), + CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)), ), ).thenAnswer((_) => Future.value(videoStream)); when( - cameraService.getFacingModeForVideoTrack( - videoStream.getVideoTracks().toDart.first, - ), + cameraService.getFacingModeForVideoTrack(videoStream.getVideoTracks().toDart.first), ).thenReturn('left'); when( cameraService.mapFacingModeToLensDirection('left'), ).thenReturn(CameraLensDirection.external); - final CameraDescription camera = - (await CameraPlatform.instance.availableCameras()).first; + final CameraDescription camera = (await CameraPlatform.instance.availableCameras()).first; expect( (CameraPlatform.instance as CameraPlugin).camerasMetadata, equals({ - camera: CameraMetadata( - deviceId: videoDevice.deviceId, - facingMode: 'left', - ), + camera: CameraMetadata(deviceId: videoDevice.deviceId, facingMode: 'left'), }), ); }); testWidgets('releases the video stream ' 'of a video input device', (WidgetTester tester) async { - final videoDevice = - createJSInteropWrapper( - FakeMediaDeviceInfo( - '1', - 'Camera 1', - MediaDeviceKind.videoInput, - ), - ) - as MediaDeviceInfo; + final videoDevice = createJSInteropWrapper( + FakeMediaDeviceInfo('1', 'Camera 1', MediaDeviceKind.videoInput), + ) as MediaDeviceInfo; final tracks = []; final stops = List.generate(2, (_) => false); @@ -482,25 +360,19 @@ void main() { tracks.add(createJSInteropWrapper(track) as MediaStreamTrack); } - final videoStream = - createJSInteropWrapper(FakeMediaStream(tracks)) as MediaStream; + final videoStream = createJSInteropWrapper(FakeMediaStream(tracks)) as MediaStream; mockMediaDevices.enumerateDevices = () { - return Future>.value( - [videoDevice].toJS, - ).toJS; + return Future>.value([videoDevice].toJS).toJS; }.toJS; when( cameraService.getMediaStreamForOptions( - CameraOptions( - video: VideoConstraints(deviceId: videoDevice.deviceId), - ), + CameraOptions(video: VideoConstraints(deviceId: videoDevice.deviceId)), ), ).thenAnswer((_) => Future.value(videoStream)); - final List _ = await CameraPlatform.instance - .availableCameras(); + final List _ = await CameraPlatform.instance.availableCameras(); expect(stops.every((bool e) => e), isTrue); }); @@ -514,34 +386,22 @@ void main() { mockMediaDevices.enumerateDevices = () { throw exception; // ignore: dead_code - return Future>.value( - [].toJS, - ).toJS; + return Future>.value([].toJS).toJS; }.toJS; expect( () => CameraPlatform.instance.availableCameras(), throwsA( - isA().having( - (CameraException e) => e.code, - 'code', - exception.name, - ), + isA().having((CameraException e) => e.code, 'code', exception.name), ), ); }); testWidgets('when CameraService.getMediaStreamForOptions ' 'throws CameraWebException', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.security, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.security, 'description'); - when( - cameraService.getMediaStreamForOptions(any), - ).thenThrow(exception); + when(cameraService.getMediaStreamForOptions(any)).thenThrow(exception); expect( CameraPlatform.instance.availableCameras(), @@ -562,18 +422,12 @@ void main() { message: 'message', ); - when( - cameraService.getMediaStreamForOptions(any), - ).thenThrow(exception); + when(cameraService.getMediaStreamForOptions(any)).thenThrow(exception); expect( () => CameraPlatform.instance.availableCameras(), throwsA( - isA().having( - (CameraException e) => e.code, - 'code', - exception.code, - ), + isA().having((CameraException e) => e.code, 'code', exception.code), ), ); }); @@ -591,20 +445,14 @@ void main() { sensorOrientation: 0, ); - const cameraMetadata = CameraMetadata( - deviceId: 'deviceId', - facingMode: 'user', - ); + const cameraMetadata = CameraMetadata(deviceId: 'deviceId', facingMode: 'user'); setUp(() { // Add metadata for the camera description. - (CameraPlatform.instance as CameraPlugin) - .camerasMetadata[cameraDescription] = + (CameraPlatform.instance as CameraPlugin).camerasMetadata[cameraDescription] = cameraMetadata; - when( - cameraService.mapFacingModeToCameraType('user'), - ).thenReturn(CameraType.user); + when(cameraService.mapFacingModeToCameraType('user')).thenReturn(CameraType.user); }); testWidgets('with appropriate options', (WidgetTester tester) async { @@ -618,24 +466,14 @@ void main() { enableAudio: true, ); - final Camera? camera = - (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; + final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; expect(camera, isA()); expect(camera!.textureId, cameraId); expect(camera.options.audio.enabled, isTrue); - expect( - camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user)), - ); - expect( - camera.options.video.width!.ideal, - ultraHighResolutionSize.width.toInt(), - ); - expect( - camera.options.video.height!.ideal, - ultraHighResolutionSize.height.toInt(), - ); + expect(camera.options.video.facingMode, equals(FacingModeConstraint(CameraType.user))); + expect(camera.options.video.width!.ideal, ultraHighResolutionSize.width.toInt()); + expect(camera.options.video.height!.ideal, ultraHighResolutionSize.height.toInt()); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); @@ -646,35 +484,24 @@ void main() { cameraService.mapResolutionPresetToSize(ResolutionPreset.ultraHigh), ).thenReturn(ultraHighResolutionSize); - final int cameraId = await CameraPlatform.instance - .createCameraWithSettings( - cameraDescription, - const MediaSettings( - resolutionPreset: ResolutionPreset.ultraHigh, - videoBitrate: 200000, - audioBitrate: 32000, - enableAudio: true, - ), - ); + final int cameraId = await CameraPlatform.instance.createCameraWithSettings( + cameraDescription, + const MediaSettings( + resolutionPreset: ResolutionPreset.ultraHigh, + videoBitrate: 200000, + audioBitrate: 32000, + enableAudio: true, + ), + ); - final Camera? camera = - (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; + final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; expect(camera, isA()); expect(camera!.textureId, cameraId); expect(camera.options.audio.enabled, isTrue); - expect( - camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user)), - ); - expect( - camera.options.video.width!.ideal, - ultraHighResolutionSize.width.toInt(), - ); - expect( - camera.options.video.height!.ideal, - ultraHighResolutionSize.height.toInt(), - ); + expect(camera.options.video.facingMode, equals(FacingModeConstraint(CameraType.user))); + expect(camera.options.video.width!.ideal, ultraHighResolutionSize.width.toInt()); + expect(camera.options.video.height!.ideal, ultraHighResolutionSize.height.toInt()); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); @@ -685,29 +512,16 @@ void main() { cameraService.mapResolutionPresetToSize(ResolutionPreset.max), ).thenReturn(maxResolutionSize); - final int cameraId = await CameraPlatform.instance.createCamera( - cameraDescription, - null, - ); + final int cameraId = await CameraPlatform.instance.createCamera(cameraDescription, null); - final Camera? camera = - (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; + final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; expect(camera, isA()); expect(camera!.textureId, cameraId); expect(camera.options.audio.enabled, isFalse); - expect( - camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user)), - ); - expect( - camera.options.video.width!.ideal, - maxResolutionSize.width.toInt(), - ); - expect( - camera.options.video.height!.ideal, - maxResolutionSize.height.toInt(), - ); + expect(camera.options.video.facingMode, equals(FacingModeConstraint(CameraType.user))); + expect(camera.options.video.width!.ideal, maxResolutionSize.width.toInt()); + expect(camera.options.video.height!.ideal, maxResolutionSize.height.toInt()); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); @@ -719,29 +533,18 @@ void main() { cameraService.mapResolutionPresetToSize(ResolutionPreset.max), ).thenReturn(maxResolutionSize); - final int cameraId = await CameraPlatform.instance - .createCameraWithSettings( - cameraDescription, - const MediaSettings(resolutionPreset: ResolutionPreset.max), - ); + final int cameraId = await CameraPlatform.instance.createCameraWithSettings( + cameraDescription, + const MediaSettings(resolutionPreset: ResolutionPreset.max), + ); - final Camera? camera = - (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; + final Camera? camera = (CameraPlatform.instance as CameraPlugin).cameras[cameraId]; expect(camera, isA()); expect(camera!.options.audio.enabled, isFalse); - expect( - camera.options.video.facingMode, - equals(FacingModeConstraint(CameraType.user)), - ); - expect( - camera.options.video.width!.ideal, - maxResolutionSize.width.toInt(), - ); - expect( - camera.options.video.height!.ideal, - maxResolutionSize.height.toInt(), - ); + expect(camera.options.video.facingMode, equals(FacingModeConstraint(CameraType.user))); + expect(camera.options.video.width!.ideal, maxResolutionSize.width.toInt()); + expect(camera.options.video.height!.ideal, maxResolutionSize.height.toInt()); expect(camera.options.video.deviceId, cameraMetadata.deviceId); }); }); @@ -811,8 +614,7 @@ void main() { setUp(() { camera = MockCamera(); mockVideoElement = MockVideoElement(); - videoElement = - createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; + videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; errorStreamController = StreamController(); abortStreamController = StreamController(); @@ -827,24 +629,20 @@ void main() { final errorProvider = MockEventStreamProvider(); final abortProvider = MockEventStreamProvider(); - (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = - errorProvider; - (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = - abortProvider; + (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider; + (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = abortProvider; - when(errorProvider.forElement(videoElement)).thenAnswer( - (_) => FakeElementStream(errorStreamController.stream), - ); - when(abortProvider.forElement(videoElement)).thenAnswer( - (_) => FakeElementStream(abortStreamController.stream), - ); + when( + errorProvider.forElement(videoElement), + ).thenAnswer((_) => FakeElementStream(errorStreamController.stream)); + when( + abortProvider.forElement(videoElement), + ).thenAnswer((_) => FakeElementStream(abortStreamController.stream)); when(camera.onEnded).thenAnswer((_) => endedStreamController.stream); }); - testWidgets('initializes and plays the camera', ( - WidgetTester tester, - ) async { + testWidgets('initializes and plays the camera', (WidgetTester tester) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -854,25 +652,22 @@ void main() { verify(camera.play()).called(1); }); - testWidgets( - 'starts listening to the camera video error and abort events', - (WidgetTester tester) async { - // Save the camera in the camera plugin. - (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; + testWidgets('starts listening to the camera video error and abort events', ( + WidgetTester tester, + ) async { + // Save the camera in the camera plugin. + (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - expect(errorStreamController.hasListener, isFalse); - expect(abortStreamController.hasListener, isFalse); + expect(errorStreamController.hasListener, isFalse); + expect(abortStreamController.hasListener, isFalse); - await CameraPlatform.instance.initializeCamera(cameraId); + await CameraPlatform.instance.initializeCamera(cameraId); - expect(errorStreamController.hasListener, isTrue); - expect(abortStreamController.hasListener, isTrue); - }, - ); + expect(errorStreamController.hasListener, isTrue); + expect(abortStreamController.hasListener, isTrue); + }); - testWidgets('starts listening to the camera ended events', ( - WidgetTester tester, - ) async { + testWidgets('starts listening to the camera ended events', (WidgetTester tester) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -898,9 +693,7 @@ void main() { ); }); - testWidgets('when camera throws CameraWebException', ( - WidgetTester tester, - ) async { + testWidgets('when camera throws CameraWebException', (WidgetTester tester) async { final exception = CameraWebException( cameraId, CameraErrorCode.permissionDenied, @@ -924,9 +717,7 @@ void main() { ); }); - testWidgets('when camera throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when camera throws DomException', (WidgetTester tester) async { final exception = DOMException('NotAllowedError'); when(camera.initialize()).thenAnswer((_) => Future.value()); @@ -975,9 +766,7 @@ void main() { testWidgets('locks the capture orientation ' 'based on the given device orientation', (WidgetTester tester) async { when( - cameraService.mapDeviceOrientationToOrientationType( - DeviceOrientation.landscapeRight, - ), + cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeRight), ).thenReturn(OrientationType.landscapeSecondary); final capturedTypes = []; @@ -992,9 +781,7 @@ void main() { ); verify( - cameraService.mapDeviceOrientationToOrientationType( - DeviceOrientation.landscapeRight, - ), + cameraService.mapDeviceOrientationToOrientationType(DeviceOrientation.landscapeRight), ).called(1); expect(capturedTypes.length, 1); @@ -1003,9 +790,7 @@ void main() { group('throws PlatformException', () { testWidgets('with orientationNotSupported error ' - 'when documentElement is not available', ( - WidgetTester tester, - ) async { + 'when documentElement is not available', (WidgetTester tester) async { mockDocument.documentElement = null; expect( @@ -1025,9 +810,7 @@ void main() { mockDocument.documentElement = documentElement; }); - testWidgets('when lock throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when lock throws DomException', (WidgetTester tester) async { final exception = DOMException('NotAllowedError'); mockScreenOrientation.lock = (OrientationLockType orientation) { @@ -1060,9 +843,7 @@ void main() { ).thenReturn(OrientationType.portraitPrimary); }); - testWidgets('unlocks the capture orientation', ( - WidgetTester tester, - ) async { + testWidgets('unlocks the capture orientation', (WidgetTester tester) async { var unlocks = 0; mockScreenOrientation.unlock = () { unlocks++; @@ -1075,9 +856,7 @@ void main() { group('throws PlatformException', () { testWidgets('with orientationNotSupported error ' - 'when documentElement is not available', ( - WidgetTester tester, - ) async { + 'when documentElement is not available', (WidgetTester tester) async { mockDocument.documentElement = null; expect( @@ -1094,9 +873,7 @@ void main() { mockDocument.documentElement = documentElement; }); - testWidgets('when unlock throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when unlock throws DomException', (WidgetTester tester) async { final exception = DOMException('NotAllowedError'); mockScreenOrientation.unlock = () { @@ -1129,9 +906,7 @@ void main() { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final XFile picture = await CameraPlatform.instance.takePicture( - cameraId, - ); + final XFile picture = await CameraPlatform.instance.takePicture(cameraId); verify(camera.takePicture()).called(1); @@ -1153,9 +928,7 @@ void main() { ); }); - testWidgets('when takePicture throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when takePicture throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('NotSupportedError'); @@ -1176,15 +949,9 @@ void main() { ); }); - testWidgets('when takePicture throws CameraWebException', ( - WidgetTester tester, - ) async { + testWidgets('when takePicture throws CameraWebException', (WidgetTester tester) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.takePicture()).thenThrow(exception); @@ -1213,9 +980,7 @@ void main() { when(camera.startVideoRecording()).thenAnswer((_) async {}); - when( - camera.onVideoRecordingError, - ).thenAnswer((_) => const Stream.empty()); + when(camera.onVideoRecordingError).thenAnswer((_) => const Stream.empty()); }); testWidgets('starts a video recording', (WidgetTester tester) async { @@ -1227,14 +992,10 @@ void main() { verify(camera.startVideoRecording()).called(1); }); - testWidgets('listens to the onVideoRecordingError stream', ( - WidgetTester tester, - ) async { + testWidgets('listens to the onVideoRecordingError stream', (WidgetTester tester) async { final videoRecordingErrorController = StreamController(); - when( - camera.onVideoRecordingError, - ).thenAnswer((_) => videoRecordingErrorController.stream); + when(camera.onVideoRecordingError).thenAnswer((_) => videoRecordingErrorController.stream); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -1259,9 +1020,7 @@ void main() { ); }); - testWidgets('when startVideoRecording throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when startVideoRecording throws DomException', (WidgetTester tester) async { final exception = DOMException('InvalidStateError'); when(camera.startVideoRecording()).thenThrow(exception); @@ -1284,11 +1043,7 @@ void main() { testWidgets('when startVideoRecording throws CameraWebException', ( WidgetTester tester, ) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.startVideoRecording()).thenThrow(exception); @@ -1317,9 +1072,7 @@ void main() { when(camera.startVideoRecording()).thenAnswer((_) async {}); - when( - camera.onVideoRecordingError, - ).thenAnswer((_) => const Stream.empty()); + when(camera.onVideoRecordingError).thenAnswer((_) => const Stream.empty()); }); testWidgets('fails if trying to stream', (WidgetTester tester) async { @@ -1328,10 +1081,7 @@ void main() { expect( () => CameraPlatform.instance.startVideoCapturing( - VideoCaptureOptions( - cameraId, - streamCallback: (CameraImageData imageData) {}, - ), + VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}), ), throwsA(isA()), ); @@ -1343,16 +1093,12 @@ void main() { final camera = MockCamera(); final capturedVideo = XFile('/bogus/test'); - when( - camera.stopVideoRecording(), - ).thenAnswer((_) async => capturedVideo); + when(camera.stopVideoRecording()).thenAnswer((_) async => capturedVideo); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final XFile video = await CameraPlatform.instance.stopVideoRecording( - cameraId, - ); + final XFile video = await CameraPlatform.instance.stopVideoRecording(cameraId); verify(camera.stopVideoRecording()).called(1); @@ -1368,21 +1114,15 @@ void main() { when(camera.startVideoRecording()).thenAnswer((_) async {}); - when( - camera.stopVideoRecording(), - ).thenAnswer((_) async => capturedVideo); + when(camera.stopVideoRecording()).thenAnswer((_) async => capturedVideo); - when( - camera.onVideoRecordingError, - ).thenAnswer((_) => videoRecordingErrorController.stream); + when(camera.onVideoRecordingError).thenAnswer((_) => videoRecordingErrorController.stream); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; await CameraPlatform.instance.startVideoRecording(cameraId); - final XFile _ = await CameraPlatform.instance.stopVideoRecording( - cameraId, - ); + final XFile _ = await CameraPlatform.instance.stopVideoRecording(cameraId); expect(videoRecordingErrorController.hasListener, isFalse); }); @@ -1402,9 +1142,7 @@ void main() { ); }); - testWidgets('when stopVideoRecording throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when stopVideoRecording throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('InvalidStateError'); @@ -1429,11 +1167,7 @@ void main() { WidgetTester tester, ) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.stopVideoRecording()).thenThrow(exception); @@ -1483,9 +1217,7 @@ void main() { ); }); - testWidgets('when pauseVideoRecording throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when pauseVideoRecording throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('InvalidStateError'); @@ -1510,11 +1242,7 @@ void main() { WidgetTester tester, ) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.pauseVideoRecording()).thenThrow(exception); @@ -1564,9 +1292,7 @@ void main() { ); }); - testWidgets('when resumeVideoRecording throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when resumeVideoRecording throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('InvalidStateError'); @@ -1591,11 +1317,7 @@ void main() { WidgetTester tester, ) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.resumeVideoRecording()).thenThrow(exception); @@ -1617,9 +1339,7 @@ void main() { }); group('setFlashMode', () { - testWidgets('calls setFlashMode on the camera', ( - WidgetTester tester, - ) async { + testWidgets('calls setFlashMode on the camera', (WidgetTester tester) async { final camera = MockCamera(); const FlashMode flashMode = FlashMode.always; @@ -1635,10 +1355,7 @@ void main() { testWidgets('with notFound error ' 'if the camera does not exist', (WidgetTester tester) async { expect( - () => CameraPlatform.instance.setFlashMode( - cameraId, - FlashMode.always, - ), + () => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.always), throwsA( isA().having( (PlatformException e) => e.code, @@ -1649,9 +1366,7 @@ void main() { ); }); - testWidgets('when setFlashMode throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when setFlashMode throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('NotSupportedError'); @@ -1661,10 +1376,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () => CameraPlatform.instance.setFlashMode( - cameraId, - FlashMode.always, - ), + () => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.always), throwsA( isA().having( (PlatformException e) => e.code, @@ -1675,15 +1387,9 @@ void main() { ); }); - testWidgets('when setFlashMode throws CameraWebException', ( - WidgetTester tester, - ) async { + testWidgets('when setFlashMode throws CameraWebException', (WidgetTester tester) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.setFlashMode(any)).thenThrow(exception); @@ -1691,8 +1397,7 @@ void main() { (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; expect( - () => - CameraPlatform.instance.setFlashMode(cameraId, FlashMode.torch), + () => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.torch), throwsA( isA().having( (PlatformException e) => e.code, @@ -1705,91 +1410,64 @@ void main() { }); }); - testWidgets('setExposureMode throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('setExposureMode throws UnimplementedError', (WidgetTester tester) async { expect( - () => CameraPlatform.instance.setExposureMode( - cameraId, - ExposureMode.auto, - ), + () => CameraPlatform.instance.setExposureMode(cameraId, ExposureMode.auto), throwsUnimplementedError, ); }); - testWidgets('setExposurePoint throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('setExposurePoint throws UnimplementedError', (WidgetTester tester) async { expect( - () => CameraPlatform.instance.setExposurePoint( - cameraId, - const Point(0, 0), - ), + () => CameraPlatform.instance.setExposurePoint(cameraId, const Point(0, 0)), throwsUnimplementedError, ); }); - testWidgets('getMinExposureOffset throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('getMinExposureOffset throws UnimplementedError', (WidgetTester tester) async { expect( () => CameraPlatform.instance.getMinExposureOffset(cameraId), throwsUnimplementedError, ); }); - testWidgets('getMaxExposureOffset throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('getMaxExposureOffset throws UnimplementedError', (WidgetTester tester) async { expect( () => CameraPlatform.instance.getMaxExposureOffset(cameraId), throwsUnimplementedError, ); }); - testWidgets('getExposureOffsetStepSize throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('getExposureOffsetStepSize throws UnimplementedError', (WidgetTester tester) async { expect( () => CameraPlatform.instance.getExposureOffsetStepSize(cameraId), throwsUnimplementedError, ); }); - testWidgets('setExposureOffset throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('setExposureOffset throws UnimplementedError', (WidgetTester tester) async { expect( () => CameraPlatform.instance.setExposureOffset(cameraId, 0), throwsUnimplementedError, ); }); - testWidgets('setFocusMode throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('setFocusMode throws UnimplementedError', (WidgetTester tester) async { expect( () => CameraPlatform.instance.setFocusMode(cameraId, FocusMode.auto), throwsUnimplementedError, ); }); - testWidgets('setFocusPoint throws UnimplementedError', ( - WidgetTester tester, - ) async { + testWidgets('setFocusPoint throws UnimplementedError', (WidgetTester tester) async { expect( - () => CameraPlatform.instance.setFocusPoint( - cameraId, - const Point(0, 0), - ), + () => CameraPlatform.instance.setFocusPoint(cameraId, const Point(0, 0)), throwsUnimplementedError, ); }); group('getMaxZoomLevel', () { - testWidgets('calls getMaxZoomLevel on the camera', ( - WidgetTester tester, - ) async { + testWidgets('calls getMaxZoomLevel on the camera', (WidgetTester tester) async { final camera = MockCamera(); const maximumZoomLevel = 100.0; @@ -1798,10 +1476,7 @@ void main() { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - expect( - await CameraPlatform.instance.getMaxZoomLevel(cameraId), - equals(maximumZoomLevel), - ); + expect(await CameraPlatform.instance.getMaxZoomLevel(cameraId), equals(maximumZoomLevel)); verify(camera.getMaxZoomLevel()).called(1); }); @@ -1821,9 +1496,7 @@ void main() { ); }); - testWidgets('when getMaxZoomLevel throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when getMaxZoomLevel throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('NotSupportedError'); @@ -1844,15 +1517,9 @@ void main() { ); }); - testWidgets('when getMaxZoomLevel throws CameraWebException', ( - WidgetTester tester, - ) async { + testWidgets('when getMaxZoomLevel throws CameraWebException', (WidgetTester tester) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.getMaxZoomLevel()).thenThrow(exception); @@ -1874,9 +1541,7 @@ void main() { }); group('getMinZoomLevel', () { - testWidgets('calls getMinZoomLevel on the camera', ( - WidgetTester tester, - ) async { + testWidgets('calls getMinZoomLevel on the camera', (WidgetTester tester) async { final camera = MockCamera(); const minimumZoomLevel = 100.0; @@ -1885,10 +1550,7 @@ void main() { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - expect( - await CameraPlatform.instance.getMinZoomLevel(cameraId), - equals(minimumZoomLevel), - ); + expect(await CameraPlatform.instance.getMinZoomLevel(cameraId), equals(minimumZoomLevel)); verify(camera.getMinZoomLevel()).called(1); }); @@ -1908,9 +1570,7 @@ void main() { ); }); - testWidgets('when getMinZoomLevel throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when getMinZoomLevel throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('NotSupportedError'); @@ -1931,15 +1591,9 @@ void main() { ); }); - testWidgets('when getMinZoomLevel throws CameraWebException', ( - WidgetTester tester, - ) async { + testWidgets('when getMinZoomLevel throws CameraWebException', (WidgetTester tester) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.getMinZoomLevel()).thenThrow(exception); @@ -1961,9 +1615,7 @@ void main() { }); group('setZoomLevel', () { - testWidgets('calls setZoomLevel on the camera', ( - WidgetTester tester, - ) async { + testWidgets('calls setZoomLevel on the camera', (WidgetTester tester) async { final camera = MockCamera(); // Save the camera in the camera plugin. @@ -1991,9 +1643,7 @@ void main() { ); }); - testWidgets('when setZoomLevel throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when setZoomLevel throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('NotSupportedError'); @@ -2005,18 +1655,12 @@ void main() { expect( () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), throwsA( - isA().having( - (CameraException e) => e.code, - 'code', - exception.name, - ), + isA().having((CameraException e) => e.code, 'code', exception.name), ), ); }); - testWidgets('when setZoomLevel throws PlatformException', ( - WidgetTester tester, - ) async { + testWidgets('when setZoomLevel throws PlatformException', (WidgetTester tester) async { final camera = MockCamera(); final exception = PlatformException( code: CameraErrorCode.notSupported.toString(), @@ -2031,24 +1675,14 @@ void main() { expect( () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), throwsA( - isA().having( - (CameraException e) => e.code, - 'code', - exception.code, - ), + isA().having((CameraException e) => e.code, 'code', exception.code), ), ); }); - testWidgets('when setZoomLevel throws CameraWebException', ( - WidgetTester tester, - ) async { + testWidgets('when setZoomLevel throws CameraWebException', (WidgetTester tester) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.setZoomLevel(any)).thenThrow(exception); @@ -2096,9 +1730,7 @@ void main() { ); }); - testWidgets('when pause throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when pause throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('NotSupportedError'); @@ -2150,9 +1782,7 @@ void main() { ); }); - testWidgets('when play throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when play throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('NotSupportedError'); @@ -2173,15 +1803,9 @@ void main() { ); }); - testWidgets('when play throws CameraWebException', ( - WidgetTester tester, - ) async { + testWidgets('when play throws CameraWebException', (WidgetTester tester) async { final camera = MockCamera(); - final exception = CameraWebException( - cameraId, - CameraErrorCode.unknown, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.unknown, 'description'); when(camera.play()).thenThrow(exception); @@ -2231,8 +1855,7 @@ void main() { setUp(() { camera = MockCamera(); mockVideoElement = MockVideoElement(); - videoElement = - createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; + videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; errorStreamController = StreamController(); abortStreamController = StreamController(); @@ -2249,23 +1872,19 @@ void main() { final errorProvider = MockEventStreamProvider(); final abortProvider = MockEventStreamProvider(); - (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = - errorProvider; - (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = - abortProvider; + (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider; + (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = abortProvider; - when(errorProvider.forElement(videoElement)).thenAnswer( - (_) => FakeElementStream(errorStreamController.stream), - ); - when(abortProvider.forElement(videoElement)).thenAnswer( - (_) => FakeElementStream(abortStreamController.stream), - ); + when( + errorProvider.forElement(videoElement), + ).thenAnswer((_) => FakeElementStream(errorStreamController.stream)); + when( + abortProvider.forElement(videoElement), + ).thenAnswer((_) => FakeElementStream(abortStreamController.stream)); when(camera.onEnded).thenAnswer((_) => endedStreamController.stream); - when( - camera.onVideoRecordingError, - ).thenAnswer((_) => videoRecordingErrorController.stream); + when(camera.onVideoRecordingError).thenAnswer((_) => videoRecordingErrorController.stream); when(camera.startVideoRecording()).thenAnswer((_) async {}); }); @@ -2313,9 +1932,7 @@ void main() { expect(abortStreamController.hasListener, isFalse); }); - testWidgets('cancels the camera ended subscriptions', ( - WidgetTester tester, - ) async { + testWidgets('cancels the camera ended subscriptions', (WidgetTester tester) async { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -2353,9 +1970,7 @@ void main() { ); }); - testWidgets('when dispose throws DomException', ( - WidgetTester tester, - ) async { + testWidgets('when dispose throws DomException', (WidgetTester tester) async { final camera = MockCamera(); final exception = DOMException('InvalidAccessError'); @@ -2380,18 +1995,12 @@ void main() { group('getCamera', () { testWidgets('returns the correct camera', (WidgetTester tester) async { - final camera = Camera( - textureId: cameraId, - cameraService: cameraService, - ); + final camera = Camera(textureId: cameraId, cameraService: cameraService); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - expect( - (CameraPlatform.instance as CameraPlugin).getCamera(cameraId), - equals(camera), - ); + expect((CameraPlatform.instance as CameraPlugin).getCamera(cameraId), equals(camera)); }); testWidgets('throws PlatformException ' @@ -2422,8 +2031,7 @@ void main() { setUp(() { camera = MockCamera(); mockVideoElement = MockVideoElement(); - videoElement = - createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; + videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; errorStreamController = StreamController(); abortStreamController = StreamController(); @@ -2439,23 +2047,19 @@ void main() { final errorProvider = MockEventStreamProvider(); final abortProvider = MockEventStreamProvider(); - (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = - errorProvider; - (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = - abortProvider; + (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider; + (CameraPlatform.instance as CameraPlugin).videoElementOnAbortProvider = abortProvider; - when(errorProvider.forElement(any)).thenAnswer( - (_) => FakeElementStream(errorStreamController.stream), - ); - when(abortProvider.forElement(any)).thenAnswer( - (_) => FakeElementStream(abortStreamController.stream), - ); + when( + errorProvider.forElement(any), + ).thenAnswer((_) => FakeElementStream(errorStreamController.stream)); + when( + abortProvider.forElement(any), + ).thenAnswer((_) => FakeElementStream(abortStreamController.stream)); when(camera.onEnded).thenAnswer((_) => endedStreamController.stream); - when( - camera.onVideoRecordingError, - ).thenAnswer((_) => videoRecordingErrorController.stream); + when(camera.onVideoRecordingError).thenAnswer((_) => videoRecordingErrorController.stream); when(camera.startVideoRecording()).thenAnswer((_) async {}); }); @@ -2471,16 +2075,12 @@ void main() { cameraService.getMediaStreamForOptions(any, cameraId: cameraId), ).thenAnswer((_) async => videoElement.captureStream()); - final camera = Camera( - textureId: cameraId, - cameraService: cameraService, - ); + final camera = Camera(textureId: cameraId, cameraService: cameraService); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final Stream eventStream = CameraPlatform - .instance + final Stream eventStream = CameraPlatform.instance .onCameraInitialized(cameraId); final streamQueue = StreamQueue(eventStream); @@ -2505,11 +2105,8 @@ void main() { await streamQueue.cancel(); }); - testWidgets('onCameraResolutionChanged emits an empty stream', ( - WidgetTester tester, - ) async { - final Stream stream = CameraPlatform - .instance + testWidgets('onCameraResolutionChanged emits an empty stream', (WidgetTester tester) async { + final Stream stream = CameraPlatform.instance .onCameraResolutionChanged(cameraId); expect(await stream.isEmpty, isTrue); }); @@ -2519,8 +2116,9 @@ void main() { // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final Stream eventStream = CameraPlatform.instance - .onCameraClosing(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraClosing( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2530,10 +2128,7 @@ void main() { createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack, ); - expect( - await streamQueue.next, - equals(const CameraClosingEvent(cameraId)), - ); + expect(await streamQueue.next, equals(const CameraClosingEvent(cameraId))); await streamQueue.cancel(); }); @@ -2547,25 +2142,19 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on the camera video error event ' 'with a message', (WidgetTester tester) async { - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); - final error = - createJSInteropWrapper( - FakeMediaError( - MediaError.MEDIA_ERR_NETWORK, - 'A network error occurred.', - ), - ) - as MediaError; + final error = createJSInteropWrapper( + FakeMediaError(MediaError.MEDIA_ERR_NETWORK, 'A network error occurred.'), + ) as MediaError; - final CameraErrorCode errorCode = CameraErrorCode.fromMediaError( - error, - ); + final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error); mockVideoElement.error = error; errorStreamController.add(Event('error')); @@ -2573,10 +2162,7 @@ void main() { expect( await streamQueue.next, equals( - CameraErrorEvent( - cameraId, - 'Error code: $errorCode, error message: ${error.message}', - ), + CameraErrorEvent(cameraId, 'Error code: $errorCode, error message: ${error.message}'), ), ); @@ -2586,21 +2172,17 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on the camera video error event ' 'with no message', (WidgetTester tester) async { - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); final error = - createJSInteropWrapper( - FakeMediaError(MediaError.MEDIA_ERR_NETWORK), - ) - as MediaError; - final CameraErrorCode errorCode = CameraErrorCode.fromMediaError( - error, - ); + createJSInteropWrapper(FakeMediaError(MediaError.MEDIA_ERR_NETWORK)) as MediaError; + final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error); mockVideoElement.error = error; errorStreamController.add(Event('error')); @@ -2620,8 +2202,9 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on the camera video abort event', (WidgetTester tester) async { - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2644,16 +2227,13 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on takePicture error', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.takePicture()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2677,24 +2257,18 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on setFlashMode error', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.setFlashMode(any)).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); expect( - () async => CameraPlatform.instance.setFlashMode( - cameraId, - FlashMode.always, - ), + () async => CameraPlatform.instance.setFlashMode(cameraId, FlashMode.always), throwsA(isA()), ); @@ -2721,8 +2295,9 @@ void main() { when(camera.getMaxZoomLevel()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2754,8 +2329,9 @@ void main() { when(camera.getMinZoomLevel()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2787,8 +2363,9 @@ void main() { when(camera.setZoomLevel(any)).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2812,16 +2389,13 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on resumePreview error', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.unknown, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.unknown, 'description'); when(camera.play()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2845,20 +2419,15 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on startVideoRecording error', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); - when( - camera.onVideoRecordingError, - ).thenAnswer((_) => const Stream.empty()); + when(camera.onVideoRecordingError).thenAnswer((_) => const Stream.empty()); when(camera.startVideoRecording()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2881,11 +2450,10 @@ void main() { }); testWidgets('emits a CameraErrorEvent ' - 'on the camera video recording error event', ( - WidgetTester tester, - ) async { - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + 'on the camera video recording error event', (WidgetTester tester) async { + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2893,8 +2461,7 @@ void main() { await CameraPlatform.instance.startVideoRecording(cameraId); final errorEvent = - createJSInteropWrapper(FakeErrorEvent('type', 'message')) - as ErrorEvent; + createJSInteropWrapper(FakeErrorEvent('type', 'message')) as ErrorEvent; videoRecordingErrorController.add(errorEvent); @@ -2913,16 +2480,13 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on stopVideoRecording error', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.stopVideoRecording()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2946,16 +2510,13 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on pauseVideoRecording error', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.pauseVideoRecording()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -2979,16 +2540,13 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on resumeVideoRecording error', (WidgetTester tester) async { - final exception = CameraWebException( - cameraId, - CameraErrorCode.notStarted, - 'description', - ); + final exception = CameraWebException(cameraId, CameraErrorCode.notStarted, 'description'); when(camera.resumeVideoRecording()).thenThrow(exception); - final Stream eventStream = CameraPlatform.instance - .onCameraError(cameraId); + final Stream eventStream = CameraPlatform.instance.onCameraError( + cameraId, + ); final streamQueue = StreamQueue(eventStream); @@ -3011,9 +2569,7 @@ void main() { }); }); - testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent', ( - WidgetTester tester, - ) async { + testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent', (WidgetTester tester) async { final camera = MockCamera(); final capturedVideo = XFile('/bogus/test'); final stream = Stream.value( @@ -3039,65 +2595,45 @@ void main() { setUp(() { final provider = MockEventStreamProvider(); - (CameraPlatform.instance as CameraPlugin) - .orientationOnChangeProvider = - provider; - when( - provider.forTarget(any), - ).thenAnswer((_) => eventStreamController.stream); + (CameraPlatform.instance as CameraPlugin).orientationOnChangeProvider = provider; + when(provider.forTarget(any)).thenAnswer((_) => eventStreamController.stream); }); - testWidgets('emits the initial DeviceOrientationChangedEvent', ( - WidgetTester tester, - ) async { + testWidgets('emits the initial DeviceOrientationChangedEvent', (WidgetTester tester) async { when( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.portraitPrimary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitPrimary), ).thenReturn(DeviceOrientation.portraitUp); // Set the initial screen orientation to portraitPrimary. mockScreenOrientation.type = OrientationType.portraitPrimary; - final Stream eventStream = - CameraPlatform.instance.onDeviceOrientationChanged(); + final Stream eventStream = CameraPlatform.instance + .onDeviceOrientationChanged(); - final streamQueue = StreamQueue( - eventStream, - ); + final streamQueue = StreamQueue(eventStream); expect( await streamQueue.next, - equals( - const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp), - ), + equals(const DeviceOrientationChangedEvent(DeviceOrientation.portraitUp)), ); await streamQueue.cancel(); }); testWidgets('emits a DeviceOrientationChangedEvent ' - 'when the screen orientation is changed', ( - WidgetTester tester, - ) async { + 'when the screen orientation is changed', (WidgetTester tester) async { when( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.landscapePrimary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.landscapePrimary), ).thenReturn(DeviceOrientation.landscapeLeft); when( - cameraService.mapOrientationTypeToDeviceOrientation( - OrientationType.portraitSecondary, - ), + cameraService.mapOrientationTypeToDeviceOrientation(OrientationType.portraitSecondary), ).thenReturn(DeviceOrientation.portraitDown); - final Stream eventStream = - CameraPlatform.instance.onDeviceOrientationChanged(); + final Stream eventStream = CameraPlatform.instance + .onDeviceOrientationChanged(); - final streamQueue = StreamQueue( - eventStream, - ); + final streamQueue = StreamQueue(eventStream); // Change the screen orientation to landscapePrimary and // emit an event on the screenOrientation.onChange stream. @@ -3107,11 +2643,7 @@ void main() { expect( await streamQueue.next, - equals( - const DeviceOrientationChangedEvent( - DeviceOrientation.landscapeLeft, - ), - ), + equals(const DeviceOrientationChangedEvent(DeviceOrientation.landscapeLeft)), ); // Change the screen orientation to portraitSecondary and @@ -3122,11 +2654,7 @@ void main() { expect( await streamQueue.next, - equals( - const DeviceOrientationChangedEvent( - DeviceOrientation.portraitDown, - ), - ), + equals(const DeviceOrientationChangedEvent(DeviceOrientation.portraitDown)), ); await streamQueue.cancel(); diff --git a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart index fa5c35214e9b..ab23b5d17e22 100644 --- a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart +++ b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart @@ -33,9 +33,7 @@ import 'package:web/web.dart' as web; }, ), MockSpec( - fallbackGenerators: { - #toMediaStreamConstraints: toMediaStreamConstraintsShim, - }, + fallbackGenerators: {#toMediaStreamConstraints: toMediaStreamConstraintsShim}, ), ]) export 'mocks.mocks.dart'; @@ -46,8 +44,7 @@ Future getMediaStreamForOptionsShim( CameraOptions? options, { int? cameraId = 0, }) async { - return createJSInteropWrapper(FakeMediaStream([])) - as web.MediaStream; + return createJSInteropWrapper(FakeMediaStream([])) as web.MediaStream; } web.HTMLVideoElement videoElementShim() { @@ -60,8 +57,7 @@ web.Blob blobBuilderShim([List? blobs, String? type]) { throw UnimplementedError(); } -web.MediaStreamConstraints toMediaStreamConstraintsShim() => - throw UnimplementedError(); +web.MediaStreamConstraints toMediaStreamConstraintsShim() => throw UnimplementedError(); @JSExport() class MockWindow { @@ -143,12 +139,18 @@ class MockVideoElement { @JSExport() class MockMediaRecorder { /// `void Function(String type, web.EventListener? callback, [JSAny options])` - JSFunction addEventListener = - (String type, web.EventListener? callback, [JSAny? options]) {}.toJS; + JSFunction addEventListener = ( + String type, + web.EventListener? callback, [ + JSAny? options, + ]) {}.toJS; /// `void Function(String type, web.EventListener? callback, [JSAny options])` - JSFunction removeEventListener = - (String type, web.EventListener? callback, [JSAny? options]) {}.toJS; + JSFunction removeEventListener = ( + String type, + web.EventListener? callback, [ + JSAny? options, + ]) {}.toJS; /// `void Function([int timeslice])` JSFunction start = ([int? timeslice]) {}.toJS; @@ -195,8 +197,7 @@ class FakeMediaError { } /// A fake [web.ElementStream] that listens to the provided [_stream] on [listen]. -class FakeElementStream extends Fake - implements web.ElementStream { +class FakeElementStream extends Fake implements web.ElementStream { FakeElementStream(this._stream); final Stream _stream; @@ -208,12 +209,7 @@ class FakeElementStream extends Fake void Function()? onDone, bool? cancelOnError, }) { - return _stream.listen( - onData, - onError: onError, - onDone: onDone, - cancelOnError: cancelOnError, - ); + return _stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } } @@ -247,8 +243,7 @@ web.HTMLVideoElement getVideoElementWithBlankStream(Size videoSize) { ..height = videoSize.height.toInt() ..context2D.fillRect(0, 0, videoSize.width, videoSize.height); - final videoElement = web.HTMLVideoElement() - ..srcObject = canvasElement.captureStream(); + final videoElement = web.HTMLVideoElement()..srcObject = canvasElement.captureStream(); return videoElement; } @@ -258,27 +253,17 @@ class MockEventStreamProvider extends Mock @override Stream forTarget(web.EventTarget? e, {bool? useCapture = false}) { return super.noSuchMethod( - Invocation.method( - #forTarget, - [e], - {#useCapture: useCapture}, - ), - returnValue: Stream.empty(), - ) - as Stream; + Invocation.method(#forTarget, [e], {#useCapture: useCapture}), + returnValue: Stream.empty(), + ) as Stream; } @override web.ElementStream forElement(web.Element? e, {bool? useCapture = false}) { return super.noSuchMethod( - Invocation.method( - #forElement, - [e], - {#useCapture: useCapture}, - ), - returnValue: FakeElementStream(Stream.empty()), - ) - as web.ElementStream; + Invocation.method(#forElement, [e], {#useCapture: useCapture}), + returnValue: FakeElementStream(Stream.empty()), + ) as web.ElementStream; } } diff --git a/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart b/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart index 321507d77174..47821df5b3f5 100644 --- a/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart +++ b/packages/camera/camera_web/example/integration_test/helpers/mocks.mocks.dart @@ -7,8 +7,7 @@ import 'dart:async' as _i5; import 'dart:js_interop' as _i13; import 'dart:ui' as _i4; -import 'package:camera_platform_interface/camera_platform_interface.dart' - as _i7; +import 'package:camera_platform_interface/camera_platform_interface.dart' as _i7; import 'package:camera_web/src/camera.dart' as _i10; import 'package:camera_web/src/camera_service.dart' as _i8; import 'package:camera_web/src/shims/dart_js_util.dart' as _i2; @@ -35,19 +34,16 @@ import 'mocks.dart' as _i9; // ignore_for_file: subtype_of_sealed_class class _FakeJsUtil_0 extends _i1.SmartFake implements _i2.JsUtil { - _FakeJsUtil_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeJsUtil_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeZoomLevelCapability_1 extends _i1.SmartFake - implements _i3.ZoomLevelCapability { +class _FakeZoomLevelCapability_1 extends _i1.SmartFake implements _i3.ZoomLevelCapability { _FakeZoomLevelCapability_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeSize_2 extends _i1.SmartFake implements _i4.Size { - _FakeSize_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeSize_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeCameraOptions_3 extends _i1.SmartFake implements _i3.CameraOptions { @@ -55,8 +51,7 @@ class _FakeCameraOptions_3 extends _i1.SmartFake implements _i3.CameraOptions { : super(parent, parentInvocation); } -class _FakeStreamController_4 extends _i1.SmartFake - implements _i5.StreamController { +class _FakeStreamController_4 extends _i1.SmartFake implements _i5.StreamController { _FakeStreamController_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -68,18 +63,15 @@ class _FakeEventStreamProvider_5 extends _i1.SmartFake } class _FakeXFile_6 extends _i1.SmartFake implements _i7.XFile { - _FakeXFile_6(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeXFile_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAudioConstraints_7 extends _i1.SmartFake - implements _i3.AudioConstraints { +class _FakeAudioConstraints_7 extends _i1.SmartFake implements _i3.AudioConstraints { _FakeAudioConstraints_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeVideoConstraints_8 extends _i1.SmartFake - implements _i3.VideoConstraints { +class _FakeVideoConstraints_8 extends _i1.SmartFake implements _i3.VideoConstraints { _FakeVideoConstraints_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -89,179 +81,121 @@ class _FakeVideoConstraints_8 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockCameraService extends _i1.Mock implements _i8.CameraService { @override - _i6.Window get window => - (super.noSuchMethod( - Invocation.getter(#window), - returnValue: _i9.windowShim(), - returnValueForMissingStub: _i9.windowShim(), - ) - as _i6.Window); + _i6.Window get window => (super.noSuchMethod( + Invocation.getter(#window), + returnValue: _i9.windowShim(), + returnValueForMissingStub: _i9.windowShim(), + ) as _i6.Window); @override - set window(_i6.Window? _window) => super.noSuchMethod( - Invocation.setter(#window, _window), - returnValueForMissingStub: null, - ); + set window(_i6.Window? _window) => + super.noSuchMethod(Invocation.setter(#window, _window), returnValueForMissingStub: null); @override - _i2.JsUtil get jsUtil => - (super.noSuchMethod( - Invocation.getter(#jsUtil), - returnValue: _FakeJsUtil_0(this, Invocation.getter(#jsUtil)), - returnValueForMissingStub: _FakeJsUtil_0( - this, - Invocation.getter(#jsUtil), - ), - ) - as _i2.JsUtil); - - @override - set jsUtil(_i2.JsUtil? _jsUtil) => super.noSuchMethod( - Invocation.setter(#jsUtil, _jsUtil), - returnValueForMissingStub: null, - ); + _i2.JsUtil get jsUtil => (super.noSuchMethod( + Invocation.getter(#jsUtil), + returnValue: _FakeJsUtil_0(this, Invocation.getter(#jsUtil)), + returnValueForMissingStub: _FakeJsUtil_0(this, Invocation.getter(#jsUtil)), + ) as _i2.JsUtil); + + @override + set jsUtil(_i2.JsUtil? _jsUtil) => + super.noSuchMethod(Invocation.setter(#jsUtil, _jsUtil), returnValueForMissingStub: null); @override _i5.Future<_i6.MediaStream> getMediaStreamForOptions( _i3.CameraOptions? options, { int? cameraId = 0, - }) => - (super.noSuchMethod( - Invocation.method( - #getMediaStreamForOptions, - [options], - {#cameraId: cameraId}, - ), - returnValue: _i9.getMediaStreamForOptionsShim( - options, - cameraId: cameraId, - ), - returnValueForMissingStub: _i9.getMediaStreamForOptionsShim( - options, - cameraId: cameraId, - ), - ) - as _i5.Future<_i6.MediaStream>); - - @override - _i3.ZoomLevelCapability getZoomLevelCapabilityForCamera( - _i10.Camera? camera, - ) => - (super.noSuchMethod( - Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), - returnValue: _FakeZoomLevelCapability_1( - this, - Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), - ), - returnValueForMissingStub: _FakeZoomLevelCapability_1( - this, - Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), - ), - ) - as _i3.ZoomLevelCapability); - - @override - String? getFacingModeForVideoTrack(_i6.MediaStreamTrack? videoTrack) => - (super.noSuchMethod( - Invocation.method(#getFacingModeForVideoTrack, [videoTrack]), - returnValueForMissingStub: null, - ) - as String?); + }) => (super.noSuchMethod( + Invocation.method(#getMediaStreamForOptions, [options], {#cameraId: cameraId}), + returnValue: _i9.getMediaStreamForOptionsShim(options, cameraId: cameraId), + returnValueForMissingStub: _i9.getMediaStreamForOptionsShim(options, cameraId: cameraId), + ) as _i5.Future<_i6.MediaStream>); @override - _i7.CameraLensDirection mapFacingModeToLensDirection(String? facingMode) => + _i3.ZoomLevelCapability getZoomLevelCapabilityForCamera(_i10.Camera? camera) => (super.noSuchMethod( - Invocation.method(#mapFacingModeToLensDirection, [facingMode]), - returnValue: _i7.CameraLensDirection.front, - returnValueForMissingStub: _i7.CameraLensDirection.front, - ) - as _i7.CameraLensDirection); + Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), + returnValue: _FakeZoomLevelCapability_1( + this, + Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), + ), + returnValueForMissingStub: _FakeZoomLevelCapability_1( + this, + Invocation.method(#getZoomLevelCapabilityForCamera, [camera]), + ), + ) as _i3.ZoomLevelCapability); @override - _i3.CameraType mapFacingModeToCameraType(String? facingMode) => - (super.noSuchMethod( - Invocation.method(#mapFacingModeToCameraType, [facingMode]), - returnValue: _i3.CameraType.environment, - returnValueForMissingStub: _i3.CameraType.environment, - ) - as _i3.CameraType); + String? getFacingModeForVideoTrack(_i6.MediaStreamTrack? videoTrack) => (super.noSuchMethod( + Invocation.method(#getFacingModeForVideoTrack, [videoTrack]), + returnValueForMissingStub: null, + ) as String?); @override - _i4.Size mapResolutionPresetToSize(_i7.ResolutionPreset? resolutionPreset) => - (super.noSuchMethod( - Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), - returnValue: _FakeSize_2( - this, - Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), - ), - returnValueForMissingStub: _FakeSize_2( - this, - Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), - ), - ) - as _i4.Size); - - @override - int mapResolutionPresetToVideoBitrate( - _i7.ResolutionPreset? resolutionPreset, - ) => + _i7.CameraLensDirection mapFacingModeToLensDirection(String? facingMode) => (super.noSuchMethod( + Invocation.method(#mapFacingModeToLensDirection, [facingMode]), + returnValue: _i7.CameraLensDirection.front, + returnValueForMissingStub: _i7.CameraLensDirection.front, + ) as _i7.CameraLensDirection); + + @override + _i3.CameraType mapFacingModeToCameraType(String? facingMode) => (super.noSuchMethod( + Invocation.method(#mapFacingModeToCameraType, [facingMode]), + returnValue: _i3.CameraType.environment, + returnValueForMissingStub: _i3.CameraType.environment, + ) as _i3.CameraType); + + @override + _i4.Size mapResolutionPresetToSize(_i7.ResolutionPreset? resolutionPreset) => (super.noSuchMethod( + Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), + returnValue: _FakeSize_2( + this, + Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), + ), + returnValueForMissingStub: _FakeSize_2( + this, + Invocation.method(#mapResolutionPresetToSize, [resolutionPreset]), + ), + ) as _i4.Size); + + @override + int mapResolutionPresetToVideoBitrate(_i7.ResolutionPreset? resolutionPreset) => (super.noSuchMethod( - Invocation.method(#mapResolutionPresetToVideoBitrate, [ - resolutionPreset, - ]), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); - - @override - int mapResolutionPresetToAudioBitrate( - _i7.ResolutionPreset? resolutionPreset, - ) => + Invocation.method(#mapResolutionPresetToVideoBitrate, [resolutionPreset]), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); + + @override + int mapResolutionPresetToAudioBitrate(_i7.ResolutionPreset? resolutionPreset) => (super.noSuchMethod( - Invocation.method(#mapResolutionPresetToAudioBitrate, [ - resolutionPreset, - ]), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); - - @override - String mapDeviceOrientationToOrientationType( - _i11.DeviceOrientation? deviceOrientation, - ) => + Invocation.method(#mapResolutionPresetToAudioBitrate, [resolutionPreset]), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); + + @override + String mapDeviceOrientationToOrientationType(_i11.DeviceOrientation? deviceOrientation) => (super.noSuchMethod( - Invocation.method(#mapDeviceOrientationToOrientationType, [ - deviceOrientation, - ]), - returnValue: _i12.dummyValue( - this, - Invocation.method(#mapDeviceOrientationToOrientationType, [ - deviceOrientation, - ]), - ), - returnValueForMissingStub: _i12.dummyValue( - this, - Invocation.method(#mapDeviceOrientationToOrientationType, [ - deviceOrientation, - ]), - ), - ) - as String); - - @override - _i11.DeviceOrientation mapOrientationTypeToDeviceOrientation( - String? orientationType, - ) => + Invocation.method(#mapDeviceOrientationToOrientationType, [deviceOrientation]), + returnValue: _i12.dummyValue( + this, + Invocation.method(#mapDeviceOrientationToOrientationType, [deviceOrientation]), + ), + returnValueForMissingStub: _i12.dummyValue( + this, + Invocation.method(#mapDeviceOrientationToOrientationType, [deviceOrientation]), + ), + ) as String); + + @override + _i11.DeviceOrientation mapOrientationTypeToDeviceOrientation(String? orientationType) => (super.noSuchMethod( - Invocation.method(#mapOrientationTypeToDeviceOrientation, [ - orientationType, - ]), - returnValue: _i11.DeviceOrientation.portraitUp, - returnValueForMissingStub: _i11.DeviceOrientation.portraitUp, - ) - as _i11.DeviceOrientation); + Invocation.method(#mapOrientationTypeToDeviceOrientation, [orientationType]), + returnValue: _i11.DeviceOrientation.portraitUp, + returnValueForMissingStub: _i11.DeviceOrientation.portraitUp, + ) as _i11.DeviceOrientation); } /// A class which mocks [JsUtil]. @@ -269,21 +203,17 @@ class MockCameraService extends _i1.Mock implements _i8.CameraService { /// See the documentation for Mockito's code generation for more information. class MockJsUtil extends _i1.Mock implements _i2.JsUtil { @override - bool hasProperty(_i13.JSObject? o, _i13.JSAny? name) => - (super.noSuchMethod( - Invocation.method(#hasProperty, [o, name]), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool hasProperty(_i13.JSObject? o, _i13.JSAny? name) => (super.noSuchMethod( + Invocation.method(#hasProperty, [o, name]), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i13.JSAny? getProperty(_i13.JSObject? o, _i13.JSAny? name) => - (super.noSuchMethod( - Invocation.method(#getProperty, [o, name]), - returnValueForMissingStub: null, - ) - as _i13.JSAny?); + _i13.JSAny? getProperty(_i13.JSObject? o, _i13.JSAny? name) => (super.noSuchMethod( + Invocation.method(#getProperty, [o, name]), + returnValueForMissingStub: null, + ) as _i13.JSAny?); } /// A class which mocks [Camera]. @@ -291,46 +221,32 @@ class MockJsUtil extends _i1.Mock implements _i2.JsUtil { /// See the documentation for Mockito's code generation for more information. class MockCamera extends _i1.Mock implements _i10.Camera { @override - int get textureId => - (super.noSuchMethod( - Invocation.getter(#textureId), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get textureId => (super.noSuchMethod( + Invocation.getter(#textureId), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - _i3.CameraOptions get options => - (super.noSuchMethod( - Invocation.getter(#options), - returnValue: _FakeCameraOptions_3( - this, - Invocation.getter(#options), - ), - returnValueForMissingStub: _FakeCameraOptions_3( - this, - Invocation.getter(#options), - ), - ) - as _i3.CameraOptions); - - @override - ({int? audioBitrate, int? videoBitrate}) get recorderOptions => - (super.noSuchMethod( - Invocation.getter(#recorderOptions), - returnValue: (audioBitrate: null, videoBitrate: null), - returnValueForMissingStub: (audioBitrate: null, videoBitrate: null), - ) - as ({int? audioBitrate, int? videoBitrate})); + _i3.CameraOptions get options => (super.noSuchMethod( + Invocation.getter(#options), + returnValue: _FakeCameraOptions_3(this, Invocation.getter(#options)), + returnValueForMissingStub: _FakeCameraOptions_3(this, Invocation.getter(#options)), + ) as _i3.CameraOptions); @override - _i6.HTMLVideoElement get videoElement => - (super.noSuchMethod( - Invocation.getter(#videoElement), - returnValue: _i9.videoElementShim(), - returnValueForMissingStub: _i9.videoElementShim(), - ) - as _i6.HTMLVideoElement); + ({int? audioBitrate, int? videoBitrate}) get recorderOptions => (super.noSuchMethod( + Invocation.getter(#recorderOptions), + returnValue: (audioBitrate: null, videoBitrate: null), + returnValueForMissingStub: (audioBitrate: null, videoBitrate: null), + ) as ({int? audioBitrate, int? videoBitrate})); + + @override + _i6.HTMLVideoElement get videoElement => (super.noSuchMethod( + Invocation.getter(#videoElement), + returnValue: _i9.videoElementShim(), + returnValueForMissingStub: _i9.videoElementShim(), + ) as _i6.HTMLVideoElement); @override set videoElement(_i6.HTMLVideoElement? _videoElement) => super.noSuchMethod( @@ -339,13 +255,11 @@ class MockCamera extends _i1.Mock implements _i10.Camera { ); @override - _i6.HTMLDivElement get divElement => - (super.noSuchMethod( - Invocation.getter(#divElement), - returnValue: _i9.divElementShim(), - returnValueForMissingStub: _i9.divElementShim(), - ) - as _i6.HTMLDivElement); + _i6.HTMLDivElement get divElement => (super.noSuchMethod( + Invocation.getter(#divElement), + returnValue: _i9.divElementShim(), + returnValueForMissingStub: _i9.divElementShim(), + ) as _i6.HTMLDivElement); @override set divElement(_i6.HTMLDivElement? _divElement) => super.noSuchMethod( @@ -354,67 +268,55 @@ class MockCamera extends _i1.Mock implements _i10.Camera { ); @override - set stream(_i6.MediaStream? _stream) => super.noSuchMethod( - Invocation.setter(#stream, _stream), - returnValueForMissingStub: null, - ); + set stream(_i6.MediaStream? _stream) => + super.noSuchMethod(Invocation.setter(#stream, _stream), returnValueForMissingStub: null); @override - _i5.StreamController<_i6.MediaStreamTrack> get onEndedController => - (super.noSuchMethod( - Invocation.getter(#onEndedController), - returnValue: _FakeStreamController_4<_i6.MediaStreamTrack>( - this, - Invocation.getter(#onEndedController), - ), - returnValueForMissingStub: - _FakeStreamController_4<_i6.MediaStreamTrack>( - this, - Invocation.getter(#onEndedController), - ), - ) - as _i5.StreamController<_i6.MediaStreamTrack>); - - @override - _i6.EventStreamProvider<_i6.Event> get mediaRecorderOnErrorProvider => - (super.noSuchMethod( - Invocation.getter(#mediaRecorderOnErrorProvider), - returnValue: _FakeEventStreamProvider_5<_i6.Event>( - this, - Invocation.getter(#mediaRecorderOnErrorProvider), - ), - returnValueForMissingStub: _FakeEventStreamProvider_5<_i6.Event>( - this, - Invocation.getter(#mediaRecorderOnErrorProvider), - ), - ) - as _i6.EventStreamProvider<_i6.Event>); + _i5.StreamController<_i6.MediaStreamTrack> get onEndedController => (super.noSuchMethod( + Invocation.getter(#onEndedController), + returnValue: _FakeStreamController_4<_i6.MediaStreamTrack>( + this, + Invocation.getter(#onEndedController), + ), + returnValueForMissingStub: _FakeStreamController_4<_i6.MediaStreamTrack>( + this, + Invocation.getter(#onEndedController), + ), + ) as _i5.StreamController<_i6.MediaStreamTrack>); + + @override + _i6.EventStreamProvider<_i6.Event> get mediaRecorderOnErrorProvider => (super.noSuchMethod( + Invocation.getter(#mediaRecorderOnErrorProvider), + returnValue: _FakeEventStreamProvider_5<_i6.Event>( + this, + Invocation.getter(#mediaRecorderOnErrorProvider), + ), + returnValueForMissingStub: _FakeEventStreamProvider_5<_i6.Event>( + this, + Invocation.getter(#mediaRecorderOnErrorProvider), + ), + ) as _i6.EventStreamProvider<_i6.Event>); @override set mediaRecorderOnErrorProvider( _i6.EventStreamProvider<_i6.Event>? _mediaRecorderOnErrorProvider, ) => super.noSuchMethod( - Invocation.setter( - #mediaRecorderOnErrorProvider, - _mediaRecorderOnErrorProvider, - ), + Invocation.setter(#mediaRecorderOnErrorProvider, _mediaRecorderOnErrorProvider), returnValueForMissingStub: null, ); @override - _i5.StreamController<_i6.ErrorEvent> get videoRecordingErrorController => - (super.noSuchMethod( - Invocation.getter(#videoRecordingErrorController), - returnValue: _FakeStreamController_4<_i6.ErrorEvent>( - this, - Invocation.getter(#videoRecordingErrorController), - ), - returnValueForMissingStub: _FakeStreamController_4<_i6.ErrorEvent>( - this, - Invocation.getter(#videoRecordingErrorController), - ), - ) - as _i5.StreamController<_i6.ErrorEvent>); + _i5.StreamController<_i6.ErrorEvent> get videoRecordingErrorController => (super.noSuchMethod( + Invocation.getter(#videoRecordingErrorController), + returnValue: _FakeStreamController_4<_i6.ErrorEvent>( + this, + Invocation.getter(#videoRecordingErrorController), + ), + returnValueForMissingStub: _FakeStreamController_4<_i6.ErrorEvent>( + this, + Invocation.getter(#videoRecordingErrorController), + ), + ) as _i5.StreamController<_i6.ErrorEvent>); @override set flashMode(_i7.FlashMode? _flashMode) => super.noSuchMethod( @@ -423,19 +325,15 @@ class MockCamera extends _i1.Mock implements _i10.Camera { ); @override - _i6.Window get window => - (super.noSuchMethod( - Invocation.getter(#window), - returnValue: _i9.windowShim(), - returnValueForMissingStub: _i9.windowShim(), - ) - as _i6.Window); + _i6.Window get window => (super.noSuchMethod( + Invocation.getter(#window), + returnValue: _i9.windowShim(), + returnValueForMissingStub: _i9.windowShim(), + ) as _i6.Window); @override - set window(_i6.Window? _window) => super.noSuchMethod( - Invocation.setter(#window, _window), - returnValueForMissingStub: null, - ); + set window(_i6.Window? _window) => + super.noSuchMethod(Invocation.setter(#window, _window), returnValueForMissingStub: null); @override set mediaRecorder(_i6.MediaRecorder? _mediaRecorder) => super.noSuchMethod( @@ -444,232 +342,171 @@ class MockCamera extends _i1.Mock implements _i10.Camera { ); @override - bool Function(String) get isVideoTypeSupported => - (super.noSuchMethod( - Invocation.getter(#isVideoTypeSupported), - returnValue: (String __p0) => false, - returnValueForMissingStub: (String __p0) => false, - ) - as bool Function(String)); + bool Function(String) get isVideoTypeSupported => (super.noSuchMethod( + Invocation.getter(#isVideoTypeSupported), + returnValue: (String __p0) => false, + returnValueForMissingStub: (String __p0) => false, + ) as bool Function(String)); @override - set isVideoTypeSupported(bool Function(String)? _isVideoTypeSupported) => - super.noSuchMethod( - Invocation.setter(#isVideoTypeSupported, _isVideoTypeSupported), - returnValueForMissingStub: null, - ); + set isVideoTypeSupported(bool Function(String)? _isVideoTypeSupported) => super.noSuchMethod( + Invocation.setter(#isVideoTypeSupported, _isVideoTypeSupported), + returnValueForMissingStub: null, + ); @override - _i6.Blob Function(List<_i6.Blob>, String) get blobBuilder => - (super.noSuchMethod( - Invocation.getter(#blobBuilder), - returnValue: _i9.blobBuilderShim(), - returnValueForMissingStub: _i9.blobBuilderShim(), - ) - as _i6.Blob Function(List<_i6.Blob>, String)); + _i6.Blob Function(List<_i6.Blob>, String) get blobBuilder => (super.noSuchMethod( + Invocation.getter(#blobBuilder), + returnValue: _i9.blobBuilderShim(), + returnValueForMissingStub: _i9.blobBuilderShim(), + ) as _i6.Blob Function(List<_i6.Blob>, String)); @override - set blobBuilder(_i6.Blob Function(List<_i6.Blob>, String)? _blobBuilder) => - super.noSuchMethod( - Invocation.setter(#blobBuilder, _blobBuilder), - returnValueForMissingStub: null, - ); + set blobBuilder(_i6.Blob Function(List<_i6.Blob>, String)? _blobBuilder) => super.noSuchMethod( + Invocation.setter(#blobBuilder, _blobBuilder), + returnValueForMissingStub: null, + ); @override - _i5.StreamController<_i7.VideoRecordedEvent> get videoRecorderController => - (super.noSuchMethod( - Invocation.getter(#videoRecorderController), - returnValue: _FakeStreamController_4<_i7.VideoRecordedEvent>( - this, - Invocation.getter(#videoRecorderController), - ), - returnValueForMissingStub: - _FakeStreamController_4<_i7.VideoRecordedEvent>( - this, - Invocation.getter(#videoRecorderController), - ), - ) - as _i5.StreamController<_i7.VideoRecordedEvent>); - - @override - _i5.Stream<_i6.MediaStreamTrack> get onEnded => - (super.noSuchMethod( - Invocation.getter(#onEnded), - returnValue: _i5.Stream<_i6.MediaStreamTrack>.empty(), - returnValueForMissingStub: _i5.Stream<_i6.MediaStreamTrack>.empty(), - ) - as _i5.Stream<_i6.MediaStreamTrack>); + _i5.StreamController<_i7.VideoRecordedEvent> get videoRecorderController => (super.noSuchMethod( + Invocation.getter(#videoRecorderController), + returnValue: _FakeStreamController_4<_i7.VideoRecordedEvent>( + this, + Invocation.getter(#videoRecorderController), + ), + returnValueForMissingStub: _FakeStreamController_4<_i7.VideoRecordedEvent>( + this, + Invocation.getter(#videoRecorderController), + ), + ) as _i5.StreamController<_i7.VideoRecordedEvent>); @override - _i5.Stream<_i6.ErrorEvent> get onVideoRecordingError => - (super.noSuchMethod( - Invocation.getter(#onVideoRecordingError), - returnValue: _i5.Stream<_i6.ErrorEvent>.empty(), - returnValueForMissingStub: _i5.Stream<_i6.ErrorEvent>.empty(), - ) - as _i5.Stream<_i6.ErrorEvent>); + _i5.Stream<_i6.MediaStreamTrack> get onEnded => (super.noSuchMethod( + Invocation.getter(#onEnded), + returnValue: _i5.Stream<_i6.MediaStreamTrack>.empty(), + returnValueForMissingStub: _i5.Stream<_i6.MediaStreamTrack>.empty(), + ) as _i5.Stream<_i6.MediaStreamTrack>); @override - _i5.Stream<_i7.VideoRecordedEvent> get onVideoRecordedEvent => - (super.noSuchMethod( - Invocation.getter(#onVideoRecordedEvent), - returnValue: _i5.Stream<_i7.VideoRecordedEvent>.empty(), - returnValueForMissingStub: - _i5.Stream<_i7.VideoRecordedEvent>.empty(), - ) - as _i5.Stream<_i7.VideoRecordedEvent>); + _i5.Stream<_i6.ErrorEvent> get onVideoRecordingError => (super.noSuchMethod( + Invocation.getter(#onVideoRecordingError), + returnValue: _i5.Stream<_i6.ErrorEvent>.empty(), + returnValueForMissingStub: _i5.Stream<_i6.ErrorEvent>.empty(), + ) as _i5.Stream<_i6.ErrorEvent>); @override - _i5.Future initialize() => - (super.noSuchMethod( - Invocation.method(#initialize, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Stream<_i7.VideoRecordedEvent> get onVideoRecordedEvent => (super.noSuchMethod( + Invocation.getter(#onVideoRecordedEvent), + returnValue: _i5.Stream<_i7.VideoRecordedEvent>.empty(), + returnValueForMissingStub: _i5.Stream<_i7.VideoRecordedEvent>.empty(), + ) as _i5.Stream<_i7.VideoRecordedEvent>); @override - _i5.Future play() => - (super.noSuchMethod( - Invocation.method(#play, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future initialize() => (super.noSuchMethod( + Invocation.method(#initialize, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - void pause() => super.noSuchMethod( - Invocation.method(#pause, []), - returnValueForMissingStub: null, - ); + _i5.Future play() => (super.noSuchMethod( + Invocation.method(#play, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - void stop() => super.noSuchMethod( - Invocation.method(#stop, []), - returnValueForMissingStub: null, - ); + void pause() => + super.noSuchMethod(Invocation.method(#pause, []), returnValueForMissingStub: null); @override - _i5.Future<_i7.XFile> takePicture() => - (super.noSuchMethod( - Invocation.method(#takePicture, []), - returnValue: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#takePicture, [])), - ), - returnValueForMissingStub: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#takePicture, [])), - ), - ) - as _i5.Future<_i7.XFile>); - - @override - _i4.Size getVideoSize() => - (super.noSuchMethod( - Invocation.method(#getVideoSize, []), - returnValue: _FakeSize_2( - this, - Invocation.method(#getVideoSize, []), - ), - returnValueForMissingStub: _FakeSize_2( - this, - Invocation.method(#getVideoSize, []), - ), - ) - as _i4.Size); - - @override - void setFlashMode(_i7.FlashMode? mode) => super.noSuchMethod( - Invocation.method(#setFlashMode, [mode]), - returnValueForMissingStub: null, - ); + void stop() => super.noSuchMethod(Invocation.method(#stop, []), returnValueForMissingStub: null); @override - double getMaxZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getMaxZoomLevel, []), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) - as double); + _i5.Future<_i7.XFile> takePicture() => (super.noSuchMethod( + Invocation.method(#takePicture, []), + returnValue: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#takePicture, [])), + ), + returnValueForMissingStub: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#takePicture, [])), + ), + ) as _i5.Future<_i7.XFile>); @override - double getMinZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getMinZoomLevel, []), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) - as double); + _i4.Size getVideoSize() => (super.noSuchMethod( + Invocation.method(#getVideoSize, []), + returnValue: _FakeSize_2(this, Invocation.method(#getVideoSize, [])), + returnValueForMissingStub: _FakeSize_2(this, Invocation.method(#getVideoSize, [])), + ) as _i4.Size); @override - void setZoomLevel(double? zoom) => super.noSuchMethod( - Invocation.method(#setZoomLevel, [zoom]), - returnValueForMissingStub: null, - ); + void setFlashMode(_i7.FlashMode? mode) => + super.noSuchMethod(Invocation.method(#setFlashMode, [mode]), returnValueForMissingStub: null); @override - String getViewType() => - (super.noSuchMethod( - Invocation.method(#getViewType, []), - returnValue: _i12.dummyValue( - this, - Invocation.method(#getViewType, []), - ), - returnValueForMissingStub: _i12.dummyValue( - this, - Invocation.method(#getViewType, []), - ), - ) - as String); - - @override - _i5.Future startVideoRecording() => - (super.noSuchMethod( - Invocation.method(#startVideoRecording, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + double getMaxZoomLevel() => (super.noSuchMethod( + Invocation.method(#getMaxZoomLevel, []), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); @override - _i5.Future pauseVideoRecording() => - (super.noSuchMethod( - Invocation.method(#pauseVideoRecording, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + double getMinZoomLevel() => (super.noSuchMethod( + Invocation.method(#getMinZoomLevel, []), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); @override - _i5.Future resumeVideoRecording() => - (super.noSuchMethod( - Invocation.method(#resumeVideoRecording, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + void setZoomLevel(double? zoom) => + super.noSuchMethod(Invocation.method(#setZoomLevel, [zoom]), returnValueForMissingStub: null); @override - _i5.Future<_i7.XFile> stopVideoRecording() => - (super.noSuchMethod( - Invocation.method(#stopVideoRecording, []), - returnValue: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), - ), - returnValueForMissingStub: _i5.Future<_i7.XFile>.value( - _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), - ), - ) - as _i5.Future<_i7.XFile>); - - @override - _i5.Future dispose() => - (super.noSuchMethod( - Invocation.method(#dispose, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + String getViewType() => (super.noSuchMethod( + Invocation.method(#getViewType, []), + returnValue: _i12.dummyValue(this, Invocation.method(#getViewType, [])), + returnValueForMissingStub: _i12.dummyValue(this, Invocation.method(#getViewType, [])), + ) as String); + + @override + _i5.Future startVideoRecording() => (super.noSuchMethod( + Invocation.method(#startVideoRecording, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future pauseVideoRecording() => (super.noSuchMethod( + Invocation.method(#pauseVideoRecording, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future resumeVideoRecording() => (super.noSuchMethod( + Invocation.method(#resumeVideoRecording, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future<_i7.XFile> stopVideoRecording() => (super.noSuchMethod( + Invocation.method(#stopVideoRecording, []), + returnValue: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), + ), + returnValueForMissingStub: _i5.Future<_i7.XFile>.value( + _FakeXFile_6(this, Invocation.method(#stopVideoRecording, [])), + ), + ) as _i5.Future<_i7.XFile>); + + @override + _i5.Future dispose() => (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [CameraOptions]. @@ -678,41 +515,23 @@ class MockCamera extends _i1.Mock implements _i10.Camera { // ignore: must_be_immutable class MockCameraOptions extends _i1.Mock implements _i3.CameraOptions { @override - _i3.AudioConstraints get audio => - (super.noSuchMethod( - Invocation.getter(#audio), - returnValue: _FakeAudioConstraints_7( - this, - Invocation.getter(#audio), - ), - returnValueForMissingStub: _FakeAudioConstraints_7( - this, - Invocation.getter(#audio), - ), - ) - as _i3.AudioConstraints); - - @override - _i3.VideoConstraints get video => - (super.noSuchMethod( - Invocation.getter(#video), - returnValue: _FakeVideoConstraints_8( - this, - Invocation.getter(#video), - ), - returnValueForMissingStub: _FakeVideoConstraints_8( - this, - Invocation.getter(#video), - ), - ) - as _i3.VideoConstraints); - - @override - _i6.MediaStreamConstraints toMediaStreamConstraints() => - (super.noSuchMethod( - Invocation.method(#toMediaStreamConstraints, []), - returnValue: _i9.toMediaStreamConstraintsShim(), - returnValueForMissingStub: _i9.toMediaStreamConstraintsShim(), - ) - as _i6.MediaStreamConstraints); + _i3.AudioConstraints get audio => (super.noSuchMethod( + Invocation.getter(#audio), + returnValue: _FakeAudioConstraints_7(this, Invocation.getter(#audio)), + returnValueForMissingStub: _FakeAudioConstraints_7(this, Invocation.getter(#audio)), + ) as _i3.AudioConstraints); + + @override + _i3.VideoConstraints get video => (super.noSuchMethod( + Invocation.getter(#video), + returnValue: _FakeVideoConstraints_8(this, Invocation.getter(#video)), + returnValueForMissingStub: _FakeVideoConstraints_8(this, Invocation.getter(#video)), + ) as _i3.VideoConstraints); + + @override + _i6.MediaStreamConstraints toMediaStreamConstraints() => (super.noSuchMethod( + Invocation.method(#toMediaStreamConstraints, []), + returnValue: _i9.toMediaStreamConstraintsShim(), + returnValueForMissingStub: _i9.toMediaStreamConstraintsShim(), + ) as _i6.MediaStreamConstraints); } diff --git a/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart b/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart index dc938d40c3ab..12218d5e7833 100644 --- a/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart +++ b/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart @@ -19,8 +19,7 @@ void main() { testWidgets('sets all properties', (WidgetTester tester) async { const minimum = 100.0; const maximum = 400.0; - final videoTrack = - createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack; + final videoTrack = createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack; final capability = ZoomLevelCapability( minimum: minimum, @@ -34,22 +33,11 @@ void main() { }); testWidgets('supports value equality', (WidgetTester tester) async { - final videoTrack = - createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack; + final videoTrack = createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack; expect( - ZoomLevelCapability( - minimum: 0.0, - maximum: 100.0, - videoTrack: videoTrack, - ), - equals( - ZoomLevelCapability( - minimum: 0.0, - maximum: 100.0, - videoTrack: videoTrack, - ), - ), + ZoomLevelCapability(minimum: 0.0, maximum: 100.0, videoTrack: videoTrack), + equals(ZoomLevelCapability(minimum: 0.0, maximum: 100.0, videoTrack: videoTrack)), ); }); }); diff --git a/packages/camera/camera_web/lib/src/camera.dart b/packages/camera/camera_web/lib/src/camera.dart index dd773d380c73..ff458e54a9ee 100644 --- a/packages/camera/camera_web/lib/src/camera.dart +++ b/packages/camera/camera_web/lib/src/camera.dart @@ -97,8 +97,7 @@ class Camera { /// /// MediaRecorder.error: /// https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/error_event - Stream get onVideoRecordingError => - videoRecordingErrorController.stream; + Stream get onVideoRecordingError => videoRecordingErrorController.stream; /// The stream provider for [MediaRecorder] error events. @visibleForTesting @@ -146,13 +145,13 @@ class Camera { /// A builder to merge a list of blobs into a single blob. @visibleForTesting - web.Blob Function(List blobs, String type) blobBuilder = - (List blobs, String type) => - web.Blob(blobs.toJS, web.BlobPropertyBag(type: type)); + web.Blob Function(List blobs, String type) blobBuilder = ( + List blobs, + String type, + ) => web.Blob(blobs.toJS, web.BlobPropertyBag(type: type)); /// The stream that emits a [VideoRecordedEvent] when a video recording is created. - Stream get onVideoRecordedEvent => - videoRecorderController.stream; + Stream get onVideoRecordedEvent => videoRecorderController.stream; /// The stream controller for the [onVideoRecordedEvent] stream. @visibleForTesting @@ -163,10 +162,7 @@ class Camera { /// Registers the camera view with [textureId] under [_getViewType] type. /// Emits the camera default video track on the [onEnded] stream when it ends. Future initialize() async { - stream = await _cameraService.getMediaStreamForOptions( - options, - cameraId: textureId, - ); + stream = await _cameraService.getMediaStreamForOptions(options, cameraId: textureId); videoElement = web.HTMLVideoElement(); @@ -176,10 +172,7 @@ class Camera { ..style.setProperty('width', '100%') ..append(videoElement); - ui_web.platformViewRegistry.registerViewFactory( - _getViewType(textureId), - (_) => divElement, - ); + ui_web.platformViewRegistry.registerViewFactory(_getViewType(textureId), (_) => divElement); videoElement ..autoplay = false @@ -189,17 +182,15 @@ class Camera { _applyDefaultVideoStyles(videoElement); - final List videoTracks = stream! - .getVideoTracks() - .toDart; + final List videoTracks = stream!.getVideoTracks().toDart; if (videoTracks.isNotEmpty) { final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; - _onEndedSubscription = EventStreamProviders.endedEvent - .forTarget(defaultVideoTrack) - .listen((web.Event _) { - onEndedController.add(defaultVideoTrack); - }); + _onEndedSubscription = EventStreamProviders.endedEvent.forTarget(defaultVideoTrack).listen(( + web.Event _, + ) { + onEndedController.add(defaultVideoTrack); + }); } } @@ -208,10 +199,7 @@ class Camera { /// Initializes the camera source if the camera was previously stopped. Future play() async { if (videoElement.srcObject == null) { - stream = await _cameraService.getMediaStreamForOptions( - options, - cameraId: textureId, - ); + stream = await _cameraService.getMediaStreamForOptions(options, cameraId: textureId); videoElement.srcObject = stream; } await videoElement.play().toDart; @@ -224,9 +212,7 @@ class Camera { /// Stops the camera stream and resets the camera source. void stop() { - final List videoTracks = stream! - .getVideoTracks() - .toDart; + final List videoTracks = stream!.getVideoTracks().toDart; if (videoTracks.isNotEmpty) { onEndedController.add(videoTracks.first); } @@ -246,8 +232,7 @@ class Camera { /// Enables the camera flash (torch mode) for a period of taking a picture /// if the flash mode is either [FlashMode.auto] or [FlashMode.always]. Future takePicture() async { - final bool shouldEnableTorchMode = - flashMode == FlashMode.auto || flashMode == FlashMode.always; + final bool shouldEnableTorchMode = flashMode == FlashMode.auto || flashMode == FlashMode.always; if (shouldEnableTorchMode) { _setTorchMode(enabled: true); @@ -267,13 +252,7 @@ class Camera { ..scale(-1, 1); } - canvas.context2D.drawImage( - videoElement, - 0, - 0, - videoWidth.toDouble(), - videoHeight.toDouble(), - ); + canvas.context2D.drawImage(videoElement, 0, 0, videoWidth.toDouble(), videoHeight.toDouble()); final blobCompleter = Completer(); canvas.toBlob( @@ -306,8 +285,7 @@ class Camera { final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; - final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack - .getSettings(); + final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack.getSettings(); final int width = defaultVideoTrackSettings.width; final int height = defaultVideoTrackSettings.height; @@ -358,13 +336,7 @@ class Camera { if (videoTracks.isNotEmpty) { final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; final bool canEnableTorchMode = - defaultVideoTrack - .getCapabilities() - .torchNullable - ?.toDart - .first - .toDart ?? - false; + defaultVideoTrack.getCapabilities().torchNullable?.toDart.first.toDart ?? false; if (canEnableTorchMode) { defaultVideoTrack.applyWebTweakConstraints( @@ -390,26 +362,24 @@ class Camera { /// /// Throws a [CameraWebException] if the zoom level is not supported /// or the camera has not been initialized or started. - double getMaxZoomLevel() => - _cameraService.getZoomLevelCapabilityForCamera(this).maximum; + double getMaxZoomLevel() => _cameraService.getZoomLevelCapabilityForCamera(this).maximum; /// Returns the camera minimum zoom level. /// /// Throws a [CameraWebException] if the zoom level is not supported /// or the camera has not been initialized or started. - double getMinZoomLevel() => - _cameraService.getZoomLevelCapabilityForCamera(this).minimum; + double getMinZoomLevel() => _cameraService.getZoomLevelCapabilityForCamera(this).minimum; /// Sets the camera zoom level to [zoom]. /// /// Throws a [CameraWebException] if the zoom level is invalid, /// not supported or the camera has not been initialized or started. void setZoomLevel(double zoom) { - final ZoomLevelCapability zoomLevelCapability = _cameraService - .getZoomLevelCapabilityForCamera(this); + final ZoomLevelCapability zoomLevelCapability = _cameraService.getZoomLevelCapabilityForCamera( + this, + ); - if (zoom < zoomLevelCapability.minimum || - zoom > zoomLevelCapability.maximum) { + if (zoom < zoomLevelCapability.minimum || zoom > zoomLevelCapability.maximum) { throw CameraWebException( textureId, CameraErrorCode.zoomLevelInvalid, @@ -436,8 +406,7 @@ class Camera { } final web.MediaStreamTrack defaultVideoTrack = videoTracks.first; - final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack - .getSettings(); + final web.MediaTrackSettings defaultVideoTrackSettings = defaultVideoTrack.getSettings(); final String? facingMode = defaultVideoTrackSettings.facingModeNullable; @@ -464,28 +433,17 @@ class Camera { options.videoBitsPerSecond = recorderOptions.videoBitrate!; } - mediaRecorder ??= web.MediaRecorder( - videoElement.srcObject! as web.MediaStream, - options, - ); + mediaRecorder ??= web.MediaRecorder(videoElement.srcObject! as web.MediaStream, options); _videoAvailableCompleter = Completer(); - _videoDataAvailableListener = (web.BlobEvent event) => - _onVideoDataAvailable(event); + _videoDataAvailableListener = (web.BlobEvent event) => _onVideoDataAvailable(event); - _videoRecordingStoppedListener = (web.Event event) => - _onVideoRecordingStopped(event); + _videoRecordingStoppedListener = (web.Event event) => _onVideoRecordingStopped(event); - mediaRecorder!.addEventListener( - 'dataavailable', - _videoDataAvailableListener?.toJS, - ); + mediaRecorder!.addEventListener('dataavailable', _videoDataAvailableListener?.toJS); - mediaRecorder!.addEventListener( - 'stop', - _videoRecordingStoppedListener?.toJS, - ); + mediaRecorder!.addEventListener('stop', _videoRecordingStoppedListener?.toJS); _onVideoRecordingErrorSubscription = mediaRecorderOnErrorProvider .forTarget(mediaRecorder) @@ -522,15 +480,9 @@ class Camera { } // Clean up the media recorder with its event listeners and video data. - mediaRecorder!.removeEventListener( - 'dataavailable', - _videoDataAvailableListener?.toJS, - ); + mediaRecorder!.removeEventListener('dataavailable', _videoDataAvailableListener?.toJS); - mediaRecorder!.removeEventListener( - 'stop', - _videoDataAvailableListener?.toJS, - ); + mediaRecorder!.removeEventListener('stop', _videoDataAvailableListener?.toJS); await _onVideoRecordingErrorSubscription?.cancel(); @@ -603,11 +555,7 @@ class Camera { /// Throws a [CameraWebException] if the browser does not support /// any of the available video mime types. String get _videoMimeType { - const types = [ - 'video/webm;codecs="vp9,opus"', - 'video/mp4', - 'video/webm', - ]; + const types = ['video/webm;codecs="vp9,opus"', 'video/mp4', 'video/webm']; return types.firstWhere( (String type) => isVideoTypeSupported(type), @@ -619,8 +567,7 @@ class Camera { ); } - CameraWebException - get _videoRecordingNotStartedException => CameraWebException( + CameraWebException get _videoRecordingNotStartedException => CameraWebException( textureId, CameraErrorCode.videoRecordingNotStarted, 'The video recorder is uninitialized. The recording might not have been started. Make sure to call `startVideoRecording` first.', diff --git a/packages/camera/camera_web/lib/src/camera_service.dart b/packages/camera/camera_web/lib/src/camera_service.dart index 9bf588a456da..d620b4a43cfb 100644 --- a/packages/camera/camera_web/lib/src/camera_service.dart +++ b/packages/camera/camera_web/lib/src/camera_service.dart @@ -34,9 +34,7 @@ class CameraService { final web.MediaDevices mediaDevices = window.navigator.mediaDevices; try { - return await mediaDevices - .getUserMedia(options.toMediaStreamConstraints()) - .toDart; + return await mediaDevices.getUserMedia(options.toMediaStreamConstraints()).toDart; } on web.DOMException catch (e) { switch (e.name) { case 'NotFoundError': @@ -195,8 +193,7 @@ class CameraService { return null; } - final web.MediaTrackCapabilities videoTrackCapabilities = videoTrack - .getCapabilities(); + final web.MediaTrackCapabilities videoTrackCapabilities = videoTrack.getCapabilities(); // A list of facing mode capabilities as // the camera may support multiple facing modes. @@ -329,9 +326,7 @@ class CameraService { } /// Maps the given [deviceOrientation] to [OrientationType]. - String mapDeviceOrientationToOrientationType( - DeviceOrientation deviceOrientation, - ) { + String mapDeviceOrientationToOrientationType(DeviceOrientation deviceOrientation) { switch (deviceOrientation) { case DeviceOrientation.portraitUp: return OrientationType.portraitPrimary; @@ -345,9 +340,7 @@ class CameraService { } /// Maps the given [orientationType] to [DeviceOrientation]. - DeviceOrientation mapOrientationTypeToDeviceOrientation( - String orientationType, - ) { + DeviceOrientation mapOrientationTypeToDeviceOrientation(String orientationType) { switch (orientationType) { case OrientationType.portraitPrimary: return DeviceOrientation.portraitUp; diff --git a/packages/camera/camera_web/lib/src/camera_web.dart b/packages/camera/camera_web/lib/src/camera_web.dart index 90033681d28a..ecb4da1e9fdc 100644 --- a/packages/camera/camera_web/lib/src/camera_web.dart +++ b/packages/camera/camera_web/lib/src/camera_web.dart @@ -29,8 +29,7 @@ const String _kDefaultErrorMessage = class CameraPlugin extends CameraPlatform { /// Creates a new instance of [CameraPlugin] /// with the given [cameraService]. - CameraPlugin({required CameraService cameraService}) - : _cameraService = cameraService; + CameraPlugin({required CameraService cameraService}) : _cameraService = cameraService; /// Registers this class as the default instance of [CameraPlatform]. static void registerWith(Registrar registrar) { @@ -74,17 +73,15 @@ class CameraPlugin extends CameraPlatform { final Map> _cameraVideoAbortSubscriptions = >{}; - final Map> - _cameraEndedSubscriptions = >{}; + final Map> _cameraEndedSubscriptions = + >{}; - final Map> - _cameraVideoRecordingErrorSubscriptions = + final Map> _cameraVideoRecordingErrorSubscriptions = >{}; /// Returns a stream of camera events for the given [cameraId]. - Stream _cameraEvents(int cameraId) => cameraEventStreamController - .stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => + cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId); /// The stream provider for [web.ScreenOrientation] change events. @visibleForTesting @@ -102,8 +99,9 @@ class CameraPlugin extends CameraPlatform { final cameras = []; // Request video permissions only. - final web.MediaStream cameraStream = await _cameraService - .getMediaStreamForOptions(const CameraOptions()); + final web.MediaStream cameraStream = await _cameraService.getMediaStreamForOptions( + const CameraOptions(), + ); // Release the camera stream used to request video permissions. cameraStream.getVideoTracks().toDart.forEach( @@ -116,10 +114,7 @@ class CameraPlugin extends CameraPlatform { // Filter video input devices. final Iterable videoInputDevices = devices - .where( - (web.MediaDeviceInfo device) => - device.kind == MediaDeviceKind.videoInput, - ) + .where((web.MediaDeviceInfo device) => device.kind == MediaDeviceKind.videoInput) /// The device id property is currently not supported on Internet Explorer: /// https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/deviceId#browser_compatibility .where((web.MediaDeviceInfo device) => device.deviceId.isNotEmpty); @@ -134,15 +129,11 @@ class CameraPlugin extends CameraPlatform { // Get all video tracks in the video stream // to later extract the lens direction from the first track. - final List videoTracks = videoStream - .getVideoTracks() - .toDart; + final List videoTracks = videoStream.getVideoTracks().toDart; if (videoTracks.isNotEmpty) { // Get the facing mode from the first available video track. - final String? facingMode = _cameraService.getFacingModeForVideoTrack( - videoTracks.first, - ); + final String? facingMode = _cameraService.getFacingModeForVideoTrack(videoTracks.first); // Get the lens direction based on the facing mode. // Fallback to the external lens direction @@ -242,9 +233,7 @@ class CameraPlugin extends CameraPlatform { options: CameraOptions( audio: AudioConstraints(enabled: mediaSettings?.enableAudio ?? true), video: VideoConstraints( - facingMode: cameraType != null - ? FacingModeConstraint(cameraType) - : null, + facingMode: cameraType != null ? FacingModeConstraint(cameraType) : null, width: VideoSizeConstraint(ideal: videoSize.width.toInt()), height: VideoSizeConstraint(ideal: videoSize.height.toInt()), deviceId: cameraMetadata.deviceId, @@ -284,18 +273,11 @@ class CameraPlugin extends CameraPlatform { // We need to look at the HTMLMediaElement.error. // See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error final web.MediaError error = camera.videoElement.error!; - final CameraErrorCode errorCode = CameraErrorCode.fromMediaError( - error, - ); - final String errorMessage = error.message != '' - ? error.message - : _kDefaultErrorMessage; + final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error); + final String errorMessage = error.message != '' ? error.message : _kDefaultErrorMessage; cameraEventStreamController.add( - CameraErrorEvent( - cameraId, - 'Error code: $errorCode, error message: $errorMessage', - ), + CameraErrorEvent(cameraId, 'Error code: $errorCode, error message: $errorMessage'), ); }); @@ -316,9 +298,7 @@ class CameraPlugin extends CameraPlatform { // Add camera's closing events to the camera events stream. // The onEnded stream fires when there is no more camera stream data. - _cameraEndedSubscriptions[cameraId] = camera.onEnded.listen(( - web.MediaStreamTrack _, - ) { + _cameraEndedSubscriptions[cameraId] = camera.onEnded.listen((web.MediaStreamTrack _) { cameraEventStreamController.add(CameraClosingEvent(cameraId)); }); @@ -394,17 +374,15 @@ class CameraPlugin extends CameraPlatform { } @override - Future lockCaptureOrientation( - int cameraId, - DeviceOrientation orientation, - ) async { + Future lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async { try { final web.ScreenOrientation screenOrientation = window.screen.orientation; final web.Element? documentElement = window.document.documentElement; if (documentElement != null) { - final String orientationType = _cameraService - .mapDeviceOrientationToOrientationType(orientation); + final String orientationType = _cameraService.mapDeviceOrientationToOrientationType( + orientation, + ); // Full-screen mode may be required to modify the device orientation. // See: https://w3c.github.io/screen-orientation/#interaction-with-fullscreen-api @@ -478,17 +456,15 @@ class CameraPlugin extends CameraPlatform { // Add camera's video recording errors to the camera events stream. // The error event fires when the video recording is not allowed or an unsupported // codec is used. - _cameraVideoRecordingErrorSubscriptions[options - .cameraId] = camera.onVideoRecordingError.listen(( - web.ErrorEvent errorEvent, - ) { - cameraEventStreamController.add( - CameraErrorEvent( - options.cameraId, - 'Error code: ${errorEvent.type}, error message: ${errorEvent.message}.', - ), - ); - }); + _cameraVideoRecordingErrorSubscriptions[options.cameraId] = camera.onVideoRecordingError + .listen((web.ErrorEvent errorEvent) { + cameraEventStreamController.add( + CameraErrorEvent( + options.cameraId, + 'Error code: ${errorEvent.type}, error message: ${errorEvent.message}.', + ), + ); + }); return camera.startVideoRecording(); } on web.DOMException catch (e) { @@ -502,9 +478,7 @@ class CameraPlugin extends CameraPlatform { @override Future stopVideoRecording(int cameraId) async { try { - final XFile videoRecording = await getCamera( - cameraId, - ).stopVideoRecording(); + final XFile videoRecording = await getCamera(cameraId).stopVideoRecording(); await _cameraVideoRecordingErrorSubscriptions[cameraId]?.cancel(); return videoRecording; } on web.DOMException catch (e) { @@ -677,9 +651,7 @@ class CameraPlugin extends CameraPlatform { /// Returns a media video stream for the device with the given [deviceId]. Future _getVideoStreamForDevice(String deviceId) { // Create camera options with the desired device id. - final cameraOptions = CameraOptions( - video: VideoConstraints(deviceId: deviceId), - ); + final cameraOptions = CameraOptions(video: VideoConstraints(deviceId: deviceId)); return _cameraService.getMediaStreamForOptions(cameraOptions); } diff --git a/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart b/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart index f5d54d7dfdfc..ddfe93b806de 100644 --- a/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart +++ b/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart @@ -15,8 +15,7 @@ extension FullScreenSupportMethods on Element { } /// Adds missing fields to [MediaTrackSupportedConstraints]. -extension NonStandardFieldsOnMediaTrackSupportedConstraints - on MediaTrackSupportedConstraints { +extension NonStandardFieldsOnMediaTrackSupportedConstraints on MediaTrackSupportedConstraints { @JS('zoom') external bool? get zoomNullable; @@ -58,17 +57,12 @@ extension type WebTweakMediaSettingsRange._(JSObject _) implements JSObject { /// Adds an applyConstraints method that accepts the WebTweakMediaTrackConstraints. extension WebTweakMethodVersions on MediaStreamTrack { @JS('applyConstraints') - external JSPromise applyWebTweakConstraints([ - WebTweakMediaTrackConstraints constraints, - ]); + external JSPromise applyWebTweakConstraints([WebTweakMediaTrackConstraints constraints]); } /// Allows creating the MediaTrackConstraints that are needed. /// Brought over from package:web 1.0.0 extension type WebTweakMediaTrackConstraints._(JSObject _) implements JSObject { @JS('MediaTrackConstraints') - external factory WebTweakMediaTrackConstraints({ - JSAny zoom, - ConstrainBoolean torch, - }); + external factory WebTweakMediaTrackConstraints({JSAny zoom, ConstrainBoolean torch}); } diff --git a/packages/camera/camera_web/lib/src/types/camera_error_code.dart b/packages/camera/camera_web/lib/src/types/camera_error_code.dart index 81b3ab308c24..c10d58efd88f 100644 --- a/packages/camera/camera_web/lib/src/types/camera_error_code.dart +++ b/packages/camera/camera_web/lib/src/types/camera_error_code.dart @@ -15,28 +15,20 @@ class CameraErrorCode { String toString() => _type; /// The camera is not supported. - static const CameraErrorCode notSupported = CameraErrorCode._( - 'cameraNotSupported', - ); + static const CameraErrorCode notSupported = CameraErrorCode._('cameraNotSupported'); /// The camera is not found. static const CameraErrorCode notFound = CameraErrorCode._('cameraNotFound'); /// The camera is not readable. - static const CameraErrorCode notReadable = CameraErrorCode._( - 'cameraNotReadable', - ); + static const CameraErrorCode notReadable = CameraErrorCode._('cameraNotReadable'); /// The camera options are impossible to satisfy. - static const CameraErrorCode overconstrained = CameraErrorCode._( - 'cameraOverconstrained', - ); + static const CameraErrorCode overconstrained = CameraErrorCode._('cameraOverconstrained'); /// The camera cannot be used or the permission /// to access the camera is not granted. - static const CameraErrorCode permissionDenied = CameraErrorCode._( - 'CameraAccessDenied', - ); + static const CameraErrorCode permissionDenied = CameraErrorCode._('CameraAccessDenied'); /// The camera options are incorrect or attempted /// to access the media input from an insecure context. @@ -49,9 +41,7 @@ class CameraErrorCode { static const CameraErrorCode security = CameraErrorCode._('cameraSecurity'); /// The camera metadata is missing. - static const CameraErrorCode missingMetadata = CameraErrorCode._( - 'cameraMissingMetadata', - ); + static const CameraErrorCode missingMetadata = CameraErrorCode._('cameraMissingMetadata'); /// The camera orientation is not supported. static const CameraErrorCode orientationNotSupported = CameraErrorCode._( @@ -59,24 +49,16 @@ class CameraErrorCode { ); /// The camera torch mode is not supported. - static const CameraErrorCode torchModeNotSupported = CameraErrorCode._( - 'torchModeNotSupported', - ); + static const CameraErrorCode torchModeNotSupported = CameraErrorCode._('torchModeNotSupported'); /// The camera zoom level is not supported. - static const CameraErrorCode zoomLevelNotSupported = CameraErrorCode._( - 'zoomLevelNotSupported', - ); + static const CameraErrorCode zoomLevelNotSupported = CameraErrorCode._('zoomLevelNotSupported'); /// The camera zoom level is invalid. - static const CameraErrorCode zoomLevelInvalid = CameraErrorCode._( - 'zoomLevelInvalid', - ); + static const CameraErrorCode zoomLevelInvalid = CameraErrorCode._('zoomLevelInvalid'); /// The camera has not been initialized or started. - static const CameraErrorCode notStarted = CameraErrorCode._( - 'cameraNotStarted', - ); + static const CameraErrorCode notStarted = CameraErrorCode._('cameraNotStarted'); /// The video recording was not started. static const CameraErrorCode videoRecordingNotStarted = CameraErrorCode._( diff --git a/packages/camera/camera_web/lib/src/types/camera_metadata.dart b/packages/camera/camera_web/lib/src/types/camera_metadata.dart index 5c9b3c5a60b1..26a95ca8437c 100644 --- a/packages/camera/camera_web/lib/src/types/camera_metadata.dart +++ b/packages/camera/camera_web/lib/src/types/camera_metadata.dart @@ -30,9 +30,7 @@ class CameraMetadata { return true; } - return other is CameraMetadata && - other.deviceId == deviceId && - other.facingMode == facingMode; + return other is CameraMetadata && other.deviceId == deviceId && other.facingMode == facingMode; } @override diff --git a/packages/camera/camera_web/lib/src/types/camera_options.dart b/packages/camera/camera_web/lib/src/types/camera_options.dart index fe3953fd5a25..f030af3126f8 100644 --- a/packages/camera/camera_web/lib/src/types/camera_options.dart +++ b/packages/camera/camera_web/lib/src/types/camera_options.dart @@ -43,9 +43,7 @@ class CameraOptions { return true; } - return other is CameraOptions && - other.audio == audio && - other.video == video; + return other is CameraOptions && other.audio == audio && other.video == video; } @override @@ -86,12 +84,7 @@ class AudioConstraints { class VideoConstraints { /// Creates a new instance of [VideoConstraints] /// with the given constraints. - const VideoConstraints({ - this.facingMode, - this.width, - this.height, - this.deviceId, - }); + const VideoConstraints({this.facingMode, this.width, this.height, this.deviceId}); /// The facing mode of the video track. final FacingModeConstraint? facingMode; @@ -164,8 +157,7 @@ enum CameraType { class FacingModeConstraint { /// Creates a new instance of [FacingModeConstraint] /// with [ideal] constraint set to [type]. - factory FacingModeConstraint(CameraType type) => - FacingModeConstraint._(ideal: type); + factory FacingModeConstraint(CameraType type) => FacingModeConstraint._(ideal: type); /// Creates a new instance of [FacingModeConstraint] /// with the given [ideal] and [exact] constraints. @@ -173,8 +165,7 @@ class FacingModeConstraint { /// Creates a new instance of [FacingModeConstraint] /// with [exact] constraint set to [type]. - factory FacingModeConstraint.exact(CameraType type) => - FacingModeConstraint._(exact: type); + factory FacingModeConstraint.exact(CameraType type) => FacingModeConstraint._(exact: type); /// The ideal facing mode constraint. /// @@ -203,9 +194,7 @@ class FacingModeConstraint { return true; } - return other is FacingModeConstraint && - other.ideal == ideal && - other.exact == exact; + return other is FacingModeConstraint && other.ideal == ideal && other.exact == exact; } @override diff --git a/packages/camera/camera_windows/example/integration_test/camera_test.dart b/packages/camera/camera_windows/example/integration_test/camera_test.dart index f26b7c67f5f2..bc835cb18bd5 100644 --- a/packages/camera/camera_windows/example/integration_test/camera_test.dart +++ b/packages/camera/camera_windows/example/integration_test/camera_test.dart @@ -19,100 +19,63 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('initializeCamera', () { - testWidgets('throws exception if camera is not created', ( - WidgetTester _, - ) async { + testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; - expect( - () async => camera.initializeCamera(1234), - throwsA(isA()), - ); + expect(() async => camera.initializeCamera(1234), throwsA(isA())); }); }); group('takePicture', () { - testWidgets('throws exception if camera is not created', ( - WidgetTester _, - ) async { + testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; - expect( - () async => camera.takePicture(1234), - throwsA(isA()), - ); + expect(() async => camera.takePicture(1234), throwsA(isA())); }); }); group('startVideoRecording', () { - testWidgets('throws exception if camera is not created', ( - WidgetTester _, - ) async { + testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; - expect( - () async => camera.startVideoRecording(1234), - throwsA(isA()), - ); + expect(() async => camera.startVideoRecording(1234), throwsA(isA())); }); }); group('stopVideoRecording', () { - testWidgets('throws exception if camera is not created', ( - WidgetTester _, - ) async { + testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; - expect( - () async => camera.stopVideoRecording(1234), - throwsA(isA()), - ); + expect(() async => camera.stopVideoRecording(1234), throwsA(isA())); }); }); group('pausePreview', () { - testWidgets('throws exception if camera is not created', ( - WidgetTester _, - ) async { + testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; - expect( - () async => camera.pausePreview(1234), - throwsA(isA()), - ); + expect(() async => camera.pausePreview(1234), throwsA(isA())); }); }); group('resumePreview', () { - testWidgets('throws exception if camera is not created', ( - WidgetTester _, - ) async { + testWidgets('throws exception if camera is not created', (WidgetTester _) async { final CameraPlatform camera = CameraPlatform.instance; - expect( - () async => camera.resumePreview(1234), - throwsA(isA()), - ); + expect(() async => camera.resumePreview(1234), throwsA(isA())); }); }); group('onDeviceOrientationChanged', () { - testWidgets('emits the initial DeviceOrientationChangedEvent', ( - WidgetTester _, - ) async { - final Stream eventStream = CameraPlatform - .instance + testWidgets('emits the initial DeviceOrientationChangedEvent', (WidgetTester _) async { + final Stream eventStream = CameraPlatform.instance .onDeviceOrientationChanged(); - final streamQueue = StreamQueue( - eventStream, - ); + final streamQueue = StreamQueue(eventStream); expect( await streamQueue.next, - equals( - const DeviceOrientationChangedEvent(DeviceOrientation.landscapeRight), - ), + equals(const DeviceOrientationChangedEvent(DeviceOrientation.landscapeRight)), ); }); }); diff --git a/packages/camera/camera_windows/example/lib/main.dart b/packages/camera/camera_windows/example/lib/main.dart index 215ecb981309..00dc930276e5 100644 --- a/packages/camera/camera_windows/example/lib/main.dart +++ b/packages/camera/camera_windows/example/lib/main.dart @@ -97,10 +97,7 @@ class _MyAppState extends State { final int cameraIndex = _cameraIndex % _cameras.length; final CameraDescription camera = _cameras[cameraIndex]; - cameraId = await CameraPlatform.instance.createCameraWithSettings( - camera, - _mediaSettings, - ); + cameraId = await CameraPlatform.instance.createCameraWithSettings(camera, _mediaSettings); unawaited(_errorStreamSubscription?.cancel()); _errorStreamSubscription = CameraPlatform.instance @@ -146,8 +143,7 @@ class _MyAppState extends State { _cameraIndex = 0; _previewSize = null; _recording = false; - _cameraInfo = - 'Failed to initialize camera: ${e.code}: ${e.description}'; + _cameraInfo = 'Failed to initialize camera: ${e.code}: ${e.description}'; }); } } @@ -171,8 +167,7 @@ class _MyAppState extends State { } on CameraException catch (e) { if (mounted) { setState(() { - _cameraInfo = - 'Failed to dispose camera: ${e.code}: ${e.description}'; + _cameraInfo = 'Failed to dispose camera: ${e.code}: ${e.description}'; }); } } @@ -193,9 +188,7 @@ class _MyAppState extends State { if (!_recording) { await CameraPlatform.instance.startVideoRecording(_cameraId); } else { - final XFile file = await CameraPlatform.instance.stopVideoRecording( - _cameraId, - ); + final XFile file = await CameraPlatform.instance.stopVideoRecording(_cameraId); _showInSnackBar('Video captured to: ${file.path}'); } @@ -302,15 +295,11 @@ class _MyAppState extends State { @override Widget build(BuildContext context) { - final List> resolutionItems = - ResolutionPreset.values.map>(( - ResolutionPreset value, - ) { - return DropdownMenuItem( - value: value, - child: Text(value.toString()), - ); - }).toList(); + final List> resolutionItems = ResolutionPreset.values + .map>((ResolutionPreset value) { + return DropdownMenuItem(value: value, child: Text(value.toString())); + }) + .toList(); return MaterialApp( scaffoldMessengerKey: _scaffoldMessengerKey, @@ -348,12 +337,8 @@ class _MyAppState extends State { ), const SizedBox(width: 20), ElevatedButton( - onPressed: _initialized - ? _disposeCurrentCamera - : _initializeCamera, - child: Text( - _initialized ? 'Dispose camera' : 'Create camera', - ), + onPressed: _initialized ? _disposeCurrentCamera : _initializeCamera, + child: Text(_initialized ? 'Dispose camera' : 'Create camera'), ), const SizedBox(width: 5), ElevatedButton( @@ -363,9 +348,7 @@ class _MyAppState extends State { const SizedBox(width: 5), ElevatedButton( onPressed: _initialized ? _togglePreview : null, - child: Text( - _previewPaused ? 'Resume preview' : 'Pause preview', - ), + child: Text(_previewPaused ? 'Resume preview' : 'Pause preview'), ), const SizedBox(width: 5), ElevatedButton( @@ -374,10 +357,7 @@ class _MyAppState extends State { ), if (_cameras.length > 1) ...[ const SizedBox(width: 5), - ElevatedButton( - onPressed: _switchCamera, - child: const Text('Switch camera'), - ), + ElevatedButton(onPressed: _switchCamera, child: const Text('Switch camera')), ], ], ), diff --git a/packages/camera/camera_windows/lib/camera_windows.dart b/packages/camera/camera_windows/lib/camera_windows.dart index 80005024b143..53b927b2b281 100644 --- a/packages/camera/camera_windows/lib/camera_windows.dart +++ b/packages/camera/camera_windows/lib/camera_windows.dart @@ -15,8 +15,7 @@ import 'src/messages.g.dart'; /// An implementation of [CameraPlatform] for Windows. class CameraWindows extends CameraPlatform { /// Creates a new Windows [CameraPlatform] implementation instance. - CameraWindows({@visibleForTesting CameraApi? api}) - : _hostApi = api ?? CameraApi(); + CameraWindows({@visibleForTesting CameraApi? api}) : _hostApi = api ?? CameraApi(); /// Registers the Windows implementation of CameraPlatform. static void registerWith() { @@ -29,8 +28,7 @@ class CameraWindows extends CameraPlatform { /// The per-camera handlers for messages that should be rebroadcast to /// clients as [CameraEvent]s. @visibleForTesting - final Map hostCameraHandlers = - {}; + final Map hostCameraHandlers = {}; /// The controller that broadcasts events coming from handleCameraMethodCall /// @@ -43,9 +41,8 @@ class CameraWindows extends CameraPlatform { StreamController.broadcast(); /// Returns a stream of camera events for the given [cameraId]. - Stream _cameraEvents(int cameraId) => cameraEventStreamController - .stream - .where((CameraEvent event) => event.cameraId == cameraId); + Stream _cameraEvents(int cameraId) => + cameraEventStreamController.stream.where((CameraEvent event) => event.cameraId == cameraId); @override Future> availableCameras() async { @@ -83,10 +80,7 @@ class CameraWindows extends CameraPlatform { ) async { try { // If resolutionPreset is not specified, plugin selects the highest resolution possible. - return await _hostApi.create( - cameraDescription.name, - _pigeonMediaSettings(mediaSettings), - ); + return await _hostApi.create(cameraDescription.name, _pigeonMediaSettings(mediaSettings)); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -169,10 +163,7 @@ class CameraWindows extends CameraPlatform { } @override - Future lockCaptureOrientation( - int cameraId, - DeviceOrientation orientation, - ) async { + Future lockCaptureOrientation(int cameraId, DeviceOrientation orientation) async { // TODO(jokerttu): Implement lock capture orientation feature, https://github.com/flutter/flutter/issues/97540. throw UnimplementedError('lockCaptureOrientation() is not implemented.'); } @@ -196,10 +187,7 @@ class CameraWindows extends CameraPlatform { } @override - Future startVideoRecording( - int cameraId, { - Duration? maxVideoDuration, - }) async { + Future startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -207,9 +195,7 @@ class CameraWindows extends CameraPlatform { @override Future startVideoCapturing(VideoCaptureOptions options) async { if (options.streamCallback != null || options.streamOptions != null) { - throw UnimplementedError( - 'Streaming is not currently supported on Windows', - ); + throw UnimplementedError('Streaming is not currently supported on Windows'); } // Currently none of `options` is supported on Windows, so it's not passed. @@ -225,16 +211,12 @@ class CameraWindows extends CameraPlatform { @override Future pauseVideoRecording(int cameraId) async { - throw UnsupportedError( - 'pauseVideoRecording() is not supported due to Win32 API limitations.', - ); + throw UnsupportedError('pauseVideoRecording() is not supported due to Win32 API limitations.'); } @override Future resumeVideoRecording(int cameraId) async { - throw UnsupportedError( - 'resumeVideoRecording() is not supported due to Win32 API limitations.', - ); + throw UnsupportedError('resumeVideoRecording() is not supported due to Win32 API limitations.'); } @override @@ -254,9 +236,7 @@ class CameraWindows extends CameraPlatform { assert(point == null || point.x >= 0 && point.x <= 1); assert(point == null || point.y >= 0 && point.y <= 1); - throw UnsupportedError( - 'setExposurePoint() is not supported due to Win32 API limitations.', - ); + throw UnsupportedError('setExposurePoint() is not supported due to Win32 API limitations.'); } @override @@ -297,9 +277,7 @@ class CameraWindows extends CameraPlatform { assert(point == null || point.x >= 0 && point.x <= 1); assert(point == null || point.y >= 0 && point.y <= 1); - throw UnsupportedError( - 'setFocusPoint() is not supported due to Win32 API limitations.', - ); + throw UnsupportedError('setFocusPoint() is not supported due to Win32 API limitations.'); } @override @@ -349,9 +327,7 @@ class CameraWindows extends CameraPlatform { } /// Returns a [ResolutionPreset]'s Pigeon representation. - PlatformResolutionPreset _pigeonResolutionPreset( - ResolutionPreset? resolutionPreset, - ) { + PlatformResolutionPreset _pigeonResolutionPreset(ResolutionPreset? resolutionPreset) { if (resolutionPreset == null) { // Provide a default if one isn't provided, since the native side needs // to set something. diff --git a/packages/camera/camera_windows/lib/src/messages.g.dart b/packages/camera/camera_windows/lib/src/messages.g.dart index 79407a5f97e2..8081a18e0c7e 100644 --- a/packages/camera/camera_windows/lib/src/messages.g.dart +++ b/packages/camera/camera_windows/lib/src/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -74,13 +68,7 @@ class PlatformMediaSettings { bool enableAudio; List _toList() { - return [ - resolutionPreset, - framesPerSecond, - videoBitrate, - audioBitrate, - enableAudio, - ]; + return [resolutionPreset, framesPerSecond, videoBitrate, audioBitrate, enableAudio]; } Object encode() { @@ -133,10 +121,7 @@ class PlatformSize { static PlatformSize decode(Object result) { result as List; - return PlatformSize( - width: result[0]! as double, - height: result[1]! as double, - ); + return PlatformSize(width: result[0]! as double, height: result[1]! as double); } @override @@ -197,13 +182,11 @@ class CameraApi { /// Constructor for [CameraApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - CameraApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + CameraApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -214,15 +197,13 @@ class CameraApi { Future> getAvailableCameras() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -245,17 +226,16 @@ class CameraApi { Future create(String cameraName, PlatformMediaSettings settings) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.create$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraName, settings], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraName, + settings, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -278,17 +258,13 @@ class CameraApi { Future initialize(int cameraId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.initialize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -311,17 +287,13 @@ class CameraApi { Future dispose(int cameraId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.dispose$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -340,17 +312,13 @@ class CameraApi { Future takePicture(int cameraId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.takePicture$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -373,17 +341,13 @@ class CameraApi { Future startVideoRecording(int cameraId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -402,17 +366,13 @@ class CameraApi { Future stopVideoRecording(int cameraId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -435,17 +395,13 @@ class CameraApi { Future pausePreview(int cameraId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.pausePreview$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -463,17 +419,13 @@ class CameraApi { Future resumePreview(int cameraId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.camera_windows.CameraApi.resumePreview$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -502,12 +454,9 @@ abstract class CameraEventApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_windows.CameraEventApi.cameraClosing$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -530,8 +479,7 @@ abstract class CameraEventApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_windows.CameraEventApi.error$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, diff --git a/packages/camera/camera_windows/test/camera_windows_test.dart b/packages/camera/camera_windows/test/camera_windows_test.dart index dcd35d3d3fa2..e4351deab055 100644 --- a/packages/camera/camera_windows/test/camera_windows_test.dart +++ b/packages/camera/camera_windows/test/camera_windows_test.dart @@ -48,9 +48,7 @@ void main() { ); // Assert - final VerificationResult verification = verify( - mockApi.create(captureAny, captureAny), - ); + final VerificationResult verification = verify(mockApi.create(captureAny, captureAny)); expect(verification.captured[0], cameraName); final settings = verification.captured[1] as PlatformMediaSettings?; expect(settings, isNotNull); @@ -58,78 +56,58 @@ void main() { expect(cameraId, 1); }); - test( - 'Should throw CameraException when create throws a PlatformException', - () { - // Arrange - const exceptionCode = 'TESTING_ERROR_CODE'; - const exceptionMessage = 'Mock error message used during testing.'; - final mockApi = MockCameraApi(); - when(mockApi.create(any, any)).thenAnswer((_) async { - throw PlatformException( - code: exceptionCode, - message: exceptionMessage, - ); - }); - final camera = CameraWindows(api: mockApi); - - // Act - expect( - () => camera.createCamera( - const CameraDescription( - name: 'Test', - lensDirection: CameraLensDirection.back, - sensorOrientation: 0, - ), - ResolutionPreset.high, - ), - throwsA( - isA() - .having((CameraException e) => e.code, 'code', exceptionCode) - .having( - (CameraException e) => e.description, - 'description', - exceptionMessage, - ), - ), - ); - }, - ); - - test( - 'Should throw CameraException when initialize throws a PlatformException', - () { - // Arrange - const exceptionCode = 'TESTING_ERROR_CODE'; - const exceptionMessage = 'Mock error message used during testing.'; - final mockApi = MockCameraApi(); - when(mockApi.initialize(any)).thenAnswer((_) async { - throw PlatformException( - code: exceptionCode, - message: exceptionMessage, - ); - }); - final plugin = CameraWindows(api: mockApi); - - // Act - expect( - () => plugin.initializeCamera(0), - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), + test('Should throw CameraException when create throws a PlatformException', () { + // Arrange + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); + when(mockApi.create(any, any)).thenAnswer((_) async { + throw PlatformException(code: exceptionCode, message: exceptionMessage); + }); + final camera = CameraWindows(api: mockApi); + + // Act + expect( + () => camera.createCamera( + const CameraDescription( + name: 'Test', + lensDirection: CameraLensDirection.back, + sensorOrientation: 0, ), - ); - }, - ); + ResolutionPreset.high, + ), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', exceptionCode) + .having((CameraException e) => e.description, 'description', exceptionMessage), + ), + ); + }); + + test('Should throw CameraException when initialize throws a PlatformException', () { + // Arrange + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); + when(mockApi.initialize(any)).thenAnswer((_) async { + throw PlatformException(code: exceptionCode, message: exceptionMessage); + }); + final plugin = CameraWindows(api: mockApi); + + // Act + expect( + () => plugin.initializeCamera(0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); test('Should send initialization data', () async { // Arrange @@ -157,9 +135,7 @@ void main() { await plugin.initializeCamera(cameraId); // Assert - final VerificationResult verification = verify( - mockApi.initialize(captureAny), - ); + final VerificationResult verification = verify(mockApi.initialize(captureAny)); expect(verification.captured[0], cameraId); }); @@ -190,9 +166,7 @@ void main() { await plugin.dispose(cameraId); // Assert - final VerificationResult verification = verify( - mockApi.dispose(captureAny), - ); + final VerificationResult verification = verify(mockApi.dispose(captureAny)); expect(verification.captured[0], cameraId); }); }); @@ -226,9 +200,7 @@ void main() { test('Should receive camera closing events', () async { // Act - final Stream eventStream = plugin.onCameraClosing( - cameraId, - ); + final Stream eventStream = plugin.onCameraClosing(cameraId); final streamQueue = StreamQueue(eventStream); // Emit test events @@ -248,9 +220,7 @@ void main() { test('Should receive camera error events', () async { // Act - final Stream errorStream = plugin.onCameraError( - cameraId, - ); + final Stream errorStream = plugin.onCameraError(cameraId); final streamQueue = StreamQueue(errorStream); // Emit test events @@ -300,60 +270,47 @@ void main() { clearInteractions(mockApi); }); - test( - 'Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final returnData = ['Test 1', 'Test 2']; - when( - mockApi.getAvailableCameras(), - ).thenAnswer((_) async => returnData); - - // Act - final List cameras = await plugin - .availableCameras(); - - // Assert - expect(cameras.length, returnData.length); - for (var i = 0; i < returnData.length; i++) { - expect(cameras[i].name, returnData[i]); - // This value isn't provided by the platform, so is hard-coded to front. - expect(cameras[i].lensDirection, CameraLensDirection.front); - // This value isn't provided by the platform, so is hard-coded to 0. - expect(cameras[i].sensorOrientation, 0); - } - }, - ); - - test( - 'Should throw CameraException when availableCameras throws a PlatformException', - () { - // Arrange - const code = 'TESTING_ERROR_CODE'; - const message = 'Mock error message used during testing.'; - when(mockApi.getAvailableCameras()).thenAnswer( - (_) async => throw PlatformException(code: code, message: message), - ); - - // Act - expect( - plugin.availableCameras, - throwsA( - isA() - .having( - (CameraException e) => e.code, - 'code', - 'TESTING_ERROR_CODE', - ) - .having( - (CameraException e) => e.description, - 'description', - 'Mock error message used during testing.', - ), - ), - ); - }, - ); + test('Should fetch CameraDescription instances for available cameras', () async { + // Arrange + final returnData = ['Test 1', 'Test 2']; + when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData); + + // Act + final List cameras = await plugin.availableCameras(); + + // Assert + expect(cameras.length, returnData.length); + for (var i = 0; i < returnData.length; i++) { + expect(cameras[i].name, returnData[i]); + // This value isn't provided by the platform, so is hard-coded to front. + expect(cameras[i].lensDirection, CameraLensDirection.front); + // This value isn't provided by the platform, so is hard-coded to 0. + expect(cameras[i].sensorOrientation, 0); + } + }); + + test('Should throw CameraException when availableCameras throws a PlatformException', () { + // Arrange + const code = 'TESTING_ERROR_CODE'; + const message = 'Mock error message used during testing.'; + when( + mockApi.getAvailableCameras(), + ).thenAnswer((_) async => throw PlatformException(code: code, message: message)); + + // Act + expect( + plugin.availableCameras, + throwsA( + isA() + .having((CameraException e) => e.code, 'code', 'TESTING_ERROR_CODE') + .having( + (CameraException e) => e.description, + 'description', + 'Mock error message used during testing.', + ), + ), + ); + }); test('Should take a picture and return an XFile instance', () async { // Arrange @@ -387,10 +344,7 @@ void main() { // Act and Assert expect( () => plugin.startVideoCapturing( - VideoCaptureOptions( - cameraId, - streamCallback: (CameraImageData imageData) {}, - ), + VideoCaptureOptions(cameraId, streamCallback: (CameraImageData imageData) {}), ), throwsA(isA()), ); @@ -408,27 +362,15 @@ void main() { expect(file.path, '/test/path.mp4'); }); - test( - 'Should throw UnsupportedError when pause video recording is called', - () async { - // Act - expect( - () => plugin.pauseVideoRecording(cameraId), - throwsA(isA()), - ); - }, - ); - - test( - 'Should throw UnsupportedError when resume video recording is called', - () async { - // Act - expect( - () => plugin.resumeVideoRecording(cameraId), - throwsA(isA()), - ); - }, - ); + test('Should throw UnsupportedError when pause video recording is called', () async { + // Act + expect(() => plugin.pauseVideoRecording(cameraId), throwsA(isA())); + }); + + test('Should throw UnsupportedError when resume video recording is called', () async { + // Act + expect(() => plugin.resumeVideoRecording(cameraId), throwsA(isA())); + }); test('Should throw UnimplementedError when flash mode is set', () async { // Act @@ -438,33 +380,22 @@ void main() { ); }); - test( - 'Should throw UnimplementedError when exposure mode is set', - () async { - // Act - expect( - () => plugin.setExposureMode(cameraId, ExposureMode.auto), - throwsA(isA()), - ); - }, - ); - - test( - 'Should throw UnsupportedError when exposure point is set', - () async { - // Act - expect( - () => plugin.setExposurePoint(cameraId, null), - throwsA(isA()), - ); - }, - ); + test('Should throw UnimplementedError when exposure mode is set', () async { + // Act + expect( + () => plugin.setExposureMode(cameraId, ExposureMode.auto), + throwsA(isA()), + ); + }); + + test('Should throw UnsupportedError when exposure point is set', () async { + // Act + expect(() => plugin.setExposurePoint(cameraId, null), throwsA(isA())); + }); test('Should get the min exposure offset', () async { // Act - final double minExposureOffset = await plugin.getMinExposureOffset( - cameraId, - ); + final double minExposureOffset = await plugin.getMinExposureOffset(cameraId); // Assert expect(minExposureOffset, 0.0); @@ -472,9 +403,7 @@ void main() { test('Should get the max exposure offset', () async { // Act - final double maxExposureOffset = await plugin.getMaxExposureOffset( - cameraId, - ); + final double maxExposureOffset = await plugin.getMaxExposureOffset(cameraId); // Assert expect(maxExposureOffset, 0.0); @@ -482,24 +411,16 @@ void main() { test('Should get the exposure offset step size', () async { // Act - final double stepSize = await plugin.getExposureOffsetStepSize( - cameraId, - ); + final double stepSize = await plugin.getExposureOffsetStepSize(cameraId); // Assert expect(stepSize, 1.0); }); - test( - 'Should throw UnimplementedError when exposure offset is set', - () async { - // Act - expect( - () => plugin.setExposureOffset(cameraId, 0.5), - throwsA(isA()), - ); - }, - ); + test('Should throw UnimplementedError when exposure offset is set', () async { + // Act + expect(() => plugin.setExposureOffset(cameraId, 0.5), throwsA(isA())); + }); test('Should throw UnimplementedError when focus mode is set', () async { // Act @@ -509,16 +430,13 @@ void main() { ); }); - test( - 'Should throw UnsupportedError when exposure point is set', - () async { - // Act - expect( - () => plugin.setFocusMode(cameraId, FocusMode.auto), - throwsA(isA()), - ); - }, - ); + test('Should throw UnsupportedError when exposure point is set', () async { + // Act + expect( + () => plugin.setFocusMode(cameraId, FocusMode.auto), + throwsA(isA()), + ); + }); test('Should build a texture widget as preview widget', () async { // Act @@ -547,42 +465,25 @@ void main() { test('Should throw UnimplementedError when zoom level is set', () async { // Act - expect( - () => plugin.setZoomLevel(cameraId, 2.0), - throwsA(isA()), - ); + expect(() => plugin.setZoomLevel(cameraId, 2.0), throwsA(isA())); }); - test( - 'Should throw UnimplementedError when lock capture orientation is called', - () async { - // Act - expect( - () => plugin.setZoomLevel(cameraId, 2.0), - throwsA(isA()), - ); - }, - ); - - test( - 'Should throw UnimplementedError when unlock capture orientation is called', - () async { - // Act - expect( - () => plugin.unlockCaptureOrientation(cameraId), - throwsA(isA()), - ); - }, - ); + test('Should throw UnimplementedError when lock capture orientation is called', () async { + // Act + expect(() => plugin.setZoomLevel(cameraId, 2.0), throwsA(isA())); + }); + + test('Should throw UnimplementedError when unlock capture orientation is called', () async { + // Act + expect(() => plugin.unlockCaptureOrientation(cameraId), throwsA(isA())); + }); test('Should pause the camera preview', () async { // Act await plugin.pausePreview(cameraId); // Assert - final VerificationResult verification = verify( - mockApi.pausePreview(captureAny), - ); + final VerificationResult verification = verify(mockApi.pausePreview(captureAny)); expect(verification.captured[0], cameraId); }); @@ -591,9 +492,7 @@ void main() { await plugin.resumePreview(cameraId); // Assert - final VerificationResult verification = verify( - mockApi.resumePreview(captureAny), - ); + final VerificationResult verification = verify(mockApi.resumePreview(captureAny)); expect(verification.captured[0], cameraId); }); }); diff --git a/packages/camera/camera_windows/test/camera_windows_test.mocks.dart b/packages/camera/camera_windows/test/camera_windows_test.mocks.dart index c81dceca765f..855659ebdc0d 100644 --- a/packages/camera/camera_windows/test/camera_windows_test.mocks.dart +++ b/packages/camera/camera_windows/test/camera_windows_test.mocks.dart @@ -23,8 +23,7 @@ import 'package:mockito/src/dummies.dart' as _i3; // ignore_for_file: subtype_of_sealed_class class _FakePlatformSize_0 extends _i1.SmartFake implements _i2.PlatformSize { - _FakePlatformSize_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakePlatformSize_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [CameraApi]. @@ -32,151 +31,102 @@ class _FakePlatformSize_0 extends _i1.SmartFake implements _i2.PlatformSize { /// See the documentation for Mockito's code generation for more information. class MockCameraApi extends _i1.Mock implements _i2.CameraApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future> getAvailableCameras() => - (super.noSuchMethod( - Invocation.method(#getAvailableCameras, []), - returnValue: _i4.Future>.value([]), - returnValueForMissingStub: _i4.Future>.value( - [], - ), - ) - as _i4.Future>); + _i4.Future> getAvailableCameras() => (super.noSuchMethod( + Invocation.method(#getAvailableCameras, []), + returnValue: _i4.Future>.value([]), + returnValueForMissingStub: _i4.Future>.value([]), + ) as _i4.Future>); @override - _i4.Future create( - String? cameraName, - _i2.PlatformMediaSettings? settings, - ) => + _i4.Future create(String? cameraName, _i2.PlatformMediaSettings? settings) => (super.noSuchMethod( - Invocation.method(#create, [cameraName, settings]), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) - as _i4.Future); + Invocation.method(#create, [cameraName, settings]), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformSize> initialize(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#initialize, [cameraId]), - returnValue: _i4.Future<_i2.PlatformSize>.value( - _FakePlatformSize_0( - this, - Invocation.method(#initialize, [cameraId]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformSize>.value( - _FakePlatformSize_0( - this, - Invocation.method(#initialize, [cameraId]), - ), - ), - ) - as _i4.Future<_i2.PlatformSize>); + _i4.Future<_i2.PlatformSize> initialize(int? cameraId) => (super.noSuchMethod( + Invocation.method(#initialize, [cameraId]), + returnValue: _i4.Future<_i2.PlatformSize>.value( + _FakePlatformSize_0(this, Invocation.method(#initialize, [cameraId])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformSize>.value( + _FakePlatformSize_0(this, Invocation.method(#initialize, [cameraId])), + ), + ) as _i4.Future<_i2.PlatformSize>); @override - _i4.Future dispose(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#dispose, [cameraId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future dispose(int? cameraId) => (super.noSuchMethod( + Invocation.method(#dispose, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future takePicture(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#takePicture, [cameraId]), - returnValue: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#takePicture, [cameraId]), - ), - ), - returnValueForMissingStub: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#takePicture, [cameraId]), - ), - ), - ) - as _i4.Future); + _i4.Future takePicture(int? cameraId) => (super.noSuchMethod( + Invocation.method(#takePicture, [cameraId]), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [cameraId])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#takePicture, [cameraId])), + ), + ) as _i4.Future); @override - _i4.Future startVideoRecording(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#startVideoRecording, [cameraId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future startVideoRecording(int? cameraId) => (super.noSuchMethod( + Invocation.method(#startVideoRecording, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future stopVideoRecording(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#stopVideoRecording, [cameraId]), - returnValue: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#stopVideoRecording, [cameraId]), - ), - ), - returnValueForMissingStub: _i4.Future.value( - _i3.dummyValue( - this, - Invocation.method(#stopVideoRecording, [cameraId]), - ), - ), - ) - as _i4.Future); + _i4.Future stopVideoRecording(int? cameraId) => (super.noSuchMethod( + Invocation.method(#stopVideoRecording, [cameraId]), + returnValue: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#stopVideoRecording, [cameraId])), + ), + returnValueForMissingStub: _i4.Future.value( + _i3.dummyValue(this, Invocation.method(#stopVideoRecording, [cameraId])), + ), + ) as _i4.Future); @override - _i4.Future startImageStream(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#startImageStream, [cameraId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future startImageStream(int? cameraId) => (super.noSuchMethod( + Invocation.method(#startImageStream, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future stopImageStream(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#stopImageStream, [cameraId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future stopImageStream(int? cameraId) => (super.noSuchMethod( + Invocation.method(#stopImageStream, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future pausePreview(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#pausePreview, [cameraId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future pausePreview(int? cameraId) => (super.noSuchMethod( + Invocation.method(#pausePreview, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future resumePreview(int? cameraId) => - (super.noSuchMethod( - Invocation.method(#resumePreview, [cameraId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future resumePreview(int? cameraId) => (super.noSuchMethod( + Invocation.method(#resumePreview, [cameraId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/cross_file/lib/src/types/html.dart b/packages/cross_file/lib/src/types/html.dart index 40703aa754fc..17570512ac2c 100644 --- a/packages/cross_file/lib/src/types/html.dart +++ b/packages/cross_file/lib/src/types/html.dart @@ -67,10 +67,7 @@ class XFile extends XFileBase { Blob _createBlobFromBytes(Uint8List bytes, String? mimeType) { return (mimeType == null) ? Blob([bytes.toJS].toJS) - : Blob( - [bytes.toJS].toJS, - BlobPropertyBag(type: mimeType), - ); + : Blob([bytes.toJS].toJS, BlobPropertyBag(type: mimeType)); } // Overridable (meta) data that can be specified by the constructors. @@ -126,10 +123,7 @@ class XFile extends XFileBase { ..open('get', path, true) ..responseType = 'blob' ..onLoad.listen((ProgressEvent e) { - assert( - request.response != null, - 'The Blob backing this XFile cannot be null!', - ); + assert(request.response != null, 'The Blob backing this XFile cannot be null!'); blobCompleter.complete(request.response! as Blob); }) ..onError.listen((ProgressEvent e) { @@ -176,8 +170,7 @@ class XFile extends XFileBase { await reader.onLoadEnd.first; - final Uint8List? result = (reader.result as JSArrayBuffer?)?.toDart - .asUint8List(); + final Uint8List? result = (reader.result as JSArrayBuffer?)?.toDart.asUint8List(); if (result == null) { throw Exception('Cannot read bytes from Blob. Is it still available?'); diff --git a/packages/cross_file/lib/src/types/interface.dart b/packages/cross_file/lib/src/types/interface.dart index d539b4e2633c..6f188852b866 100644 --- a/packages/cross_file/lib/src/types/interface.dart +++ b/packages/cross_file/lib/src/types/interface.dart @@ -30,9 +30,7 @@ class XFile extends XFileBase { DateTime? lastModified, @visibleForTesting CrossFileTestOverrides? overrides, }) { - throw UnimplementedError( - 'CrossFile is not available in your current platform.', - ); + throw UnimplementedError('CrossFile is not available in your current platform.'); } /// Construct a CrossFile object from its data. @@ -48,9 +46,7 @@ class XFile extends XFileBase { String? path, @visibleForTesting CrossFileTestOverrides? overrides, }) : super(path) { - throw UnimplementedError( - 'CrossFile is not available in your current platform.', - ); + throw UnimplementedError('CrossFile is not available in your current platform.'); } } diff --git a/packages/cross_file/lib/src/types/io.dart b/packages/cross_file/lib/src/types/io.dart index c1931a743a89..45a03b389d27 100644 --- a/packages/cross_file/lib/src/types/io.dart +++ b/packages/cross_file/lib/src/types/io.dart @@ -133,9 +133,7 @@ class XFile extends XFileBase { if (_bytes != null) { return _getBytes(start, end); } else { - return _file - .openRead(start ?? 0, end) - .map((List chunk) => Uint8List.fromList(chunk)); + return _file.openRead(start ?? 0, end).map((List chunk) => Uint8List.fromList(chunk)); } } } diff --git a/packages/cross_file/lib/src/web_helpers/web_helpers.dart b/packages/cross_file/lib/src/web_helpers/web_helpers.dart index 58231dd8c30e..76eb830a30c1 100644 --- a/packages/cross_file/lib/src/web_helpers/web_helpers.dart +++ b/packages/cross_file/lib/src/web_helpers/web_helpers.dart @@ -8,16 +8,13 @@ import 'package:web/web.dart'; import '../types/html.dart'; /// Type definition for function that creates anchor elements -typedef CreateAnchorElement = - HTMLAnchorElement Function(String href, String? suggestedName); +typedef CreateAnchorElement = HTMLAnchorElement Function(String href, String? suggestedName); /// Create anchor element with download attribute -HTMLAnchorElement _createAnchorElementImpl( - String href, - String? suggestedName, -) => (document.createElement('a') as HTMLAnchorElement) - ..href = href - ..download = suggestedName ?? 'download'; +HTMLAnchorElement _createAnchorElementImpl(String href, String? suggestedName) => + (document.createElement('a') as HTMLAnchorElement) + ..href = href + ..download = suggestedName ?? 'download'; /// Function for creating anchor elements. Can be overridden for testing. @visibleForTesting @@ -55,10 +52,7 @@ Future saveFileAs(XFile file) async { final Element target = ensureInitialized('__x_file_dom_element'); // Create element. - final HTMLAnchorElement element = createAnchorElementFunction( - file.path, - file.name, - ); + final HTMLAnchorElement element = createAnchorElementFunction(file.path, file.name); // Clear existing children before appending new one. while (target.children.length > 0) { diff --git a/packages/cross_file/test/x_file_html_test.dart b/packages/cross_file/test/x_file_html_test.dart index e57e36c285c7..bea856d7d481 100644 --- a/packages/cross_file/test/x_file_html_test.dart +++ b/packages/cross_file/test/x_file_html_test.dart @@ -16,10 +16,7 @@ import 'package:web/web.dart' as html; const String expectedStringContents = 'Hello, world! I ❤ ñ! 空手'; final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents)); -final html.File textFile = html.File( - [bytes.toJS].toJS, - 'hello.txt', -); +final html.File textFile = html.File([bytes.toJS].toJS, 'hello.txt'); final String textFileUrl = // TODO(kevmoo): drop ignore when pkg:web constraint excludes v0.3 // ignore: unnecessary_cast @@ -89,9 +86,7 @@ void main() { test('Stores data as a Blob', () async { // Read the blob from its path 'natively' - final html.Response response = await html.window - .fetch(file.path.toJS) - .toDart; + final html.Response response = await html.window.fetch(file.path.toJS).toDart; final JSAny arrayBuffer = await response.arrayBuffer().toDart; final ByteBuffer data = (arrayBuffer as JSArrayBuffer).toDart; @@ -116,9 +111,7 @@ void main() { await file.saveTo(''); - final html.Element? container = html.document.querySelector( - '#$crossFileDomElementId', - ); + final html.Element? container = html.document.querySelector('#$crossFileDomElementId'); expect(container, isNotNull); }); @@ -128,9 +121,7 @@ void main() { await file.saveTo('path'); - final html.Element container = html.document.querySelector( - '#$crossFileDomElementId', - )!; + final html.Element container = html.document.querySelector('#$crossFileDomElementId')!; late html.HTMLAnchorElement element; for (var i = 0; i < container.childNodes.length; i++) { @@ -147,12 +138,10 @@ void main() { }); test('anchor element is clicked', () async { - final mockAnchor = - html.document.createElement('a') as html.HTMLAnchorElement; + final mockAnchor = html.document.createElement('a') as html.HTMLAnchorElement; // Save original function so we can restore it - final helpers.CreateAnchorElement original = - helpers.createAnchorElementFunction; + final helpers.CreateAnchorElement original = helpers.createAnchorElementFunction; addTearDown(() { helpers.createAnchorElementFunction = original; diff --git a/packages/cross_file/test/x_file_io_test.dart b/packages/cross_file/test/x_file_io_test.dart index 904a5c08c507..8ca6768b36f3 100644 --- a/packages/cross_file/test/x_file_io_test.dart +++ b/packages/cross_file/test/x_file_io_test.dart @@ -12,9 +12,7 @@ import 'dart:typed_data'; import 'package:cross_file/cross_file.dart'; import 'package:test/test.dart'; -final String pathPrefix = Directory.current.path.endsWith('test') - ? './assets/' - : './test/assets/'; +final String pathPrefix = Directory.current.path.endsWith('test') ? './assets/' : './test/assets/'; final String path = '${pathPrefix}hello.txt'; const String expectedStringContents = 'Hello, world!'; final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents)); diff --git a/packages/cupertino_ui/test/flutter_test_config.dart b/packages/cupertino_ui/test/flutter_test_config.dart index 89496e15a775..decec135ddd1 100644 --- a/packages/cupertino_ui/test/flutter_test_config.dart +++ b/packages/cupertino_ui/test/flutter_test_config.dart @@ -4,9 +4,7 @@ import 'dart:async'; -import 'goldens_io.dart' - if (dart.library.js_interop) 'goldens_web.dart' - as flutter_goldens; +import 'goldens_io.dart' if (dart.library.js_interop) 'goldens_web.dart' as flutter_goldens; Future testExecutable(FutureOr Function() testMain) { // Enable golden file testing using Skia Gold. diff --git a/packages/cupertino_ui/test/goldens/goldens_test.dart b/packages/cupertino_ui/test/goldens/goldens_test.dart index d099e7ac14bc..955d4a3df852 100644 --- a/packages/cupertino_ui/test/goldens/goldens_test.dart +++ b/packages/cupertino_ui/test/goldens/goldens_test.dart @@ -10,9 +10,7 @@ void main() { testWidgets('Inconsequential golden test', (WidgetTester tester) async { // The test validates the Flutter Gold integration. Any changes to the // golden file can be approved at any time. - await tester.pumpWidget( - const CupertinoApp(home: Center(child: Text('Cupertino Goldens'))), - ); + await tester.pumpWidget(const CupertinoApp(home: Center(child: Text('Cupertino Goldens')))); await tester.pumpAndSettle(); await expectLater( diff --git a/packages/cupertino_ui/test/goldens_web.dart b/packages/cupertino_ui/test/goldens_web.dart index 80945b782d2e..fd3ea2d23fb2 100644 --- a/packages/cupertino_ui/test/goldens_web.dart +++ b/packages/cupertino_ui/test/goldens_web.dart @@ -5,7 +5,5 @@ import 'dart:async'; // package:flutter_goldens is not used as part of the test process for web. -Future testExecutable( - FutureOr Function() testMain, { - String? namePrefix, -}) async => testMain(); +Future testExecutable(FutureOr Function() testMain, {String? namePrefix}) async => + testMain(); diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart b/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart index c857a070288a..79018cfcc2ba 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/lib/main.dart @@ -12,15 +12,14 @@ import 'package:google_sign_in/google_sign_in.dart'; import 'package:googleapis/people/v1.dart'; // #docregion CreateAPIClient import 'package:googleapis_auth/googleapis_auth.dart' as auth show AuthClient; + // #enddocregion CreateAPIClient /// The scopes used by this example. const List scopes = [PeopleServiceApi.contactsReadonlyScope]; void main() { - runApp( - const MaterialApp(title: 'Google Sign In + googleapis', home: SignInDemo()), - ); + runApp(const MaterialApp(title: 'Google Sign In + googleapis', home: SignInDemo())); } /// The main widget of this demo. @@ -89,9 +88,7 @@ class SignInDemoState extends State { } Future _checkAuthorization() async { - _updateAuthorization( - await _currentUser?.authorizationClient.authorizationForScopes(scopes), - ); + _updateAuthorization(await _currentUser?.authorizationClient.authorizationForScopes(scopes)); } Future _requestAuthorization() async { @@ -102,9 +99,7 @@ class SignInDemoState extends State { ); } - Future _handleGetContact( - GoogleSignInClientAuthorization authorization, - ) async { + Future _handleGetContact(GoogleSignInClientAuthorization authorization) async { if (!mounted) { return; } @@ -119,13 +114,13 @@ class SignInDemoState extends State { // Prepare a People Service authenticated client. final peopleApi = PeopleServiceApi(client); // Retrieve a list of connected contacts' names. - final ListConnectionsResponse response = await peopleApi.people.connections - .list('people/me', personFields: 'names'); + final ListConnectionsResponse response = await peopleApi.people.connections.list( + 'people/me', + personFields: 'names', + ); // #enddocregion CreateAPIClient - final String? firstNamedContactName = _pickFirstNamedContact( - response.connections, - ); + final String? firstNamedContactName = _pickFirstNamedContact(response.connections); if (mounted) { setState(() { @@ -187,26 +182,17 @@ class SignInDemoState extends State { child: const Text('LOAD CONTACTS'), ), ], - ElevatedButton( - onPressed: _handleSignOut, - child: const Text('SIGN OUT'), - ), + ElevatedButton(onPressed: _handleSignOut, child: const Text('SIGN OUT')), ] else ...[ const Text('You are not currently signed in.'), - ElevatedButton( - onPressed: _handleSignIn, - child: const Text('SIGN IN'), - ), + ElevatedButton(onPressed: _handleSignIn, child: const Text('SIGN IN')), ], ]; } else { children = [const CircularProgressIndicator()]; } - return Column( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: children, - ); + return Column(mainAxisAlignment: MainAxisAlignment.spaceAround, children: children); }, ); } @@ -215,10 +201,7 @@ class SignInDemoState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Google Sign In + googleapis')), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - ), + body: ConstrainedBox(constraints: const BoxConstraints.expand(), child: _buildBody()), ); } } diff --git a/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart b/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart index 334941fe0f3b..3c259ee8bccb 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart +++ b/packages/extension_google_sign_in_as_googleapis_auth/test/extension_google_sign_in_as_googleapis_auth_test.dart @@ -9,24 +9,17 @@ import 'package:googleapis_auth/googleapis_auth.dart' as gapis; const String SOME_FAKE_ACCESS_TOKEN = 'this-is-something-not-null'; -class FakeGoogleSignInClientAuthorization extends Fake - implements GoogleSignInClientAuthorization { +class FakeGoogleSignInClientAuthorization extends Fake implements GoogleSignInClientAuthorization { @override final String accessToken = SOME_FAKE_ACCESS_TOKEN; } void main() { - test( - 'authClient returned client contains the expected information', - () async { - const scopes = ['some-scope', 'another-scope']; - final signInAuth = FakeGoogleSignInClientAuthorization(); - final gapis.AuthClient client = signInAuth.authClient(scopes: scopes); - expect( - client.credentials.accessToken.data, - equals(SOME_FAKE_ACCESS_TOKEN), - ); - expect(client.credentials.scopes, equals(scopes)); - }, - ); + test('authClient returned client contains the expected information', () async { + const scopes = ['some-scope', 'another-scope']; + final signInAuth = FakeGoogleSignInClientAuthorization(); + final gapis.AuthClient client = signInAuth.authClient(scopes: scopes); + expect(client.credentials.accessToken.data, equals(SOME_FAKE_ACCESS_TOKEN)); + expect(client.credentials.scopes, equals(scopes)); + }); } diff --git a/packages/file_selector/file_selector/example/lib/get_directory_page.dart b/packages/file_selector/file_selector/example/lib/get_directory_page.dart index 9f8b6fdc37be..3e24bbbf0cf9 100644 --- a/packages/file_selector/file_selector/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector/example/lib/get_directory_page.dart @@ -15,9 +15,7 @@ class GetDirectoryPage extends StatelessWidget { Future _getDirectoryPath(BuildContext context) async { const confirmButtonText = 'Choose'; - final String? directoryPath = await getDirectoryPath( - confirmButtonText: confirmButtonText, - ); + final String? directoryPath = await getDirectoryPath(confirmButtonText: confirmButtonText); if (directoryPath == null) { // Operation was canceled by the user. return; @@ -65,14 +63,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directory'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoryPath)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart index aa519552e048..e81afac13bc5 100644 --- a/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector/example/lib/get_multiple_directories_page.dart @@ -45,9 +45,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { backgroundColor: Colors.blue, foregroundColor: Colors.white, ), - child: const Text( - 'Press to ask user to choose multiple directories', - ), + child: const Text('Press to ask user to choose multiple directories'), onPressed: () => _getDirectoryPaths(context), ), ], @@ -69,14 +67,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directories'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoriesPaths)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoriesPaths))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector/example/lib/home_page.dart b/packages/file_selector/file_selector/example/lib/home_page.dart index 76801d5fa58b..d895a50a09c4 100644 --- a/packages/file_selector/file_selector/example/lib/home_page.dart +++ b/packages/file_selector/file_selector/example/lib/home_page.dart @@ -64,8 +64,7 @@ class HomePage extends StatelessWidget { ElevatedButton( style: style, child: const Text('Open a get multi directories dialog'), - onPressed: () => - Navigator.pushNamed(context, '/multi-directories'), + onPressed: () => Navigator.pushNamed(context, '/multi-directories'), ), ], ], diff --git a/packages/file_selector/file_selector/example/lib/main.dart b/packages/file_selector/file_selector/example/lib/main.dart index da38163967d7..db70eb540e89 100644 --- a/packages/file_selector/file_selector/example/lib/main.dart +++ b/packages/file_selector/file_selector/example/lib/main.dart @@ -32,13 +32,11 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': (BuildContext context) => - const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => GetDirectoryPage(), - '/multi-directories': (BuildContext context) => - const GetMultipleDirectoriesPage(), + '/multi-directories': (BuildContext context) => const GetMultipleDirectoriesPage(), }, ); } diff --git a/packages/file_selector/file_selector/example/lib/open_image_page.dart b/packages/file_selector/file_selector/example/lib/open_image_page.dart index e2260c97860f..0d3d01d04342 100644 --- a/packages/file_selector/file_selector/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector/example/lib/open_image_page.dart @@ -20,9 +20,7 @@ class OpenImagePage extends StatelessWidget { extensions: ['jpg', 'png'], uniformTypeIdentifiers: ['public.jpeg', 'public.png'], ); - final XFile? file = await openFile( - acceptedTypeGroups: [typeGroup], - ); + final XFile? file = await openFile(acceptedTypeGroups: [typeGroup]); // #enddocregion SingleOpen if (file == null) { // Operation was canceled by the user. diff --git a/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart index eb6b0e9f91f3..523cca0f2621 100644 --- a/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector/example/lib/open_multiple_images_page.dart @@ -82,11 +82,8 @@ class MultipleImagesDisplay extends StatelessWidget { child: Row( children: [ ...files.map( - (XFile file) => Flexible( - child: kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), - ), + (XFile file) => + Flexible(child: kIsWeb ? Image.network(file.path) : Image.file(File(file.path))), ), ], ), diff --git a/packages/file_selector/file_selector/example/lib/open_text_page.dart b/packages/file_selector/file_selector/example/lib/open_text_page.dart index ab6dd5a6825f..167f9d1b7984 100644 --- a/packages/file_selector/file_selector/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector/example/lib/open_text_page.dart @@ -81,14 +81,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), - content: Scrollbar( - child: SingleChildScrollView(child: Text(fileContent)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart b/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart index cbfc728c8843..fb71f5304c1c 100644 --- a/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart +++ b/packages/file_selector/file_selector/example/lib/readme_standalone_excerpts.dart @@ -37,9 +37,7 @@ class _MyAppState extends State { Future saveFile() async { // #docregion Save const fileName = 'suggested_name.txt'; - final FileSaveLocation? result = await getSaveLocation( - suggestedName: fileName, - ); + final FileSaveLocation? result = await getSaveLocation(suggestedName: fileName); if (result == null) { // Operation was canceled by the user. return; @@ -47,11 +45,7 @@ class _MyAppState extends State { final fileData = Uint8List.fromList('Hello World!'.codeUnits); const mimeType = 'text/plain'; - final textFile = XFile.fromData( - fileData, - mimeType: mimeType, - name: fileName, - ); + final textFile = XFile.fromData(fileData, mimeType: mimeType, name: fileName); await textFile.saveTo(result.path); // #enddocregion Save } diff --git a/packages/file_selector/file_selector/example/lib/save_text_page.dart b/packages/file_selector/file_selector/example/lib/save_text_page.dart index 809c7f43d20f..59b71e202feb 100644 --- a/packages/file_selector/file_selector/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector/example/lib/save_text_page.dart @@ -38,11 +38,7 @@ class SaveTextPage extends StatelessWidget { final String text = _contentController.text; final fileData = Uint8List.fromList(text.codeUnits); const fileMimeType = 'text/plain'; - final textFile = XFile.fromData( - fileData, - mimeType: fileMimeType, - name: fileName, - ); + final textFile = XFile.fromData(fileData, mimeType: fileMimeType, name: fileName); await textFile.saveTo(result.path); } @@ -61,9 +57,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _nameController, - decoration: const InputDecoration( - hintText: '(Optional) Suggest File Name', - ), + decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'), ), ), SizedBox( @@ -72,9 +66,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _contentController, - decoration: const InputDecoration( - hintText: 'Enter File Contents', - ), + decoration: const InputDecoration(hintText: 'Enter File Contents'), ), ), const SizedBox(height: 10), diff --git a/packages/file_selector/file_selector/test/file_selector_test.dart b/packages/file_selector/file_selector/test/file_selector_test.dart index 9b4b95286d51..374a9a8cefce 100644 --- a/packages/file_selector/file_selector/test/file_selector_test.dart +++ b/packages/file_selector/file_selector/test/file_selector_test.dart @@ -81,9 +81,7 @@ void main() { ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse([expectedFile]); - final XFile? file = await openFile( - acceptedTypeGroups: acceptedTypeGroups, - ); + final XFile? file = await openFile(acceptedTypeGroups: acceptedTypeGroups); expect(file, expectedFile); }); }); @@ -122,9 +120,7 @@ void main() { ..setExpectations(initialDirectory: initialDirectory) ..setFileResponse(expectedFiles); - final List files = await openFiles( - initialDirectory: initialDirectory, - ); + final List files = await openFiles(initialDirectory: initialDirectory); expect(files, expectedFiles); }); @@ -133,9 +129,7 @@ void main() { ..setExpectations(confirmButtonText: confirmButtonText) ..setFileResponse(expectedFiles); - final List files = await openFiles( - confirmButtonText: confirmButtonText, - ); + final List files = await openFiles(confirmButtonText: confirmButtonText); expect(files, expectedFiles); }); @@ -144,9 +138,7 @@ void main() { ..setExpectations(acceptedTypeGroups: acceptedTypeGroups) ..setFileResponse(expectedFiles); - final List files = await openFiles( - acceptedTypeGroups: acceptedTypeGroups, - ); + final List files = await openFiles(acceptedTypeGroups: acceptedTypeGroups); expect(files, expectedFiles); }); }); @@ -163,9 +155,7 @@ void main() { acceptedTypeGroups: acceptedTypeGroups, suggestedName: suggestedName, ) - ..setPathsResponse([ - expectedSavePath, - ], activeFilter: expectedActiveFilter); + ..setPathsResponse([expectedSavePath], activeFilter: expectedActiveFilter); final FileSaveLocation? location = await getSaveLocation( initialDirectory: initialDirectory, @@ -190,9 +180,7 @@ void main() { ..setExpectations(initialDirectory: initialDirectory) ..setPathsResponse([expectedSavePath]); - final FileSaveLocation? location = await getSaveLocation( - initialDirectory: initialDirectory, - ); + final FileSaveLocation? location = await getSaveLocation(initialDirectory: initialDirectory); expect(location?.path, expectedSavePath); }); @@ -223,9 +211,7 @@ void main() { ..setExpectations(suggestedName: suggestedName) ..setPathsResponse([expectedSavePath]); - final FileSaveLocation? location = await getSaveLocation( - suggestedName: suggestedName, - ); + final FileSaveLocation? location = await getSaveLocation(suggestedName: suggestedName); expect(location?.path, expectedSavePath); }); @@ -247,10 +233,7 @@ void main() { test('works', () async { fakePlatformImplementation - ..setExpectations( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - ) + ..setExpectations(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText) ..setPathsResponse([expectedDirectoryPath]); final String? directoryPath = await getDirectoryPath( @@ -262,9 +245,7 @@ void main() { }); test('works with no arguments', () async { - fakePlatformImplementation.setPathsResponse([ - expectedDirectoryPath, - ]); + fakePlatformImplementation.setPathsResponse([expectedDirectoryPath]); final String? directoryPath = await getDirectoryPath(); expect(directoryPath, expectedDirectoryPath); @@ -275,9 +256,7 @@ void main() { ..setExpectations(initialDirectory: initialDirectory) ..setPathsResponse([expectedDirectoryPath]); - final String? directoryPath = await getDirectoryPath( - initialDirectory: initialDirectory, - ); + final String? directoryPath = await getDirectoryPath(initialDirectory: initialDirectory); expect(directoryPath, expectedDirectoryPath); }); @@ -286,9 +265,7 @@ void main() { ..setExpectations(confirmButtonText: confirmButtonText) ..setPathsResponse([expectedDirectoryPath]); - final String? directoryPath = await getDirectoryPath( - confirmButtonText: confirmButtonText, - ); + final String? directoryPath = await getDirectoryPath(confirmButtonText: confirmButtonText); expect(directoryPath, expectedDirectoryPath); }); @@ -310,10 +287,7 @@ void main() { test('works', () async { fakePlatformImplementation - ..setExpectations( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - ) + ..setExpectations(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText) ..setPathsResponse(expectedDirectoryPaths); final List directoryPaths = await getDirectoryPaths( @@ -461,9 +435,7 @@ class FakeFileSelector extends Fake ? null : FileSaveLocation( path, - activeFilter: activeFilterIndex == null - ? null - : acceptedTypeGroups?[activeFilterIndex], + activeFilter: activeFilterIndex == null ? null : acceptedTypeGroups?[activeFilterIndex], ); } @@ -500,9 +472,7 @@ class FakeFileSelector extends Fake } @override - Future> getDirectoryPathsWithOptions( - FileDialogOptions options, - ) async { + Future> getDirectoryPathsWithOptions(FileDialogOptions options) async { expect(options.initialDirectory, initialDirectory); expect(options.confirmButtonText, confirmButtonText); expect(options.canCreateDirectories, canCreateDirectories); diff --git a/packages/file_selector/file_selector_android/example/lib/main.dart b/packages/file_selector/file_selector_android/example/lib/main.dart index b69b4c1e4e94..f0da87947832 100644 --- a/packages/file_selector/file_selector_android/example/lib/main.dart +++ b/packages/file_selector/file_selector_android/example/lib/main.dart @@ -40,8 +40,7 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': (BuildContext context) => - const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), }, ); diff --git a/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart index 9bc2cfa80fc2..88208db86d53 100644 --- a/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_android/example/lib/open_multiple_images_page.dart @@ -84,10 +84,7 @@ class MultipleImagesDisplay extends StatelessWidget { child: Row( children: [ for (int i = 0; i < fileBytes.length; i++) - Flexible( - key: Key('result_image_name$i'), - child: Image.memory(fileBytes[i]), - ), + Flexible(key: Key('result_image_name$i'), child: Image.memory(fileBytes[i])), ], ), ), diff --git a/packages/file_selector/file_selector_android/example/lib/open_text_page.dart b/packages/file_selector/file_selector_android/example/lib/open_text_page.dart index 5469e580146b..815c723754a9 100644 --- a/packages/file_selector/file_selector_android/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_android/example/lib/open_text_page.dart @@ -73,14 +73,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), - content: Scrollbar( - child: SingleChildScrollView(child: Text(fileContent)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart b/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart index 461ede2e67e4..fe8b08009ef6 100644 --- a/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart +++ b/packages/file_selector/file_selector_android/lib/src/file_selector_android.dart @@ -12,8 +12,7 @@ import 'types/native_illegal_argument_exception.dart'; /// An implementation of [FileSelectorPlatform] for Android. class FileSelectorAndroid extends FileSelectorPlatform { - FileSelectorAndroid({@visibleForTesting FileSelectorApi? api}) - : _api = api ?? FileSelectorApi(); + FileSelectorAndroid({@visibleForTesting FileSelectorApi? api}) : _api = api ?? FileSelectorApi(); final FileSelectorApi _api; @@ -49,10 +48,7 @@ class FileSelectorAndroid extends FileSelectorPlatform { } @override - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) async { + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async { return _api.getDirectoryPath(initialDirectory); } @@ -80,9 +76,7 @@ class FileSelectorAndroid extends FileSelectorPlatform { final extensions = {}; for (final XTypeGroup group in typeGroups) { - if (!group.allowsAny && - group.mimeTypes == null && - group.extensions == null) { + if (!group.allowsAny && group.mimeTypes == null && group.extensions == null) { throw ArgumentError( 'Provided type group $group does not allow all files, but does not ' 'set any of the Android supported filter categories. At least one of ' @@ -94,22 +88,15 @@ class FileSelectorAndroid extends FileSelectorPlatform { extensions.addAll(group.extensions ?? {}); } - return FileTypes( - mimeTypes: mimeTypes.toList(), - extensions: extensions.toList(), - ); + return FileTypes(mimeTypes: mimeTypes.toList(), extensions: extensions.toList()); } /// Translates a [FileSelectorExceptionCode] to its corresponding error and /// handles throwing. - void _resolveErrorCodeAndMaybeThrow( - FileSelectorNativeException fileSelectorNativeException, - ) { + void _resolveErrorCodeAndMaybeThrow(FileSelectorNativeException fileSelectorNativeException) { switch (fileSelectorNativeException.fileSelectorExceptionCode) { case FileSelectorExceptionCode.illegalArgumentException: - throw NativeIllegalArgumentException( - fileSelectorNativeException.message, - ); + throw NativeIllegalArgumentException(fileSelectorNativeException.message); case (FileSelectorExceptionCode.illegalStateException || FileSelectorExceptionCode.ioException || FileSelectorExceptionCode.securityException): diff --git a/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart b/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart index 2d76187bea81..5a2094e024c3 100644 --- a/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart +++ b/packages/file_selector/file_selector_android/lib/src/file_selector_api.g.dart @@ -49,9 +49,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -108,10 +106,7 @@ enum FileSelectorExceptionCode { } class FileSelectorNativeException { - FileSelectorNativeException({ - required this.fileSelectorExceptionCode, - required this.message, - }); + FileSelectorNativeException({required this.fileSelectorExceptionCode, required this.message}); FileSelectorExceptionCode fileSelectorExceptionCode; @@ -136,17 +131,13 @@ class FileSelectorNativeException { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! FileSelectorNativeException || - other.runtimeType != runtimeType) { + if (other is! FileSelectorNativeException || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { return true; } - return _deepEquals( - fileSelectorExceptionCode, - other.fileSelectorExceptionCode, - ) && + return _deepEquals(fileSelectorExceptionCode, other.fileSelectorExceptionCode) && _deepEquals(message, other.message); } @@ -178,14 +169,7 @@ class FileResponse { FileSelectorNativeException? fileSelectorNativeException; List _toList() { - return [ - path, - mimeType, - name, - size, - bytes, - fileSelectorNativeException, - ]; + return [path, mimeType, name, size, bytes, fileSelectorNativeException]; } Object encode() { @@ -218,10 +202,7 @@ class FileResponse { _deepEquals(name, other.name) && _deepEquals(size, other.size) && _deepEquals(bytes, other.bytes) && - _deepEquals( - fileSelectorNativeException, - other.fileSelectorNativeException, - ); + _deepEquals(fileSelectorNativeException, other.fileSelectorNativeException); } @override @@ -261,8 +242,7 @@ class FileTypes { if (identical(this, other)) { return true; } - return _deepEquals(mimeTypes, other.mimeTypes) && - _deepEquals(extensions, other.extensions); + return _deepEquals(mimeTypes, other.mimeTypes) && _deepEquals(extensions, other.extensions); } @override @@ -317,13 +297,11 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + FileSelectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -333,10 +311,7 @@ class FileSelectorApi { /// Opens a file dialog for loading files and returns a file path. /// /// Returns `null` if user cancels the operation. - Future openFile( - String? initialDirectory, - FileTypes allowedTypes, - ) async { + Future openFile(String? initialDirectory, FileTypes allowedTypes) async { final pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_android.FileSelectorApi.openFile$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -344,9 +319,10 @@ class FileSelectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [initialDirectory, allowedTypes], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + initialDirectory, + allowedTypes, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -359,10 +335,7 @@ class FileSelectorApi { /// Opens a file dialog for loading files and returns a list of file responses /// chosen by the user. - Future> openFiles( - String? initialDirectory, - FileTypes allowedTypes, - ) async { + Future> openFiles(String? initialDirectory, FileTypes allowedTypes) async { final pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_android.FileSelectorApi.openFiles$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -370,9 +343,10 @@ class FileSelectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [initialDirectory, allowedTypes], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + initialDirectory, + allowedTypes, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -394,9 +368,9 @@ class FileSelectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [initialDirectory], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + initialDirectory, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( diff --git a/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart b/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart index 63900221f0cd..9dc72fb6ac53 100644 --- a/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart +++ b/packages/file_selector/file_selector_android/pigeons/file_selector_api.dart @@ -9,9 +9,7 @@ import 'package:pigeon/pigeon.dart'; dartOut: 'lib/src/file_selector_api.g.dart', kotlinOut: 'android/src/main/kotlin/dev/flutter/packages/file_selector_android/GeneratedFileSelectorApi.kt', - kotlinOptions: KotlinOptions( - package: 'dev.flutter.packages.file_selector_android', - ), + kotlinOptions: KotlinOptions(package: 'dev.flutter.packages.file_selector_android'), copyrightHeader: 'pigeons/copyright.txt', ), ) @@ -53,10 +51,7 @@ abstract class FileSelectorApi { /// Opens a file dialog for loading files and returns a list of file responses /// chosen by the user. @async - List openFiles( - String? initialDirectory, - FileTypes allowedTypes, - ); + List openFiles(String? initialDirectory, FileTypes allowedTypes); /// Opens a file dialog for loading directories and returns a directory path. /// diff --git a/packages/file_selector/file_selector_android/test/file_selector_android_test.dart b/packages/file_selector/file_selector_android/test/file_selector_android_test.dart index b4f7ece33b9a..2bd5bd278095 100644 --- a/packages/file_selector/file_selector_android/test/file_selector_android_test.dart +++ b/packages/file_selector/file_selector_android/test/file_selector_android_test.dart @@ -37,16 +37,14 @@ void main() { 'some/path/', argThat( isA() - .having( - (FileTypes types) => types.mimeTypes, - 'mimeTypes', - ['text/plain', 'image/jpg'], - ) - .having( - (FileTypes types) => types.extensions, - 'extensions', - ['txt', 'jpg'], - ), + .having((FileTypes types) => types.mimeTypes, 'mimeTypes', [ + 'text/plain', + 'image/jpg', + ]) + .having((FileTypes types) => types.extensions, 'extensions', [ + 'txt', + 'jpg', + ]), ), ), ).thenAnswer( @@ -61,15 +59,9 @@ void main() { ), ); - const group = XTypeGroup( - extensions: ['txt'], - mimeTypes: ['text/plain'], - ); + const group = XTypeGroup(extensions: ['txt'], mimeTypes: ['text/plain']); - const group2 = XTypeGroup( - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - ); + const group2 = XTypeGroup(extensions: ['jpg'], mimeTypes: ['image/jpg']); final XFile? file = await plugin.openFile( acceptedTypeGroups: [group, group2], @@ -90,16 +82,14 @@ void main() { 'some/path/', argThat( isA() - .having( - (FileTypes types) => types.mimeTypes, - 'mimeTypes', - ['text/plain', 'image/jpg'], - ) - .having( - (FileTypes types) => types.extensions, - 'extensions', - ['txt', 'jpg'], - ), + .having((FileTypes types) => types.mimeTypes, 'mimeTypes', [ + 'text/plain', + 'image/jpg', + ]) + .having((FileTypes types) => types.extensions, 'extensions', [ + 'txt', + 'jpg', + ]), ), ), ).thenAnswer( @@ -111,24 +101,13 @@ void main() { name: 'name', mimeType: 'text/plain', ), - FileResponse( - path: 'other/dir.jpg', - size: 40, - bytes: Uint8List(0), - mimeType: 'image/jpg', - ), + FileResponse(path: 'other/dir.jpg', size: 40, bytes: Uint8List(0), mimeType: 'image/jpg'), ]), ); - const group = XTypeGroup( - extensions: ['txt'], - mimeTypes: ['text/plain'], - ); + const group = XTypeGroup(extensions: ['txt'], mimeTypes: ['text/plain']); - const group2 = XTypeGroup( - extensions: ['jpg'], - mimeTypes: ['image/jpg'], - ); + const group2 = XTypeGroup(extensions: ['jpg'], mimeTypes: ['image/jpg']); final List files = await plugin.openFiles( acceptedTypeGroups: [group, group2], @@ -152,9 +131,7 @@ void main() { mockApi.getDirectoryPath('some/path'), ).thenAnswer((_) => Future.value('some/path/chosen/')); - final String? path = await plugin.getDirectoryPath( - initialDirectory: 'some/path', - ); + final String? path = await plugin.getDirectoryPath(initialDirectory: 'some/path'); expect(path, 'some/path/chosen/'); }); diff --git a/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart b/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart index 45cfa755255a..e4093c785fd4 100644 --- a/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart +++ b/packages/file_selector/file_selector_android/test/file_selector_android_test.mocks.dart @@ -31,45 +31,30 @@ class MockFileSelectorApi extends _i1.Mock implements _i2.FileSelectorApi { } @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + ) as String); @override - _i4.Future<_i2.FileResponse?> openFile( - String? initialDirectory, - _i2.FileTypes? allowedTypes, - ) => + _i4.Future<_i2.FileResponse?> openFile(String? initialDirectory, _i2.FileTypes? allowedTypes) => (super.noSuchMethod( - Invocation.method(#openFile, [initialDirectory, allowedTypes]), - returnValue: _i4.Future<_i2.FileResponse?>.value(), - ) - as _i4.Future<_i2.FileResponse?>); + Invocation.method(#openFile, [initialDirectory, allowedTypes]), + returnValue: _i4.Future<_i2.FileResponse?>.value(), + ) as _i4.Future<_i2.FileResponse?>); @override _i4.Future> openFiles( String? initialDirectory, _i2.FileTypes? allowedTypes, - ) => - (super.noSuchMethod( - Invocation.method(#openFiles, [initialDirectory, allowedTypes]), - returnValue: _i4.Future>.value( - <_i2.FileResponse>[], - ), - ) - as _i4.Future>); + ) => (super.noSuchMethod( + Invocation.method(#openFiles, [initialDirectory, allowedTypes]), + returnValue: _i4.Future>.value(<_i2.FileResponse>[]), + ) as _i4.Future>); @override - _i4.Future getDirectoryPath(String? initialDirectory) => - (super.noSuchMethod( - Invocation.method(#getDirectoryPath, [initialDirectory]), - returnValue: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getDirectoryPath(String? initialDirectory) => (super.noSuchMethod( + Invocation.method(#getDirectoryPath, [initialDirectory]), + returnValue: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/file_selector/file_selector_ios/example/lib/main.dart b/packages/file_selector/file_selector_ios/example/lib/main.dart index 556f420b8fd1..28b56d3aa713 100644 --- a/packages/file_selector/file_selector_ios/example/lib/main.dart +++ b/packages/file_selector/file_selector_ios/example/lib/main.dart @@ -30,8 +30,7 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': (BuildContext context) => - const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/open/any': (BuildContext context) => const OpenAnyPage(), }, diff --git a/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart b/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart index 999617432133..cef0fc6030c7 100644 --- a/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/open_any_page.dart @@ -66,10 +66,7 @@ class PathDisplay extends StatelessWidget { title: Text(fileName), content: Text(filePath), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart index 9585ac87debe..2b5f2c8f53bb 100644 --- a/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/open_multiple_images_page.dart @@ -81,11 +81,8 @@ class MultipleImagesDisplay extends StatelessWidget { child: Row( children: [ ...files.map( - (XFile file) => Flexible( - child: kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), - ), + (XFile file) => + Flexible(child: kIsWeb ? Image.network(file.path) : Image.file(File(file.path))), ), ], ), diff --git a/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart b/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart index 9a9b36126b15..0e12eb787fa1 100644 --- a/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_ios/example/lib/open_text_page.dart @@ -73,14 +73,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), - content: Scrollbar( - child: SingleChildScrollView(child: Text(fileContent)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart b/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart index 2f6f241333f0..4fc9d3de565a 100644 --- a/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart +++ b/packages/file_selector/file_selector_ios/lib/file_selector_ios.dart @@ -10,8 +10,7 @@ import 'src/messages.g.dart'; /// An implementation of [FileSelectorPlatform] for iOS. class FileSelectorIOS extends FileSelectorPlatform { /// Creates a new plugin implementation instance. - FileSelectorIOS({@visibleForTesting FileSelectorApi? api}) - : _hostApi = api ?? FileSelectorApi(); + FileSelectorIOS({@visibleForTesting FileSelectorApi? api}) : _hostApi = api ?? FileSelectorApi(); final FileSelectorApi _hostApi; @@ -27,9 +26,7 @@ class FileSelectorIOS extends FileSelectorPlatform { String? confirmButtonText, }) async { final List path = await _hostApi.openFile( - FileSelectorConfig( - utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups), - ), + FileSelectorConfig(utis: _allowedUtiListFromTypeGroups(acceptedTypeGroups)), ); return path.isEmpty ? null : XFile(path.first); } diff --git a/packages/file_selector/file_selector_ios/lib/src/messages.g.dart b/packages/file_selector/file_selector_ios/lib/src/messages.g.dart index 6e3795225ca9..6679ba8fd0b0 100644 --- a/packages/file_selector/file_selector_ios/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_ios/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -37,10 +35,7 @@ bool _deepEquals(Object? a, Object? b) { } class FileSelectorConfig { - FileSelectorConfig({ - this.utis = const [], - this.allowMultiSelection = false, - }); + FileSelectorConfig({this.utis = const [], this.allowMultiSelection = false}); List utis; @@ -109,13 +104,11 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + FileSelectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -125,17 +118,13 @@ class FileSelectorApi { Future> openFile(FileSelectorConfig config) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_ios.FileSelectorApi.openFile$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [config], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([config]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/file_selector/file_selector_ios/pigeons/messages.dart b/packages/file_selector/file_selector_ios/pigeons/messages.dart index 857e888c2846..815e7b2f4093 100644 --- a/packages/file_selector/file_selector_ios/pigeons/messages.dart +++ b/packages/file_selector/file_selector_ios/pigeons/messages.dart @@ -7,16 +7,12 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - swiftOut: - 'ios/file_selector_ios/Sources/file_selector_ios/messages.g.swift', + swiftOut: 'ios/file_selector_ios/Sources/file_selector_ios/messages.g.swift', copyrightHeader: 'pigeons/copyright.txt', ), ) class FileSelectorConfig { - FileSelectorConfig({ - this.utis = const [], - this.allowMultiSelection = false, - }); + FileSelectorConfig({this.utis = const [], this.allowMultiSelection = false}); List utis; bool allowMultiSelection; } diff --git a/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart b/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart index ef6bad4693bd..0e414297989d 100644 --- a/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart +++ b/packages/file_selector/file_selector_ios/test/file_selector_ios_test.dart @@ -49,20 +49,11 @@ void main() { await plugin.openFile(acceptedTypeGroups: [group, groupTwo]); // iOS only accepts uniformTypeIdentifiers. - expect( - listEquals(api.passedConfig?.utis, [ - 'public.text', - 'public.image', - ]), - isTrue, - ); + expect(listEquals(api.passedConfig?.utis, ['public.text', 'public.image']), isTrue); expect(api.passedConfig?.allowMultiSelection, isFalse); }); test('throws for a type group that does not support iOS', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.openFile(acceptedTypeGroups: [group]), @@ -72,23 +63,14 @@ void main() { test('correctly handles no type groups', () async { await expectLater(plugin.openFile(), completes); - expect( - listEquals(api.passedConfig?.utis, ['public.data']), - isTrue, - ); + expect(listEquals(api.passedConfig?.utis, ['public.data']), isTrue); }); test('correctly handles a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), - completes, - ); - expect( - listEquals(api.passedConfig?.utis, ['public.data']), - isTrue, - ); + await expectLater(plugin.openFile(acceptedTypeGroups: [group]), completes); + expect(listEquals(api.passedConfig?.utis, ['public.data']), isTrue); }); }); @@ -115,21 +97,12 @@ void main() { await plugin.openFiles(acceptedTypeGroups: [group, groupTwo]); - expect( - listEquals(api.passedConfig?.utis, [ - 'public.text', - 'public.image', - ]), - isTrue, - ); + expect(listEquals(api.passedConfig?.utis, ['public.text', 'public.image']), isTrue); expect(api.passedConfig?.allowMultiSelection, isTrue); }); test('throws for a type group that does not support iOS', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.openFiles(acceptedTypeGroups: [group]), @@ -139,23 +112,14 @@ void main() { test('correctly handles no type groups', () async { await expectLater(plugin.openFiles(), completes); - expect( - listEquals(api.passedConfig?.utis, ['public.data']), - isTrue, - ); + expect(listEquals(api.passedConfig?.utis, ['public.data']), isTrue); }); test('correctly handles a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), - completes, - ); - expect( - listEquals(api.passedConfig?.utis, ['public.data']), - isTrue, - ); + await expectLater(plugin.openFiles(acceptedTypeGroups: [group]), completes); + expect(listEquals(api.passedConfig?.utis, ['public.data']), isTrue); }); }); } diff --git a/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart b/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart index 4e3fa8651920..718f67dc1f85 100644 --- a/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/get_directory_page.dart @@ -13,10 +13,9 @@ class GetDirectoryPage extends StatelessWidget { Future _getDirectoryPath(BuildContext context) async { const confirmButtonText = 'Choose'; - final String? directoryPath = await FileSelectorPlatform.instance - .getDirectoryPathWithOptions( - const FileDialogOptions(confirmButtonText: confirmButtonText), - ); + final String? directoryPath = await FileSelectorPlatform.instance.getDirectoryPathWithOptions( + const FileDialogOptions(confirmButtonText: confirmButtonText), + ); if (directoryPath == null) { // Operation was canceled by the user. return; @@ -64,14 +63,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directory'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoryPath)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart index 9e2d2cc8b542..07263ac0fa68 100644 --- a/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/get_multiple_directories_page.dart @@ -24,8 +24,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { if (context.mounted) { await showDialog( context: context, - builder: (BuildContext context) => - TextDisplay(directoryPaths.join('\n')), + builder: (BuildContext context) => TextDisplay(directoryPaths.join('\n')), ); } } @@ -43,9 +42,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { backgroundColor: Colors.blue, foregroundColor: Colors.white, ), - child: const Text( - 'Press to ask user to choose multiple directories', - ), + child: const Text('Press to ask user to choose multiple directories'), onPressed: () => _getDirectoryPaths(context), ), ], @@ -67,14 +64,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directories'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoriesPaths)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoriesPaths))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_linux/example/lib/home_page.dart b/packages/file_selector/file_selector_linux/example/lib/home_page.dart index b49884852ba7..f90d366432e8 100644 --- a/packages/file_selector/file_selector_linux/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/home_page.dart @@ -54,8 +54,7 @@ class HomePage extends StatelessWidget { ElevatedButton( style: style, child: const Text('Open a get directories dialog'), - onPressed: () => - Navigator.pushNamed(context, '/multi-directories'), + onPressed: () => Navigator.pushNamed(context, '/multi-directories'), ), ], ), diff --git a/packages/file_selector/file_selector_linux/example/lib/main.dart b/packages/file_selector/file_selector_linux/example/lib/main.dart index 28a342002746..4fefa8b6b35b 100644 --- a/packages/file_selector/file_selector_linux/example/lib/main.dart +++ b/packages/file_selector/file_selector_linux/example/lib/main.dart @@ -32,13 +32,11 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': (BuildContext context) => - const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => const GetDirectoryPage(), - '/multi-directories': (BuildContext context) => - const GetMultipleDirectoriesPage(), + '/multi-directories': (BuildContext context) => const GetMultipleDirectoriesPage(), }, ); } diff --git a/packages/file_selector/file_selector_linux/example/lib/open_image_page.dart b/packages/file_selector/file_selector_linux/example/lib/open_image_page.dart index 6554cbfb8b8e..5983fa524649 100644 --- a/packages/file_selector/file_selector_linux/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/open_image_page.dart @@ -15,10 +15,7 @@ class OpenImagePage extends StatelessWidget { const OpenImagePage({super.key}); Future _openImageFile(BuildContext context) async { - const typeGroup = XTypeGroup( - label: 'images', - extensions: ['jpg', 'png'], - ); + const typeGroup = XTypeGroup(label: 'images', extensions: ['jpg', 'png']); final XFile? file = await FileSelectorPlatform.instance.openFile( acceptedTypeGroups: [typeGroup], ); diff --git a/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart index da7e3076c2ad..da35dc55df68 100644 --- a/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/open_multiple_images_page.dart @@ -15,10 +15,7 @@ class OpenMultipleImagesPage extends StatelessWidget { const OpenMultipleImagesPage({super.key}); Future _openImageFile(BuildContext context) async { - const jpgsTypeGroup = XTypeGroup( - label: 'JPEGs', - extensions: ['jpg', 'jpeg'], - ); + const jpgsTypeGroup = XTypeGroup(label: 'JPEGs', extensions: ['jpg', 'jpeg']); const pngTypeGroup = XTypeGroup(label: 'PNGs', extensions: ['png']); final List files = await FileSelectorPlatform.instance.openFiles( acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], @@ -76,11 +73,8 @@ class MultipleImagesDisplay extends StatelessWidget { child: Row( children: [ ...files.map( - (XFile file) => Flexible( - child: kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), - ), + (XFile file) => + Flexible(child: kIsWeb ? Image.network(file.path) : Image.file(File(file.path))), ), ], ), diff --git a/packages/file_selector/file_selector_linux/example/lib/open_text_page.dart b/packages/file_selector/file_selector_linux/example/lib/open_text_page.dart index 023cd8c03a79..5b5abbce9ae4 100644 --- a/packages/file_selector/file_selector_linux/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/open_text_page.dart @@ -12,10 +12,7 @@ class OpenTextPage extends StatelessWidget { const OpenTextPage({super.key}); Future _openTextFile(BuildContext context) async { - const typeGroup = XTypeGroup( - label: 'text', - extensions: ['txt', 'json'], - ); + const typeGroup = XTypeGroup(label: 'text', extensions: ['txt', 'json']); final XFile? file = await FileSelectorPlatform.instance.openFile( acceptedTypeGroups: [typeGroup], ); @@ -72,14 +69,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), - content: Scrollbar( - child: SingleChildScrollView(child: Text(fileContent)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart b/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart index 988176f6498d..156f095c42a1 100644 --- a/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector_linux/example/lib/save_text_page.dart @@ -17,8 +17,9 @@ class SaveTextPage extends StatelessWidget { Future _saveFile() async { final String fileName = _nameController.text; - final FileSaveLocation? result = await FileSelectorPlatform.instance - .getSaveLocation(options: SaveDialogOptions(suggestedName: fileName)); + final FileSaveLocation? result = await FileSelectorPlatform.instance.getSaveLocation( + options: SaveDialogOptions(suggestedName: fileName), + ); // Operation was canceled by the user. if (result == null) { return; @@ -26,11 +27,7 @@ class SaveTextPage extends StatelessWidget { final String text = _contentController.text; final fileData = Uint8List.fromList(text.codeUnits); const fileMimeType = 'text/plain'; - final textFile = XFile.fromData( - fileData, - mimeType: fileMimeType, - name: fileName, - ); + final textFile = XFile.fromData(fileData, mimeType: fileMimeType, name: fileName); await textFile.saveTo(result.path); } @@ -48,9 +45,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _nameController, - decoration: const InputDecoration( - hintText: '(Optional) Suggest File Name', - ), + decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'), ), ), SizedBox( @@ -59,9 +54,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _contentController, - decoration: const InputDecoration( - hintText: 'Enter File Contents', - ), + decoration: const InputDecoration(hintText: 'Enter File Contents'), ), ), const SizedBox(height: 10), diff --git a/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart b/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart index f80c9f60d3b2..e8d7fe403e00 100644 --- a/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart +++ b/packages/file_selector/file_selector_linux/lib/file_selector_linux.dart @@ -29,9 +29,7 @@ class FileSelectorLinux extends FileSelectorPlatform { final List paths = await _hostApi.showFileChooser( PlatformFileChooserActionType.open, PlatformFileChooserOptions( - allowedFileTypes: _platformTypeGroupsFromXTypeGroups( - acceptedTypeGroups, - ), + allowedFileTypes: _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups), currentFolderPath: initialDirectory, acceptButtonLabel: confirmButtonText, selectMultiple: false, @@ -49,9 +47,7 @@ class FileSelectorLinux extends FileSelectorPlatform { final List paths = await _hostApi.showFileChooser( PlatformFileChooserActionType.open, PlatformFileChooserOptions( - allowedFileTypes: _platformTypeGroupsFromXTypeGroups( - acceptedTypeGroups, - ), + allowedFileTypes: _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups), currentFolderPath: initialDirectory, acceptButtonLabel: confirmButtonText, selectMultiple: true, @@ -88,9 +84,7 @@ class FileSelectorLinux extends FileSelectorPlatform { final List paths = await _hostApi.showFileChooser( PlatformFileChooserActionType.save, PlatformFileChooserOptions( - allowedFileTypes: _platformTypeGroupsFromXTypeGroups( - acceptedTypeGroups, - ), + allowedFileTypes: _platformTypeGroupsFromXTypeGroups(acceptedTypeGroups), currentFolderPath: options.initialDirectory, currentName: options.suggestedName, acceptButtonLabel: options.confirmButtonText, @@ -101,15 +95,9 @@ class FileSelectorLinux extends FileSelectorPlatform { } @override - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) async { + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async { return getDirectoryPathWithOptions( - FileDialogOptions( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - ), + FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText), ); } @@ -133,17 +121,12 @@ class FileSelectorLinux extends FileSelectorPlatform { String? confirmButtonText, }) async { return getDirectoryPathsWithOptions( - FileDialogOptions( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - ), + FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText), ); } @override - Future> getDirectoryPathsWithOptions( - FileDialogOptions options, - ) async { + Future> getDirectoryPathsWithOptions(FileDialogOptions options) async { return _hostApi.showFileChooser( PlatformFileChooserActionType.chooseDirectory, PlatformFileChooserOptions( @@ -156,9 +139,7 @@ class FileSelectorLinux extends FileSelectorPlatform { } } -List? _platformTypeGroupsFromXTypeGroups( - List? groups, -) { +List? _platformTypeGroupsFromXTypeGroups(List? groups) { return groups?.map(_platformTypeGroupFromXTypeGroup).toList(); } @@ -167,8 +148,7 @@ PlatformTypeGroup _platformTypeGroupFromXTypeGroup(XTypeGroup group) { if (group.allowsAny) { return PlatformTypeGroup(label: label, extensions: ['*']); } - if ((group.extensions?.isEmpty ?? true) && - (group.mimeTypes?.isEmpty ?? true)) { + if ((group.extensions?.isEmpty ?? true) && (group.mimeTypes?.isEmpty ?? true)) { throw ArgumentError( 'Provided type group $group does not allow ' 'all files, but does not set any of the Linux-supported filter ' @@ -179,9 +159,7 @@ PlatformTypeGroup _platformTypeGroupFromXTypeGroup(XTypeGroup group) { return PlatformTypeGroup( label: label, // Covert to GtkFileFilter's *. format. - extensions: - group.extensions?.map((String extension) => '*.$extension').toList() ?? - [], + extensions: group.extensions?.map((String extension) => '*.$extension').toList() ?? [], mimeTypes: group.mimeTypes ?? [], ); } diff --git a/packages/file_selector/file_selector_linux/lib/src/messages.g.dart b/packages/file_selector/file_selector_linux/lib/src/messages.g.dart index 592db0366e33..464fe875ebb6 100644 --- a/packages/file_selector/file_selector_linux/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_linux/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -136,8 +134,7 @@ class PlatformFileChooserOptions { static PlatformFileChooserOptions decode(Object result) { result as List; return PlatformFileChooserOptions( - allowedFileTypes: (result[0] as List?) - ?.cast(), + allowedFileTypes: (result[0] as List?)?.cast(), currentFolderPath: result[1] as String?, currentName: result[2] as String?, acceptButtonLabel: result[3] as String?, @@ -149,8 +146,7 @@ class PlatformFileChooserOptions { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformFileChooserOptions || - other.runtimeType != runtimeType) { + if (other is! PlatformFileChooserOptions || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -190,9 +186,7 @@ class _PigeonCodec extends StandardMessageCodec { switch (type) { case 129: final int? value = readValue(buffer) as int?; - return value == null - ? null - : PlatformFileChooserActionType.values[value]; + return value == null ? null : PlatformFileChooserActionType.values[value]; case 130: return PlatformTypeGroup.decode(readValue(buffer)!); case 131: @@ -207,13 +201,11 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + FileSelectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -230,17 +222,13 @@ class FileSelectorApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_linux.FileSelectorApi.showFileChooser$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [type, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([type, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart b/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart index 01c068d42796..b5fc1657f6da 100644 --- a/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart +++ b/packages/file_selector/file_selector_linux/test/file_selector_linux_test.dart @@ -58,21 +58,11 @@ void main() { expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ - '*.txt', - ]); - expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, - group.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ - '*.jpg', - ]); - expect( - api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, ['*.jpg']); + expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes); }); test('passes initialDirectory correctly', () async { @@ -90,10 +80,7 @@ void main() { }); test('throws for a type group that does not support Linux', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.openFile(acceptedTypeGroups: [group]), @@ -141,21 +128,11 @@ void main() { expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ - '*.txt', - ]); - expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, - group.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ - '*.jpg', - ]); - expect( - api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, ['*.jpg']); + expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes); }); test('passes initialDirectory correctly', () async { @@ -173,10 +150,7 @@ void main() { }); test('throws for a type group that does not support Linux', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.openFiles(acceptedTypeGroups: [group]), @@ -216,52 +190,33 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin.getSaveLocation( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.getSaveLocation(acceptedTypeGroups: [group, groupTwo]); expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ - '*.txt', - ]); - expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, - group.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ - '*.jpg', - ]); - expect( - api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, ['*.jpg']); + expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes); }); test('passes initialDirectory correctly', () async { const path = '/example/directory'; - await plugin.getSaveLocation( - options: const SaveDialogOptions(initialDirectory: path), - ); + await plugin.getSaveLocation(options: const SaveDialogOptions(initialDirectory: path)); expect(api.passedOptions?.currentFolderPath, path); }); test('passes confirmButtonText correctly', () async { const button = 'Open File'; - await plugin.getSaveLocation( - options: const SaveDialogOptions(confirmButtonText: button), - ); + await plugin.getSaveLocation(options: const SaveDialogOptions(confirmButtonText: button)); expect(api.passedOptions?.acceptButtonLabel, button); }); test('throws for a type group that does not support Linux', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.getSaveLocation(acceptedTypeGroups: [group]), @@ -301,27 +256,15 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin.getSavePath( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.getSavePath(acceptedTypeGroups: [group, groupTwo]); expect(api.passedOptions?.allowedFileTypes?[0].label, group.label); // Extensions should be converted to *. format. - expect(api.passedOptions?.allowedFileTypes?[0].extensions, [ - '*.txt', - ]); - expect( - api.passedOptions?.allowedFileTypes?[0].mimeTypes, - group.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[0].extensions, ['*.txt']); + expect(api.passedOptions?.allowedFileTypes?[0].mimeTypes, group.mimeTypes); expect(api.passedOptions?.allowedFileTypes?[1].label, groupTwo.label); - expect(api.passedOptions?.allowedFileTypes?[1].extensions, [ - '*.jpg', - ]); - expect( - api.passedOptions?.allowedFileTypes?[1].mimeTypes, - groupTwo.mimeTypes, - ); + expect(api.passedOptions?.allowedFileTypes?[1].extensions, ['*.jpg']); + expect(api.passedOptions?.allowedFileTypes?[1].mimeTypes, groupTwo.mimeTypes); }); test('passes initialDirectory correctly', () async { @@ -339,10 +282,7 @@ void main() { }); test('throws for a type group that does not support Linux', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.getSavePath(acceptedTypeGroups: [group]), @@ -390,10 +330,7 @@ void main() { const path = '/foo/bar'; api.result = [path]; - expect( - await plugin.getDirectoryPathWithOptions(const FileDialogOptions()), - path, - ); + expect(await plugin.getDirectoryPathWithOptions(const FileDialogOptions()), path); expect(api.passedType, PlatformFileChooserActionType.chooseDirectory); expect(api.passedOptions?.selectMultiple, false); @@ -401,25 +338,19 @@ void main() { test('passes initialDirectory correctly', () async { const path = '/example/directory'; - await plugin.getDirectoryPathWithOptions( - const FileDialogOptions(initialDirectory: path), - ); + await plugin.getDirectoryPathWithOptions(const FileDialogOptions(initialDirectory: path)); expect(api.passedOptions?.currentFolderPath, path); }); test('passes confirmButtonText correctly', () async { const button = 'Select Folder'; - await plugin.getDirectoryPathWithOptions( - const FileDialogOptions(confirmButtonText: button), - ); + await plugin.getDirectoryPathWithOptions(const FileDialogOptions(confirmButtonText: button)); expect(api.passedOptions?.acceptButtonLabel, button); }); test('passes canCreateDirectories correctly', () async { - await plugin.getDirectoryPathWithOptions( - const FileDialogOptions(canCreateDirectories: true), - ); + await plugin.getDirectoryPathWithOptions(const FileDialogOptions(canCreateDirectories: true)); expect(api.passedOptions?.createFolders, true); }); }); @@ -459,10 +390,7 @@ void main() { test('passes the core flags correctly', () async { api.result = ['/foo/bar', 'baz']; - expect( - await plugin.getDirectoryPathsWithOptions(const FileDialogOptions()), - api.result, - ); + expect(await plugin.getDirectoryPathsWithOptions(const FileDialogOptions()), api.result); expect(api.passedType, PlatformFileChooserActionType.chooseDirectory); expect(api.passedOptions?.selectMultiple, true); @@ -470,18 +398,14 @@ void main() { test('passes initialDirectory correctly', () async { const path = '/example/directory'; - await plugin.getDirectoryPathsWithOptions( - const FileDialogOptions(initialDirectory: path), - ); + await plugin.getDirectoryPathsWithOptions(const FileDialogOptions(initialDirectory: path)); expect(api.passedOptions?.currentFolderPath, path); }); test('passes confirmButtonText correctly', () async { const button = 'Select one or mode folders'; - await plugin.getDirectoryPathsWithOptions( - const FileDialogOptions(confirmButtonText: button), - ); + await plugin.getDirectoryPathsWithOptions(const FileDialogOptions(confirmButtonText: button)); expect(api.passedOptions?.acceptButtonLabel, button); }); diff --git a/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart b/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart index 065f5c0837e3..b3150be2a437 100644 --- a/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/get_directory_page.dart @@ -13,13 +13,9 @@ class GetDirectoryPage extends StatelessWidget { Future _getDirectoryPath(BuildContext context) async { const confirmButtonText = 'Choose'; - final String? directoryPath = await FileSelectorPlatform.instance - .getDirectoryPathWithOptions( - const FileDialogOptions( - confirmButtonText: confirmButtonText, - canCreateDirectories: true, - ), - ); + final String? directoryPath = await FileSelectorPlatform.instance.getDirectoryPathWithOptions( + const FileDialogOptions(confirmButtonText: confirmButtonText, canCreateDirectories: true), + ); if (directoryPath == null) { // Operation was canceled by the user. return; @@ -67,14 +63,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directory'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoryPath)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart index 18ae7f52db3e..a2c5df75e434 100644 --- a/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/get_multiple_directories_page.dart @@ -15,10 +15,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { const confirmButtonText = 'Choose'; final List directoriesPaths = await FileSelectorPlatform.instance .getDirectoryPathsWithOptions( - const FileDialogOptions( - confirmButtonText: confirmButtonText, - canCreateDirectories: true, - ), + const FileDialogOptions(confirmButtonText: confirmButtonText, canCreateDirectories: true), ); if (directoriesPaths.isEmpty) { // Operation was canceled by the user. @@ -27,8 +24,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { if (context.mounted) { await showDialog( context: context, - builder: (BuildContext context) => - TextDisplay(directoriesPaths.join('\n')), + builder: (BuildContext context) => TextDisplay(directoriesPaths.join('\n')), ); } } @@ -46,9 +42,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { backgroundColor: Colors.blue, foregroundColor: Colors.white, ), - child: const Text( - 'Press to ask user to choose multiple directories', - ), + child: const Text('Press to ask user to choose multiple directories'), onPressed: () => _getDirectoryPaths(context), ), ], @@ -70,14 +64,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directories'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoryPaths)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPaths))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_macos/example/lib/home_page.dart b/packages/file_selector/file_selector_macos/example/lib/home_page.dart index b49884852ba7..f90d366432e8 100644 --- a/packages/file_selector/file_selector_macos/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/home_page.dart @@ -54,8 +54,7 @@ class HomePage extends StatelessWidget { ElevatedButton( style: style, child: const Text('Open a get directories dialog'), - onPressed: () => - Navigator.pushNamed(context, '/multi-directories'), + onPressed: () => Navigator.pushNamed(context, '/multi-directories'), ), ], ), diff --git a/packages/file_selector/file_selector_macos/example/lib/main.dart b/packages/file_selector/file_selector_macos/example/lib/main.dart index 28a342002746..4fefa8b6b35b 100644 --- a/packages/file_selector/file_selector_macos/example/lib/main.dart +++ b/packages/file_selector/file_selector_macos/example/lib/main.dart @@ -32,13 +32,11 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': (BuildContext context) => - const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => const GetDirectoryPage(), - '/multi-directories': (BuildContext context) => - const GetMultipleDirectoriesPage(), + '/multi-directories': (BuildContext context) => const GetMultipleDirectoriesPage(), }, ); } diff --git a/packages/file_selector/file_selector_macos/example/lib/open_image_page.dart b/packages/file_selector/file_selector_macos/example/lib/open_image_page.dart index 6554cbfb8b8e..5983fa524649 100644 --- a/packages/file_selector/file_selector_macos/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/open_image_page.dart @@ -15,10 +15,7 @@ class OpenImagePage extends StatelessWidget { const OpenImagePage({super.key}); Future _openImageFile(BuildContext context) async { - const typeGroup = XTypeGroup( - label: 'images', - extensions: ['jpg', 'png'], - ); + const typeGroup = XTypeGroup(label: 'images', extensions: ['jpg', 'png']); final XFile? file = await FileSelectorPlatform.instance.openFile( acceptedTypeGroups: [typeGroup], ); diff --git a/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart index da7e3076c2ad..da35dc55df68 100644 --- a/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/open_multiple_images_page.dart @@ -15,10 +15,7 @@ class OpenMultipleImagesPage extends StatelessWidget { const OpenMultipleImagesPage({super.key}); Future _openImageFile(BuildContext context) async { - const jpgsTypeGroup = XTypeGroup( - label: 'JPEGs', - extensions: ['jpg', 'jpeg'], - ); + const jpgsTypeGroup = XTypeGroup(label: 'JPEGs', extensions: ['jpg', 'jpeg']); const pngTypeGroup = XTypeGroup(label: 'PNGs', extensions: ['png']); final List files = await FileSelectorPlatform.instance.openFiles( acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], @@ -76,11 +73,8 @@ class MultipleImagesDisplay extends StatelessWidget { child: Row( children: [ ...files.map( - (XFile file) => Flexible( - child: kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), - ), + (XFile file) => + Flexible(child: kIsWeb ? Image.network(file.path) : Image.file(File(file.path))), ), ], ), diff --git a/packages/file_selector/file_selector_macos/example/lib/open_text_page.dart b/packages/file_selector/file_selector_macos/example/lib/open_text_page.dart index 023cd8c03a79..5b5abbce9ae4 100644 --- a/packages/file_selector/file_selector_macos/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/open_text_page.dart @@ -12,10 +12,7 @@ class OpenTextPage extends StatelessWidget { const OpenTextPage({super.key}); Future _openTextFile(BuildContext context) async { - const typeGroup = XTypeGroup( - label: 'text', - extensions: ['txt', 'json'], - ); + const typeGroup = XTypeGroup(label: 'text', extensions: ['txt', 'json']); final XFile? file = await FileSelectorPlatform.instance.openFile( acceptedTypeGroups: [typeGroup], ); @@ -72,14 +69,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), - content: Scrollbar( - child: SingleChildScrollView(child: Text(fileContent)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart b/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart index b7847bdcc1f6..f86e1bb40d3a 100644 --- a/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector_macos/example/lib/save_text_page.dart @@ -17,8 +17,9 @@ class SaveTextPage extends StatelessWidget { Future _saveFile() async { final String fileName = _nameController.text; - final FileSaveLocation? result = await FileSelectorPlatform.instance - .getSaveLocation(options: SaveDialogOptions(suggestedName: fileName)); + final FileSaveLocation? result = await FileSelectorPlatform.instance.getSaveLocation( + options: SaveDialogOptions(suggestedName: fileName), + ); if (result == null) { // Operation was canceled by the user. return; @@ -26,11 +27,7 @@ class SaveTextPage extends StatelessWidget { final String text = _contentController.text; final fileData = Uint8List.fromList(text.codeUnits); const fileMimeType = 'text/plain'; - final textFile = XFile.fromData( - fileData, - mimeType: fileMimeType, - name: fileName, - ); + final textFile = XFile.fromData(fileData, mimeType: fileMimeType, name: fileName); await textFile.saveTo(result.path); } @@ -48,9 +45,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _nameController, - decoration: const InputDecoration( - hintText: '(Optional) Suggest File Name', - ), + decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'), ), ), SizedBox( @@ -59,9 +54,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _contentController, - decoration: const InputDecoration( - hintText: 'Enter File Contents', - ), + decoration: const InputDecoration(hintText: 'Enter File Contents'), ), ), const SizedBox(height: 10), diff --git a/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart b/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart index c534e43df1db..761f46675dca 100644 --- a/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart +++ b/packages/file_selector/file_selector_macos/lib/file_selector_macos.dart @@ -98,15 +98,9 @@ class FileSelectorMacOS extends FileSelectorPlatform { } @override - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) async { + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async { return getDirectoryPathWithOptions( - FileDialogOptions( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - ), + FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText), ); } @@ -133,17 +127,12 @@ class FileSelectorMacOS extends FileSelectorPlatform { String? confirmButtonText, }) async { return getDirectoryPathsWithOptions( - FileDialogOptions( - initialDirectory: initialDirectory, - confirmButtonText: confirmButtonText, - ), + FileDialogOptions(initialDirectory: initialDirectory, confirmButtonText: confirmButtonText), ); } @override - Future> getDirectoryPathsWithOptions( - FileDialogOptions options, - ) async { + Future> getDirectoryPathsWithOptions(FileDialogOptions options) async { final List paths = await _hostApi.displayOpenPanel( OpenPanelOptions( allowsMultipleSelection: true, diff --git a/packages/file_selector/file_selector_macos/lib/src/messages.g.dart b/packages/file_selector/file_selector_macos/lib/src/messages.g.dart index f91bc53fee31..8e625345e683 100644 --- a/packages/file_selector/file_selector_macos/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_macos/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -169,12 +167,7 @@ class OpenPanelOptions { SavePanelOptions baseOptions; List _toList() { - return [ - allowsMultipleSelection, - canChooseDirectories, - canChooseFiles, - baseOptions, - ]; + return [allowsMultipleSelection, canChooseDirectories, canChooseFiles, baseOptions]; } Object encode() { @@ -248,13 +241,11 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + FileSelectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -268,17 +259,13 @@ class FileSelectorApi { Future> displayOpenPanel(OpenPanelOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displayOpenPanel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -303,17 +290,13 @@ class FileSelectorApi { Future displaySavePanel(SavePanelOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_macos.FileSelectorApi.displaySavePanel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/file_selector/file_selector_macos/pigeons/messages.dart b/packages/file_selector/file_selector_macos/pigeons/messages.dart index e65780f0c20c..eda934eb5acd 100644 --- a/packages/file_selector/file_selector_macos/pigeons/messages.dart +++ b/packages/file_selector/file_selector_macos/pigeons/messages.dart @@ -6,8 +6,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( input: 'pigeons/messages.dart', - swiftOut: - 'macos/file_selector_macos/Sources/file_selector_macos/messages.g.swift', + swiftOut: 'macos/file_selector_macos/Sources/file_selector_macos/messages.g.swift', dartOut: 'lib/src/messages.g.dart', copyrightHeader: 'pigeons/copyright.txt', ), diff --git a/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart b/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart index 58563ddcff8d..97973505d0b7 100644 --- a/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart +++ b/packages/file_selector/file_selector_macos/test/file_selector_macos_test.dart @@ -68,18 +68,9 @@ void main() { await plugin.openFile(acceptedTypeGroups: [group, groupTwo]); final OpenPanelOptions options = api.passedOpenPanelOptions!; - expect(options.baseOptions.allowedFileTypes!.extensions, [ - 'txt', - 'jpg', - ]); - expect(options.baseOptions.allowedFileTypes!.mimeTypes, [ - 'text/plain', - 'image/jpg', - ]); - expect(options.baseOptions.allowedFileTypes!.utis, [ - 'public.text', - 'public.image', - ]); + expect(options.baseOptions.allowedFileTypes!.extensions, ['txt', 'jpg']); + expect(options.baseOptions.allowedFileTypes!.mimeTypes, ['text/plain', 'image/jpg']); + expect(options.baseOptions.allowedFileTypes!.utis, ['public.text', 'public.image']); }); test('passes initialDirectory correctly', () async { @@ -97,10 +88,7 @@ void main() { }); test('throws for a type group that does not support macOS', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.openFile(acceptedTypeGroups: [group]), @@ -111,10 +99,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.openFile(acceptedTypeGroups: [group]), completes); }); }); @@ -163,18 +148,9 @@ void main() { await plugin.openFiles(acceptedTypeGroups: [group, groupTwo]); final OpenPanelOptions options = api.passedOpenPanelOptions!; - expect(options.baseOptions.allowedFileTypes!.extensions, [ - 'txt', - 'jpg', - ]); - expect(options.baseOptions.allowedFileTypes!.mimeTypes, [ - 'text/plain', - 'image/jpg', - ]); - expect(options.baseOptions.allowedFileTypes!.utis, [ - 'public.text', - 'public.image', - ]); + expect(options.baseOptions.allowedFileTypes!.extensions, ['txt', 'jpg']); + expect(options.baseOptions.allowedFileTypes!.mimeTypes, ['text/plain', 'image/jpg']); + expect(options.baseOptions.allowedFileTypes!.utis, ['public.text', 'public.image']); }); test('passes initialDirectory correctly', () async { @@ -192,10 +168,7 @@ void main() { }); test('throws for a type group that does not support macOS', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.openFiles(acceptedTypeGroups: [group]), @@ -206,10 +179,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.openFiles(acceptedTypeGroups: [group]), completes); }); }); @@ -251,20 +221,12 @@ void main() { webWildCards: ['image/*'], ); - await plugin.getSavePath( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.getSavePath(acceptedTypeGroups: [group, groupTwo]); final SavePanelOptions options = api.passedSavePanelOptions!; expect(options.allowedFileTypes!.extensions, ['txt', 'jpg']); - expect(options.allowedFileTypes!.mimeTypes, [ - 'text/plain', - 'image/jpg', - ]); - expect(options.allowedFileTypes!.utis, [ - 'public.text', - 'public.image', - ]); + expect(options.allowedFileTypes!.mimeTypes, ['text/plain', 'image/jpg']); + expect(options.allowedFileTypes!.utis, ['public.text', 'public.image']); }); test('passes initialDirectory correctly', () async { @@ -282,10 +244,7 @@ void main() { }); test('throws for a type group that does not support macOS', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.getSavePath(acceptedTypeGroups: [group]), @@ -296,10 +255,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.getSavePath(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.getSavePath(acceptedTypeGroups: [group]), completes); }); test('ignores all type groups if any of them is a wildcard', () async { @@ -364,27 +320,17 @@ void main() { webWildCards: ['image/*'], ); - await plugin.getSaveLocation( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.getSaveLocation(acceptedTypeGroups: [group, groupTwo]); final SavePanelOptions options = api.passedSavePanelOptions!; expect(options.allowedFileTypes!.extensions, ['txt', 'jpg']); - expect(options.allowedFileTypes!.mimeTypes, [ - 'text/plain', - 'image/jpg', - ]); - expect(options.allowedFileTypes!.utis, [ - 'public.text', - 'public.image', - ]); + expect(options.allowedFileTypes!.mimeTypes, ['text/plain', 'image/jpg']); + expect(options.allowedFileTypes!.utis, ['public.text', 'public.image']); }); test('passes initialDirectory correctly', () async { await plugin.getSaveLocation( - options: const SaveDialogOptions( - initialDirectory: '/example/directory', - ), + options: const SaveDialogOptions(initialDirectory: '/example/directory'), ); final SavePanelOptions options = api.passedSavePanelOptions!; @@ -401,10 +347,7 @@ void main() { }); test('throws for a type group that does not support macOS', () async { - const group = XTypeGroup( - label: 'images', - webWildCards: ['images/*'], - ); + const group = XTypeGroup(label: 'images', webWildCards: ['images/*']); await expectLater( plugin.getSaveLocation(acceptedTypeGroups: [group]), @@ -415,10 +358,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.getSaveLocation(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.getSaveLocation(acceptedTypeGroups: [group]), completes); }); test('ignores all type groups if any of them is a wildcard', () async { @@ -489,9 +429,7 @@ void main() { test('works as expected with no arguments', () async { api.result = ['foo']; - final String? path = await plugin.getDirectoryPathWithOptions( - const FileDialogOptions(), - ); + final String? path = await plugin.getDirectoryPathWithOptions(const FileDialogOptions()); expect(path, 'foo'); final OpenPanelOptions options = api.passedOpenPanelOptions!; @@ -543,19 +481,11 @@ void main() { group('getDirectoryPaths', () { test('works as expected with no arguments', () async { - api.result = [ - 'firstDirectory', - 'secondDirectory', - 'thirdDirectory', - ]; + api.result = ['firstDirectory', 'secondDirectory', 'thirdDirectory']; final List path = await plugin.getDirectoryPaths(); - expect(path, [ - 'firstDirectory', - 'secondDirectory', - 'thirdDirectory', - ]); + expect(path, ['firstDirectory', 'secondDirectory', 'thirdDirectory']); final OpenPanelOptions options = api.passedOpenPanelOptions!; expect(options.allowsMultipleSelection, true); expect(options.canChooseFiles, false); @@ -591,21 +521,13 @@ void main() { group('getDirectoryPathsWithOptions', () { test('works as expected with no arguments', () async { - api.result = [ - 'firstDirectory', - 'secondDirectory', - 'thirdDirectory', - ]; + api.result = ['firstDirectory', 'secondDirectory', 'thirdDirectory']; final List path = await plugin.getDirectoryPathsWithOptions( const FileDialogOptions(), ); - expect(path, [ - 'firstDirectory', - 'secondDirectory', - 'thirdDirectory', - ]); + expect(path, ['firstDirectory', 'secondDirectory', 'thirdDirectory']); final OpenPanelOptions options = api.passedOpenPanelOptions!; expect(options.allowsMultipleSelection, true); expect(options.canChooseFiles, false); diff --git a/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart b/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart index a39a18933880..29961b32a1c1 100644 --- a/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart +++ b/packages/file_selector/file_selector_platform_interface/lib/src/method_channel/method_channel_file_selector.dart @@ -7,9 +7,7 @@ import 'package:flutter/services.dart'; import '../../file_selector_platform_interface.dart'; -const MethodChannel _channel = MethodChannel( - 'plugins.flutter.io/file_selector', -); +const MethodChannel _channel = MethodChannel('plugins.flutter.io/file_selector'); /// An implementation of [FileSelectorPlatform] that uses method channels. class MethodChannelFileSelector extends FileSelectorPlatform { @@ -61,9 +59,7 @@ class MethodChannelFileSelector extends FileSelectorPlatform { String? confirmButtonText, }) async { return _channel.invokeMethod('getSavePath', { - 'acceptedTypeGroups': acceptedTypeGroups - ?.map((XTypeGroup group) => group.toJSON()) - .toList(), + 'acceptedTypeGroups': acceptedTypeGroups?.map((XTypeGroup group) => group.toJSON()).toList(), 'initialDirectory': initialDirectory, 'suggestedName': suggestedName, 'confirmButtonText': confirmButtonText, @@ -71,10 +67,7 @@ class MethodChannelFileSelector extends FileSelectorPlatform { } @override - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) async { + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async { return _channel.invokeMethod('getDirectoryPath', { 'initialDirectory': initialDirectory, 'confirmButtonText': confirmButtonText, diff --git a/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart b/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart index 97c59688168d..c32ecef5a0a7 100644 --- a/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart +++ b/packages/file_selector/file_selector_platform_interface/lib/src/platform_interface/file_selector_interface.dart @@ -97,10 +97,7 @@ abstract class FileSelectorPlatform extends PlatformInterface { /// /// Returns `null` if the user cancels the operation. @Deprecated('Use getDirectoryPathWithOptions instead') - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) { + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) { throw UnimplementedError('getDirectoryPath() has not been implemented.'); } @@ -122,10 +119,7 @@ abstract class FileSelectorPlatform extends PlatformInterface { /// /// Returns an empty list if the user cancels the operation. @Deprecated('Use getDirectoryPathsWithOptions instead') - Future> getDirectoryPaths({ - String? initialDirectory, - String? confirmButtonText, - }) { + Future> getDirectoryPaths({String? initialDirectory, String? confirmButtonText}) { throw UnimplementedError('getDirectoryPaths() has not been implemented.'); } diff --git a/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart b/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart index 12761e90504f..fffba3ceb9c0 100644 --- a/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart +++ b/packages/file_selector/file_selector_platform_interface/lib/src/types/x_type_group.dart @@ -70,7 +70,6 @@ class XTypeGroup { @Deprecated('Use uniformTypeIdentifiers instead') List? get macUTIs => uniformTypeIdentifiers; - static List? _removeLeadingDots(List? exts) => exts - ?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext) - .toList(); + static List? _removeLeadingDots(List? exts) => + exts?.map((String ext) => ext.startsWith('.') ? ext.substring(1) : ext).toList(); } diff --git a/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart b/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart index 541897b81ce0..90bdce1de36a 100644 --- a/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart +++ b/packages/file_selector/file_selector_platform_interface/test/file_selector_platform_interface_test.dart @@ -32,8 +32,7 @@ void main() { group('getDirectoryPathWithOptions', () { test('Should fall back to getDirectoryPath by default', () async { - final FileSelectorPlatform fileSelector = - OldFileSelectorPlatformImplementation(); + final FileSelectorPlatform fileSelector = OldFileSelectorPlatformImplementation(); final String? result = await fileSelector.getDirectoryPathWithOptions( const FileDialogOptions(), @@ -56,22 +55,19 @@ void main() { group('getDirectoryPathsWithOptions', () { test('Should fall back to getDirectoryPaths by default', () async { - final FileSelectorPlatform fileSelector = - OldFileSelectorPlatformImplementation(); + final FileSelectorPlatform fileSelector = OldFileSelectorPlatformImplementation(); - final List result = await fileSelector - .getDirectoryPathsWithOptions(const FileDialogOptions()); + final List result = await fileSelector.getDirectoryPathsWithOptions( + const FileDialogOptions(), + ); // Should call the old method and return its result - expect(result, [ - OldFileSelectorPlatformImplementation.directoryPath, - ]); + expect(result, [OldFileSelectorPlatformImplementation.directoryPath]); }); }); test('getSaveLocation falls back to getSavePath by default', () async { - final FileSelectorPlatform fileSelector = - OldFileSelectorPlatformImplementation(); + final FileSelectorPlatform fileSelector = OldFileSelectorPlatformImplementation(); final FileSaveLocation? result = await fileSelector.getSaveLocation(); @@ -97,10 +93,7 @@ class OldFileSelectorPlatformImplementation extends FileSelectorPlatform { } @override - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) async { + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async { return directoryPath; } diff --git a/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart b/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart index 12b3839b8b89..77b0010569ec 100644 --- a/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart +++ b/packages/file_selector/file_selector_platform_interface/test/method_channel_file_selector_test.dart @@ -16,13 +16,13 @@ void main() { final log = []; setUp(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(plugin.channel, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + plugin.channel, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); log.clear(); }); @@ -44,18 +44,13 @@ void main() { webWildCards: ['image/*'], ); - await plugin.openFile( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.openFile(acceptedTypeGroups: [group, groupTwo]); expectMethodCall( log, 'openFile', arguments: { - 'acceptedTypeGroups': >[ - group.toJSON(), - groupTwo.toJSON(), - ], + 'acceptedTypeGroups': >[group.toJSON(), groupTwo.toJSON()], 'initialDirectory': null, 'confirmButtonText': null, 'multiple': false, @@ -108,18 +103,13 @@ void main() { webWildCards: ['image/*'], ); - await plugin.openFiles( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.openFiles(acceptedTypeGroups: [group, groupTwo]); expectMethodCall( log, 'openFile', arguments: { - 'acceptedTypeGroups': >[ - group.toJSON(), - groupTwo.toJSON(), - ], + 'acceptedTypeGroups': >[group.toJSON(), groupTwo.toJSON()], 'initialDirectory': null, 'confirmButtonText': null, 'multiple': true, @@ -173,18 +163,13 @@ void main() { webWildCards: ['image/*'], ); - await plugin.getSavePath( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.getSavePath(acceptedTypeGroups: [group, groupTwo]); expectMethodCall( log, 'getSavePath', arguments: { - 'acceptedTypeGroups': >[ - group.toJSON(), - groupTwo.toJSON(), - ], + 'acceptedTypeGroups': >[group.toJSON(), groupTwo.toJSON()], 'initialDirectory': null, 'suggestedName': null, 'confirmButtonText': null, @@ -260,9 +245,7 @@ void main() { ); }); test('passes confirmButtonText correctly', () async { - await plugin.getDirectoryPaths( - confirmButtonText: 'Select one or more Folders', - ); + await plugin.getDirectoryPaths(confirmButtonText: 'Select one or more Folders'); expectMethodCall( log, @@ -277,10 +260,6 @@ void main() { }); } -void expectMethodCall( - List log, - String methodName, { - Map? arguments, -}) { +void expectMethodCall(List log, String methodName, {Map? arguments}) { expect(log, [isMethodCall(methodName, arguments: arguments)]); } diff --git a/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart b/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart index 795fe337245a..5bac916d14d0 100644 --- a/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart +++ b/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart @@ -55,18 +55,9 @@ void main() { }); test('allowsAny returns false if anything is set', () { - const extensionOnly = XTypeGroup( - label: 'extensions', - extensions: ['txt'], - ); - const mimeOnly = XTypeGroup( - label: 'mime', - mimeTypes: ['text/plain'], - ); - const utiOnly = XTypeGroup( - label: 'utis', - uniformTypeIdentifiers: ['public.text'], - ); + const extensionOnly = XTypeGroup(label: 'extensions', extensions: ['txt']); + const mimeOnly = XTypeGroup(label: 'mime', mimeTypes: ['text/plain']); + const utiOnly = XTypeGroup(label: 'utis', uniformTypeIdentifiers: ['public.text']); const webOnly = XTypeGroup(label: 'web', webWildCards: ['.txt']); expect(extensionOnly.allowsAny, false); @@ -83,17 +74,12 @@ void main() { expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers); }); - test( - 'passing only uniformTypeIdentifiers should fill uniformTypeIdentifiers', - () { - const uniformTypeIdentifiers = ['public.plain-text']; - const group = XTypeGroup( - uniformTypeIdentifiers: uniformTypeIdentifiers, - ); + test('passing only uniformTypeIdentifiers should fill uniformTypeIdentifiers', () { + const uniformTypeIdentifiers = ['public.plain-text']; + const group = XTypeGroup(uniformTypeIdentifiers: uniformTypeIdentifiers); - expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers); - }, - ); + expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers); + }); test('macUTIs getter return macUTIs value passed in constructor', () { const uniformTypeIdentifiers = ['public.plain-text']; @@ -102,17 +88,12 @@ void main() { expect(group.macUTIs, uniformTypeIdentifiers); }); - test( - 'macUTIs getter returns uniformTypeIdentifiers value passed in constructor', - () { - const uniformTypeIdentifiers = ['public.plain-text']; - const group = XTypeGroup( - uniformTypeIdentifiers: uniformTypeIdentifiers, - ); + test('macUTIs getter returns uniformTypeIdentifiers value passed in constructor', () { + const uniformTypeIdentifiers = ['public.plain-text']; + const group = XTypeGroup(uniformTypeIdentifiers: uniformTypeIdentifiers); - expect(group.macUTIs, uniformTypeIdentifiers); - }, - ); + expect(group.macUTIs, uniformTypeIdentifiers); + }); test('passing both uniformTypeIdentifiers and macUTIs should throw', () { expect( @@ -124,8 +105,7 @@ void main() { predicate( (Object? e) => e is AssertionError && - e.message == - 'Only one of uniformTypeIdentifiers or macUTIs can be non-null', + e.message == 'Only one of uniformTypeIdentifiers or macUTIs can be non-null', ), ), ); diff --git a/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart b/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart index b8b07cd0c246..b2e798a9e437 100644 --- a/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart +++ b/packages/file_selector/file_selector_web/example/integration_test/dom_helper_test.dart @@ -41,8 +41,7 @@ void main() { setUp(() { domHelper = DomHelper(); - input = (document.createElement('input') as HTMLInputElement) - ..type = 'file'; + input = (document.createElement('input') as HTMLInputElement)..type = 'file'; }); group('getFiles', () { @@ -50,9 +49,7 @@ void main() { final mockFile2 = File([].toJS, 'file2.txt'); testWidgets('works', (_) async { - final Future> futureFiles = domHelper.getFiles( - input: input, - ); + final Future> futureFiles = domHelper.getFiles(input: input); setFilesAndTriggerChange([mockFile1, mockFile2]); @@ -72,9 +69,7 @@ void main() { }); testWidgets('"cancel" returns an empty selection', (_) async { - final Future> futureFiles = domHelper.getFiles( - input: input, - ); + final Future> futureFiles = domHelper.getFiles(input: input); setFilesAndTriggerCancel([mockFile1, mockFile2]); @@ -117,18 +112,13 @@ void main() { input: input, ); - expect( - input.isConnected, - true, - reason: 'input must be injected into the DOM', - ); + expect(input.isConnected, true, reason: 'input must be injected into the DOM'); expect(input.accept, accept); expect(input.multiple, multiple); expect( await wasClicked, true, - reason: - 'The should be clicked otherwise no dialog will be shown', + reason: 'The should be clicked otherwise no dialog will be shown', ); setFilesAndTriggerChange([]); diff --git a/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart b/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart index 72cb0de90b1e..d7729e218af6 100644 --- a/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart +++ b/packages/file_selector/file_selector_web/example/integration_test/file_selector_web_test.dart @@ -33,9 +33,7 @@ void main() { webWildCards: ['image/*'], ); - final XFile? file = await plugin.openFile( - acceptedTypeGroups: [typeGroup], - ); + final XFile? file = await plugin.openFile(acceptedTypeGroups: [typeGroup]); expect(file, isNotNull); expect(file!.name, mockFile.name); @@ -44,9 +42,7 @@ void main() { expect(await file.lastModified(), isNotNull); }); - testWidgets('returns null when getFiles returns an empty list', ( - WidgetTester _, - ) async { + testWidgets('returns null when getFiles returns an empty list', (WidgetTester _) async { // Simulate returning an empty list of files from the DomHelper... final mockDomHelper = MockDomHelper(files: []); @@ -71,10 +67,7 @@ void main() { final plugin = FileSelectorWeb(domHelper: mockDomHelper); - const typeGroup = XTypeGroup( - label: 'files', - extensions: ['.txt'], - ); + const typeGroup = XTypeGroup(label: 'files', extensions: ['.txt']); final List files = await plugin.openFiles( acceptedTypeGroups: [typeGroup], @@ -123,16 +116,8 @@ class MockDomHelper implements DomHelper { bool multiple = false, HTMLInputElement? input, }) { - expect( - accept, - _expectedAccept, - reason: 'Expected "accept" value does not match.', - ); - expect( - multiple, - _expectedMultiple, - reason: 'Expected "multiple" value does not match.', - ); + expect(accept, _expectedAccept, reason: 'Expected "accept" value does not match.'); + expect(multiple, _expectedMultiple, reason: 'Expected "multiple" value does not match.'); return Future>.value(_files); } } diff --git a/packages/file_selector/file_selector_web/lib/file_selector_web.dart b/packages/file_selector/file_selector_web/lib/file_selector_web.dart index 381cd6c6185e..baf0507eec95 100644 --- a/packages/file_selector/file_selector_web/lib/file_selector_web.dart +++ b/packages/file_selector/file_selector_web/lib/file_selector_web.dart @@ -34,9 +34,7 @@ class FileSelectorWeb extends FileSelectorPlatform { String? initialDirectory, String? confirmButtonText, }) async { - final List files = await _openFiles( - acceptedTypeGroups: acceptedTypeGroups, - ); + final List files = await _openFiles(acceptedTypeGroups: acceptedTypeGroups); return files.isNotEmpty ? files.first : null; } @@ -71,10 +69,8 @@ class FileSelectorWeb extends FileSelectorPlatform { } @override - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) async => null; + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async => + null; Future> _openFiles({ List? acceptedTypeGroups, diff --git a/packages/file_selector/file_selector_web/lib/src/dom_helper.dart b/packages/file_selector/file_selector_web/lib/src/dom_helper.dart index 2c0205c61550..f1f1a55e60c3 100644 --- a/packages/file_selector/file_selector_web/lib/src/dom_helper.dart +++ b/packages/file_selector/file_selector_web/lib/src/dom_helper.dart @@ -48,10 +48,7 @@ class DomHelper { inputElement.onError.first.then((Event event) { final error = event as ErrorEvent; - final platformException = PlatformException( - code: error.type, - message: error.message, - ); + final platformException = PlatformException(code: error.type, message: error.message); inputElement.remove(); completer.completeError(platformException); }); diff --git a/packages/file_selector/file_selector_web/test/utils_test.dart b/packages/file_selector/file_selector_web/test/utils_test.dart index 33d76d4380ec..afc509ae95de 100644 --- a/packages/file_selector/file_selector_web/test/utils_test.dart +++ b/packages/file_selector/file_selector_web/test/utils_test.dart @@ -39,10 +39,7 @@ void main() { test('works with mime types', () { const acceptedTypes = [ - XTypeGroup( - label: 'jpgs', - mimeTypes: ['image/jpeg', 'image/jpg'], - ), + XTypeGroup(label: 'jpgs', mimeTypes: ['image/jpeg', 'image/jpg']), XTypeGroup(label: 'pngs', mimeTypes: ['image/png']), ]; final String accepts = acceptedTypesToString(acceptedTypes); @@ -61,10 +58,7 @@ void main() { test('throws for a type group that does not support web', () { const acceptedTypes = [ - XTypeGroup( - label: 'text', - uniformTypeIdentifiers: ['public.text'], - ), + XTypeGroup(label: 'text', uniformTypeIdentifiers: ['public.text']), ]; expect(() => acceptedTypesToString(acceptedTypes), throwsArgumentError); }); diff --git a/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart b/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart index 4e3fa8651920..718f67dc1f85 100644 --- a/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/get_directory_page.dart @@ -13,10 +13,9 @@ class GetDirectoryPage extends StatelessWidget { Future _getDirectoryPath(BuildContext context) async { const confirmButtonText = 'Choose'; - final String? directoryPath = await FileSelectorPlatform.instance - .getDirectoryPathWithOptions( - const FileDialogOptions(confirmButtonText: confirmButtonText), - ); + final String? directoryPath = await FileSelectorPlatform.instance.getDirectoryPathWithOptions( + const FileDialogOptions(confirmButtonText: confirmButtonText), + ); if (directoryPath == null) { // Operation was canceled by the user. return; @@ -64,14 +63,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directory'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoryPath)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPath))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart b/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart index a4d751e798cc..5abe62a4d99e 100644 --- a/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/get_multiple_directories_page.dart @@ -24,8 +24,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { if (context.mounted) { await showDialog( context: context, - builder: (BuildContext context) => - TextDisplay(directoriesPaths.join('\n')), + builder: (BuildContext context) => TextDisplay(directoriesPaths.join('\n')), ); } } @@ -43,9 +42,7 @@ class GetMultipleDirectoriesPage extends StatelessWidget { backgroundColor: Colors.blue, foregroundColor: Colors.white, ), - child: const Text( - 'Press to ask user to choose multiple directories', - ), + child: const Text('Press to ask user to choose multiple directories'), onPressed: () => _getDirectoryPaths(context), ), ], @@ -67,14 +64,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: const Text('Selected Directories'), - content: Scrollbar( - child: SingleChildScrollView(child: Text(directoryPaths)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(directoryPaths))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_windows/example/lib/home_page.dart b/packages/file_selector/file_selector_windows/example/lib/home_page.dart index b49884852ba7..f90d366432e8 100644 --- a/packages/file_selector/file_selector_windows/example/lib/home_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/home_page.dart @@ -54,8 +54,7 @@ class HomePage extends StatelessWidget { ElevatedButton( style: style, child: const Text('Open a get directories dialog'), - onPressed: () => - Navigator.pushNamed(context, '/multi-directories'), + onPressed: () => Navigator.pushNamed(context, '/multi-directories'), ), ], ), diff --git a/packages/file_selector/file_selector_windows/example/lib/main.dart b/packages/file_selector/file_selector_windows/example/lib/main.dart index 28a342002746..4fefa8b6b35b 100644 --- a/packages/file_selector/file_selector_windows/example/lib/main.dart +++ b/packages/file_selector/file_selector_windows/example/lib/main.dart @@ -32,13 +32,11 @@ class MyApp extends StatelessWidget { home: const HomePage(), routes: { '/open/image': (BuildContext context) => const OpenImagePage(), - '/open/images': (BuildContext context) => - const OpenMultipleImagesPage(), + '/open/images': (BuildContext context) => const OpenMultipleImagesPage(), '/open/text': (BuildContext context) => const OpenTextPage(), '/save/text': (BuildContext context) => SaveTextPage(), '/directory': (BuildContext context) => const GetDirectoryPage(), - '/multi-directories': (BuildContext context) => - const GetMultipleDirectoriesPage(), + '/multi-directories': (BuildContext context) => const GetMultipleDirectoriesPage(), }, ); } diff --git a/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart b/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart index 6554cbfb8b8e..5983fa524649 100644 --- a/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/open_image_page.dart @@ -15,10 +15,7 @@ class OpenImagePage extends StatelessWidget { const OpenImagePage({super.key}); Future _openImageFile(BuildContext context) async { - const typeGroup = XTypeGroup( - label: 'images', - extensions: ['jpg', 'png'], - ); + const typeGroup = XTypeGroup(label: 'images', extensions: ['jpg', 'png']); final XFile? file = await FileSelectorPlatform.instance.openFile( acceptedTypeGroups: [typeGroup], ); diff --git a/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart b/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart index da7e3076c2ad..da35dc55df68 100644 --- a/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/open_multiple_images_page.dart @@ -15,10 +15,7 @@ class OpenMultipleImagesPage extends StatelessWidget { const OpenMultipleImagesPage({super.key}); Future _openImageFile(BuildContext context) async { - const jpgsTypeGroup = XTypeGroup( - label: 'JPEGs', - extensions: ['jpg', 'jpeg'], - ); + const jpgsTypeGroup = XTypeGroup(label: 'JPEGs', extensions: ['jpg', 'jpeg']); const pngTypeGroup = XTypeGroup(label: 'PNGs', extensions: ['png']); final List files = await FileSelectorPlatform.instance.openFiles( acceptedTypeGroups: [jpgsTypeGroup, pngTypeGroup], @@ -76,11 +73,8 @@ class MultipleImagesDisplay extends StatelessWidget { child: Row( children: [ ...files.map( - (XFile file) => Flexible( - child: kIsWeb - ? Image.network(file.path) - : Image.file(File(file.path)), - ), + (XFile file) => + Flexible(child: kIsWeb ? Image.network(file.path) : Image.file(File(file.path))), ), ], ), diff --git a/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart b/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart index 023cd8c03a79..5b5abbce9ae4 100644 --- a/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/open_text_page.dart @@ -12,10 +12,7 @@ class OpenTextPage extends StatelessWidget { const OpenTextPage({super.key}); Future _openTextFile(BuildContext context) async { - const typeGroup = XTypeGroup( - label: 'text', - extensions: ['txt', 'json'], - ); + const typeGroup = XTypeGroup(label: 'text', extensions: ['txt', 'json']); final XFile? file = await FileSelectorPlatform.instance.openFile( acceptedTypeGroups: [typeGroup], ); @@ -72,14 +69,9 @@ class TextDisplay extends StatelessWidget { Widget build(BuildContext context) { return AlertDialog( title: Text(fileName), - content: Scrollbar( - child: SingleChildScrollView(child: Text(fileContent)), - ), + content: Scrollbar(child: SingleChildScrollView(child: Text(fileContent))), actions: [ - TextButton( - child: const Text('Close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('Close'), onPressed: () => Navigator.pop(context)), ], ); } diff --git a/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart b/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart index ff45a7c969f1..0d467b8c12a7 100644 --- a/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart +++ b/packages/file_selector/file_selector_windows/example/lib/save_text_page.dart @@ -18,14 +18,13 @@ class SaveTextPage extends StatelessWidget { Future _saveFile() async { final String fileName = _nameController.text; - final FileSaveLocation? result = await FileSelectorPlatform.instance - .getSaveLocation( - options: SaveDialogOptions(suggestedName: fileName), - acceptedTypeGroups: const [ - XTypeGroup(label: 'Plain text', extensions: ['txt']), - XTypeGroup(label: 'JSON', extensions: ['json']), - ], - ); + final FileSaveLocation? result = await FileSelectorPlatform.instance.getSaveLocation( + options: SaveDialogOptions(suggestedName: fileName), + acceptedTypeGroups: const [ + XTypeGroup(label: 'Plain text', extensions: ['txt']), + XTypeGroup(label: 'JSON', extensions: ['json']), + ], + ); // Operation was canceled by the user. if (result == null) { return; @@ -61,9 +60,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _nameController, - decoration: const InputDecoration( - hintText: '(Optional) Suggest File Name', - ), + decoration: const InputDecoration(hintText: '(Optional) Suggest File Name'), ), ), SizedBox( @@ -72,9 +69,7 @@ class SaveTextPage extends StatelessWidget { minLines: 1, maxLines: 12, controller: _contentController, - decoration: const InputDecoration( - hintText: 'Enter File Contents', - ), + decoration: const InputDecoration(hintText: 'Enter File Contents'), ), ), const SizedBox(height: 10), diff --git a/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart b/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart index fe5b7a963622..444d0fe3ee1a 100644 --- a/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart +++ b/packages/file_selector/file_selector_windows/lib/file_selector_windows.dart @@ -27,9 +27,7 @@ class FileSelectorWindows extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileDialogResult result = await _hostApi.showOpenDialog( - SelectionOptions( - allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), - ), + SelectionOptions(allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups)), initialDirectory, confirmButtonText, ); @@ -77,9 +75,7 @@ class FileSelectorWindows extends FileSelectorPlatform { SaveDialogOptions options = const SaveDialogOptions(), }) async { final FileDialogResult result = await _hostApi.showSaveDialog( - SelectionOptions( - allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups), - ), + SelectionOptions(allowedTypes: _typeGroupsFromXTypeGroups(acceptedTypeGroups)), options.initialDirectory, options.suggestedName, options.confirmButtonText, @@ -89,17 +85,12 @@ class FileSelectorWindows extends FileSelectorPlatform { ? null : FileSaveLocation( result.paths.first, - activeFilter: groupIndex == null - ? null - : acceptedTypeGroups?[groupIndex], + activeFilter: groupIndex == null ? null : acceptedTypeGroups?[groupIndex], ); } @override - Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) async { + Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) async { final FileDialogResult result = await _hostApi.showOpenDialog( SelectionOptions(selectFolders: true, allowedTypes: []), initialDirectory, @@ -114,11 +105,7 @@ class FileSelectorWindows extends FileSelectorPlatform { String? confirmButtonText, }) async { final FileDialogResult result = await _hostApi.showOpenDialog( - SelectionOptions( - allowMultiple: true, - selectFolders: true, - allowedTypes: [], - ), + SelectionOptions(allowMultiple: true, selectFolders: true, allowedTypes: []), initialDirectory, confirmButtonText, ); @@ -136,9 +123,6 @@ List _typeGroupsFromXTypeGroups(List? xtypes) { 'anything is non-empty.', ); } - return TypeGroup( - label: xtype.label ?? '', - extensions: xtype.extensions ?? [], - ); + return TypeGroup(label: xtype.label ?? '', extensions: xtype.extensions ?? []); }).toList(); } diff --git a/packages/file_selector/file_selector_windows/lib/src/messages.g.dart b/packages/file_selector/file_selector_windows/lib/src/messages.g.dart index 7e2ec3e4244a..633c2a1cf3ed 100644 --- a/packages/file_selector/file_selector_windows/lib/src/messages.g.dart +++ b/packages/file_selector/file_selector_windows/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -211,13 +209,11 @@ class FileSelectorApi { /// Constructor for [FileSelectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - FileSelectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + FileSelectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -231,17 +227,17 @@ class FileSelectorApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showOpenDialog$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [options, initialDirectory, confirmButtonText], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + options, + initialDirectory, + confirmButtonText, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -268,17 +264,18 @@ class FileSelectorApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.file_selector_windows.FileSelectorApi.showSaveDialog$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [options, initialDirectory, suggestedName, confirmButtonText], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + options, + initialDirectory, + suggestedName, + confirmButtonText, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart b/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart index 30349f956f75..ed31ed627d69 100644 --- a/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart +++ b/packages/file_selector/file_selector_windows/test/file_selector_windows_test.dart @@ -75,10 +75,7 @@ void main() { }); test('throws for a type group that does not support Windows', () async { - const group = XTypeGroup( - label: 'text', - mimeTypes: ['text/plain'], - ); + const group = XTypeGroup(label: 'text', mimeTypes: ['text/plain']); await expectLater( plugin.openFile(acceptedTypeGroups: [group]), @@ -89,10 +86,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.openFile(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.openFile(acceptedTypeGroups: [group]), completes); }); }); @@ -147,10 +141,7 @@ void main() { }); test('throws for a type group that does not support Windows', () async { - const group = XTypeGroup( - label: 'text', - mimeTypes: ['text/plain'], - ); + const group = XTypeGroup(label: 'text', mimeTypes: ['text/plain']); await expectLater( plugin.openFiles(acceptedTypeGroups: [group]), @@ -161,10 +152,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.openFiles(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.openFiles(acceptedTypeGroups: [group]), completes); }); }); @@ -248,9 +236,7 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin.getSaveLocation( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.getSaveLocation(acceptedTypeGroups: [group, groupTwo]); expect( _typeGroupListsMatch(api.passedOptions!.allowedTypes, [ @@ -285,18 +271,14 @@ void main() { test('passes initialDirectory correctly', () async { await plugin.getSaveLocation( - options: const SaveDialogOptions( - initialDirectory: '/example/directory', - ), + options: const SaveDialogOptions(initialDirectory: '/example/directory'), ); expect(api.passedInitialDirectory, '/example/directory'); }); test('passes suggestedName correctly', () async { - await plugin.getSaveLocation( - options: const SaveDialogOptions(suggestedName: 'baz.txt'), - ); + await plugin.getSaveLocation(options: const SaveDialogOptions(suggestedName: 'baz.txt')); expect(api.passedSuggestedName, 'baz.txt'); }); @@ -310,10 +292,7 @@ void main() { }); test('throws for a type group that does not support Windows', () async { - const group = XTypeGroup( - label: 'text', - mimeTypes: ['text/plain'], - ); + const group = XTypeGroup(label: 'text', mimeTypes: ['text/plain']); await expectLater( plugin.getSaveLocation(acceptedTypeGroups: [group]), @@ -324,10 +303,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.getSaveLocation(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.getSaveLocation(acceptedTypeGroups: [group]), completes); }); }); @@ -357,9 +333,7 @@ void main() { mimeTypes: ['image/jpg'], ); - await plugin.getSavePath( - acceptedTypeGroups: [group, groupTwo], - ); + await plugin.getSavePath(acceptedTypeGroups: [group, groupTwo]); expect( _typeGroupListsMatch(api.passedOptions!.allowedTypes, [ @@ -389,10 +363,7 @@ void main() { }); test('throws for a type group that does not support Windows', () async { - const group = XTypeGroup( - label: 'text', - mimeTypes: ['text/plain'], - ); + const group = XTypeGroup(label: 'text', mimeTypes: ['text/plain']); await expectLater( plugin.getSavePath(acceptedTypeGroups: [group]), @@ -403,10 +374,7 @@ void main() { test('allows a wildcard group', () async { const group = XTypeGroup(label: 'text'); - await expectLater( - plugin.getSavePath(acceptedTypeGroups: [group]), - completes, - ); + await expectLater(plugin.getSavePath(acceptedTypeGroups: [group]), completes); }); }); } @@ -453,10 +421,7 @@ class FakeFileSelectorApi implements FileSelectorApi { passedInitialDirectory = initialDirectory; passedConfirmButtonText = confirmButtonText; passedOptions = options; - return FileDialogResult( - paths: result, - typeGroupIndex: resultTypeGroupIndex, - ); + return FileDialogResult(paths: result, typeGroupIndex: resultTypeGroupIndex); } @override @@ -470,10 +435,7 @@ class FakeFileSelectorApi implements FileSelectorApi { passedConfirmButtonText = confirmButtonText; passedSuggestedName = suggestedName; passedOptions = options; - return FileDialogResult( - paths: result, - typeGroupIndex: resultTypeGroupIndex, - ); + return FileDialogResult(paths: result, typeGroupIndex: resultTypeGroupIndex); } @override diff --git a/packages/flutter_plugin_android_lifecycle/example/lib/main.dart b/packages/flutter_plugin_android_lifecycle/example/lib/main.dart index 0a0361bd3694..f3c4510d086a 100644 --- a/packages/flutter_plugin_android_lifecycle/example/lib/main.dart +++ b/packages/flutter_plugin_android_lifecycle/example/lib/main.dart @@ -15,9 +15,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Sample flutter_plugin_android_lifecycle usage'), - ), + appBar: AppBar(title: const Text('Sample flutter_plugin_android_lifecycle usage')), body: const Center( child: Text( 'This plugin only provides Android Lifecycle API\n for other Android plugins.', diff --git a/packages/go_router/example/lib/async_redirection.dart b/packages/go_router/example/lib/async_redirection.dart index b36de3b190db..bf59ead30dfd 100644 --- a/packages/go_router/example/lib/async_redirection.dart +++ b/packages/go_router/example/lib/async_redirection.dart @@ -29,23 +29,18 @@ class App extends StatelessWidget { // add the login info into the tree as app state that can change over time @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - debugShowCheckedModeBanner: false, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title, debugShowCheckedModeBanner: false); late final GoRouter _router = GoRouter( routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], @@ -81,19 +76,17 @@ class LoginScreen extends StatefulWidget { State createState() => _LoginScreenState(); } -class _LoginScreenState extends State - with TickerProviderStateMixin { +class _LoginScreenState extends State with TickerProviderStateMixin { bool loggingIn = false; late final AnimationController controller; @override void initState() { super.initState(); - controller = - AnimationController(vsync: this, duration: const Duration(seconds: 1)) - ..addListener(() { - setState(() {}); - }); + controller = AnimationController(vsync: this, duration: const Duration(seconds: 1)) + ..addListener(() { + setState(() {}); + }); controller.repeat(); } @@ -155,15 +148,11 @@ class HomeScreen extends StatelessWidget { /// A scope that provides [StreamAuth] for the subtree. class StreamAuthScope extends InheritedNotifier { /// Creates a [StreamAuthScope] sign in scope. - StreamAuthScope({super.key, required super.child}) - : super(notifier: StreamAuthNotifier()); + StreamAuthScope({super.key, required super.child}) : super(notifier: StreamAuthNotifier()); /// Gets the [StreamAuth]. static StreamAuth of(BuildContext context) { - return context - .dependOnInheritedWidgetOfExactType()! - .notifier! - .streamAuth; + return context.dependOnInheritedWidgetOfExactType()!.notifier!.streamAuth; } } diff --git a/packages/go_router/example/lib/books/main.dart b/packages/go_router/example/lib/books/main.dart index 083ce3737868..97cb658cd5e1 100644 --- a/packages/go_router/example/lib/books/main.dart +++ b/packages/go_router/example/lib/books/main.dart @@ -28,10 +28,8 @@ class Bookstore extends StatelessWidget { final ValueKey _scaffoldKey = const ValueKey('App scaffold'); @override - Widget build(BuildContext context) => BookstoreAuthScope( - notifier: _auth, - child: MaterialApp.router(routerConfig: _router), - ); + Widget build(BuildContext context) => + BookstoreAuthScope(notifier: _auth, child: MaterialApp.router(routerConfig: _router)); final BookstoreAuth _auth = BookstoreAuth(); @@ -40,14 +38,12 @@ class Bookstore extends StatelessWidget { GoRoute(path: '/', redirect: (_, __) => '/books'), GoRoute( path: '/signin', - pageBuilder: (BuildContext context, GoRouterState state) => - FadeTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( key: state.pageKey, child: SignInScreen( onSignIn: (Credentials credentials) { - BookstoreAuthScope.of( - context, - ).signIn(credentials.username, credentials.password); + BookstoreAuthScope.of(context).signIn(credentials.username, credentials.password); }, ), ), @@ -55,13 +51,14 @@ class Bookstore extends StatelessWidget { GoRoute(path: '/books', redirect: (_, __) => '/books/popular'), GoRoute( path: '/book/:bookId', - redirect: (BuildContext context, GoRouterState state) => - '/books/all/${state.pathParameters['bookId']}', + redirect: + (BuildContext context, GoRouterState state) => + '/books/all/${state.pathParameters['bookId']}', ), GoRoute( path: '/books/:kind(new|all|popular)', - pageBuilder: (BuildContext context, GoRouterState state) => - FadeTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( key: _scaffoldKey, child: BookstoreScaffold( selectedTab: ScaffoldTab.books, @@ -73,8 +70,9 @@ class Bookstore extends StatelessWidget { path: ':bookId', builder: (BuildContext context, GoRouterState state) { final String bookId = state.pathParameters['bookId']!; - final Book? selectedBook = libraryInstance.allBooks - .firstWhereOrNull((Book b) => b.id.toString() == bookId); + final Book? selectedBook = libraryInstance.allBooks.firstWhereOrNull( + (Book b) => b.id.toString() == bookId, + ); return BookDetailsScreen(book: selectedBook); }, @@ -83,13 +81,14 @@ class Bookstore extends StatelessWidget { ), GoRoute( path: '/author/:authorId', - redirect: (BuildContext context, GoRouterState state) => - '/authors/${state.pathParameters['authorId']}', + redirect: + (BuildContext context, GoRouterState state) => + '/authors/${state.pathParameters['authorId']}', ), GoRoute( path: '/authors', - pageBuilder: (BuildContext context, GoRouterState state) => - FadeTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( key: _scaffoldKey, child: const BookstoreScaffold( selectedTab: ScaffoldTab.authors, @@ -101,8 +100,9 @@ class Bookstore extends StatelessWidget { path: ':authorId', builder: (BuildContext context, GoRouterState state) { final int authorId = int.parse(state.pathParameters['authorId']!); - final Author? selectedAuthor = libraryInstance.allAuthors - .firstWhereOrNull((Author a) => a.id == authorId); + final Author? selectedAuthor = libraryInstance.allAuthors.firstWhereOrNull( + (Author a) => a.id == authorId, + ); return AuthorDetailsScreen(author: selectedAuthor); }, @@ -111,8 +111,8 @@ class Bookstore extends StatelessWidget { ), GoRoute( path: '/settings', - pageBuilder: (BuildContext context, GoRouterState state) => - FadeTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => FadeTransitionPage( key: _scaffoldKey, child: const BookstoreScaffold( selectedTab: ScaffoldTab.settings, @@ -155,10 +155,7 @@ class FadeTransitionPage extends CustomTransitionPage { Animation animation, Animation secondaryAnimation, Widget child, - ) => FadeTransition( - opacity: animation.drive(_curveTween), - child: child, - ), + ) => FadeTransition(opacity: animation.drive(_curveTween), child: child), ); static final CurveTween _curveTween = CurveTween(curve: Curves.easeIn); diff --git a/packages/go_router/example/lib/books/src/auth.dart b/packages/go_router/example/lib/books/src/auth.dart index 65a9a470d98d..0e3e154a25c2 100644 --- a/packages/go_router/example/lib/books/src/auth.dart +++ b/packages/go_router/example/lib/books/src/auth.dart @@ -40,7 +40,6 @@ class BookstoreAuthScope extends InheritedNotifier { }); /// Gets the [BookstoreAuth] above the context. - static BookstoreAuth of(BuildContext context) => context - .dependOnInheritedWidgetOfExactType()! - .notifier!; + static BookstoreAuth of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()!.notifier!; } diff --git a/packages/go_router/example/lib/books/src/data/library.dart b/packages/go_router/example/lib/books/src/data/library.dart index 769b078e29b5..72b7dd7fd8fe 100644 --- a/packages/go_router/example/lib/books/src/data/library.dart +++ b/packages/go_router/example/lib/books/src/data/library.dart @@ -6,31 +6,27 @@ import 'author.dart'; import 'book.dart'; /// Library data mock. -final Library libraryInstance = Library() - ..addBook( - title: 'Left Hand of Darkness', - authorName: 'Ursula K. Le Guin', - isPopular: true, - isNew: true, - ) - ..addBook( - title: 'Too Like the Lightning', - authorName: 'Ada Palmer', - isPopular: false, - isNew: true, - ) - ..addBook( - title: 'Kindred', - authorName: 'Octavia E. Butler', - isPopular: true, - isNew: false, - ) - ..addBook( - title: 'The Lathe of Heaven', - authorName: 'Ursula K. Le Guin', - isPopular: false, - isNew: false, - ); +final Library libraryInstance = + Library() + ..addBook( + title: 'Left Hand of Darkness', + authorName: 'Ursula K. Le Guin', + isPopular: true, + isNew: true, + ) + ..addBook( + title: 'Too Like the Lightning', + authorName: 'Ada Palmer', + isPopular: false, + isNew: true, + ) + ..addBook(title: 'Kindred', authorName: 'Octavia E. Butler', isPopular: true, isNew: false) + ..addBook( + title: 'The Lathe of Heaven', + authorName: 'Ursula K. Le Guin', + isPopular: false, + isNew: false, + ); /// A library that contains books and authors. class Library { @@ -69,12 +65,8 @@ class Library { } /// The list of popular books in the library. - List get popularBooks => [ - ...allBooks.where((Book book) => book.isPopular), - ]; + List get popularBooks => [...allBooks.where((Book book) => book.isPopular)]; /// The list of new books in the library. - List get newBooks => [ - ...allBooks.where((Book book) => book.isNew), - ]; + List get newBooks => [...allBooks.where((Book book) => book.isNew)]; } diff --git a/packages/go_router/example/lib/books/src/screens/book_details.dart b/packages/go_router/example/lib/books/src/screens/book_details.dart index 83626824f2fc..384be0e46a90 100644 --- a/packages/go_router/example/lib/books/src/screens/book_details.dart +++ b/packages/go_router/example/lib/books/src/screens/book_details.dart @@ -27,20 +27,13 @@ class BookDetailsScreen extends StatelessWidget { body: Center( child: Column( children: [ - Text( - book!.title, - style: Theme.of(context).textTheme.headlineMedium, - ), - Text( - book!.author.name, - style: Theme.of(context).textTheme.titleMedium, - ), + Text(book!.title, style: Theme.of(context).textTheme.headlineMedium), + Text(book!.author.name, style: Theme.of(context).textTheme.titleMedium), TextButton( onPressed: () { Navigator.of(context).push( MaterialPageRoute( - builder: (BuildContext context) => - AuthorDetailsScreen(author: book!.author), + builder: (BuildContext context) => AuthorDetailsScreen(author: book!.author), ), ); }, @@ -48,11 +41,9 @@ class BookDetailsScreen extends StatelessWidget { ), Link( uri: Uri.parse('/author/${book!.author.id}'), - builder: (BuildContext context, FollowLink? followLink) => - TextButton( - onPressed: followLink, - child: const Text('View author (Link)'), - ), + builder: + (BuildContext context, FollowLink? followLink) => + TextButton(onPressed: followLink, child: const Text('View author (Link)')), ), TextButton( onPressed: () { diff --git a/packages/go_router/example/lib/books/src/screens/books.dart b/packages/go_router/example/lib/books/src/screens/books.dart index 56e1e2b2d4df..3bee36aeff19 100644 --- a/packages/go_router/example/lib/books/src/screens/books.dart +++ b/packages/go_router/example/lib/books/src/screens/books.dart @@ -20,8 +20,7 @@ class BooksScreen extends StatefulWidget { State createState() => _BooksScreenState(); } -class _BooksScreenState extends State - with SingleTickerProviderStateMixin { +class _BooksScreenState extends State with SingleTickerProviderStateMixin { late TabController _tabController; @override diff --git a/packages/go_router/example/lib/books/src/screens/scaffold.dart b/packages/go_router/example/lib/books/src/screens/scaffold.dart index e32963cbfbb0..633fea090d75 100644 --- a/packages/go_router/example/lib/books/src/screens/scaffold.dart +++ b/packages/go_router/example/lib/books/src/screens/scaffold.dart @@ -22,11 +22,7 @@ enum ScaffoldTab { /// The scaffold for the book store. class BookstoreScaffold extends StatelessWidget { /// Creates a [BookstoreScaffold]. - const BookstoreScaffold({ - required this.selectedTab, - required this.child, - super.key, - }); + const BookstoreScaffold({required this.selectedTab, required this.child, super.key}); /// Which tab of the scaffold to display. final ScaffoldTab selectedTab; diff --git a/packages/go_router/example/lib/books/src/screens/settings.dart b/packages/go_router/example/lib/books/src/screens/settings.dart index 4b0a386f2436..739eb840267d 100644 --- a/packages/go_router/example/lib/books/src/screens/settings.dart +++ b/packages/go_router/example/lib/books/src/screens/settings.dart @@ -57,10 +57,11 @@ class SettingsContent extends StatelessWidget { ), Link( uri: Uri.parse('/book/0'), - builder: (BuildContext context, FollowLink? followLink) => TextButton( - onPressed: followLink, - child: const Text('Go directly to /book/0 (Link)'), - ), + builder: + (BuildContext context, FollowLink? followLink) => TextButton( + onPressed: followLink, + child: const Text('Go directly to /book/0 (Link)'), + ), ), TextButton( onPressed: () { @@ -68,27 +69,27 @@ class SettingsContent extends StatelessWidget { }, child: const Text('Go directly to /book/0 (GoRouter)'), ), - ].map( - (Widget w) => Padding(padding: const EdgeInsets.all(8), child: w), - ), + ].map((Widget w) => Padding(padding: const EdgeInsets.all(8), child: w)), TextButton( - onPressed: () => showDialog( - context: context, - builder: (BuildContext context) => AlertDialog( - title: const Text('Alert!'), - content: const Text('The alert description goes here.'), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context, 'Cancel'), - child: const Text('Cancel'), - ), - TextButton( - onPressed: () => Navigator.pop(context, 'OK'), - child: const Text('OK'), - ), - ], - ), - ), + onPressed: + () => showDialog( + context: context, + builder: + (BuildContext context) => AlertDialog( + title: const Text('Alert!'), + content: const Text('The alert description goes here.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'Cancel'), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ), child: const Text('Show Dialog'), ), ], diff --git a/packages/go_router/example/lib/books/src/screens/sign_in.dart b/packages/go_router/example/lib/books/src/screens/sign_in.dart index 9d2c209a8886..07c0110b77af 100644 --- a/packages/go_router/example/lib/books/src/screens/sign_in.dart +++ b/packages/go_router/example/lib/books/src/screens/sign_in.dart @@ -43,10 +43,7 @@ class _SignInScreenState extends State { mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ - Text( - 'Sign in', - style: Theme.of(context).textTheme.headlineMedium, - ), + Text('Sign in', style: Theme.of(context).textTheme.headlineMedium), TextField( decoration: const InputDecoration(labelText: 'Username'), controller: _usernameController, @@ -61,10 +58,7 @@ class _SignInScreenState extends State { child: TextButton( onPressed: () async { widget.onSignIn( - Credentials( - _usernameController.value.text, - _passwordController.value.text, - ), + Credentials(_usernameController.value.text, _passwordController.value.text), ); }, child: const Text('Sign in'), diff --git a/packages/go_router/example/lib/books/src/widgets/author_list.dart b/packages/go_router/example/lib/books/src/widgets/author_list.dart index 1cfb22014e9e..855cd5f1b371 100644 --- a/packages/go_router/example/lib/books/src/widgets/author_list.dart +++ b/packages/go_router/example/lib/books/src/widgets/author_list.dart @@ -20,10 +20,11 @@ class AuthorList extends StatelessWidget { @override Widget build(BuildContext context) => ListView.builder( itemCount: authors.length, - itemBuilder: (BuildContext context, int index) => ListTile( - title: Text(authors[index].name), - subtitle: Text('${authors[index].books.length} books'), - onTap: onTap != null ? () => onTap!(authors[index]) : null, - ), + itemBuilder: + (BuildContext context, int index) => ListTile( + title: Text(authors[index].name), + subtitle: Text('${authors[index].books.length} books'), + onTap: onTap != null ? () => onTap!(authors[index]) : null, + ), ); } diff --git a/packages/go_router/example/lib/books/src/widgets/book_list.dart b/packages/go_router/example/lib/books/src/widgets/book_list.dart index 3c78b6655911..330e4b2e983d 100644 --- a/packages/go_router/example/lib/books/src/widgets/book_list.dart +++ b/packages/go_router/example/lib/books/src/widgets/book_list.dart @@ -20,10 +20,11 @@ class BookList extends StatelessWidget { @override Widget build(BuildContext context) => ListView.builder( itemCount: books.length, - itemBuilder: (BuildContext context, int index) => ListTile( - title: Text(books[index].title), - subtitle: Text(books[index].author.name), - onTap: onTap != null ? () => onTap!(books[index]) : null, - ), + itemBuilder: + (BuildContext context, int index) => ListTile( + title: Text(books[index].title), + subtitle: Text(books[index].author.name), + onTap: onTap != null ? () => onTap!(books[index]) : null, + ), ); } diff --git a/packages/go_router/example/lib/extra_codec.dart b/packages/go_router/example/lib/extra_codec.dart index a273b8cf0c6a..a8e53f080e56 100644 --- a/packages/go_router/example/lib/extra_codec.dart +++ b/packages/go_router/example/lib/extra_codec.dart @@ -13,11 +13,7 @@ void main() => runApp(const MyApp()); /// The router configuration. final GoRouter _router = GoRouter( routes: [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), + GoRoute(path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen()), ], extraCodec: const MyExtraCodec(), ); @@ -49,9 +45,7 @@ class HomeScreen extends StatelessWidget { const Text( "If running in web, use the browser's backward and forward button to test extra codec after setting extra several times.", ), - Text( - 'The extra for this page is: ${GoRouterState.of(context).extra}', - ), + Text('The extra for this page is: ${GoRouterState.of(context).extra}'), ElevatedButton( onPressed: () => context.go('/', extra: ComplexData1('data')), child: const Text('Set extra to ComplexData1'), diff --git a/packages/go_router/example/lib/named_routes.dart b/packages/go_router/example/lib/named_routes.dart index 4223486f019a..df9f36d1c53c 100644 --- a/packages/go_router/example/lib/named_routes.dart +++ b/packages/go_router/example/lib/named_routes.dart @@ -65,11 +65,8 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Named Routes'; @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - debugShowCheckedModeBanner: false, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title, debugShowCheckedModeBanner: false); late final GoRouter _router = GoRouter( debugLogDiagnostics: true, @@ -77,14 +74,14 @@ class App extends StatelessWidget { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(fid: state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(fid: state.pathParameters['fid']!), routes: [ GoRoute( name: 'person', @@ -118,12 +115,13 @@ class HomeScreen extends StatelessWidget { for (final MapEntry entry in _families.entries) ListTile( title: Text(entry.value.name), - onTap: () => context.go( - context.namedLocation( - 'family', - pathParameters: {'fid': entry.key}, - ), - ), + onTap: + () => context.go( + context.namedLocation( + 'family', + pathParameters: {'fid': entry.key}, + ), + ), ), ], ), @@ -149,16 +147,14 @@ class FamilyScreen extends StatelessWidget { for (final MapEntry entry in people.entries) ListTile( title: Text(entry.value.name), - onTap: () => context.go( - context.namedLocation( - 'person', - pathParameters: { - 'fid': fid, - 'pid': entry.key, - }, - queryParameters: {'qid': 'quid'}, - ), - ), + onTap: + () => context.go( + context.namedLocation( + 'person', + pathParameters: {'fid': fid, 'pid': entry.key}, + queryParameters: {'qid': 'quid'}, + ), + ), ), ], ), diff --git a/packages/go_router/example/lib/others/custom_stateful_shell_route.dart b/packages/go_router/example/lib/others/custom_stateful_shell_route.dart index 0755d2bf3307..80587d43f4e8 100644 --- a/packages/go_router/example/lib/others/custom_stateful_shell_route.dart +++ b/packages/go_router/example/lib/others/custom_stateful_shell_route.dart @@ -7,9 +7,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = GlobalKey( - debugLabel: 'root', -); +final GlobalKey _rootNavigatorKey = GlobalKey(debugLabel: 'root'); final GlobalKey _tabANavigatorKey = GlobalKey( debugLabel: 'tabANav', ); @@ -25,8 +23,9 @@ final GlobalKey _tabB2NavigatorKey = GlobalKey( @visibleForTesting // ignore: public_member_api_docs -final GlobalKey tabbedRootScreenKey = - GlobalKey(debugLabel: 'TabbedRootScreen'); +final GlobalKey tabbedRootScreenKey = GlobalKey( + debugLabel: 'TabbedRootScreen', +); // This example demonstrates how to setup nested navigation using a // BottomNavigationBar, where each bar item uses its own persistent navigator, @@ -50,38 +49,33 @@ class NestedTabNavigationExampleApp extends StatelessWidget { initialLocation: '/a', routes: [ StatefulShellRoute( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - // This nested StatefulShellRoute demonstrates the use of a - // custom container for the branch Navigators. In this implementation, - // no customization is done in the builder function (navigationShell - // itself is simply used as the Widget for the route). Instead, the - // navigatorContainerBuilder function below is provided to - // customize the container for the branch Navigators. - return navigationShell; - }, - navigatorContainerBuilder: - ( - BuildContext context, - StatefulNavigationShell navigationShell, - List children, - ) { - // Returning a customized container for the branch - // Navigators (i.e. the `List children` argument). - // - // See ScaffoldWithNavBar for more details on how the children - // are managed (using AnimatedBranchContainer). - return ScaffoldWithNavBar( - navigationShell: navigationShell, - children: children, - ); - // NOTE: To use a Cupertino version of ScaffoldWithNavBar, replace - // ScaffoldWithNavBar above with CupertinoScaffoldWithNavBar. - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + // This nested StatefulShellRoute demonstrates the use of a + // custom container for the branch Navigators. In this implementation, + // no customization is done in the builder function (navigationShell + // itself is simply used as the Widget for the route). Instead, the + // navigatorContainerBuilder function below is provided to + // customize the container for the branch Navigators. + return navigationShell; + }, + navigatorContainerBuilder: ( + BuildContext context, + StatefulNavigationShell navigationShell, + List children, + ) { + // Returning a customized container for the branch + // Navigators (i.e. the `List children` argument). + // + // See ScaffoldWithNavBar for more details on how the children + // are managed (using AnimatedBranchContainer). + return ScaffoldWithNavBar(navigationShell: navigationShell, children: children); + // NOTE: To use a Cupertino version of ScaffoldWithNavBar, replace + // ScaffoldWithNavBar above with CupertinoScaffoldWithNavBar. + }, branches: [ // The route branch for the first tab of the bottom navigation bar. StatefulShellBranch( @@ -91,16 +85,16 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', - builder: (BuildContext context, GoRouterState state) => - const RootScreenA(), + builder: (BuildContext context, GoRouterState state) => const RootScreenA(), routes: [ // The details screen to display stacked on navigator of the // first tab. This will cover screen A but not the application // shell (bottom navigation bar). GoRoute( path: 'details', - builder: (BuildContext context, GoRouterState state) => - const DetailsScreen(label: 'A'), + builder: + (BuildContext context, GoRouterState state) => + const DetailsScreen(label: 'A'), ), ], ), @@ -120,35 +114,33 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // defaultLocation: '/b1', routes: [ StatefulShellRoute( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - // Just like with the top level StatefulShellRoute, no - // customization is done in the builder function. - return navigationShell; - }, - navigatorContainerBuilder: - ( - BuildContext context, - StatefulNavigationShell navigationShell, - List children, - ) { - // Returning a customized container for the branch - // Navigators (i.e. the `List children` argument). - // - // See TabbedRootScreen for more details on how the children - // are managed (in a TabBarView). - return TabbedRootScreen( - navigationShell: navigationShell, - key: tabbedRootScreenKey, - children: children, - ); - // NOTE: To use a PageView version of TabbedRootScreen, - // replace TabbedRootScreen above with PagedRootScreen. - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + // Just like with the top level StatefulShellRoute, no + // customization is done in the builder function. + return navigationShell; + }, + navigatorContainerBuilder: ( + BuildContext context, + StatefulNavigationShell navigationShell, + List children, + ) { + // Returning a customized container for the branch + // Navigators (i.e. the `List children` argument). + // + // See TabbedRootScreen for more details on how the children + // are managed (in a TabBarView). + return TabbedRootScreen( + navigationShell: navigationShell, + key: tabbedRootScreenKey, + children: children, + ); + // NOTE: To use a PageView version of TabbedRootScreen, + // replace TabbedRootScreen above with PagedRootScreen. + }, // This bottom tab uses a nested shell, wrapping sub routes in a // top TabBar. branches: [ @@ -157,20 +149,15 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ GoRoute( path: '/b1', - builder: (BuildContext context, GoRouterState state) => - const TabScreen( - label: 'B1', - detailsPath: '/b1/details', - ), + builder: + (BuildContext context, GoRouterState state) => + const TabScreen(label: 'B1', detailsPath: '/b1/details'), routes: [ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) => - const DetailsScreen( - label: 'B1', - withScaffold: false, - ), + const DetailsScreen(label: 'B1', withScaffold: false), ), ], ), @@ -184,20 +171,15 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ GoRoute( path: '/b2', - builder: (BuildContext context, GoRouterState state) => - const TabScreen( - label: 'B2', - detailsPath: '/b2/details', - ), + builder: + (BuildContext context, GoRouterState state) => + const TabScreen(label: 'B2', detailsPath: '/b2/details'), routes: [ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) => - const DetailsScreen( - label: 'B2', - withScaffold: false, - ), + const DetailsScreen(label: 'B2', withScaffold: false), ), ], ), @@ -226,11 +208,8 @@ class NestedTabNavigationExampleApp extends StatelessWidget { /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. - const ScaffoldWithNavBar({ - required this.navigationShell, - required this.children, - Key? key, - }) : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); + const ScaffoldWithNavBar({required this.navigationShell, required this.children, Key? key}) + : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); /// The navigation shell and container for the branch Navigators. final StatefulNavigationShell navigationShell; @@ -242,10 +221,7 @@ class ScaffoldWithNavBar extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - body: AnimatedBranchContainer( - currentIndex: navigationShell.currentIndex, - children: children, - ), + body: AnimatedBranchContainer(currentIndex: navigationShell.currentIndex, children: children), bottomNavigationBar: BottomNavigationBar( // Here, the items of BottomNavigationBar are hard coded. In a real // world scenario, the items would most likely be generated from the @@ -302,8 +278,7 @@ class CupertinoScaffoldWithNavBar extends StatefulWidget { State createState() => _CupertinoScaffoldWithNavBarState(); } -class _CupertinoScaffoldWithNavBarState - extends State { +class _CupertinoScaffoldWithNavBarState extends State { late final CupertinoTabController tabController = CupertinoTabController( initialIndex: widget.navigationShell.currentIndex, ); @@ -347,11 +322,7 @@ class _CupertinoScaffoldWithNavBarState /// when switching branches. class AnimatedBranchContainer extends StatelessWidget { /// Creates a AnimatedBranchContainer - const AnimatedBranchContainer({ - super.key, - required this.currentIndex, - required this.children, - }); + const AnimatedBranchContainer({super.key, required this.currentIndex, required this.children}); /// The index (in [children]) of the branch Navigator to display. final int currentIndex; @@ -362,17 +333,18 @@ class AnimatedBranchContainer extends StatelessWidget { @override Widget build(BuildContext context) { return Stack( - children: children.mapIndexed((int index, Widget navigator) { - return AnimatedScale( - scale: index == currentIndex ? 1 : 1.5, - duration: const Duration(milliseconds: 400), - child: AnimatedOpacity( - opacity: index == currentIndex ? 1 : 0, - duration: const Duration(milliseconds: 400), - child: _branchNavigatorWrapper(index, navigator), - ), - ); - }).toList(), + children: + children.mapIndexed((int index, Widget navigator) { + return AnimatedScale( + scale: index == currentIndex ? 1 : 1.5, + duration: const Duration(milliseconds: 400), + child: AnimatedOpacity( + opacity: index == currentIndex ? 1 : 0, + duration: const Duration(milliseconds: 400), + child: _branchNavigatorWrapper(index, navigator), + ), + ); + }).toList(), ); } @@ -413,12 +385,7 @@ class RootScreenA extends StatelessWidget { /// The details screen for either the A or B screen. class DetailsScreen extends StatefulWidget { /// Constructs a [DetailsScreen]. - const DetailsScreen({ - required this.label, - this.param, - this.withScaffold = true, - super.key, - }); + const DetailsScreen({required this.label, this.param, this.withScaffold = true, super.key}); /// The label to display in the center of the screen. final String label; @@ -445,10 +412,7 @@ class DetailsScreenState extends State { body: _build(context), ); } else { - return ColoredBox( - color: Theme.of(context).scaffoldBackgroundColor, - child: _build(context), - ); + return ColoredBox(color: Theme.of(context).scaffoldBackgroundColor, child: _build(context)); } } @@ -472,10 +436,7 @@ class DetailsScreenState extends State { ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) - Text( - 'Parameter: ${widget.param!}', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Parameter: ${widget.param!}', style: Theme.of(context).textTheme.titleMedium), const Padding(padding: EdgeInsets.all(8)), if (!widget.withScaffold) ...[ const Padding(padding: EdgeInsets.all(16)), @@ -498,11 +459,7 @@ class DetailsScreenState extends State { /// Builds a nested shell using a [TabBar] and [TabBarView]. class TabbedRootScreen extends StatefulWidget { /// Constructs a TabbedRootScreen - const TabbedRootScreen({ - required this.navigationShell, - required this.children, - super.key, - }); + const TabbedRootScreen({required this.navigationShell, required this.children, super.key}); /// The current state of the parent StatefulShellRoute. final StatefulNavigationShell navigationShell; @@ -516,8 +473,7 @@ class TabbedRootScreen extends StatefulWidget { @visibleForTesting // ignore: public_member_api_docs -class TabbedRootScreenState extends State - with SingleTickerProviderStateMixin { +class TabbedRootScreenState extends State with SingleTickerProviderStateMixin { @visibleForTesting // ignore: public_member_api_docs late final TabController tabController = TabController( @@ -553,15 +509,12 @@ class TabbedRootScreenState extends State @override Widget build(BuildContext context) { - final List tabs = widget.children - .mapIndexed((int i, _) => Tab(text: 'Tab ${i + 1}')) - .toList(); + final List tabs = + widget.children.mapIndexed((int i, _) => Tab(text: 'Tab ${i + 1}')).toList(); return Scaffold( appBar: AppBar( - title: Text( - 'Section B root (tab: ${widget.navigationShell.currentIndex + 1})', - ), + title: Text('Section B root (tab: ${widget.navigationShell.currentIndex + 1})'), bottom: TabBar( controller: tabController, tabs: tabs, @@ -583,11 +536,7 @@ class TabbedRootScreenState extends State class PagedRootScreen extends StatefulWidget { /// Constructs a PagedRootScreen // ignore: unreachable_from_main - const PagedRootScreen({ - required this.navigationShell, - required this.children, - super.key, - }); + const PagedRootScreen({required this.navigationShell, required this.children, super.key}); /// The current state of the parent StatefulShellRoute. // ignore: unreachable_from_main @@ -618,23 +567,15 @@ class _PagedRootScreenState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text( - 'Section B root (tab ${widget.navigationShell.currentIndex + 1})', - ), + title: Text('Section B root (tab ${widget.navigationShell.currentIndex + 1})'), ), body: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - ElevatedButton( - onPressed: () => _animateToPage(0), - child: const Text('Tab 1'), - ), - ElevatedButton( - onPressed: () => _animateToPage(1), - child: const Text('Tab 2'), - ), + ElevatedButton(onPressed: () => _animateToPage(0), child: const Text('Tab 1')), + ElevatedButton(onPressed: () => _animateToPage(1), child: const Text('Tab 2')), ], ), Expanded( diff --git a/packages/go_router/example/lib/others/error_screen.dart b/packages/go_router/example/lib/others/error_screen.dart index 27b30a956f02..b6ee48bf4c2e 100644 --- a/packages/go_router/example/lib/others/error_screen.dart +++ b/packages/go_router/example/lib/others/error_screen.dart @@ -16,24 +16,20 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Custom Error Screen'; @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: title); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: '/page2', - builder: (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => const Page2Screen(), ), ], - errorBuilder: (BuildContext context, GoRouterState state) => - ErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => ErrorScreen(state.error!), ); } @@ -49,10 +45,7 @@ class Page1Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), + ElevatedButton(onPressed: () => context.go('/page2'), child: const Text('Go to page 2')), ], ), ), @@ -71,10 +64,7 @@ class Page2Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), + ElevatedButton(onPressed: () => context.go('/'), child: const Text('Go to home page')), ], ), ), @@ -97,10 +87,7 @@ class ErrorScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ SelectableText(error.toString()), - TextButton( - onPressed: () => context.go('/'), - child: const Text('Home'), - ), + TextButton(onPressed: () => context.go('/'), child: const Text('Home')), ], ), ), diff --git a/packages/go_router/example/lib/others/extra_param.dart b/packages/go_router/example/lib/others/extra_param.dart index 0b0b2d5bc5e9..d6e1d13f263c 100644 --- a/packages/go_router/example/lib/others/extra_param.dart +++ b/packages/go_router/example/lib/others/extra_param.dart @@ -29,17 +29,11 @@ class Person { const Map _families = { 'f1': Family( name: 'Doe', - people: { - 'p1': Person(name: 'Jane'), - 'p2': Person(name: 'John'), - }, + people: {'p1': Person(name: 'Jane'), 'p2': Person(name: 'John')}, ), 'f2': Family( name: 'Wong', - people: { - 'p1': Person(name: 'June'), - 'p2': Person(name: 'Xin'), - }, + people: {'p1': Person(name: 'June'), 'p2': Person(name: 'Xin')}, ), }; @@ -54,23 +48,20 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Extra Parameter'; @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: title); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: title); late final GoRouter _router = GoRouter( routes: [ GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family', builder: (BuildContext context, GoRouterState state) { - final Map params = - state.extra! as Map; + final Map params = state.extra! as Map; final fid = params['fid']! as String; return FamilyScreen(fid: fid); }, @@ -94,10 +85,7 @@ class HomeScreen extends StatelessWidget { for (final MapEntry entry in _families.entries) ListTile( title: Text(entry.value.name), - onTap: () => context.goNamed( - 'family', - extra: {'fid': entry.key}, - ), + onTap: () => context.goNamed('family', extra: {'fid': entry.key}), ), ], ), @@ -118,9 +106,7 @@ class FamilyScreen extends StatelessWidget { return Scaffold( appBar: AppBar(title: Text(_families[fid]!.name)), body: ListView( - children: [ - for (final Person p in people.values) ListTile(title: Text(p.name)), - ], + children: [for (final Person p in people.values) ListTile(title: Text(p.name))], ), ); } diff --git a/packages/go_router/example/lib/others/init_loc.dart b/packages/go_router/example/lib/others/init_loc.dart index a980b8df6194..7c98b8ccd6e9 100644 --- a/packages/go_router/example/lib/others/init_loc.dart +++ b/packages/go_router/example/lib/others/init_loc.dart @@ -16,26 +16,22 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Initial Location'; @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: title); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( initialLocation: '/page3', routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: '/page2', - builder: (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => const Page2Screen(), ), GoRoute( path: '/page3', - builder: (BuildContext context, GoRouterState state) => - const Page3Screen(), + builder: (BuildContext context, GoRouterState state) => const Page3Screen(), ), ], ); @@ -53,10 +49,7 @@ class Page1Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), + ElevatedButton(onPressed: () => context.go('/page2'), child: const Text('Go to page 2')), ], ), ), @@ -75,10 +68,7 @@ class Page2Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), + ElevatedButton(onPressed: () => context.go('/'), child: const Text('Go to home page')), ], ), ), @@ -97,10 +87,7 @@ class Page3Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), + ElevatedButton(onPressed: () => context.go('/page2'), child: const Text('Go to page 2')), ], ), ), diff --git a/packages/go_router/example/lib/others/nav_observer.dart b/packages/go_router/example/lib/others/nav_observer.dart index fea069fa3c29..722f4063bed7 100644 --- a/packages/go_router/example/lib/others/nav_observer.dart +++ b/packages/go_router/example/lib/others/nav_observer.dart @@ -17,8 +17,7 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Navigator Observer'; @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: title); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( observers: [MyNavObserver()], @@ -26,20 +25,17 @@ class App extends StatelessWidget { GoRoute( // if there's no name, path will be used as name for observers path: '/', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), routes: [ GoRoute( name: 'page2', path: 'page2/:p1', - builder: (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => const Page2Screen(), routes: [ GoRoute( name: 'page3', path: 'page3', - builder: (BuildContext context, GoRouterState state) => - const Page3Screen(), + builder: (BuildContext context, GoRouterState state) => const Page3Screen(), ), ], ), @@ -76,10 +72,7 @@ class MyNavObserver extends NavigatorObserver { log.info('didReplace: new= ${newRoute?.str}, old= ${oldRoute?.str}'); @override - void didStartUserGesture( - Route route, - Route? previousRoute, - ) => log.info( + void didStartUserGesture(Route route, Route? previousRoute) => log.info( 'didStartUserGesture: ${route.str}, ' 'previousRoute= ${previousRoute?.str}', ); @@ -105,11 +98,12 @@ class Page1Screen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( - onPressed: () => context.goNamed( - 'page2', - pathParameters: {'p1': 'pv1'}, - queryParameters: {'q1': 'qv1'}, - ), + onPressed: + () => context.goNamed( + 'page2', + pathParameters: {'p1': 'pv1'}, + queryParameters: {'q1': 'qv1'}, + ), child: const Text('Go to page 2'), ), ], @@ -131,10 +125,8 @@ class Page2Screen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( - onPressed: () => context.goNamed( - 'page3', - pathParameters: {'p1': 'pv2'}, - ), + onPressed: + () => context.goNamed('page3', pathParameters: {'p1': 'pv2'}), child: const Text('Go to page 3'), ), ], @@ -155,10 +147,7 @@ class Page3Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), + ElevatedButton(onPressed: () => context.go('/'), child: const Text('Go to home page')), ], ), ), diff --git a/packages/go_router/example/lib/others/push.dart b/packages/go_router/example/lib/others/push.dart index f915bae847fd..83b451a766d1 100644 --- a/packages/go_router/example/lib/others/push.dart +++ b/packages/go_router/example/lib/others/push.dart @@ -16,22 +16,19 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Push'; @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: title); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: title); late final GoRouter _router = GoRouter( routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const Page1ScreenWithPush(), + builder: (BuildContext context, GoRouterState state) => const Page1ScreenWithPush(), ), GoRoute( path: '/page2', - builder: (BuildContext context, GoRouterState state) => - Page2ScreenWithPush( - int.parse(state.uri.queryParameters['push-count']!), - ), + builder: + (BuildContext context, GoRouterState state) => + Page2ScreenWithPush(int.parse(state.uri.queryParameters['push-count']!)), ), ], ); @@ -69,9 +66,7 @@ class Page2ScreenWithPush extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar( - title: Text('${App.title}: page 2 w/ push count $pushCount'), - ), + appBar: AppBar(title: Text('${App.title}: page 2 w/ push count $pushCount')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -86,8 +81,7 @@ class Page2ScreenWithPush extends StatelessWidget { Padding( padding: const EdgeInsets.all(8), child: ElevatedButton( - onPressed: () => - context.push('/page2?push-count=${pushCount + 1}'), + onPressed: () => context.push('/page2?push-count=${pushCount + 1}'), child: const Text('Push page 2 (again)'), ), ), diff --git a/packages/go_router/example/lib/others/router_neglect.dart b/packages/go_router/example/lib/others/router_neglect.dart index 3c1e4bcc768e..21bb7c9563dd 100644 --- a/packages/go_router/example/lib/others/router_neglect.dart +++ b/packages/go_router/example/lib/others/router_neglect.dart @@ -16,8 +16,7 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Router neglect'; @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: title); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( // To turn off history tracking in the browser for the entire application, @@ -26,13 +25,11 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: '/page2', - builder: (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => const Page2Screen(), ), ], ); @@ -50,17 +47,13 @@ class Page1Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/page2'), - child: const Text('Go to page 2'), - ), + ElevatedButton(onPressed: () => context.go('/page2'), child: const Text('Go to page 2')), const SizedBox(height: 8), ElevatedButton( // turn off history tracking in the browser for this navigation; // note that this isn't necessary when you've set routerNeglect // but it does illustrate the technique - onPressed: () => - Router.neglect(context, () => context.push('/page2')), + onPressed: () => Router.neglect(context, () => context.push('/page2')), child: const Text('Push page 2'), ), ], @@ -81,10 +74,7 @@ class Page2Screen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - ElevatedButton( - onPressed: () => context.go('/'), - child: const Text('Go to home page'), - ), + ElevatedButton(onPressed: () => context.go('/'), child: const Text('Go to home page')), ], ), ), diff --git a/packages/go_router/example/lib/others/transitions.dart b/packages/go_router/example/lib/others/transitions.dart index d95862b19620..1d52b46438c5 100644 --- a/packages/go_router/example/lib/others/transitions.dart +++ b/packages/go_router/example/lib/others/transitions.dart @@ -16,21 +16,17 @@ class App extends StatelessWidget { static const String title = 'GoRouter Example: Custom Transitions'; @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: title); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: title); final GoRouter _router = GoRouter( routes: [ GoRoute(path: '/', redirect: (_, __) => '/none'), GoRoute( path: '/fade', - pageBuilder: (BuildContext context, GoRouterState state) => - CustomTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => CustomTransitionPage( key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'fade', - color: Colors.red, - ), + child: const ExampleTransitionsScreen(kind: 'fade', color: Colors.red), transitionsBuilder: ( BuildContext context, @@ -42,13 +38,10 @@ class App extends StatelessWidget { ), GoRoute( path: '/scale', - pageBuilder: (BuildContext context, GoRouterState state) => - CustomTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => CustomTransitionPage( key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'scale', - color: Colors.green, - ), + child: const ExampleTransitionsScreen(kind: 'scale', color: Colors.green), transitionsBuilder: ( BuildContext context, @@ -60,13 +53,10 @@ class App extends StatelessWidget { ), GoRoute( path: '/slide', - pageBuilder: (BuildContext context, GoRouterState state) => - CustomTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => CustomTransitionPage( key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'slide', - color: Colors.yellow, - ), + child: const ExampleTransitionsScreen(kind: 'slide', color: Colors.yellow), transitionsBuilder: ( BuildContext context, @@ -86,13 +76,10 @@ class App extends StatelessWidget { ), GoRoute( path: '/rotation', - pageBuilder: (BuildContext context, GoRouterState state) => - CustomTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => CustomTransitionPage( key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'rotation', - color: Colors.purple, - ), + child: const ExampleTransitionsScreen(kind: 'rotation', color: Colors.purple), transitionsBuilder: ( BuildContext context, @@ -104,13 +91,10 @@ class App extends StatelessWidget { ), GoRoute( path: '/none', - pageBuilder: (BuildContext context, GoRouterState state) => - NoTransitionPage( + pageBuilder: + (BuildContext context, GoRouterState state) => NoTransitionPage( key: state.pageKey, - child: const ExampleTransitionsScreen( - kind: 'none', - color: Colors.white, - ), + child: const ExampleTransitionsScreen(kind: 'none', color: Colors.white), ), ), ], @@ -120,20 +104,10 @@ class App extends StatelessWidget { /// An Example transitions screen. class ExampleTransitionsScreen extends StatelessWidget { /// Creates an [ExampleTransitionsScreen]. - const ExampleTransitionsScreen({ - required this.color, - required this.kind, - super.key, - }); + const ExampleTransitionsScreen({required this.color, required this.kind, super.key}); /// The available transition kinds. - static final List kinds = [ - 'fade', - 'scale', - 'slide', - 'rotation', - 'none', - ]; + static final List kinds = ['fade', 'scale', 'slide', 'rotation', 'none']; /// The color of the container. final Color color; diff --git a/packages/go_router/example/lib/path_and_query_parameters.dart b/packages/go_router/example/lib/path_and_query_parameters.dart index 6cd8a4b77d3c..f4b381785dbc 100755 --- a/packages/go_router/example/lib/path_and_query_parameters.dart +++ b/packages/go_router/example/lib/path_and_query_parameters.dart @@ -37,17 +37,11 @@ class Person { const Map _families = { 'f1': Family( name: 'Doe', - people: { - 'p1': Person(name: 'Jane'), - 'p2': Person(name: 'John'), - }, + people: {'p1': Person(name: 'Jane'), 'p2': Person(name: 'John')}, ), 'f2': Family( name: 'Wong', - people: { - 'p1': Person(name: 'June'), - 'p2': Person(name: 'Xin'), - }, + people: {'p1': Person(name: 'June'), 'p2': Person(name: 'Xin')}, ), }; @@ -63,18 +57,14 @@ class App extends StatelessWidget { // add the login info into the tree as app state that can change over time @override - Widget build(BuildContext context) => MaterialApp.router( - routerConfig: _router, - title: title, - debugShowCheckedModeBanner: false, - ); + Widget build(BuildContext context) => + MaterialApp.router(routerConfig: _router, title: title, debugShowCheckedModeBanner: false); late final GoRouter _router = GoRouter( routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'family', @@ -128,9 +118,8 @@ class FamilyScreen extends StatelessWidget { @override Widget build(BuildContext context) { final Map newQueries; - final List names = _families[fid]!.people.values - .map((Person p) => p.name) - .toList(); + final List names = + _families[fid]!.people.values.map((Person p) => p.name).toList(); names.sort(); if (asc) { newQueries = const {'sort': 'desc'}; @@ -142,11 +131,12 @@ class FamilyScreen extends StatelessWidget { title: Text(_families[fid]!.name), actions: [ IconButton( - onPressed: () => context.goNamed( - 'family', - pathParameters: {'fid': fid}, - queryParameters: newQueries, - ), + onPressed: + () => context.goNamed( + 'family', + pathParameters: {'fid': fid}, + queryParameters: newQueries, + ), tooltip: 'sort ascending or descending', icon: const Icon(Icons.sort), ), @@ -154,8 +144,7 @@ class FamilyScreen extends StatelessWidget { ), body: ListView( children: [ - for (final String name in asc ? names : names.reversed) - ListTile(title: Text(name)), + for (final String name in asc ? names : names.reversed) ListTile(title: Text(name)), ], ), ); diff --git a/packages/go_router/example/lib/push_with_shell_route.dart b/packages/go_router/example/lib/push_with_shell_route.dart index 95d04c5be0e2..0209cc0d735e 100644 --- a/packages/go_router/example/lib/push_with_shell_route.dart +++ b/packages/go_router/example/lib/push_with_shell_route.dart @@ -38,9 +38,8 @@ class PushWithShellRouteExampleApp extends StatelessWidget { ), GoRoute( path: '/shell1', - pageBuilder: (_, __) => const NoTransitionPage( - child: Center(child: Text('shell1 body')), - ), + pageBuilder: + (_, __) => const NoTransitionPage(child: Center(child: Text('shell1 body'))), ), ], ), @@ -87,10 +86,7 @@ class ScaffoldForShell1 extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: const Text('shell1')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell1')), body: child); } } @@ -105,10 +101,7 @@ class ScaffoldForShell2 extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: const Text('shell2')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell2')), body: child); } } diff --git a/packages/go_router/example/lib/redirection.dart b/packages/go_router/example/lib/redirection.dart index 35232b655c8f..3ce09d335a75 100644 --- a/packages/go_router/example/lib/redirection.dart +++ b/packages/go_router/example/lib/redirection.dart @@ -36,20 +36,15 @@ class LoginInfo extends ChangeNotifier { /// Provides login information to its descendants. class LoginInfoProvider extends InheritedNotifier { /// Creates a [LoginInfoProvider]. - const LoginInfoProvider({ - super.key, - required super.notifier, - required super.child, - }); + const LoginInfoProvider({super.key, required super.notifier, required super.child}); /// Returns the [LoginInfo] from the closest [LoginInfoProvider] ancestor. static LoginInfo of(BuildContext context, {bool listen = true}) { - final LoginInfoProvider? result = listen - ? context.dependOnInheritedWidgetOfExactType() - : context - .getElementForInheritedWidgetOfExactType() - ?.widget - as LoginInfoProvider?; + final LoginInfoProvider? result = + listen + ? context.dependOnInheritedWidgetOfExactType() + : context.getElementForInheritedWidgetOfExactType()?.widget + as LoginInfoProvider?; assert(result != null, 'No LoginInfoProvider found in context'); return result!.notifier!; } @@ -82,13 +77,11 @@ class App extends StatelessWidget { routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], diff --git a/packages/go_router/example/lib/routing_config.dart b/packages/go_router/example/lib/routing_config.dart index 209e1176c342..13616f9fd8de 100644 --- a/packages/go_router/example/lib/routing_config.dart +++ b/packages/go_router/example/lib/routing_config.dart @@ -20,26 +20,25 @@ class MyApp extends StatefulWidget { class _MyAppState extends State { bool isNewRouteAdded = false; - late final ValueNotifier myConfig = - ValueNotifier(_generateRoutingConfig()); + late final ValueNotifier myConfig = ValueNotifier( + _generateRoutingConfig(), + ); late final GoRouter router = GoRouter.routingConfig( routingConfig: myConfig, - errorBuilder: (_, GoRouterState state) => Scaffold( - appBar: AppBar(title: const Text('Page not found')), - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text('${state.uri} does not exist'), - ElevatedButton( - onPressed: () => router.go('/'), - child: const Text('Go to home'), + errorBuilder: + (_, GoRouterState state) => Scaffold( + appBar: AppBar(title: const Text('Page not found')), + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('${state.uri} does not exist'), + ElevatedButton(onPressed: () => router.go('/'), child: const Text('Go to home')), + ], ), - ], + ), ), - ), - ), ); RoutingConfig _generateRoutingConfig() { @@ -55,18 +54,20 @@ class _MyAppState extends State { mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( - onPressed: isNewRouteAdded - ? null - : () { - setState(() { - isNewRouteAdded = true; - // Modify the routing config. - myConfig.value = _generateRoutingConfig(); - }); - }, - child: isNewRouteAdded - ? const Text('A route has been added') - : const Text('Add a new route'), + onPressed: + isNewRouteAdded + ? null + : () { + setState(() { + isNewRouteAdded = true; + // Modify the routing config. + myConfig.value = _generateRoutingConfig(); + }); + }, + child: + isNewRouteAdded + ? const Text('A route has been added') + : const Text('Add a new route'), ), ElevatedButton( onPressed: () { diff --git a/packages/go_router/example/lib/shell_route.dart b/packages/go_router/example/lib/shell_route.dart index aa8e36c7c5f0..69b533a1b8a7 100644 --- a/packages/go_router/example/lib/shell_route.dart +++ b/packages/go_router/example/lib/shell_route.dart @@ -5,12 +5,8 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = GlobalKey( - debugLabel: 'root', -); -final GlobalKey _shellNavigatorKey = GlobalKey( - debugLabel: 'shell', -); +final GlobalKey _rootNavigatorKey = GlobalKey(debugLabel: 'root'); +final GlobalKey _shellNavigatorKey = GlobalKey(debugLabel: 'shell'); // This scenario demonstrates how to set up nested navigation using ShellRoute, // which is a pattern where an additional Navigator is placed in the widget tree @@ -130,10 +126,7 @@ class ScaffoldWithNavBar extends StatelessWidget { bottomNavigationBar: BottomNavigationBar( items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'A Screen'), - BottomNavigationBarItem( - icon: Icon(Icons.business), - label: 'B Screen', - ), + BottomNavigationBarItem(icon: Icon(Icons.business), label: 'B Screen'), BottomNavigationBarItem( icon: Icon(Icons.notification_important_rounded), label: 'C Screen', @@ -265,10 +258,7 @@ class DetailsScreen extends StatelessWidget { return Scaffold( appBar: AppBar(title: const Text('Details Screen')), body: Center( - child: Text( - 'Details for $label', - style: Theme.of(context).textTheme.headlineMedium, - ), + child: Text('Details for $label', style: Theme.of(context).textTheme.headlineMedium), ), ); } diff --git a/packages/go_router/example/lib/shell_route_top_route.dart b/packages/go_router/example/lib/shell_route_top_route.dart index 9fa2df1e9ee0..6e9017210547 100644 --- a/packages/go_router/example/lib/shell_route_top_route.dart +++ b/packages/go_router/example/lib/shell_route_top_route.dart @@ -5,12 +5,8 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = GlobalKey( - debugLabel: 'root', -); -final GlobalKey _shellNavigatorKey = GlobalKey( - debugLabel: 'shell', -); +final GlobalKey _rootNavigatorKey = GlobalKey(debugLabel: 'root'); +final GlobalKey _shellNavigatorKey = GlobalKey(debugLabel: 'shell'); // This scenario demonstrates how to set up nested navigation using ShellRoute, // which is a pattern where an additional Navigator is placed in the widget tree @@ -137,11 +133,7 @@ class ShellRouteExampleApp extends StatelessWidget { /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. - const ScaffoldWithNavBar({ - super.key, - required this.title, - required this.child, - }); + const ScaffoldWithNavBar({super.key, required this.title, required this.child}); /// The title to display in the AppBar. final String title; @@ -158,10 +150,7 @@ class ScaffoldWithNavBar extends StatelessWidget { bottomNavigationBar: BottomNavigationBar( items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'A Screen'), - BottomNavigationBarItem( - icon: Icon(Icons.business), - label: 'B Screen', - ), + BottomNavigationBarItem(icon: Icon(Icons.business), label: 'B Screen'), BottomNavigationBarItem( icon: Icon(Icons.notification_important_rounded), label: 'C Screen', @@ -178,13 +167,11 @@ class ScaffoldWithNavBar extends StatelessWidget { /// The [Scaffold]'s default back button cannot be used because it doesn't /// have the context of the current child. Widget? _buildLeadingButton(BuildContext context) { - final RouteMatchList currentConfiguration = GoRouter.of( - context, - ).routerDelegate.currentConfiguration; + final RouteMatchList currentConfiguration = + GoRouter.of(context).routerDelegate.currentConfiguration; final RouteMatch lastMatch = currentConfiguration.last; - final Uri location = lastMatch is ImperativeRouteMatch - ? lastMatch.matches.uri - : currentConfiguration.uri; + final Uri location = + lastMatch is ImperativeRouteMatch ? lastMatch.matches.uri : currentConfiguration.uri; final bool canPop = location.pathSegments.length > 1; return canPop ? BackButton(onPressed: GoRouter.of(context).pop) : null; } @@ -287,10 +274,7 @@ class DetailsScreen extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( body: Center( - child: Text( - 'Details for $label', - style: Theme.of(context).textTheme.headlineMedium, - ), + child: Text('Details for $label', style: Theme.of(context).textTheme.headlineMedium), ), ); } diff --git a/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart index 3df568e39140..bcffd41a45cb 100644 --- a/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart +++ b/packages/go_router/example/lib/state_restoration/go_route_state_restoration.dart @@ -48,10 +48,7 @@ class _AppState extends State { @override Widget build(BuildContext context) { - return MaterialApp.router( - restorationScopeId: 'mainApp', - routerConfig: _router, - ); + return MaterialApp.router(restorationScopeId: 'mainApp', routerConfig: _router); } } diff --git a/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart index e3ee30b9fc27..72836946ef6e 100644 --- a/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart +++ b/packages/go_router/example/lib/state_restoration/shell_route_state_restoration.dart @@ -29,13 +29,12 @@ class _AppState extends State { routes: [ ShellRoute( restorationScopeId: 'onboardingShell', - pageBuilder: - (BuildContext context, GoRouterState state, Widget child) { - return MaterialPage( - restorationId: 'onboardingPage', - child: OnboardingScaffold(child: child), - ); - }, + pageBuilder: (BuildContext context, GoRouterState state, Widget child) { + return MaterialPage( + restorationId: 'onboardingPage', + child: OnboardingScaffold(child: child), + ); + }, routes: [ GoRoute( path: 'welcome', @@ -97,10 +96,7 @@ class OnboardingScaffold extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Onboarding'), - automaticallyImplyLeading: false, - ), + appBar: AppBar(title: const Text('Onboarding'), automaticallyImplyLeading: false), body: child, ); } diff --git a/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart b/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart index a81a1031b7cd..b6b6f3700efb 100644 --- a/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart +++ b/packages/go_router/example/lib/state_restoration/stateful_shell_route_state_restoration.dart @@ -23,17 +23,16 @@ class _AppState extends State { routes: [ StatefulShellRoute.indexedStack( restorationScopeId: 'appShell', - pageBuilder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - return MaterialPage( - restorationId: 'appShellPage', - child: AppShell(navigationShell: navigationShell), - ); - }, + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + return MaterialPage( + restorationId: 'appShellPage', + child: AppShell(navigationShell: navigationShell), + ); + }, branches: [ StatefulShellBranch( restorationScopeId: 'homeBranch', @@ -89,10 +88,7 @@ class AppShell extends StatelessWidget { }, destinations: const [ NavigationDestination(icon: Icon(Icons.home), label: 'Home'), - NavigationDestination( - icon: Icon(Icons.account_circle), - label: 'Profile', - ), + NavigationDestination(icon: Icon(Icons.account_circle), label: 'Profile'), ], ), ); @@ -108,10 +104,7 @@ class HomeBody extends StatelessWidget { Widget build(BuildContext context) { return const Column( children: [ - TextField( - restorationId: 'homeTextField', - decoration: InputDecoration(labelText: 'Home'), - ), + TextField(restorationId: 'homeTextField', decoration: InputDecoration(labelText: 'Home')), ], ); } diff --git a/packages/go_router/example/lib/stateful_shell_route.dart b/packages/go_router/example/lib/stateful_shell_route.dart index 39e14ad53c35..8c78d98fcd67 100644 --- a/packages/go_router/example/lib/stateful_shell_route.dart +++ b/packages/go_router/example/lib/stateful_shell_route.dart @@ -5,11 +5,10 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -final GlobalKey _rootNavigatorKey = GlobalKey( - debugLabel: 'root', +final GlobalKey _rootNavigatorKey = GlobalKey(debugLabel: 'root'); +final GlobalKey _sectionANavigatorKey = GlobalKey( + debugLabel: 'sectionANav', ); -final GlobalKey _sectionANavigatorKey = - GlobalKey(debugLabel: 'sectionANav'); // This example demonstrates how to setup nested navigation using a // BottomNavigationBar, where each bar item uses its own persistent navigator, @@ -31,18 +30,17 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ // #docregion configuration-builder StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - // Return the widget that implements the custom shell (in this case - // using a BottomNavigationBar). The StatefulNavigationShell is passed - // to be able access the state of the shell and to navigate to other - // branches in a stateful way. - return ScaffoldWithNavBar(navigationShell: navigationShell); - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + // Return the widget that implements the custom shell (in this case + // using a BottomNavigationBar). The StatefulNavigationShell is passed + // to be able access the state of the shell and to navigate to other + // branches in a stateful way. + return ScaffoldWithNavBar(navigationShell: navigationShell); + }, // #enddocregion configuration-builder // #docregion configuration-branches branches: [ @@ -54,16 +52,18 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the first tab of the // bottom navigation bar. path: '/a', - builder: (BuildContext context, GoRouterState state) => - const RootScreen(label: 'A', detailsPath: '/a/details'), + builder: + (BuildContext context, GoRouterState state) => + const RootScreen(label: 'A', detailsPath: '/a/details'), routes: [ // The details screen to display stacked on navigator of the // first tab. This will cover screen A but not the application // shell (bottom navigation bar). GoRoute( path: 'details', - builder: (BuildContext context, GoRouterState state) => - const DetailsScreen(label: 'A'), + builder: + (BuildContext context, GoRouterState state) => + const DetailsScreen(label: 'A'), ), ], ), @@ -82,8 +82,8 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the second tab of the // bottom navigation bar. path: '/b', - builder: (BuildContext context, GoRouterState state) => - const RootScreen( + builder: + (BuildContext context, GoRouterState state) => const RootScreen( label: 'B', detailsPath: '/b/details/1', secondDetailsPath: '/b/details/2', @@ -91,11 +91,9 @@ class NestedTabNavigationExampleApp extends StatelessWidget { routes: [ GoRoute( path: 'details/:param', - builder: (BuildContext context, GoRouterState state) => - DetailsScreen( - label: 'B', - param: state.pathParameters['param'], - ), + builder: + (BuildContext context, GoRouterState state) => + DetailsScreen(label: 'B', param: state.pathParameters['param']), ), ], ), @@ -109,13 +107,15 @@ class NestedTabNavigationExampleApp extends StatelessWidget { // The screen to display as the root in the third tab of the // bottom navigation bar. path: '/c', - builder: (BuildContext context, GoRouterState state) => - const RootScreen(label: 'C', detailsPath: '/c/details'), + builder: + (BuildContext context, GoRouterState state) => + const RootScreen(label: 'C', detailsPath: '/c/details'), routes: [ GoRoute( path: 'details', - builder: (BuildContext context, GoRouterState state) => - DetailsScreen(label: 'C', extra: state.extra), + builder: + (BuildContext context, GoRouterState state) => + DetailsScreen(label: 'C', extra: state.extra), ), ], ), @@ -170,6 +170,7 @@ class ScaffoldWithNavBar extends StatelessWidget { ), ); } + // #enddocregion configuration-custom-shell /// NOTE: For a slightly more sophisticated branch switching, change the onTap @@ -218,10 +219,7 @@ class RootScreen extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Text( - 'Screen $label', - style: Theme.of(context).textTheme.titleLarge, - ), + Text('Screen $label', style: Theme.of(context).textTheme.titleLarge), const Padding(padding: EdgeInsets.all(4)), TextButton( onPressed: () { @@ -283,10 +281,7 @@ class DetailsScreenState extends State { body: _build(context), ); } else { - return ColoredBox( - color: Theme.of(context).scaffoldBackgroundColor, - child: _build(context), - ); + return ColoredBox(color: Theme.of(context).scaffoldBackgroundColor, child: _build(context)); } } @@ -310,16 +305,10 @@ class DetailsScreenState extends State { ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) - Text( - 'Parameter: ${widget.param!}', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Parameter: ${widget.param!}', style: Theme.of(context).textTheme.titleMedium), const Padding(padding: EdgeInsets.all(8)), if (widget.extra != null) - Text( - 'Extra: ${widget.extra!}', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Extra: ${widget.extra!}', style: Theme.of(context).textTheme.titleMedium), if (!widget.withScaffold) ...[ const Padding(padding: EdgeInsets.all(16)), TextButton( diff --git a/packages/go_router/example/lib/top_level_on_enter.dart b/packages/go_router/example/lib/top_level_on_enter.dart index 58b63c8a32f4..a1fbffa8038f 100644 --- a/packages/go_router/example/lib/top_level_on_enter.dart +++ b/packages/go_router/example/lib/top_level_on_enter.dart @@ -35,10 +35,7 @@ class App extends StatelessWidget { Widget build(BuildContext context) { final key = GlobalKey(); - return MaterialApp.router( - routerConfig: _router(key), - title: 'Top-level onEnter', - ); + return MaterialApp.router(routerConfig: _router(key), title: 'Top-level onEnter'); } /// Configures the router with navigation handling and deep link support. @@ -50,112 +47,102 @@ class App extends StatelessWidget { // If anything goes sideways during parsing/guards/redirects, // surface a friendly message and offer a one-tap “Go Home”. - onException: - (BuildContext context, GoRouterState state, GoRouter router) { - // Show a user-friendly error message - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Navigation error: ${state.error}'), - backgroundColor: Colors.red, - duration: const Duration(seconds: 5), - action: SnackBarAction( - label: 'Go Home', - onPressed: () => router.go('/home'), - ), - ), - ); - } - // Log the error for debugging - debugPrint('Router exception: ${state.error}'); - - // Navigate to error screen if needed - if (state.uri.path == '/crash-test') { - router.go('/error'); - } - }, + onException: (BuildContext context, GoRouterState state, GoRouter router) { + // Show a user-friendly error message + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Navigation error: ${state.error}'), + backgroundColor: Colors.red, + duration: const Duration(seconds: 5), + action: SnackBarAction(label: 'Go Home', onPressed: () => router.go('/home')), + ), + ); + } + // Log the error for debugging + debugPrint('Router exception: ${state.error}'); + + // Navigate to error screen if needed + if (state.uri.path == '/crash-test') { + router.go('/error'); + } + }, /// Top-level guard runs BEFORE legacy top-level redirects and route-level redirects. /// Return: /// - `Allow()` to proceed (optionally with `then:` side-effects) /// - `Block.stop()` to cancel navigation immediately /// - `Block.then(() => ...)` to cancel navigation and run follow-up work - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter router, - ) async { - // Example: fire-and-forget analytics for deep links; never block the nav - if (next.uri.hasQuery || next.uri.hasFragment) { - // Don't await: keep the guard non-blocking for best UX. - unawaited(ReferralService.trackDeepLink(next.uri)); - } - - switch (next.uri.path) { - // Block deep-link routes that should never render a page - // (we stay on the current page and show a lightweight UI instead). - case '/referral': - { - final String? code = next.uri.queryParameters['code']; - if (code != null) { - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Processing referral code...'), - duration: Duration(seconds: 2), - ), - ); - } - // Do the real work in the background; don’t keep the user waiting. - await _processReferralCodeInBackground(context, code); - } - return const Block.stop(); // keep user where they are - } - - // Simulate an OAuth callback: do background work + toast; never show a page at /auth - case '/auth': - { - final String? token = next.uri.queryParameters['token']; - if (token != null) { - _handleAuthToken(context, token); - return const Block.stop(); // cancel showing any /auth page - } - return const Allow(); + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter router, + ) async { + // Example: fire-and-forget analytics for deep links; never block the nav + if (next.uri.hasQuery || next.uri.hasFragment) { + // Don't await: keep the guard non-blocking for best UX. + unawaited(ReferralService.trackDeepLink(next.uri)); + } + + switch (next.uri.path) { + // Block deep-link routes that should never render a page + // (we stay on the current page and show a lightweight UI instead). + case '/referral': + { + final String? code = next.uri.queryParameters['code']; + if (code != null) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Processing referral code...'), + duration: Duration(seconds: 2), + ), + ); } + // Do the real work in the background; don’t keep the user waiting. + await _processReferralCodeInBackground(context, code); + } + return const Block.stop(); // keep user where they are + } - // Demonstrate error reporting path - case '/crash-test': - throw Exception('Simulated error in onEnter callback!'); - - case '/protected': - { - // ignore: prefer_final_locals - var isLoggedIn = false; // pretend we’re not authenticated - if (!isLoggedIn) { - // Chaining block: cancel the original nav, then redirect to /login. - // This preserves redirection history to detect loops. - final String from = Uri.encodeComponent( - next.uri.toString(), - ); - return Block.then(() => router.go('/login?from=$from')); - } - // ignore: dead_code - return const Allow(); - } + // Simulate an OAuth callback: do background work + toast; never show a page at /auth + case '/auth': + { + final String? token = next.uri.queryParameters['token']; + if (token != null) { + _handleAuthToken(context, token); + return const Block.stop(); // cancel showing any /auth page + } + return const Allow(); + } - default: - return const Allow(); + // Demonstrate error reporting path + case '/crash-test': + throw Exception('Simulated error in onEnter callback!'); + + case '/protected': + { + // ignore: prefer_final_locals + var isLoggedIn = false; // pretend we’re not authenticated + if (!isLoggedIn) { + // Chaining block: cancel the original nav, then redirect to /login. + // This preserves redirection history to detect loops. + final String from = Uri.encodeComponent(next.uri.toString()); + return Block.then(() => router.go('/login?from=$from')); + } + // ignore: dead_code + return const Allow(); } - }, + + default: + return const Allow(); + } + }, routes: [ // Simple “root → home” - GoRoute( - path: '/', - redirect: (BuildContext _, GoRouterState __) => '/home', - ), + GoRoute(path: '/', redirect: (BuildContext _, GoRouterState __) => '/home'), // Auth + simple pages GoRoute(path: '/login', builder: (_, __) => const LoginScreen()), @@ -166,10 +153,7 @@ class App extends StatelessWidget { // but they exist so deep-links resolve safely. GoRoute(path: '/referral', builder: (_, __) => const SizedBox.shrink()), GoRoute(path: '/auth', builder: (_, __) => const SizedBox.shrink()), - GoRoute( - path: '/crash-test', - builder: (_, __) => const SizedBox.shrink(), - ), + GoRoute(path: '/crash-test', builder: (_, __) => const SizedBox.shrink()), // Route-level redirect happens AFTER top-level onEnter allows. GoRoute( @@ -186,9 +170,7 @@ class App extends StatelessWidget { return Scaffold( appBar: AppBar(title: const Text('Article')), body: Center( - child: Text( - 'id=${state.pathParameters['id']}; fragment=${state.uri.fragment}', - ), + child: Text('id=${state.pathParameters['id']}; fragment=${state.uri.fragment}'), ), ); }, @@ -200,10 +182,7 @@ class App extends StatelessWidget { } /// Processes referral code in the background without blocking navigation - Future _processReferralCodeInBackground( - BuildContext context, - String code, - ) async { + Future _processReferralCodeInBackground(BuildContext context, String code) async { final bool ok = await ReferralService.processReferralCode(code); if (!context.mounted) { return; @@ -213,9 +192,7 @@ class App extends StatelessWidget { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( - ok - ? 'Referral code $code applied successfully!' - : 'Failed to apply referral code', + ok ? 'Referral code $code applied successfully!' : 'Failed to apply referral code', ), ), ); @@ -268,10 +245,7 @@ class HomeScreen extends StatelessWidget { appBar: AppBar( title: const Text('Top-level onEnter'), actions: [ - IconButton( - icon: const Icon(Icons.settings), - onPressed: () => context.go('/settings'), - ), + IconButton(icon: const Icon(Icons.settings), onPressed: () => context.go('/settings')), ], ), body: ListView( @@ -285,10 +259,7 @@ class HomeScreen extends StatelessWidget { ), const SizedBox(height: 16), - Text( - 'Deep Link Tests', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Deep Link Tests', style: Theme.of(context).textTheme.titleMedium), const SizedBox(height: 8), const _DeepLinkButton( label: 'Process Referral', @@ -303,10 +274,7 @@ class HomeScreen extends StatelessWidget { ), const SizedBox(height: 24), - Text( - 'Guards & Redirects', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Guards & Redirects', style: Theme.of(context).textTheme.titleMedium), const SizedBox(height: 8), const _DeepLinkButton( label: 'Protected Route (redirects to login)', @@ -321,10 +289,7 @@ class HomeScreen extends StatelessWidget { ), const SizedBox(height: 24), - Text( - 'Fragments (hash)', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Fragments (hash)', style: Theme.of(context).textTheme.titleMedium), const SizedBox(height: 8), OutlinedButton( onPressed: goArticleWithFragment, @@ -343,11 +308,7 @@ class HomeScreen extends StatelessWidget { /// A button that demonstrates a deep link scenario. class _DeepLinkButton extends StatelessWidget { - const _DeepLinkButton({ - required this.label, - required this.path, - required this.description, - }); + const _DeepLinkButton({required this.label, required this.path, required this.description}); final String label; final String path; @@ -435,10 +396,7 @@ class ErrorScreen extends StatelessWidget { children: [ const Icon(Icons.error_outline, color: Colors.red, size: 60), const SizedBox(height: 16), - const Text( - 'An error occurred during navigation', - style: TextStyle(fontSize: 18), - ), + const Text('An error occurred during navigation', style: TextStyle(fontSize: 18)), const SizedBox(height: 24), ElevatedButton.icon( onPressed: () => context.go('/home'), diff --git a/packages/go_router/example/lib/transition_animations.dart b/packages/go_router/example/lib/transition_animations.dart index 96f93f1d9f8d..36d26c337f6b 100644 --- a/packages/go_router/example/lib/transition_animations.dart +++ b/packages/go_router/example/lib/transition_animations.dart @@ -29,22 +29,19 @@ final GoRouter _router = GoRouter( key: state.pageKey, child: const DetailsScreen(), transitionDuration: const Duration(milliseconds: 150), - transitionsBuilder: - ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) { - // Change the opacity of the screen using a Curve based on the the animation's - // value - return FadeTransition( - opacity: CurveTween( - curve: Curves.easeInOut, - ).animate(animation), - child: child, - ); - }, + transitionsBuilder: ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + // Change the opacity of the screen using a Curve based on the the animation's + // value + return FadeTransition( + opacity: CurveTween(curve: Curves.easeInOut).animate(animation), + child: child, + ); + }, ); }, ), @@ -73,15 +70,14 @@ final GoRouter _router = GoRouter( opaque: false, transitionDuration: const Duration(milliseconds: 500), reverseTransitionDuration: const Duration(milliseconds: 200), - transitionsBuilder: - ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) { - return FadeTransition(opacity: animation, child: child); - }, + transitionsBuilder: ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + return FadeTransition(opacity: animation, child: child); + }, ); }, ), @@ -125,11 +121,8 @@ class HomeScreen extends StatelessWidget { ), const SizedBox(height: 48), ElevatedButton( - onPressed: () => - context.go('/custom-reverse-transition-duration'), - child: const Text( - 'Go to the Custom Reverse Transition Duration Screen', - ), + onPressed: () => context.go('/custom-reverse-transition-duration'), + child: const Text('Go to the Custom Reverse Transition Duration Screen'), ), ], ), @@ -169,9 +162,6 @@ class DismissibleDetails extends StatelessWidget { @override Widget build(BuildContext context) { - return const Padding( - padding: EdgeInsets.all(48), - child: ColoredBox(color: Colors.red), - ); + return const Padding(padding: EdgeInsets.all(48), child: ColoredBox(color: Colors.red)); } } diff --git a/packages/go_router/example/test/custom_stateful_shell_route_test.dart b/packages/go_router/example/test/custom_stateful_shell_route_test.dart index d88c3bc153f7..b770a847f16c 100644 --- a/packages/go_router/example/test/custom_stateful_shell_route_test.dart +++ b/packages/go_router/example/test/custom_stateful_shell_route_test.dart @@ -7,27 +7,25 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_examples/others/custom_stateful_shell_route.dart'; void main() { - testWidgets( - 'Changing active tab in TabController of TabbedRootScreen (root screen ' - 'of branch/section B) correctly navigates to appropriate screen', - (WidgetTester tester) async { - await tester.pumpWidget(NestedTabNavigationExampleApp()); - expect(find.text('Screen A'), findsOneWidget); + testWidgets('Changing active tab in TabController of TabbedRootScreen (root screen ' + 'of branch/section B) correctly navigates to appropriate screen', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(NestedTabNavigationExampleApp()); + expect(find.text('Screen A'), findsOneWidget); - // navigate to ScreenB - await tester.tap(find.text('Section B')); - await tester.pumpAndSettle(); - expect(find.text('Screen B1'), findsOneWidget); + // navigate to ScreenB + await tester.tap(find.text('Section B')); + await tester.pumpAndSettle(); + expect(find.text('Screen B1'), findsOneWidget); - // Get TabController from TabbedRootScreen (root screen of branch/section B) - final TabController? tabController = - tabbedRootScreenKey.currentState?.tabController; - expect(tabController, isNotNull); + // Get TabController from TabbedRootScreen (root screen of branch/section B) + final TabController? tabController = tabbedRootScreenKey.currentState?.tabController; + expect(tabController, isNotNull); - // Simulate swiping TabView to change active tab in TabController - tabbedRootScreenKey.currentState?.tabController.index = 1; - await tester.pumpAndSettle(); - expect(find.text('Screen B2'), findsOneWidget); - }, - ); + // Simulate swiping TabView to change active tab in TabController + tabbedRootScreenKey.currentState?.tabController.index = 1; + await tester.pumpAndSettle(); + expect(find.text('Screen B2'), findsOneWidget); + }); } diff --git a/packages/go_router/example/test/exception_handling_test.dart b/packages/go_router/example/test/exception_handling_test.dart index 69ed829c5eec..cf4abc205aac 100644 --- a/packages/go_router/example/test/exception_handling_test.dart +++ b/packages/go_router/example/test/exception_handling_test.dart @@ -12,9 +12,6 @@ void main() { await tester.tap(find.text('Simulates user entering unknown url')); await tester.pumpAndSettle(); - expect( - find.text("Can't find a page for: /some-unknown-route"), - findsOneWidget, - ); + expect(find.text("Can't find a page for: /some-unknown-route"), findsOneWidget); }); } diff --git a/packages/go_router/example/test/extra_codec_test.dart b/packages/go_router/example/test/extra_codec_test.dart index 345698e67e93..c1829870bce9 100644 --- a/packages/go_router/example/test/extra_codec_test.dart +++ b/packages/go_router/example/test/extra_codec_test.dart @@ -12,17 +12,11 @@ void main() { await tester.tap(find.text('Set extra to ComplexData1')); await tester.pumpAndSettle(); - expect( - find.text('The extra for this page is: ComplexData1(data: data)'), - findsOneWidget, - ); + expect(find.text('The extra for this page is: ComplexData1(data: data)'), findsOneWidget); await tester.tap(find.text('Set extra to ComplexData2')); await tester.pumpAndSettle(); - expect( - find.text('The extra for this page is: ComplexData2(data: data)'), - findsOneWidget, - ); + expect(find.text('The extra for this page is: ComplexData2(data: data)'), findsOneWidget); }); test('invalid extra throws', () { diff --git a/packages/go_router/example/test/path_and_query_params_test.dart b/packages/go_router/example/test/path_and_query_params_test.dart index 19ec52d0614c..d35da344dde6 100644 --- a/packages/go_router/example/test/path_and_query_params_test.dart +++ b/packages/go_router/example/test/path_and_query_params_test.dart @@ -12,9 +12,7 @@ void main() { expect(find.text(example.App.title), findsOneWidget); // Directly set the url through platform message. - var testRouteInformation = { - 'location': '/family/f1?sort=asc', - }; + var testRouteInformation = {'location': '/family/f1?sort=asc'}; ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); @@ -26,15 +24,9 @@ void main() { await tester.pumpAndSettle(); // 'Chris' should be higher than 'Tom'. - expect( - tester.getCenter(find.text('Jane')).dy < - tester.getCenter(find.text('John')).dy, - isTrue, - ); + expect(tester.getCenter(find.text('Jane')).dy < tester.getCenter(find.text('John')).dy, isTrue); - testRouteInformation = { - 'location': '/family/f1?privacy=false', - }; + testRouteInformation = {'location': '/family/f1?privacy=false'}; message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); @@ -46,10 +38,6 @@ void main() { await tester.pumpAndSettle(); // 'Chris' should be lower than 'Tom'. - expect( - tester.getCenter(find.text('Jane')).dy > - tester.getCenter(find.text('John')).dy, - isTrue, - ); + expect(tester.getCenter(find.text('Jane')).dy > tester.getCenter(find.text('John')).dy, isTrue); }); } diff --git a/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart b/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart index e471c0acdac0..bac4fe9912d8 100644 --- a/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart +++ b/packages/go_router/example/test/state_restoration/go_route_state_restoration_test.dart @@ -8,9 +8,7 @@ import 'package:go_router_examples/state_restoration/go_route_state_restoration. void main() { testWidgets('GoRoute navigation location and route state ' - 'is restored when restorationIds are provided', ( - WidgetTester tester, - ) async { + 'is restored when restorationIds are provided', (WidgetTester tester) async { const homeTitle = 'Home'; const loginTitle = 'Login'; diff --git a/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart b/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart index 98b3dd075217..80977cfe8ade 100644 --- a/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart +++ b/packages/go_router/example/test/state_restoration/shell_route_state_restoration_test.dart @@ -8,9 +8,7 @@ import 'package:go_router_examples/state_restoration/shell_route_state_restorati void main() { testWidgets('ShellRoute navigation location and route state ' - 'is restored when restorationIds are provided', ( - WidgetTester tester, - ) async { + 'is restored when restorationIds are provided', (WidgetTester tester) async { const homeTitle = 'Home'; const welcomeTitle = 'Welcome'; const setupTitle = 'Setup'; diff --git a/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart b/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart index 2f4cd1068789..4ad7e6c55674 100644 --- a/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart +++ b/packages/go_router/example/test/state_restoration/stateful_shell_route_state_restoration_test.dart @@ -8,9 +8,7 @@ import 'package:go_router_examples/state_restoration/stateful_shell_route_state_ void main() { testWidgets('StatefulShellRoute navigation location and route state ' - 'is restored when restorationIds are provided', ( - WidgetTester tester, - ) async { + 'is restored when restorationIds are provided', (WidgetTester tester) async { const homeLabel = 'Home'; const profileLabel = 'Profile'; diff --git a/packages/go_router/lib/go_router.dart b/packages/go_router/lib/go_router.dart index 8ec3fb22ba21..0decf2eb2542 100644 --- a/packages/go_router/lib/go_router.dart +++ b/packages/go_router/lib/go_router.dart @@ -15,12 +15,10 @@ export 'src/misc/custom_parameter.dart'; export 'src/misc/errors.dart'; export 'src/misc/extensions.dart'; export 'src/misc/inherited_router.dart'; -export 'src/on_enter.dart' - show Allow, Block, OnEnterResult, OnEnterThenCallback; +export 'src/on_enter.dart' show Allow, Block, OnEnterResult, OnEnterThenCallback; export 'src/pages/custom_transition_page.dart'; export 'src/parser.dart'; export 'src/route.dart'; export 'src/route_data.dart' hide NoOpPage; -export 'src/router.dart' - show GoExceptionHandler, GoRouter, OnEnter, RoutingConfig; +export 'src/router.dart' show GoExceptionHandler, GoRouter, OnEnter, RoutingConfig; export 'src/state.dart' hide GoRouterStateRegistry, GoRouterStateRegistryScope; diff --git a/packages/go_router/lib/src/builder.dart b/packages/go_router/lib/src/builder.dart index 4eb036ea190b..272bc1a9f384 100644 --- a/packages/go_router/lib/src/builder.dart +++ b/packages/go_router/lib/src/builder.dart @@ -17,8 +17,7 @@ import 'route_data.dart'; import 'state.dart'; /// Signature of a go router builder function with navigator. -typedef GoRouterBuilderWithNav = - Widget Function(BuildContext context, Widget child); +typedef GoRouterBuilderWithNav = Widget Function(BuildContext context, Widget child); typedef _PageBuilderForAppType = Page Function({ @@ -29,8 +28,7 @@ typedef _PageBuilderForAppType = required Widget child, }); -typedef _ErrorBuilderForAppType = - Widget Function(BuildContext context, GoRouterState state); +typedef _ErrorBuilderForAppType = Widget Function(BuildContext context, GoRouterState state); /// Signature for a function that takes in a `route` to be popped with /// the `result` and returns a boolean decision on whether the pop @@ -214,10 +212,7 @@ class _CustomNavigatorState extends State<_CustomNavigator> { } pages.add(page); pageToRouteMatchBase[page] = match; - registry[page] = match.buildState( - widget.configuration, - widget.matchList, - ); + registry[page] = match.buildState(widget.configuration, widget.matchList); } } _pages = pages; @@ -241,10 +236,7 @@ class _CustomNavigatorState extends State<_CustomNavigator> { /// Builds a [Page] for a [RouteMatch] Page? _buildPageForGoRoute(BuildContext context, RouteMatch match) { final GoRouterPageBuilder? pageBuilder = match.route.pageBuilder; - final GoRouterState state = match.buildState( - widget.configuration, - widget.matchList, - ); + final GoRouterState state = match.buildState(widget.configuration, widget.matchList); if (pageBuilder != null) { final Page page = pageBuilder(context, state); if (page is! NoOpPage) { @@ -269,14 +261,8 @@ class _CustomNavigatorState extends State<_CustomNavigator> { } /// Builds a [Page] for a [ShellRouteMatch] - Page _buildPageForShellRoute( - BuildContext context, - ShellRouteMatch match, - ) { - final GoRouterState state = match.buildState( - widget.configuration, - widget.matchList, - ); + Page _buildPageForShellRoute(BuildContext context, ShellRouteMatch match) { + final GoRouterState state = match.buildState(widget.configuration, widget.matchList); final GlobalKey navigatorKey = match.navigatorKey; final shellRouteContext = ShellRouteContext( route: match.route, @@ -284,43 +270,38 @@ class _CustomNavigatorState extends State<_CustomNavigator> { navigatorKey: navigatorKey, match: match, routeMatchList: widget.matchList, - navigatorBuilder: - ( - GlobalKey navigatorKey, - ShellRouteMatch match, - RouteMatchList matchList, - List? observers, - String? restorationScopeId, - ) { - return PopScope( - // Prevent ShellRoute from being popped, for example - // by an iOS back gesture, when the route has active sub-routes. - // TODO(LukasMirbt): Remove when minimum flutter version includes - // https://github.com/flutter/flutter/pull/152330. - canPop: match.matches.length == 1, - child: _CustomNavigator( - // The state needs to persist across rebuild. - key: GlobalObjectKey(navigatorKey.hashCode), - navigatorRestorationId: restorationScopeId, - navigatorKey: navigatorKey, - matches: match.matches, - matchList: matchList, - configuration: widget.configuration, - observers: observers ?? const [], - onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch, - // This is used to recursively build pages under this shell route. - errorBuilder: widget.errorBuilder, - errorPageBuilder: widget.errorPageBuilder, - requestFocus: widget.requestFocus, - ), - ); - }, - ); - final Page? page = match.route.buildPage( - context, - state, - shellRouteContext, + navigatorBuilder: ( + GlobalKey navigatorKey, + ShellRouteMatch match, + RouteMatchList matchList, + List? observers, + String? restorationScopeId, + ) { + return PopScope( + // Prevent ShellRoute from being popped, for example + // by an iOS back gesture, when the route has active sub-routes. + // TODO(LukasMirbt): Remove when minimum flutter version includes + // https://github.com/flutter/flutter/pull/152330. + canPop: match.matches.length == 1, + child: _CustomNavigator( + // The state needs to persist across rebuild. + key: GlobalObjectKey(navigatorKey.hashCode), + navigatorRestorationId: restorationScopeId, + navigatorKey: navigatorKey, + matches: match.matches, + matchList: matchList, + configuration: widget.configuration, + observers: observers ?? const [], + onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch, + // This is used to recursively build pages under this shell route. + errorBuilder: widget.errorBuilder, + errorPageBuilder: widget.errorPageBuilder, + requestFocus: widget.requestFocus, + ), + ); + }, ); + final Page? page = match.route.buildPage(context, state, shellRouteContext); if (page != null && page is! NoOpPage) { return page; } @@ -352,13 +333,12 @@ class _CustomNavigatorState extends State<_CustomNavigator> { if (elem != null && isMaterialApp(elem)) { log('Using MaterialApp configuration'); _pageBuilderForAppType = pageBuilderForMaterialApp; - _errorBuilderForAppType = (BuildContext c, GoRouterState s) => - MaterialErrorScreen(s.error); + _errorBuilderForAppType = (BuildContext c, GoRouterState s) => MaterialErrorScreen(s.error); } else if (elem != null && isCupertinoApp(elem)) { log('Using CupertinoApp configuration'); _pageBuilderForAppType = pageBuilderForCupertinoApp; - _errorBuilderForAppType = (BuildContext c, GoRouterState s) => - CupertinoErrorScreen(s.error); + _errorBuilderForAppType = + (BuildContext c, GoRouterState s) => CupertinoErrorScreen(s.error); } else { log('Using WidgetsApp configuration'); _pageBuilderForAppType = @@ -375,8 +355,7 @@ class _CustomNavigatorState extends State<_CustomNavigator> { restorationId: restorationId, child: child, ); - _errorBuilderForAppType = (BuildContext c, GoRouterState s) => - ErrorScreen(s.error); + _errorBuilderForAppType = (BuildContext c, GoRouterState s) => ErrorScreen(s.error); } } @@ -385,20 +364,13 @@ class _CustomNavigatorState extends State<_CustomNavigator> { } /// builds the page based on app type, i.e. MaterialApp vs. CupertinoApp - Page _buildPlatformAdapterPage( - BuildContext context, - GoRouterState state, - Widget child, - ) { + Page _buildPlatformAdapterPage(BuildContext context, GoRouterState state, Widget child) { // build the page based on app type _cacheAppType(context); return _pageBuilderForAppType!( key: state.pageKey, name: state.name ?? state.path, - arguments: { - ...state.pathParameters, - ...state.uri.queryParameters, - }, + arguments: {...state.pathParameters, ...state.uri.queryParameters}, restorationId: state.pageKey.value, child: child, ); @@ -432,12 +404,12 @@ class _CustomNavigatorState extends State<_CustomNavigator> { return widget.errorPageBuilder != null ? widget.errorPageBuilder!(context, state) : _buildPlatformAdapterPage( - context, - state, - errorBuilder != null - ? errorBuilder(context, state) - : _errorBuilderForAppType!(context, state), - ); + context, + state, + errorBuilder != null + ? errorBuilder(context, state) + : _errorBuilderForAppType!(context, state), + ); } bool _handlePopPage(Route route, Object? result) { diff --git a/packages/go_router/lib/src/configuration.dart b/packages/go_router/lib/src/configuration.dart index 15c159af5506..3c6c08003688 100644 --- a/packages/go_router/lib/src/configuration.dart +++ b/packages/go_router/lib/src/configuration.dart @@ -18,8 +18,7 @@ import 'router.dart' show GoRouter, OnEnter, RoutingConfig; import 'state.dart'; /// The signature of the redirect callback. -typedef GoRouterRedirect = - FutureOr Function(BuildContext context, GoRouterState state); +typedef GoRouterRedirect = FutureOr Function(BuildContext context, GoRouterState state); typedef _NamedPath = ({String path, bool caseSensitive}); @@ -74,25 +73,19 @@ class RouteConfiguration { ' navigatorKey', ); - _debugCheckParentNavigatorKeys( - route.routes, - >[ - // Once a parentNavigatorKey is used, only that navigator key - // or keys above it can be used. - ...allowedKeys.sublist(0, allowedKeys.indexOf(parentKey) + 1), - ], - ); + _debugCheckParentNavigatorKeys(route.routes, >[ + // Once a parentNavigatorKey is used, only that navigator key + // or keys above it can be used. + ...allowedKeys.sublist(0, allowedKeys.indexOf(parentKey) + 1), + ]); } else { - _debugCheckParentNavigatorKeys( - route.routes, - >[...allowedKeys], - ); + _debugCheckParentNavigatorKeys(route.routes, >[...allowedKeys]); } } else if (route is ShellRoute) { - _debugCheckParentNavigatorKeys( - route.routes, - >[...allowedKeys, route.navigatorKey], - ); + _debugCheckParentNavigatorKeys(route.routes, >[ + ...allowedKeys, + route.navigatorKey, + ]); } else if (route is StatefulShellRoute) { for (final StatefulShellBranch branch in route.branches) { assert( @@ -101,10 +94,10 @@ class RouteConfiguration { '(${branch.navigatorKey})', ); - _debugCheckParentNavigatorKeys( - branch.routes, - >[...allowedKeys, branch.navigatorKey], - ); + _debugCheckParentNavigatorKeys(branch.routes, >[ + ...allowedKeys, + branch.navigatorKey, + ]); } } } @@ -144,9 +137,8 @@ class RouteConfiguration { // Recursively search for the first GoRoute descendant. Will // throw assertion error if not found. final GoRoute? defaultGoRoute = branch.defaultRoute; - final String? initialLocation = defaultGoRoute != null - ? locationForRoute(defaultGoRoute) - : null; + final String? initialLocation = + defaultGoRoute != null ? locationForRoute(defaultGoRoute) : null; assert( initialLocation != null, 'The default location of a StatefulShellBranch must be ' @@ -158,9 +150,7 @@ class RouteConfiguration { 'a parameterized route', ); } else { - final RouteMatchList matchList = findMatch( - Uri.parse(branch.initialLocation!), - ); + final RouteMatchList matchList = findMatch(Uri.parse(branch.initialLocation!)); assert( !matchList.isError, 'initialLocation (${matchList.uri}) of StatefulShellBranch must ' @@ -188,11 +178,7 @@ class RouteConfiguration { } /// The match used when there is an error during parsing. - static RouteMatchList _errorRouteMatchList( - Uri uri, - GoException exception, { - Object? extra, - }) { + static RouteMatchList _errorRouteMatchList(Uri uri, GoException exception, {Object? extra}) { return RouteMatchList( matches: const [], extra: extra, @@ -205,17 +191,11 @@ class RouteConfiguration { void _onRoutingTableChanged() { final RoutingConfig routingTable = _routingConfig.value; assert(_debugCheckPath(routingTable.routes, true)); + assert(_debugVerifyNoDuplicatePathParameter(routingTable.routes, {})); assert( - _debugVerifyNoDuplicatePathParameter( - routingTable.routes, - {}, - ), - ); - assert( - _debugCheckParentNavigatorKeys( - routingTable.routes, - >[navigatorKey], - ), + _debugCheckParentNavigatorKeys(routingTable.routes, >[ + navigatorKey, + ]), ); assert(_debugCheckStatefulShellBranchDefaultLocations(routingTable.routes)); _nameToPath.clear(); @@ -322,10 +302,7 @@ class RouteConfiguration { final paramNames = []; patternToRegExp(path.path, paramNames, caseSensitive: path.caseSensitive); for (final paramName in paramNames) { - assert( - pathParameters.containsKey(paramName), - 'missing param "$paramName" for $path', - ); + assert(pathParameters.containsKey(paramName), 'missing param "$paramName" for $path'); } // Check that there are no extra params @@ -349,24 +326,12 @@ class RouteConfiguration { /// Finds the routes that matched the given URL. RouteMatchList findMatch(Uri uri, {Object? extra}) { final pathParameters = {}; - final List matches = _getLocRouteMatches( - uri, - pathParameters, - ); + final List matches = _getLocRouteMatches(uri, pathParameters); if (matches.isEmpty) { - return _errorRouteMatchList( - uri, - GoException('no routes for location: $uri'), - extra: extra, - ); + return _errorRouteMatchList(uri, GoException('no routes for location: $uri'), extra: extra); } - return RouteMatchList( - matches: matches, - uri: uri, - pathParameters: pathParameters, - extra: extra, - ); + return RouteMatchList(matches: matches, uri: uri, pathParameters: pathParameters, extra: extra); } /// Reparse the input RouteMatchList @@ -377,10 +342,7 @@ class RouteConfiguration { in matchList.matches.whereType()) { final match = ImperativeRouteMatch( pageKey: imperativeMatch.pageKey, - matches: findMatch( - imperativeMatch.matches.uri, - extra: imperativeMatch.matches.extra, - ), + matches: findMatch(imperativeMatch.matches.uri, extra: imperativeMatch.matches.extra), completer: imperativeMatch.completer, ); result = result.push(match); @@ -388,10 +350,7 @@ class RouteConfiguration { return result; } - List _getLocRouteMatches( - Uri uri, - Map pathParameters, - ) { + List _getLocRouteMatches(Uri uri, Map pathParameters) { for (final RouteBase route in _routingConfig.value.routes) { final List result = RouteMatchBase.match( rootNavigatorKey: navigatorKey, @@ -428,11 +387,7 @@ class RouteConfiguration { // Step 2: Then apply route-level redirects on the post-top-level result. if (afterTopLevel is RouteMatchList) { - return _processRouteLevelRedirects( - context, - afterTopLevel, - redirectHistory, - ); + return _processRouteLevelRedirects(context, afterTopLevel, redirectHistory); } return afterTopLevel.then((RouteMatchList ml) { if (!context.mounted) { @@ -459,11 +414,8 @@ class RouteConfiguration { ) { final prevLocation = matchList.uri.toString(); - FutureOr processRouteLevelRedirect( - String? routeRedirectLocation, - ) { - if (routeRedirectLocation != null && - routeRedirectLocation != prevLocation) { + FutureOr processRouteLevelRedirect(String? routeRedirectLocation) { + if (routeRedirectLocation != null && routeRedirectLocation != prevLocation) { final RouteMatchList newMatch = _getNewMatches( routeRedirectLocation, matchList.uri, @@ -499,27 +451,19 @@ class RouteConfiguration { if (routeLevelRedirectResult is String?) { return processRouteLevelRedirect(routeLevelRedirectResult); } - return routeLevelRedirectResult - .then(processRouteLevelRedirect) - .catchError((Object error) { - final GoException goException = error is GoException - ? error - : GoException('Exception during route redirect: $error'); - return _errorRouteMatchList( - matchList.uri, - goException, - extra: matchList.extra, - ); - }); + return routeLevelRedirectResult.then(processRouteLevelRedirect).catchError(( + Object error, + ) { + final GoException goException = + error is GoException ? error : GoException('Exception during route redirect: $error'); + return _errorRouteMatchList(matchList.uri, goException, extra: matchList.extra); + }); } catch (exception) { - final GoException goException = exception is GoException - ? exception - : GoException('Exception during route redirect: $exception'); - return _errorRouteMatchList( - matchList.uri, - goException, - extra: matchList.extra, - ); + final GoException goException = + exception is GoException + ? exception + : GoException('Exception during route redirect: $exception'); + return _errorRouteMatchList(matchList.uri, goException, extra: matchList.extra); } } @@ -551,44 +495,29 @@ class RouteConfiguration { return newMatch; } // Recursively re-evaluate the top-level redirect on the new location. - return applyTopLegacyRedirect( - context, - newMatch, - redirectHistory: redirectHistory, - ); + return applyTopLegacyRedirect(context, newMatch, redirectHistory: redirectHistory); } return prevMatchList; } try { final FutureOr res = _runInRouterZone(() { - return _routingConfig.value.redirect( - context, - buildTopLevelGoRouterState(prevMatchList), - ); + return _routingConfig.value.redirect(context, buildTopLevelGoRouterState(prevMatchList)); }); if (res is String?) { return done(res); } return res.then(done).catchError((Object error) { - final GoException goException = error is GoException - ? error - : GoException('Exception during redirect: $error'); - return _errorRouteMatchList( - prevMatchList.uri, - goException, - extra: prevMatchList.extra, - ); + final GoException goException = + error is GoException ? error : GoException('Exception during redirect: $error'); + return _errorRouteMatchList(prevMatchList.uri, goException, extra: prevMatchList.extra); }); } catch (exception) { - final GoException goException = exception is GoException - ? exception - : GoException('Exception during redirect: $exception'); - return _errorRouteMatchList( - prevMatchList.uri, - goException, - extra: prevMatchList.extra, - ); + final GoException goException = + exception is GoException + ? exception + : GoException('Exception during redirect: $exception'); + return _errorRouteMatchList(prevMatchList.uri, goException, extra: prevMatchList.extra); } } @@ -604,12 +533,7 @@ class RouteConfiguration { final RouteMatchBase match = routeMatches[currentCheckIndex]; FutureOr processRouteRedirect(String? newLocation) => newLocation ?? - _getRouteLevelRedirect( - context, - matchList, - routeMatches, - currentCheckIndex + 1, - ); + _getRouteLevelRedirect(context, matchList, routeMatches, currentCheckIndex + 1); final RouteBase route = match.route; try { final FutureOr routeRedirectResult = _runInRouterZone(() { @@ -618,21 +542,19 @@ class RouteConfiguration { if (routeRedirectResult is String?) { return processRouteRedirect(routeRedirectResult); } - return routeRedirectResult.then(processRouteRedirect).catchError( - (Object error) { - // Convert any exception during async route redirect to a GoException - final GoException goException = error is GoException - ? error - : GoException('Exception during route redirect: $error'); - // Throw the GoException to be caught by the redirect handling chain - throw goException; - }, - ); + return routeRedirectResult.then(processRouteRedirect).catchError((Object error) { + // Convert any exception during async route redirect to a GoException + final GoException goException = + error is GoException ? error : GoException('Exception during route redirect: $error'); + // Throw the GoException to be caught by the redirect handling chain + throw goException; + }); } catch (exception) { // Convert any exception during route redirect to a GoException - final GoException goException = exception is GoException - ? exception - : GoException('Exception during route redirect: $exception'); + final GoException goException = + exception is GoException + ? exception + : GoException('Exception during route redirect: $exception'); // Throw the GoException to be caught by the redirect handling chain throw goException; } @@ -654,9 +576,10 @@ class RouteConfiguration { } return newMatch; } catch (exception) { - final GoException goException = exception is GoException - ? exception - : GoException('Exception during redirect: $exception'); + final GoException goException = + exception is GoException + ? exception + : GoException('Exception during redirect: $exception'); log('Redirection exception: ${goException.message}'); return _errorRouteMatchList(previousLocation, goException); } @@ -685,9 +608,7 @@ class RouteConfiguration { String _formatRedirectionHistory(List redirections) { return redirections - .map( - (RouteMatchList routeMatches) => routeMatches.uri.toString(), - ) + .map((RouteMatchList routeMatches) => routeMatches.uri.toString()) .join(' => '); } @@ -707,9 +628,8 @@ class RouteConfiguration { (Object error, StackTrace stack) { errorOccurred = true; // Convert any exception during redirect to a GoException and rethrow - final GoException goException = error is GoException - ? error - : GoException('Exception during redirect: $error'); + final GoException goException = + error is GoException ? error : GoException('Exception during redirect: $error'); throw goException; }, zoneValues: {currentRouterKey: router}, @@ -743,12 +663,7 @@ class RouteConfiguration { String debugKnownRoutes() { final sb = StringBuffer(); sb.writeln('Full paths for routes:'); - _debugFullPathsFor( - _routingConfig.value.routes, - '', - const <_DecorationType>[], - sb, - ); + _debugFullPathsFor(_routingConfig.value.routes, '', const <_DecorationType>[], sb); if (_nameToPath.isNotEmpty) { sb.writeln('known full paths for route names:'); @@ -774,16 +689,11 @@ class RouteConfiguration { index, routes.length, ); - final String decorationString = decoration - .map((_DecorationType e) => e.toString()) - .join(); + final String decorationString = decoration.map((_DecorationType e) => e.toString()).join(); var path = parentFullpath; if (route is GoRoute) { path = concatenatePaths(parentFullpath, route.path); - final String? screenName = route.builder?.runtimeType - .toString() - .split('=> ') - .last; + final String? screenName = route.builder?.runtimeType.toString().split('=> ').last; sb.writeln( '$decorationString$path ' '${screenName == null ? '' : '($screenName)'}', @@ -800,9 +710,7 @@ class RouteConfiguration { int index, int length, ) { - final Iterable<_DecorationType> newDecoration = parentDecoration.map(( - _DecorationType e, - ) { + final Iterable<_DecorationType> newDecoration = parentDecoration.map((_DecorationType e) { switch (e) { // swap case _DecorationType.branch: @@ -835,10 +743,7 @@ class RouteConfiguration { 'duplication fullpaths for name ' '"$name":${_nameToPath[name]!.path}, $fullPath', ); - _nameToPath[name] = ( - path: fullPath, - caseSensitive: route.caseSensitive, - ); + _nameToPath[name] = (path: fullPath, caseSensitive: route.caseSensitive); } if (route.routes.isNotEmpty) { diff --git a/packages/go_router/lib/src/delegate.dart b/packages/go_router/lib/src/delegate.dart index 37e56987e358..95ef5a4b3a8a 100644 --- a/packages/go_router/lib/src/delegate.dart +++ b/packages/go_router/lib/src/delegate.dart @@ -16,8 +16,7 @@ import 'route.dart'; import 'state.dart'; /// GoRouter implementation of [RouterDelegate]. -class GoRouterDelegate extends RouterDelegate - with ChangeNotifier { +class GoRouterDelegate extends RouterDelegate with ChangeNotifier { /// Constructor for GoRouter's implementation of the RouterDelegate base /// class. GoRouterDelegate({ @@ -68,10 +67,7 @@ class GoRouterDelegate extends RouterDelegate if (lastRoute.onExit != null && navigatorKey.currentContext != null) { return !(await lastRoute.onExit!( navigatorKey.currentContext!, - currentConfiguration.last.buildState( - _configuration, - currentConfiguration, - ), + currentConfiguration.last.buildState(_configuration, currentConfiguration), )); } @@ -122,12 +118,9 @@ class GoRouterDelegate extends RouterDelegate RouteMatchBase walker = currentConfiguration.matches.last; while (walker is ShellRouteMatch) { - final NavigatorState potentialCandidate = - walker.navigatorKey.currentState!; + final NavigatorState potentialCandidate = walker.navigatorKey.currentState!; - final ModalRoute? modalRoute = ModalRoute.of( - potentialCandidate.context, - ); + final ModalRoute? modalRoute = ModalRoute.of(potentialCandidate.context); if (modalRoute == null || !modalRoute.isCurrent) { // Stop if there is a pageless route on top of the shell route. break; @@ -138,11 +131,7 @@ class GoRouterDelegate extends RouterDelegate return states.reversed; } - bool _handlePopPageWithRouteMatch( - Route route, - Object? result, - RouteMatchBase match, - ) { + bool _handlePopPageWithRouteMatch(Route route, Object? result, RouteMatchBase match) { if (route.willHandlePopInternally) { final bool popped = route.didPop(result); assert(!popped); @@ -198,10 +187,8 @@ class GoRouterDelegate extends RouterDelegate /// The top [GoRouterState], the state of the route that was /// last used in either [GoRouter.go] or [GoRouter.push]. - GoRouterState get state => currentConfiguration.last.buildState( - _configuration, - currentConfiguration, - ); + GoRouterState get state => + currentConfiguration.last.buildState(_configuration, currentConfiguration); /// For use by the Router architecture as part of the RouterDelegate. GlobalKey get navigatorKey => _configuration.navigatorKey; @@ -245,22 +232,17 @@ class GoRouterDelegate extends RouterDelegate return true; }); - final int compareUntil = math.min( - currentGoRouteMatches.length, - newGoRouteMatches.length, - ); + final int compareUntil = math.min(currentGoRouteMatches.length, newGoRouteMatches.length); var indexOfFirstDiff = 0; for (; indexOfFirstDiff < compareUntil; indexOfFirstDiff++) { - if (currentGoRouteMatches[indexOfFirstDiff] != - newGoRouteMatches[indexOfFirstDiff]) { + if (currentGoRouteMatches[indexOfFirstDiff] != newGoRouteMatches[indexOfFirstDiff]) { break; } } if (indexOfFirstDiff < currentGoRouteMatches.length) { - final List exitingMatches = currentGoRouteMatches - .sublist(indexOfFirstDiff) - .toList(); + final List exitingMatches = + currentGoRouteMatches.sublist(indexOfFirstDiff).toList(); return _callOnExitStartsAt( exitingMatches.length - 1, context: navigatorContext, @@ -297,11 +279,7 @@ class GoRouterDelegate extends RouterDelegate Future handleOnExitResult(bool exit) { if (exit) { - return _callOnExitStartsAt( - index - 1, - context: context, - matches: matches, - ); + return _callOnExitStartsAt(index - 1, context: context, matches: matches); } return SynchronousFuture(false); } diff --git a/packages/go_router/lib/src/information_provider.dart b/packages/go_router/lib/src/information_provider.dart index 5c0e1f191a27..2674c9799320 100644 --- a/packages/go_router/lib/src/information_provider.dart +++ b/packages/go_router/lib/src/information_provider.dart @@ -44,16 +44,9 @@ enum NavigatingType { class RouteInformationState { /// Creates an InternalRouteInformationState. @visibleForTesting - RouteInformationState({ - this.extra, - this.completer, - this.baseRouteMatchList, - required this.type, - }) : assert( - (type == NavigatingType.go || type == NavigatingType.restore) == - (completer == null), - ), - assert((type != NavigatingType.go) == (baseRouteMatchList != null)); + RouteInformationState({this.extra, this.completer, this.baseRouteMatchList, required this.type}) + : assert((type == NavigatingType.go || type == NavigatingType.restore) == (completer == null)), + assert((type != NavigatingType.go) == (baseRouteMatchList != null)); /// The extra object used when navigating with [GoRouter]. final Object? extra; @@ -78,14 +71,12 @@ class RouteInformationState { RouteInformationState(extra: extra, type: NavigatingType.go); /// Factory constructor for 'restore' navigation type. - static RouteInformationState restore({ - required RouteMatchList base, - Object? extra, - }) => RouteInformationState( - extra: extra ?? base.extra, - baseRouteMatchList: base, - type: NavigatingType.restore, - ); + static RouteInformationState restore({required RouteMatchList base, Object? extra}) => + RouteInformationState( + extra: extra ?? base.extra, + baseRouteMatchList: base, + type: NavigatingType.restore, + ); } /// The [RouteInformationProvider] created by go_router. @@ -100,10 +91,7 @@ class GoRouteInformationProvider extends RouteInformationProvider }) : _refreshListenable = refreshListenable, _value = RouteInformation( uri: Uri.parse(initialLocation), - state: RouteInformationState( - extra: initialExtra, - type: NavigatingType.go, - ), + state: RouteInformationState(extra: initialExtra, type: NavigatingType.go), ), _valueInEngine = _kEmptyRouteInformation, _routerNeglect = routerNeglect { @@ -115,9 +103,7 @@ class GoRouteInformationProvider extends RouteInformationProvider final bool _routerNeglect; static WidgetsBinding get _binding => WidgetsBinding.instance; - static final RouteInformation _kEmptyRouteInformation = RouteInformation( - uri: Uri.parse(''), - ); + static final RouteInformation _kEmptyRouteInformation = RouteInformation(uri: Uri.parse('')); @override void routerReportsNewRouteInformation( @@ -168,10 +154,7 @@ class GoRouteInformationProvider extends RouteInformationProvider uri = concatenateUris(_value.uri, uri); } - final bool shouldNotify = _valueHasChanged( - newLocationUri: uri, - newState: state, - ); + final bool shouldNotify = _valueHasChanged(newLocationUri: uri, newState: state); _value = RouteInformation(uri: uri, state: state); if (shouldNotify) { notifyListeners(); @@ -179,11 +162,7 @@ class GoRouteInformationProvider extends RouteInformationProvider } /// Pushes the `location` as a new route on top of `base`. - Future push( - String location, { - required RouteMatchList base, - Object? extra, - }) { + Future push(String location, {required RouteMatchList base, Object? extra}) { final completer = Completer(); _setValue( location, @@ -199,10 +178,7 @@ class GoRouteInformationProvider extends RouteInformationProvider /// Replace the current route matches with the `location`. void go(String location, {Object? extra}) { - _setValue( - location, - RouteInformationState(extra: extra, type: NavigatingType.go), - ); + _setValue(location, RouteInformationState(extra: extra, type: NavigatingType.go)); } /// Restores the current route matches with the `matchList`. @@ -219,11 +195,7 @@ class GoRouteInformationProvider extends RouteInformationProvider /// Removes the top-most route match from `base` and pushes the `location` as a /// new route on top. - Future pushReplacement( - String location, { - required RouteMatchList base, - Object? extra, - }) { + Future pushReplacement(String location, {required RouteMatchList base, Object? extra}) { final completer = Completer(); _setValue( location, @@ -238,11 +210,7 @@ class GoRouteInformationProvider extends RouteInformationProvider } /// Replaces the top-most route match from `base` with the `location`. - Future replace( - String location, { - required RouteMatchList base, - Object? extra, - }) { + Future replace(String location, {required RouteMatchList base, Object? extra}) { final completer = Completer(); _setValue( location, @@ -265,32 +233,20 @@ class GoRouteInformationProvider extends RouteInformationProvider if (routeInformation.state != null) { _value = _valueInEngine = routeInformation; } else { - _value = RouteInformation( - uri: routeInformation.uri, - state: RouteInformationState.go(), - ); + _value = RouteInformation(uri: routeInformation.uri, state: RouteInformationState.go()); _valueInEngine = _kEmptyRouteInformation; } notifyListeners(); } - bool _valueHasChanged({ - required Uri newLocationUri, - required Object? newState, - }) { + bool _valueHasChanged({required Uri newLocationUri, required Object? newState}) { const deepCollectionEquality = DeepCollectionEquality(); - return !deepCollectionEquality.equals( - _value.uri.path, - newLocationUri.path, - ) || + return !deepCollectionEquality.equals(_value.uri.path, newLocationUri.path) || !deepCollectionEquality.equals( _value.uri.queryParameters, newLocationUri.queryParameters, ) || - !deepCollectionEquality.equals( - _value.uri.fragment, - newLocationUri.fragment, - ) || + !deepCollectionEquality.equals(_value.uri.fragment, newLocationUri.fragment) || !deepCollectionEquality.equals(_value.state, newState); } diff --git a/packages/go_router/lib/src/logging.dart b/packages/go_router/lib/src/logging.dart index f25d21177714..d4f1cb0098d8 100644 --- a/packages/go_router/lib/src/logging.dart +++ b/packages/go_router/lib/src/logging.dart @@ -70,5 +70,4 @@ void _developerLog(LogRecord record) { void Function(LogRecord)? testDeveloperLog; /// The function used to log messages. -void Function(LogRecord) get _developerLogFunction => - testDeveloperLog ?? _developerLog; +void Function(LogRecord) get _developerLogFunction => testDeveloperLog ?? _developerLog; diff --git a/packages/go_router/lib/src/match.dart b/packages/go_router/lib/src/match.dart index 87f588a3eeef..5bb1db3ca0c6 100644 --- a/packages/go_router/lib/src/match.dart +++ b/packages/go_router/lib/src/match.dart @@ -47,10 +47,7 @@ abstract class RouteMatchBase with Diagnosticable { String get matchedLocation; /// Gets the state that represent this route match. - GoRouterState buildState( - RouteConfiguration configuration, - RouteMatchList matches, - ); + GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches); /// Generates a list of [RouteMatchBase] objects by matching the `route` and /// its sub-routes with `uri`. @@ -89,8 +86,7 @@ abstract class RouteMatchBase with Diagnosticable { /// The null key corresponds to the route matches of `scopedNavigatorKey`. /// The scopedNavigatorKey must not be part of the returned map; otherwise, /// it is impossible to order the matches. - static Map?, List> - _matchByNavigatorKey({ + static Map?, List> _matchByNavigatorKey({ required RouteBase route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 @@ -127,19 +123,14 @@ abstract class RouteMatchBase with Diagnosticable { // Grab the route matches for the scope navigator key and put it into the // matches for `null`. if (result.containsKey(scopedNavigatorKey)) { - final List matchesForScopedNavigator = result.remove( - scopedNavigatorKey, - )!; + final List matchesForScopedNavigator = result.remove(scopedNavigatorKey)!; assert(matchesForScopedNavigator.isNotEmpty); - result - .putIfAbsent(null, () => []) - .addAll(matchesForScopedNavigator); + result.putIfAbsent(null, () => []).addAll(matchesForScopedNavigator); } return result; } - static Map?, List> - _matchByNavigatorKeyForShellRoute({ + static Map?, List> _matchByNavigatorKeyForShellRoute({ required ShellRouteBase route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 @@ -149,9 +140,7 @@ abstract class RouteMatchBase with Diagnosticable { required Uri uri, }) { final GlobalKey? parentKey = - route.parentNavigatorKey == scopedNavigatorKey - ? null - : route.parentNavigatorKey; + route.parentNavigatorKey == scopedNavigatorKey ? null : route.parentNavigatorKey; Map?, List>? subRouteMatches; late GlobalKey navigatorKeyUsed; for (final RouteBase subRoute in route.routes) { @@ -165,9 +154,7 @@ abstract class RouteMatchBase with Diagnosticable { uri: uri, scopedNavigatorKey: navigatorKeyUsed, ); - assert( - !subRouteMatches.containsKey(route.navigatorKeyForSubRoute(subRoute)), - ); + assert(!subRouteMatches.containsKey(route.navigatorKeyForSubRoute(subRoute))); if (subRouteMatches.isNotEmpty) { break; } @@ -184,15 +171,12 @@ abstract class RouteMatchBase with Diagnosticable { pageKey: ValueKey(route.hashCode.toString()), navigatorKey: navigatorKeyUsed, ); - subRouteMatches - .putIfAbsent(parentKey, () => []) - .insert(0, result); + subRouteMatches.putIfAbsent(parentKey, () => []).insert(0, result); return subRouteMatches; } - static Map?, List> - _matchByNavigatorKeyForGoRoute({ + static Map?, List> _matchByNavigatorKeyForGoRoute({ required GoRoute route, required String matchedPath, // e.g. /family/:fid required String remainingLocation, // e.g. person/p1 @@ -202,32 +186,21 @@ abstract class RouteMatchBase with Diagnosticable { required Uri uri, }) { final GlobalKey? parentKey = - route.parentNavigatorKey == scopedNavigatorKey - ? null - : route.parentNavigatorKey; + route.parentNavigatorKey == scopedNavigatorKey ? null : route.parentNavigatorKey; - final RegExpMatch? regExpMatch = route.matchPatternAsPrefix( - remainingLocation, - ); + final RegExpMatch? regExpMatch = route.matchPatternAsPrefix(remainingLocation); if (regExpMatch == null) { return _empty; } - final Map encodedParams = route.extractPathParams( - regExpMatch, - ); + final Map encodedParams = route.extractPathParams(regExpMatch); // A temporary map to hold path parameters. This map is merged into // pathParameters only when this route is part of the returned result. - final Map currentPathParameter = encodedParams - .map( - (String key, String value) => - MapEntry(key, Uri.decodeComponent(value)), - ); - final String pathLoc = patternToPath(route.path, encodedParams); - final String newMatchedLocation = concatenatePaths( - matchedLocation, - pathLoc, + final Map currentPathParameter = encodedParams.map( + (String key, String value) => MapEntry(key, Uri.decodeComponent(value)), ); + final String pathLoc = patternToPath(route.path, encodedParams); + final String newMatchedLocation = concatenatePaths(matchedLocation, pathLoc); final String newMatchedPath = concatenatePaths(matchedPath, route.path); final String newMatchedLocationToCompare; @@ -308,11 +281,7 @@ abstract class RouteMatchBase with Diagnosticable { @immutable class RouteMatch extends RouteMatchBase { /// Constructor for [RouteMatch]. - const RouteMatch({ - required this.route, - required this.matchedLocation, - required this.pageKey, - }); + const RouteMatch({required this.route, required this.matchedLocation, required this.pageKey}); /// The matched route. @override @@ -339,10 +308,7 @@ class RouteMatch extends RouteMatchBase { int get hashCode => Object.hash(route, matchedLocation, pageKey); @override - GoRouterState buildState( - RouteConfiguration configuration, - RouteMatchList matches, - ) { + GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches) { return GoRouterState( configuration, uri: matches.uri, @@ -396,10 +362,7 @@ class ShellRouteMatch extends RouteMatchBase { final ValueKey pageKey; @override - GoRouterState buildState( - RouteConfiguration configuration, - RouteMatchList matches, - ) { + GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches) { // The route related data is stored in the leaf route match. final RouteMatch leafMatch = _lastLeaf; if (leafMatch is ImperativeRouteMatch) { @@ -444,28 +407,21 @@ class ShellRouteMatch extends RouteMatchBase { } @override - int get hashCode => - Object.hash(route, matchedLocation, Object.hashAll(matches), pageKey); + int get hashCode => Object.hash(route, matchedLocation, Object.hashAll(matches), pageKey); } /// The route match that represent route pushed through [GoRouter.push]. class ImperativeRouteMatch extends RouteMatch { /// Constructor for [ImperativeRouteMatch]. - ImperativeRouteMatch({ - required super.pageKey, - required this.matches, - required this.completer, - }) : super( - route: _getsLastRouteFromMatches(matches), - matchedLocation: _getsMatchedLocationFromMatches(matches), - ); + ImperativeRouteMatch({required super.pageKey, required this.matches, required this.completer}) + : super( + route: _getsLastRouteFromMatches(matches), + matchedLocation: _getsMatchedLocationFromMatches(matches), + ); static GoRoute _getsLastRouteFromMatches(RouteMatchList matchList) { if (matchList.isError) { - return GoRoute( - path: 'error', - builder: (_, __) => throw UnimplementedError(), - ); + return GoRoute(path: 'error', builder: (_, __) => throw UnimplementedError()); } return matchList.last.route; } @@ -490,10 +446,7 @@ class ImperativeRouteMatch extends RouteMatch { } @override - GoRouterState buildState( - RouteConfiguration configuration, - RouteMatchList matches, - ) { + GoRouterState buildState(RouteConfiguration configuration, RouteMatchList matches) { return super.buildState(configuration, this.matches); } @@ -623,11 +576,7 @@ class RouteMatchList with Diagnosticable { return copyWith(matches: [...matches, match]); } return copyWith( - matches: _createNewMatchUntilIncompatible( - matches, - match.matches.matches, - match, - ), + matches: _createNewMatchUntilIncompatible(matches, match.matches.matches, match), ); } @@ -654,9 +603,7 @@ class RouteMatchList with Diagnosticable { ); return newMatches; } - newMatches.add( - _cloneBranchAndInsertImperativeMatch(otherMatches.last, match), - ); + newMatches.add(_cloneBranchAndInsertImperativeMatch(otherMatches.last, match)); return newMatches; } @@ -666,9 +613,7 @@ class RouteMatchList with Diagnosticable { ) { if (branch is ShellRouteMatch) { return branch.copyWith( - matches: [ - _cloneBranchAndInsertImperativeMatch(branch.matches.last, match), - ], + matches: [_cloneBranchAndInsertImperativeMatch(branch.matches.last, match)], ); } // Add the input `match` instead of the incompatibleMatch since it contains @@ -680,10 +625,7 @@ class RouteMatchList with Diagnosticable { /// Returns a new instance of RouteMatchList with the input `match` removed /// from the current instance. RouteMatchList remove(RouteMatchBase match) { - final List newMatches = _removeRouteMatchFromList( - matches, - match, - ); + final List newMatches = _removeRouteMatchFromList(matches, match); if (newMatches == matches) { return this; } @@ -704,25 +646,15 @@ class RouteMatchList with Diagnosticable { newRoute as GoRoute; // Need to remove path parameters that are no longer in the fullPath. final newParameters = []; - patternToRegExp( - fullPath, - newParameters, - caseSensitive: newRoute.caseSensitive, - ); + patternToRegExp(fullPath, newParameters, caseSensitive: newRoute.caseSensitive); final Set validParameters = newParameters.toSet(); final newPathParameters = Map.fromEntries( pathParameters.entries.where( (MapEntry value) => validParameters.contains(value.key), ), ); - final Uri newUri = uri.replace( - path: patternToPath(fullPath, newPathParameters), - ); - return copyWith( - matches: newMatches, - uri: newUri, - pathParameters: newPathParameters, - ); + final Uri newUri = uri.replace(path: patternToPath(fullPath, newPathParameters)); + return copyWith(matches: newMatches, uri: newUri, pathParameters: newPathParameters); } /// Returns a new List from the input matches with target removed. @@ -755,10 +687,7 @@ class RouteMatchList with Diagnosticable { return matches.sublist(0, index); } if (match is ShellRouteMatch) { - final List newSubMatches = _removeRouteMatchFromList( - match.matches, - target, - ); + final List newSubMatches = _removeRouteMatchFromList(match.matches, target); if (newSubMatches == match.matches) { // Didn't find target in the newSubMatches. continue; @@ -824,16 +753,12 @@ class RouteMatchList with Diagnosticable { _visitRouteMatches(matches, visitor); } - static bool _visitRouteMatches( - List matches, - RouteMatchVisitor visitor, - ) { + static bool _visitRouteMatches(List matches, RouteMatchVisitor visitor) { for (final routeMatch in matches) { if (!visitor(routeMatch)) { return false; } - if (routeMatch is ShellRouteMatch && - !_visitRouteMatches(routeMatch.matches, visitor)) { + if (routeMatch is ShellRouteMatch && !_visitRouteMatches(routeMatch.matches, visitor)) { return false; } } @@ -868,10 +793,7 @@ class RouteMatchList with Diagnosticable { extra == other.extra && error == other.error && const ListEquality().equals(matches, other.matches) && - const MapEquality().equals( - pathParameters, - other.pathParameters, - ); + const MapEquality().equals(pathParameters, other.pathParameters); } @override @@ -883,8 +805,7 @@ class RouteMatchList with Diagnosticable { error, Object.hashAllUnordered( pathParameters.entries.map( - (MapEntry entry) => - Object.hash(entry.key, entry.value), + (MapEntry entry) => Object.hash(entry.key, entry.value), ), ), ); @@ -894,9 +815,7 @@ class RouteMatchList with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('uri', uri)); - properties.add( - DiagnosticsProperty>('matches', matches), - ); + properties.add(DiagnosticsProperty>('matches', matches)); } } @@ -929,8 +848,7 @@ class RouteMatchListCodec extends Codec> { final Converter, RouteMatchList> decoder; } -class _RouteMatchListEncoder - extends Converter> { +class _RouteMatchListEncoder extends Converter> { const _RouteMatchListEncoder(this.configuration); final RouteConfiguration configuration; @@ -971,9 +889,7 @@ class _RouteMatchListEncoder if (configuration.extraCodec != null) { encodedExtra = { RouteMatchListCodec._codecKey: RouteMatchListCodec._customCodecName, - RouteMatchListCodec._encodedKey: configuration.extraCodec?.encode( - extra, - ), + RouteMatchListCodec._encodedKey: configuration.extraCodec?.encode(extra), }; } else { String jsonEncodedExtra; @@ -997,15 +913,13 @@ class _RouteMatchListEncoder return { RouteMatchListCodec._locationKey: location, RouteMatchListCodec._extraKey: encodedExtra, - if (imperativeMatches != null) - RouteMatchListCodec._imperativeMatchesKey: imperativeMatches, + if (imperativeMatches != null) RouteMatchListCodec._imperativeMatchesKey: imperativeMatches, if (pageKey != null) RouteMatchListCodec._pageKey: pageKey, }; } } -class _RouteMatchListDecoder - extends Converter, RouteMatchList> { +class _RouteMatchListDecoder extends Converter, RouteMatchList> { _RouteMatchListDecoder(this.configuration); final RouteConfiguration configuration; @@ -1013,33 +927,21 @@ class _RouteMatchListDecoder @override RouteMatchList convert(Map input) { final rootLocation = input[RouteMatchListCodec._locationKey]! as String; - final encodedExtra = - input[RouteMatchListCodec._extraKey]! as Map; + final encodedExtra = input[RouteMatchListCodec._extraKey]! as Map; final Object? extra; - if (encodedExtra[RouteMatchListCodec._codecKey] == - RouteMatchListCodec._jsonCodecName) { - extra = json.decoder.convert( - encodedExtra[RouteMatchListCodec._encodedKey]! as String, - ); + if (encodedExtra[RouteMatchListCodec._codecKey] == RouteMatchListCodec._jsonCodecName) { + extra = json.decoder.convert(encodedExtra[RouteMatchListCodec._encodedKey]! as String); } else { - extra = configuration.extraCodec?.decode( - encodedExtra[RouteMatchListCodec._encodedKey], - ); + extra = configuration.extraCodec?.decode(encodedExtra[RouteMatchListCodec._encodedKey]); } - RouteMatchList matchList = configuration.findMatch( - Uri.parse(rootLocation), - extra: extra, - ); + RouteMatchList matchList = configuration.findMatch(Uri.parse(rootLocation), extra: extra); - final imperativeMatches = - input[RouteMatchListCodec._imperativeMatchesKey] as List?; + final imperativeMatches = input[RouteMatchListCodec._imperativeMatchesKey] as List?; if (imperativeMatches != null) { for (final Map encodedImperativeMatch in imperativeMatches.whereType>()) { - final RouteMatchList imperativeMatchList = convert( - encodedImperativeMatch, - ); + final RouteMatchList imperativeMatchList = convert(encodedImperativeMatch); final pageKey = ValueKey( encodedImperativeMatch[RouteMatchListCodec._pageKey]! as String, ); diff --git a/packages/go_router/lib/src/misc/error_screen.dart b/packages/go_router/lib/src/misc/error_screen.dart index 2556944cc55e..55a76a431d25 100644 --- a/packages/go_router/lib/src/misc/error_screen.dart +++ b/packages/go_router/lib/src/misc/error_screen.dart @@ -22,19 +22,13 @@ class ErrorScreen extends StatelessWidget { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Text( - 'Page Not Found', - style: TextStyle(fontWeight: FontWeight.bold), - ), + const Text('Page Not Found', style: TextStyle(fontWeight: FontWeight.bold)), const SizedBox(height: 16), Text(error?.toString() ?? 'page not found'), const SizedBox(height: 16), _Button( onPressed: () => context.go('/'), - child: const Text( - 'Go to home page', - style: TextStyle(color: _kWhite), - ), + child: const Text('Go to home page', style: TextStyle(color: _kWhite)), ), ], ), @@ -61,19 +55,13 @@ class _ButtonState extends State<_Button> { void didChangeDependencies() { super.didChangeDependencies(); _color = - (context as Element) - .findAncestorWidgetOfExactType() - ?.color ?? + (context as Element).findAncestorWidgetOfExactType()?.color ?? const Color(0xFF2196F3); // blue } @override Widget build(BuildContext context) => GestureDetector( onTap: widget.onPressed, - child: Container( - padding: const EdgeInsets.all(8), - color: _color, - child: widget.child, - ), + child: Container(padding: const EdgeInsets.all(8), color: _color, child: widget.child), ); } diff --git a/packages/go_router/lib/src/misc/extensions.dart b/packages/go_router/lib/src/misc/extensions.dart index 4c06c6da9eee..36cb7e3142e6 100644 --- a/packages/go_router/lib/src/misc/extensions.dart +++ b/packages/go_router/lib/src/misc/extensions.dart @@ -23,8 +23,7 @@ extension GoRouterHelper on BuildContext { ); /// Navigate to a location. - void go(String location, {Object? extra}) => - GoRouter.of(this).go(location, extra: extra); + void go(String location, {Object? extra}) => GoRouter.of(this).go(location, extra: extra); /// Navigate to a named route. void goNamed( diff --git a/packages/go_router/lib/src/misc/inherited_router.dart b/packages/go_router/lib/src/misc/inherited_router.dart index f5fd5e08032a..39e2d7cb8944 100644 --- a/packages/go_router/lib/src/misc/inherited_router.dart +++ b/packages/go_router/lib/src/misc/inherited_router.dart @@ -13,11 +13,7 @@ import '../router.dart'; /// when routing from anywhere in your app. class InheritedGoRouter extends InheritedWidget { /// Default constructor for the inherited go router. - const InheritedGoRouter({ - required super.child, - required this.goRouter, - super.key, - }); + const InheritedGoRouter({required super.child, required this.goRouter, super.key}); /// The [GoRouter] that is made available to the widget tree. final GoRouter goRouter; diff --git a/packages/go_router/lib/src/pages/cupertino.dart b/packages/go_router/lib/src/pages/cupertino.dart index 152eae606174..3061059d44b9 100644 --- a/packages/go_router/lib/src/pages/cupertino.dart +++ b/packages/go_router/lib/src/pages/cupertino.dart @@ -12,8 +12,7 @@ bool isCupertinoApp(BuildContext context) => context.findAncestorWidgetOfExactType() != null; /// Creates a Cupertino HeroController. -HeroController createCupertinoHeroController() => - CupertinoApp.createCupertinoHeroController(); +HeroController createCupertinoHeroController() => CupertinoApp.createCupertinoHeroController(); /// Builds a Cupertino page. CupertinoPage pageBuilderForCupertinoApp({ @@ -46,10 +45,7 @@ class CupertinoErrorScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ Text(error?.toString() ?? 'page not found'), - CupertinoButton( - onPressed: () => context.go('/'), - child: const Text('Home'), - ), + CupertinoButton(onPressed: () => context.go('/'), child: const Text('Home')), ], ), ), diff --git a/packages/go_router/lib/src/pages/custom_transition_page.dart b/packages/go_router/lib/src/pages/custom_transition_page.dart index 8164e7ac3705..606db68dc88d 100644 --- a/packages/go_router/lib/src/pages/custom_transition_page.dart +++ b/packages/go_router/lib/src/pages/custom_transition_page.dart @@ -108,13 +108,11 @@ class CustomTransitionPage extends Page { transitionsBuilder; @override - Route createRoute(BuildContext context) => - _CustomTransitionPageRoute(this); + Route createRoute(BuildContext context) => _CustomTransitionPageRoute(this); } class _CustomTransitionPageRoute extends PageRoute { - _CustomTransitionPageRoute(CustomTransitionPage page) - : super(settings: page); + _CustomTransitionPageRoute(CustomTransitionPage page) : super(settings: page); CustomTransitionPage get _page => settings as CustomTransitionPage; @@ -147,11 +145,7 @@ class _CustomTransitionPageRoute extends PageRoute { BuildContext context, Animation animation, Animation secondaryAnimation, - ) => Semantics( - scopesRoute: true, - explicitChildNodes: true, - child: _page.child, - ); + ) => Semantics(scopesRoute: true, explicitChildNodes: true, child: _page.child); @override Widget buildTransitions( diff --git a/packages/go_router/lib/src/pages/material.dart b/packages/go_router/lib/src/pages/material.dart index 953cc0d42014..299bfbf42427 100644 --- a/packages/go_router/lib/src/pages/material.dart +++ b/packages/go_router/lib/src/pages/material.dart @@ -13,8 +13,7 @@ bool isMaterialApp(BuildContext context) => context.findAncestorWidgetOfExactType() != null; /// Creates a Material HeroController. -HeroController createMaterialHeroController() => - MaterialApp.createMaterialHeroController(); +HeroController createMaterialHeroController() => MaterialApp.createMaterialHeroController(); /// Builds a Material page. MaterialPage pageBuilderForMaterialApp({ @@ -47,10 +46,7 @@ class MaterialErrorScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ SelectableText(error?.toString() ?? 'page not found'), - TextButton( - onPressed: () => context.go('/'), - child: const Text('Home'), - ), + TextButton(onPressed: () => context.go('/'), child: const Text('Home')), ], ), ), diff --git a/packages/go_router/lib/src/parser.dart b/packages/go_router/lib/src/parser.dart index 5b91b0e81ff9..cd037e2343b6 100644 --- a/packages/go_router/lib/src/parser.dart +++ b/packages/go_router/lib/src/parser.dart @@ -24,10 +24,7 @@ import 'state.dart'; /// The returned [RouteMatchList] is used as parsed result for the /// [GoRouterDelegate]. typedef ParserExceptionHandler = - RouteMatchList Function( - BuildContext context, - RouteMatchList routeMatchList, - ); + RouteMatchList Function(BuildContext context, RouteMatchList routeMatchList); /// The function signature for navigation callbacks in [_OnEnterHandler]. typedef NavigationCallback = Future Function(); @@ -94,9 +91,7 @@ class GoRouteInformationParser extends RouteInformationParser { incomingUri = routeInformation.uri; } else if (raw is! RouteInformationState) { // Restoration/back-forward: decode the stored match list and treat as restore. - final RouteMatchList decoded = _routeMatchListCodec.decode( - raw as Map, - ); + final RouteMatchList decoded = _routeMatchListCodec.decode(raw as Map); infoState = RouteInformationState.restore(base: decoded); incomingUri = decoded.uri; } else { @@ -121,19 +116,12 @@ class GoRouteInformationParser extends RouteInformationParser { effectiveRoute.uri, extra: infoState.extra, ); - return _navigate( - effectiveRoute, - context, - infoState, - startingMatches: initialMatches, - ); + return _navigate(effectiveRoute, context, infoState, startingMatches: initialMatches); }, onCanNotEnter: () { // If blocked, stay on the current route by restoring the last known good configuration. if (router.routerDelegate.currentConfiguration.isNotEmpty) { - return SynchronousFuture( - router.routerDelegate.currentConfiguration, - ); + return SynchronousFuture(router.routerDelegate.currentConfiguration); } if (_lastMatchList != null) { @@ -149,9 +137,8 @@ class GoRouteInformationParser extends RouteInformationParser { ), extra: infoState.extra, ); - final RouteMatchList resolved = onParserException != null - ? onParserException!(context, blocked) - : blocked; + final RouteMatchList resolved = + onParserException != null ? onParserException!(context, blocked) : blocked; return SynchronousFuture(resolved); }, ); @@ -170,87 +157,71 @@ class GoRouteInformationParser extends RouteInformationParser { // If we weren't given matches, compute them here. The URI has already been // normalized at the parser entry point. final FutureOr baseMatches = - startingMatches ?? - configuration.findMatch(routeInformation.uri, extra: infoState.extra); + startingMatches ?? configuration.findMatch(routeInformation.uri, extra: infoState.extra); final redirectHistory = []; // redirect() handles both top-level and route-level redirects. FutureOr applyRedirects(FutureOr base) { if (base is RouteMatchList) { - return configuration.redirect( - context, - base, - redirectHistory: redirectHistory, - ); + return configuration.redirect(context, base, redirectHistory: redirectHistory); } return base.then((RouteMatchList ml) { if (!context.mounted) { return ml; } - return configuration.redirect( - context, - ml, - redirectHistory: redirectHistory, - ); + return configuration.redirect(context, ml, redirectHistory: redirectHistory); }); } final FutureOr redirected = applyRedirects(baseMatches); - return debugParserFuture = - (redirected is RouteMatchList - ? SynchronousFuture(redirected) - : redirected) - .then((RouteMatchList matchList) { - // Guard against context disposal during async redirects. - if (!context.mounted) { - return _lastMatchList ?? - _OnEnterHandler._errorRouteMatchList( - routeInformation.uri, - GoException( - 'Navigation aborted because the router context was disposed.', - ), - extra: infoState.extra, - ); - } - if (matchList.isError && onParserException != null) { - return onParserException!(context, matchList); - } - - // Validate that redirect-only routes actually perform a redirection. - assert(() { - if (matchList.isNotEmpty) { - assert( - !matchList.last.route.redirectOnly, - 'A redirect-only route must redirect to location different from itself.\n The offending route: ${matchList.last.route}', - ); - } - return true; - }()); - - // Update the route match list based on the navigation type. - final RouteMatchList updated = _updateRouteMatchList( - matchList, - baseRouteMatchList: infoState.baseRouteMatchList, - completer: infoState.completer, - type: infoState.type, + return debugParserFuture = (redirected is RouteMatchList + ? SynchronousFuture(redirected) + : redirected) + .then((RouteMatchList matchList) { + // Guard against context disposal during async redirects. + if (!context.mounted) { + return _lastMatchList ?? + _OnEnterHandler._errorRouteMatchList( + routeInformation.uri, + GoException('Navigation aborted because the router context was disposed.'), + extra: infoState.extra, + ); + } + if (matchList.isError && onParserException != null) { + return onParserException!(context, matchList); + } + + // Validate that redirect-only routes actually perform a redirection. + assert(() { + if (matchList.isNotEmpty) { + assert( + !matchList.last.route.redirectOnly, + 'A redirect-only route must redirect to location different from itself.\n The offending route: ${matchList.last.route}', ); + } + return true; + }()); + + // Update the route match list based on the navigation type. + final RouteMatchList updated = _updateRouteMatchList( + matchList, + baseRouteMatchList: infoState.baseRouteMatchList, + completer: infoState.completer, + type: infoState.type, + ); - // Cache the successful match list. - _lastMatchList = updated; - return updated; - }); + // Cache the successful match list. + _lastMatchList = updated; + return updated; + }); } @override - Future parseRouteInformation( - RouteInformation routeInformation, - ) { + Future parseRouteInformation(RouteInformation routeInformation) { // Not used in go_router; instruct users to use parseRouteInformationWithDependencies. - throw UnimplementedError( - 'Use parseRouteInformationWithDependencies instead', - ); + throw UnimplementedError('Use parseRouteInformationWithDependencies instead'); } @override @@ -338,9 +309,7 @@ class GoRouteInformationParser extends RouteInformationParser { /// Returns a unique [ValueKey] for a new route. ValueKey _getUniqueValueKey() { return ValueKey( - String.fromCharCodes( - List.generate(32, (_) => _random.nextInt(33) + 89), - ), + String.fromCharCodes(List.generate(32, (_) => _random.nextInt(33) + 89)), ); } } @@ -418,8 +387,11 @@ class _OnEnterHandler { // Check if the redirection history exceeds the configured limit. // `routeInformation` has already been normalized by the parser entrypoint. - final RouteMatchList? redirectionErrorMatchList = - _redirectionErrorMatchList(context, routeInformation.uri, infoState); + final RouteMatchList? redirectionErrorMatchList = _redirectionErrorMatchList( + context, + routeInformation.uri, + infoState, + ); if (redirectionErrorMatchList != null) { // Return immediately if the redirection limit is exceeded. @@ -433,30 +405,20 @@ class _OnEnterHandler { ); // Build the next navigation state. - final GoRouterState nextState = _buildTopLevelGoRouterState( - incomingMatches, - ); + final GoRouterState nextState = _buildTopLevelGoRouterState(incomingMatches); // Get the current state from the router delegate. - final RouteMatchList currentMatchList = - _router.routerDelegate.currentConfiguration; - final GoRouterState currentState = currentMatchList.isNotEmpty - ? _buildTopLevelGoRouterState(currentMatchList) - : nextState; + final RouteMatchList currentMatchList = _router.routerDelegate.currentConfiguration; + final GoRouterState currentState = + currentMatchList.isNotEmpty ? _buildTopLevelGoRouterState(currentMatchList) : nextState; // Execute the onEnter callback in a try-catch to capture synchronous exceptions. Future onEnterResultFuture; try { - final FutureOr result = topOnEnter( - context, - currentState, - nextState, - _router, - ); + final FutureOr result = topOnEnter(context, currentState, nextState, _router); // Convert FutureOr to Future - onEnterResultFuture = result is OnEnterResult - ? SynchronousFuture(result) - : result; + onEnterResultFuture = + result is OnEnterResult ? SynchronousFuture(result) : result; } catch (error) { final RouteMatchList errorMatchList = _errorRouteMatchList( routeInformation.uri, @@ -466,11 +428,9 @@ class _OnEnterHandler { _resetRedirectionHistory(); - final bool canHandleException = - _onParserException != null && context.mounted; - final RouteMatchList handledMatchList = canHandleException - ? _onParserException(context, errorMatchList) - : errorMatchList; + final bool canHandleException = _onParserException != null && context.mounted; + final RouteMatchList handledMatchList = + canHandleException ? _onParserException(context, errorMatchList) : errorMatchList; return SynchronousFuture(handledMatchList); } @@ -486,9 +446,7 @@ class _OnEnterHandler { _resetRedirectionHistory(); // reset after committed navigation } else { // Block: check if this is a hard stop or chaining block - log( - 'onEnter blocked navigation from ${currentState.uri} to ${nextState.uri}', - ); + log('onEnter blocked navigation from ${currentState.uri} to ${nextState.uri}'); matchList = await onCanNotEnter(); // Treat `Block.stop()` as the explicit hard stop. @@ -609,9 +567,7 @@ class _OnEnterHandler { ) { _redirectionHistory.add(redirectedUri); if (_redirectionHistory.length > _configuration.redirectLimit) { - final String formattedHistory = _formatOnEnterRedirectionHistory( - _redirectionHistory, - ); + final String formattedHistory = _formatOnEnterRedirectionHistory(_redirectionHistory); final RouteMatchList errorMatchList = _errorRouteMatchList( redirectedUri, GoException('Too many onEnter calls detected: $formattedHistory'), @@ -639,11 +595,7 @@ class _OnEnterHandler { /// Creates an error [RouteMatchList] for the given [uri] and [exception]. /// /// This is used to encapsulate errors encountered during redirection or parsing. - static RouteMatchList _errorRouteMatchList( - Uri uri, - GoException exception, { - Object? extra, - }) { + static RouteMatchList _errorRouteMatchList(Uri uri, GoException exception, {Object? extra}) { return RouteMatchList( matches: const [], extra: extra, diff --git a/packages/go_router/lib/src/path_utils.dart b/packages/go_router/lib/src/path_utils.dart index ed1ce7cc2015..0360a670b0ae 100644 --- a/packages/go_router/lib/src/path_utils.dart +++ b/packages/go_router/lib/src/path_utils.dart @@ -23,11 +23,7 @@ final RegExp _parameterRegExp = RegExp(r':(\w+)(\((?:\\.|[^\\()])+\))?'); /// To extract the path parameter values from a [RegExpMatch], pass the /// [RegExpMatch] into [extractPathParameters] with the `parameters` that are /// used for generating the [RegExp]. -RegExp patternToRegExp( - String pattern, - List parameters, { - required bool caseSensitive, -}) { +RegExp patternToRegExp(String pattern, List parameters, {required bool caseSensitive}) { final buffer = StringBuffer('^'); var start = 0; for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) { @@ -36,9 +32,8 @@ RegExp patternToRegExp( } final String name = match[1]!; final String? optionalPattern = match[2]; - final String regex = optionalPattern != null - ? _escapeGroup(optionalPattern, name) - : '(?<$name>[^/]+)'; + final String regex = + optionalPattern != null ? _escapeGroup(optionalPattern, name) : '(?<$name>[^/]+)'; buffer.write(regex); parameters.add(name); start = match.end; @@ -99,13 +94,9 @@ String patternToPath(String pattern, Map pathParameters) { /// /// The [parameters] should originate from the call to [patternToRegExp] that /// creates the [RegExp]. -Map extractPathParameters( - List parameters, - RegExpMatch match, -) { +Map extractPathParameters(List parameters, RegExpMatch match) { return { - for (int i = 0; i < parameters.length; ++i) - parameters[i]: match.namedGroup(parameters[i])!, + for (int i = 0; i < parameters.length; ++i) parameters[i]: match.namedGroup(parameters[i])!, }; } @@ -125,9 +116,7 @@ String concatenatePaths(String parentPath, String childPath) { /// /// e.g: pathA = /a?fid=f1, pathB = c/d?pid=p2, concatenatePaths(pathA, pathB) = /a/c/d?pid=2. Uri concatenateUris(Uri parentUri, Uri childUri) { - Uri newUri = childUri.replace( - path: concatenatePaths(parentUri.path, childUri.path), - ); + Uri newUri = childUri.replace(path: concatenatePaths(parentUri.path, childUri.path)); // Parse the new normalized uri to remove unnecessary parts, like the trailing '?'. newUri = Uri.parse(canonicalUri(newUri.toString())); @@ -148,21 +137,19 @@ String canonicalUri(String loc) { // / => / // /login?from=/ => /login?from=/ canon = - uri.path.endsWith('/') && - uri.path != '/' && - !uri.hasQuery && - !uri.hasFragment - ? canon.substring(0, canon.length - 1) - : canon; + uri.path.endsWith('/') && uri.path != '/' && !uri.hasQuery && !uri.hasFragment + ? canon.substring(0, canon.length - 1) + : canon; // replace '/?', except for first occurrence, from path only // /login/?from=/ => /login?from=/ // /?from=/ => /?from=/ - final int pathStartIndex = uri.host.isNotEmpty - ? uri.toString().indexOf(uri.host) + uri.host.length - : uri.hasScheme - ? uri.toString().indexOf(uri.scheme) + uri.scheme.length - : 0; + final int pathStartIndex = + uri.host.isNotEmpty + ? uri.toString().indexOf(uri.host) + uri.host.length + : uri.hasScheme + ? uri.toString().indexOf(uri.scheme) + uri.scheme.length + : 0; if (pathStartIndex < canon.length) { canon = canon.replaceFirst('/?', '?', pathStartIndex + 1); } @@ -171,24 +158,15 @@ String canonicalUri(String loc) { } /// Builds an absolute path for the provided route. -String? fullPathForRoute( - RouteBase targetRoute, - String parentFullpath, - List routes, -) { +String? fullPathForRoute(RouteBase targetRoute, String parentFullpath, List routes) { for (final route in routes) { - final String fullPath = (route is GoRoute) - ? concatenatePaths(parentFullpath, route.path) - : parentFullpath; + final String fullPath = + (route is GoRoute) ? concatenatePaths(parentFullpath, route.path) : parentFullpath; if (route == targetRoute) { return fullPath; } else { - final String? subRoutePath = fullPathForRoute( - targetRoute, - fullPath, - route.routes, - ); + final String? subRoutePath = fullPathForRoute(targetRoute, fullPath, route.routes); if (subRoutePath != null) { return subRoutePath; } diff --git a/packages/go_router/lib/src/route.dart b/packages/go_router/lib/src/route.dart index cf1a7e240827..358dde76f36d 100644 --- a/packages/go_router/lib/src/route.dart +++ b/packages/go_router/lib/src/route.dart @@ -18,12 +18,10 @@ import 'router.dart'; import 'state.dart'; /// The page builder for [GoRoute]. -typedef GoRouterPageBuilder = - Page Function(BuildContext context, GoRouterState state); +typedef GoRouterPageBuilder = Page Function(BuildContext context, GoRouterState state); /// The widget builder for [GoRoute]. -typedef GoRouterWidgetBuilder = - Widget Function(BuildContext context, GoRouterState state); +typedef GoRouterWidgetBuilder = Widget Function(BuildContext context, GoRouterState state); /// The widget builder for [ShellRoute]. typedef ShellRouteBuilder = @@ -31,11 +29,7 @@ typedef ShellRouteBuilder = /// The page builder for [ShellRoute]. typedef ShellRoutePageBuilder = - Page Function( - BuildContext context, - GoRouterState state, - Widget child, - ); + Page Function(BuildContext context, GoRouterState state, Widget child); /// The widget builder for [StatefulShellRoute]. typedef StatefulShellRouteBuilder = @@ -67,8 +61,7 @@ typedef NavigatorBuilder = /// /// If the return value is true or the future resolve to true, the route will /// exit as usual. Otherwise, the operation will abort. -typedef ExitCallback = - FutureOr Function(BuildContext context, GoRouterState state); +typedef ExitCallback = FutureOr Function(BuildContext context, GoRouterState state); /// The base class for [GoRoute] and [ShellRoute]. /// @@ -158,11 +151,7 @@ typedef ExitCallback = /// See [main.dart](https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/main.dart) @immutable abstract class RouteBase with Diagnosticable { - const RouteBase._({ - this.redirect, - required this.routes, - required this.parentNavigatorKey, - }); + const RouteBase._({this.redirect, required this.routes, required this.parentNavigatorKey}); /// An optional redirect function for this route. /// @@ -233,9 +222,7 @@ abstract class RouteBase with Diagnosticable { /// Builds a lists containing the provided routes along with all their /// descendant [routes]. static Iterable routesRecursively(Iterable routes) { - return routes.expand( - (RouteBase e) => [e, ...routesRecursively(e.routes)], - ); + return routes.expand((RouteBase e) => [e, ...routesRecursively(e.routes)]); } @override @@ -243,10 +230,7 @@ abstract class RouteBase with Diagnosticable { super.debugFillProperties(properties); if (parentNavigatorKey != null) { properties.add( - DiagnosticsProperty>( - 'parentNavKey', - parentNavigatorKey, - ), + DiagnosticsProperty>('parentNavKey', parentNavigatorKey), ); } } @@ -294,11 +278,7 @@ class GoRoute extends RouteBase { ), super._() { // cache the path regexp and parameters - _pathRE = patternToRegExp( - path, - pathParameters, - caseSensitive: caseSensitive, - ); + _pathRE = patternToRegExp(path, pathParameters, caseSensitive: caseSensitive); } /// Whether this [GoRoute] only redirects to another route. @@ -482,9 +462,7 @@ class GoRoute extends RouteBase { super.debugFillProperties(properties); properties.add(StringProperty('name', name)); properties.add(StringProperty('path', path)); - properties.add( - FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only'), - ); + properties.add(FlagProperty('redirect', value: redirectOnly, ifTrue: 'Redirect Only')); } late final RegExp _pathRE; @@ -515,8 +493,7 @@ abstract class ShellRouteBase extends RouteBase { ) { for (final route in subRoutes) { assert( - route.parentNavigatorKey == null || - route.parentNavigatorKey == navigatorKey, + route.parentNavigatorKey == null || route.parentNavigatorKey == navigatorKey, "sub-route's parent navigator key must either be null or has the same navigator key as parent's key", ); if (route is GoRoute && route.redirectOnly) { @@ -594,9 +571,7 @@ class ShellRouteContext { final effectiveObservers = [...?observers]; if (notifyRootObserver) { - final List? rootObservers = GoRouter.maybeOf( - context, - )?.observers; + final List? rootObservers = GoRouter.maybeOf(context)?.observers; if (rootObservers != null) { effectiveObservers.add(_MergedNavigatorObserver(rootObservers)); } @@ -723,10 +698,7 @@ class ShellRoute extends ShellRouteBase { navigatorKey = navigatorKey ?? GlobalKey(), super._() { assert(() { - ShellRouteBase._debugCheckSubRouteParentNavigatorKeys( - routes, - this.navigatorKey, - ); + ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(routes, this.navigatorKey); return true; }()); } @@ -807,12 +779,7 @@ class ShellRoute extends ShellRouteBase { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add( - DiagnosticsProperty>( - 'navigatorKey', - navigatorKey, - ), - ); + properties.add(DiagnosticsProperty>('navigatorKey', navigatorKey)); } } @@ -1021,11 +988,7 @@ class StatefulShellRoute extends ShellRouteBase { ShellRouteContext shellRouteContext, ) { if (pageBuilder != null) { - return pageBuilder!( - context, - state, - _createShell(context, shellRouteContext), - ); + return pageBuilder!(context, state, _createShell(context, shellRouteContext)); } return null; } @@ -1042,14 +1005,12 @@ class StatefulShellRoute extends ShellRouteBase { Iterable> get _navigatorKeys => branches.map((StatefulShellBranch b) => b.navigatorKey); - StatefulNavigationShell _createShell( - BuildContext context, - ShellRouteContext shellRouteContext, - ) => StatefulNavigationShell( - shellRouteContext: shellRouteContext, - router: GoRouter.of(context), - containerBuilder: navigatorContainerBuilder, - ); + StatefulNavigationShell _createShell(BuildContext context, ShellRouteContext shellRouteContext) => + StatefulNavigationShell( + shellRouteContext: shellRouteContext, + router: GoRouter.of(context), + containerBuilder: navigatorContainerBuilder, + ); static Widget _indexedStackContainerBuilder( BuildContext context, @@ -1067,19 +1028,14 @@ class StatefulShellRoute extends ShellRouteBase { static Set> _debugUniqueNavigatorKeys( List branches, - ) => Set>.from( - branches.map((StatefulShellBranch e) => e.navigatorKey), - ); + ) => Set>.from(branches.map((StatefulShellBranch e) => e.navigatorKey)); - static bool _debugValidateParentNavigatorKeys( - List branches, - ) { + static bool _debugValidateParentNavigatorKeys(List branches) { for (final branch in branches) { for (final RouteBase route in branch.routes) { if (route is GoRoute) { assert( - route.parentNavigatorKey == null || - route.parentNavigatorKey == branch.navigatorKey, + route.parentNavigatorKey == null || route.parentNavigatorKey == branch.navigatorKey, ); } } @@ -1091,10 +1047,7 @@ class StatefulShellRoute extends ShellRouteBase { String? restorationScopeId, List branches, ) { - if (branches - .map((StatefulShellBranch e) => e.restorationScopeId) - .nonNulls - .isNotEmpty) { + if (branches.map((StatefulShellBranch e) => e.restorationScopeId).nonNulls.isNotEmpty) { assert( restorationScopeId != null, 'A restorationScopeId must be set for ' @@ -1109,10 +1062,7 @@ class StatefulShellRoute extends ShellRouteBase { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add( - DiagnosticsProperty>>( - 'navigatorKeys', - _navigatorKeys, - ), + DiagnosticsProperty>>('navigatorKeys', _navigatorKeys), ); } } @@ -1144,10 +1094,7 @@ class StatefulShellBranch { this.preload = false, }) : navigatorKey = navigatorKey ?? GlobalKey() { assert(() { - ShellRouteBase._debugCheckSubRouteParentNavigatorKeys( - routes, - this.navigatorKey, - ); + ShellRouteBase._debugCheckSubRouteParentNavigatorKeys(routes, this.navigatorKey); return true; }()); } @@ -1199,8 +1146,7 @@ class StatefulShellBranch { /// /// This route will be used when loading the branch for the first time, if /// an [initialLocation] has not been provided. - GoRoute? get defaultRoute => - RouteBase.routesRecursively(routes).whereType().firstOrNull; + GoRoute? get defaultRoute => RouteBase.routesRecursively(routes).whereType().firstOrNull; } /// Builder for a custom container for the branch Navigators of a @@ -1243,9 +1189,7 @@ class StatefulNavigationShell extends StatefulWidget { shellRouteContext.route as StatefulShellRoute, shellRouteContext.navigatorKey, ), - super( - key: (shellRouteContext.route as StatefulShellRoute)._shellStateKey, - ); + super(key: (shellRouteContext.route as StatefulShellRoute)._shellStateKey); /// The ShellRouteContext responsible for building the Navigator for the /// current [StatefulShellBranch]. @@ -1275,8 +1219,7 @@ class StatefulNavigationShell extends StatefulWidget { // class. void goBranch(int index, {bool initialLocation = false}) { final route = shellRouteContext.route as StatefulShellRoute; - final StatefulNavigationShellState? shellState = - route._shellStateKey.currentState; + final StatefulNavigationShellState? shellState = route._shellStateKey.currentState; if (shellState != null) { shellState.goBranch(index, initialLocation: initialLocation); } else { @@ -1288,8 +1231,7 @@ class StatefulNavigationShell extends StatefulWidget { /// associated with it). @visibleForTesting List get debugLoadedBranches => - route._shellStateKey.currentState?._loadedBranches ?? - []; + route._shellStateKey.currentState?._loadedBranches ?? []; /// Gets the effective initial location for the branch at the provided index /// in the associated [StatefulShellRoute]. @@ -1308,17 +1250,10 @@ class StatefulNavigationShell extends StatefulWidget { /// find the first GoRoute, from which a full path will be derived. final GoRoute route = branch.defaultRoute!; final parameters = []; - patternToRegExp( - route.path, - parameters, - caseSensitive: route.caseSensitive, - ); + patternToRegExp(route.path, parameters, caseSensitive: route.caseSensitive); assert(parameters.isEmpty); final String fullPath = _router.configuration.locationForRoute(route)!; - return patternToPath( - fullPath, - shellRouteContext.routerState.pathParameters, - ); + return patternToPath(fullPath, shellRouteContext.routerState.pathParameters); } } @@ -1327,8 +1262,8 @@ class StatefulNavigationShell extends StatefulWidget { /// Gets the state for the nearest stateful shell route in the Widget tree. static StatefulNavigationShellState of(BuildContext context) { - final StatefulNavigationShellState? shellState = context - .findAncestorStateOfType(); + final StatefulNavigationShellState? shellState = + context.findAncestorStateOfType(); assert(shellState != null); return shellState!; } @@ -1337,8 +1272,8 @@ class StatefulNavigationShell extends StatefulWidget { /// /// Returns null if no stateful shell route is found. static StatefulNavigationShellState? maybeOf(BuildContext context) { - final StatefulNavigationShellState? shellState = context - .findAncestorStateOfType(); + final StatefulNavigationShellState? shellState = + context.findAncestorStateOfType(); return shellState; } @@ -1355,8 +1290,7 @@ class StatefulNavigationShell extends StatefulWidget { } /// State for StatefulNavigationShell. -class StatefulNavigationShellState extends State - with RestorationMixin { +class StatefulNavigationShellState extends State with RestorationMixin { final Map _branchState = {}; @@ -1365,8 +1299,7 @@ class StatefulNavigationShellState extends State GoRouter get _router => widget._router; - bool _isBranchLoaded(StatefulShellBranch branch) => - _branchState[branch] != null; + bool _isBranchLoaded(StatefulShellBranch branch) => _branchState[branch] != null; List get _loadedBranches => _branchState.keys.toList(); @@ -1382,19 +1315,13 @@ class StatefulNavigationShellState extends State : identityHashCode(branch).toString(); } - _StatefulShellBranchState _branchStateFor( - StatefulShellBranch branch, [ - bool register = true, - ]) { + _StatefulShellBranchState _branchStateFor(StatefulShellBranch branch, [bool register = true]) { return _branchState.putIfAbsent(branch, () { final branchState = _StatefulShellBranchState( location: _RestorableRouteMatchList(_router.configuration), ); if (register) { - registerForRestoration( - branchState.location, - _branchLocationRestorationScopeId(branch), - ); + registerForRestoration(branchState.location, _branchLocationRestorationScopeId(branch)); } return branchState; }); @@ -1433,14 +1360,9 @@ class StatefulNavigationShellState extends State final StatefulShellBranch branch = route.branches[widget.currentIndex]; final ShellRouteContext shellRouteContext = widget.shellRouteContext; - final RouteMatchList currentBranchLocation = _scopedMatchList( - shellRouteContext.routeMatchList, - ); + final RouteMatchList currentBranchLocation = _scopedMatchList(shellRouteContext.routeMatchList); - final _StatefulShellBranchState branchState = _branchStateFor( - branch, - false, - ); + final _StatefulShellBranchState branchState = _branchStateFor(branch, false); final RouteMatchList previousBranchLocation = branchState.location.value; branchState.location.value = currentBranchLocation; final hasExistingNavigator = branchState.navigator != null; @@ -1484,10 +1406,7 @@ class StatefulNavigationShellState extends State branch.restorationScopeId, ); - final _StatefulShellBranchState branchState = _branchStateFor( - branch, - false, - ); + final _StatefulShellBranchState branchState = _branchStateFor(branch, false); branchState.location.value = matchList; branchState.navigator = navigator; } @@ -1495,10 +1414,7 @@ class StatefulNavigationShellState extends State } void _cleanUpObsoleteBranches() { - _branchState.removeWhere(( - StatefulShellBranch branch, - _StatefulShellBranchState branchState, - ) { + _branchState.removeWhere((StatefulShellBranch branch, _StatefulShellBranchState branchState) { if (!route.branches.contains(branch)) { branchState.dispose(); return true; @@ -1521,9 +1437,7 @@ class StatefulNavigationShellState extends State /// the branch (see [StatefulShellBranch.initialLocation]). void goBranch(int index, {bool initialLocation = false}) { assert(index >= 0 && index < route.branches.length); - final RouteMatchList? matchList = initialLocation - ? null - : _matchListForBranch(index); + final RouteMatchList? matchList = initialLocation ? null : _matchListForBranch(index); if (matchList != null && matchList.isNotEmpty) { _router.restore(matchList); } else { @@ -1558,16 +1472,16 @@ class StatefulNavigationShellState extends State @override Widget build(BuildContext context) { - final List children = route.branches - .map( - (StatefulShellBranch branch) => _BranchNavigatorProxy( - key: ObjectKey(branch), - branch: branch, - navigatorForBranch: (StatefulShellBranch branch) => - _branchState[branch]?.navigator, - ), - ) - .toList(); + final List children = + route.branches + .map( + (StatefulShellBranch branch) => _BranchNavigatorProxy( + key: ObjectKey(branch), + branch: branch, + navigatorForBranch: (StatefulShellBranch branch) => _branchState[branch]?.navigator, + ), + ) + .toList(); return widget.containerBuilder(context, widget, children); } @@ -1635,11 +1549,7 @@ typedef _NavigatorForBranch = Widget? Function(StatefulShellBranch); /// important for container implementations that cache child widgets, /// such as [TabBarView]. class _BranchNavigatorProxy extends StatefulWidget { - const _BranchNavigatorProxy({ - super.key, - required this.branch, - required this.navigatorForBranch, - }); + const _BranchNavigatorProxy({super.key, required this.branch, required this.navigatorForBranch}); final StatefulShellBranch branch; final _NavigatorForBranch navigatorForBranch; @@ -1666,10 +1576,7 @@ class _BranchNavigatorProxyState extends State<_BranchNavigatorProxy> /// Default implementation of a container widget for the [Navigator]s of the /// route branches. This implementation uses an [IndexedStack] as a container. class _IndexedStackedRouteBranchContainer extends StatelessWidget { - const _IndexedStackedRouteBranchContainer({ - required this.currentIndex, - required this.children, - }); + const _IndexedStackedRouteBranchContainer({required this.currentIndex, required this.children}); final int currentIndex; @@ -1677,25 +1584,19 @@ class _IndexedStackedRouteBranchContainer extends StatelessWidget { @override Widget build(BuildContext context) { - final List stackItems = children - .mapIndexed( - (int index, Widget child) => - _buildRouteBranchContainer(context, currentIndex == index, child), - ) - .toList(); + final List stackItems = + children + .mapIndexed( + (int index, Widget child) => + _buildRouteBranchContainer(context, currentIndex == index, child), + ) + .toList(); return IndexedStack(index: currentIndex, children: stackItems); } - Widget _buildRouteBranchContainer( - BuildContext context, - bool isActive, - Widget child, - ) { - return Offstage( - offstage: !isActive, - child: TickerMode(enabled: isActive, child: child), - ); + Widget _buildRouteBranchContainer(BuildContext context, bool isActive, Widget child) { + return Offstage(offstage: !isActive, child: TickerMode(enabled: isActive, child: child)); } } @@ -1746,10 +1647,7 @@ class _MergedNavigatorObserver extends NavigatorObserver { } @override - void didStartUserGesture( - Route route, - Route? previousRoute, - ) { + void didStartUserGesture(Route route, Route? previousRoute) { for (final NavigatorObserver observer in observers) { observer.didStartUserGesture(route, previousRoute); } diff --git a/packages/go_router/lib/src/route_data.dart b/packages/go_router/lib/src/route_data.dart index 1d156afca729..82a97e880357 100644 --- a/packages/go_router/lib/src/route_data.dart +++ b/packages/go_router/lib/src/route_data.dart @@ -31,9 +31,7 @@ abstract class _GoRouteDataBase extends RouteData { /// /// Corresponds to [GoRoute.builder]. Widget build(BuildContext context, GoRouterState state) => - throw UnimplementedError( - 'One of `build` or `buildPage` must be implemented.', - ); + throw UnimplementedError('One of `build` or `buildPage` must be implemented.'); /// A page builder for this route. /// @@ -46,8 +44,7 @@ abstract class _GoRouteDataBase extends RouteData { /// /// By default, returns a [Page] instance that is ignored, causing a default /// [Page] implementation to be used with the results of [build]. - Page buildPage(BuildContext context, GoRouterState state) => - const NoOpPage(); + Page buildPage(BuildContext context, GoRouterState state) => const NoOpPage(); /// An optional redirect function for this route. /// @@ -70,8 +67,9 @@ abstract class _GoRouteDataBase extends RouteData { /// Used to cache [_GoRouteDataBase] that corresponds to a given [GoRouterState] /// to minimize the number of times it has to be deserialized. - static final Expando<_GoRouteDataBase> stateObjectExpando = - Expando<_GoRouteDataBase>('GoRouteState to _GoRouteDataBase expando'); + static final Expando<_GoRouteDataBase> stateObjectExpando = Expando<_GoRouteDataBase>( + 'GoRouteState to _GoRouteDataBase expando', + ); } /// Helper to build a location string from a path and query parameters. @@ -117,14 +115,14 @@ _GoRouteParameters _createGoRouteParameters({ } return _GoRouteParameters( - builder: (BuildContext context, GoRouterState state) => - factoryImpl(state).build(context, state), - pageBuilder: (BuildContext context, GoRouterState state) => - factoryImpl(state).buildPage(context, state), - redirect: (BuildContext context, GoRouterState state) => - factoryImpl(state).redirect(context, state), - onExit: (BuildContext context, GoRouterState state) => - factoryImpl(state).onExit(context, state), + builder: + (BuildContext context, GoRouterState state) => factoryImpl(state).build(context, state), + pageBuilder: + (BuildContext context, GoRouterState state) => factoryImpl(state).buildPage(context, state), + redirect: + (BuildContext context, GoRouterState state) => factoryImpl(state).redirect(context, state), + onExit: + (BuildContext context, GoRouterState state) => factoryImpl(state).onExit(context, state), ); } @@ -179,16 +177,13 @@ abstract class GoRouteData extends _GoRouteDataBase { String get location => throw _GoRouteDataBase.shouldBeGeneratedError; /// Navigate to the route. - void go(BuildContext context) => - throw _GoRouteDataBase.shouldBeGeneratedError; + void go(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError; /// Push the route onto the page stack. - Future push(BuildContext context) => - throw _GoRouteDataBase.shouldBeGeneratedError; + Future push(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError; /// Replaces the top-most page of the page stack with the route. - void pushReplacement(BuildContext context) => - throw _GoRouteDataBase.shouldBeGeneratedError; + void pushReplacement(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError; /// Replaces the top-most page of the page stack with the route but treats /// it as the same page. @@ -196,8 +191,7 @@ abstract class GoRouteData extends _GoRouteDataBase { /// The page key will be reused. This will preserve the state and not run any /// page animation. /// - void replace(BuildContext context) => - throw _GoRouteDataBase.shouldBeGeneratedError; + void replace(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError; } /// A class to represent a relative [GoRoute] in @@ -252,12 +246,10 @@ abstract class RelativeGoRouteData extends _GoRouteDataBase { String get relativeLocation => throw _GoRouteDataBase.shouldBeGeneratedError; /// Navigate to the route. - void goRelative(BuildContext context) => - throw _GoRouteDataBase.shouldBeGeneratedError; + void goRelative(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError; /// Push the route onto the page stack. - Future pushRelative(BuildContext context) => - throw _GoRouteDataBase.shouldBeGeneratedError; + Future pushRelative(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError; /// Replaces the top-most page of the page stack with the route. void pushReplacementRelative(BuildContext context) => @@ -269,8 +261,7 @@ abstract class RelativeGoRouteData extends _GoRouteDataBase { /// The page key will be reused. This will preserve the state and not run any /// page animation. /// - void replaceRelative(BuildContext context) => - throw _GoRouteDataBase.shouldBeGeneratedError; + void replaceRelative(BuildContext context) => throw _GoRouteDataBase.shouldBeGeneratedError; } /// A class to represent a [ShellRoute] in @@ -282,17 +273,12 @@ abstract class ShellRouteData extends RouteData { const ShellRouteData(); /// [pageBuilder] is used to build the page - Page pageBuilder( - BuildContext context, - GoRouterState state, - Widget navigator, - ) => const NoOpPage(); + Page pageBuilder(BuildContext context, GoRouterState state, Widget navigator) => + const NoOpPage(); /// [builder] is used to build the widget Widget builder(BuildContext context, GoRouterState state, Widget navigator) => - throw UnimplementedError( - 'One of `builder` or `pageBuilder` must be implemented.', - ); + throw UnimplementedError('One of `builder` or `pageBuilder` must be implemented.'); /// An optional redirect function for this route. /// @@ -321,17 +307,11 @@ abstract class ShellRouteData extends RouteData { FutureOr redirect(BuildContext context, GoRouterState state) => factoryImpl(state).redirect(context, state); - Widget builder( - BuildContext context, - GoRouterState state, - Widget navigator, - ) => factoryImpl(state).builder(context, state, navigator); + Widget builder(BuildContext context, GoRouterState state, Widget navigator) => + factoryImpl(state).builder(context, state, navigator); - Page pageBuilder( - BuildContext context, - GoRouterState state, - Widget navigator, - ) => factoryImpl(state).pageBuilder(context, state, navigator); + Page pageBuilder(BuildContext context, GoRouterState state, Widget navigator) => + factoryImpl(state).pageBuilder(context, state, navigator); return ShellRoute( builder: builder, @@ -348,8 +328,9 @@ abstract class ShellRouteData extends RouteData { /// Used to cache [ShellRouteData] that corresponds to a given [GoRouterState] /// to minimize the number of times it has to be deserialized. - static final Expando _stateObjectExpando = - Expando('GoRouteState to ShellRouteData expando'); + static final Expando _stateObjectExpando = Expando( + 'GoRouteState to ShellRouteData expando', + ); } /// Base class for supporting @@ -378,9 +359,7 @@ abstract class StatefulShellRouteData extends RouteData { BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, - ) => throw UnimplementedError( - 'One of `builder` or `pageBuilder` must be implemented.', - ); + ) => throw UnimplementedError('One of `builder` or `pageBuilder` must be implemented.'); /// A helper function used by generated code. /// @@ -435,9 +414,7 @@ abstract class StatefulShellRouteData extends RouteData { /// Used to cache [StatefulShellRouteData] that corresponds to a given [GoRouterState] /// to minimize the number of times it has to be deserialized. static final Expando _stateObjectExpando = - Expando( - 'GoRouteState to StatefulShellRouteData expando', - ); + Expando('GoRouteState to StatefulShellRouteData expando'); } /// Base class for supporting @@ -519,8 +496,7 @@ class TypedGoRoute extends TypedRoute { /// A superclass for each typed relative go route descendant @Target({TargetKind.library, TargetKind.classType}) -class TypedRelativeGoRoute - extends TypedRoute { +class TypedRelativeGoRoute extends TypedRoute { /// Default const constructor const TypedRelativeGoRoute({ required this.path, @@ -575,8 +551,7 @@ class TypedShellRoute extends TypedRoute { /// A superclass for each typed shell route descendant @Target({TargetKind.library, TargetKind.classType}) -class TypedStatefulShellRoute - extends TypedRoute { +class TypedStatefulShellRoute extends TypedRoute { /// Default const constructor const TypedStatefulShellRoute({ this.notifyRootObserver = true, @@ -599,9 +574,7 @@ class TypedStatefulShellRoute @Target({TargetKind.library, TargetKind.classType}) class TypedStatefulShellBranch { /// Default const constructor - const TypedStatefulShellBranch({ - this.routes = const >[], - }); + const TypedStatefulShellBranch({this.routes = const >[]}); /// Child route definitions. /// @@ -616,8 +589,7 @@ class NoOpPage extends Page { const NoOpPage(); @override - Route createRoute(BuildContext context) => - throw UnsupportedError('Should never be called'); + Route createRoute(BuildContext context) => throw UnsupportedError('Should never be called'); } /// Signature of custom query parameter encoding. @@ -643,19 +615,15 @@ typedef QueryParameterDecoder = T Function(String value); @Target({TargetKind.parameter}) class TypedQueryParameter { /// Annotation to override the URI name for a route parameter. - const TypedQueryParameter({ - this.name, - this.encoder, - this.decoder, - this.compare, - }) : assert( - (encoder == null) == (decoder == null), - 'encoder and decoder must both be provided together', - ), - assert( - compare == null || encoder != null, - 'compare function requires an encoder to be provided', - ); + const TypedQueryParameter({this.name, this.encoder, this.decoder, this.compare}) + : assert( + (encoder == null) == (decoder == null), + 'encoder and decoder must both be provided together', + ), + assert( + compare == null || encoder != null, + 'compare function requires an encoder to be provided', + ); /// The name of the parameter in the URI. /// diff --git a/packages/go_router/lib/src/router.dart b/packages/go_router/lib/src/router.dart index de8bdf1b8887..f830cf64266e 100644 --- a/packages/go_router/lib/src/router.dart +++ b/packages/go_router/lib/src/router.dart @@ -59,10 +59,7 @@ class RoutingConfig { this.redirectLimit = 5, }); - static FutureOr _defaultRedirect( - BuildContext context, - GoRouterState state, - ) => null; + static FutureOr _defaultRedirect(BuildContext context, GoRouterState state) => null; /// The supported routes. /// @@ -272,16 +269,11 @@ class GoRouter implements RouterConfig { final ParserExceptionHandler? parserExceptionHandler; if (onException != null) { - parserExceptionHandler = - (BuildContext context, RouteMatchList routeMatchList) { - onException( - context, - configuration.buildTopLevelGoRouterState(routeMatchList), - this, - ); - // Avoid updating GoRouterDelegate if onException is provided. - return routerDelegate.currentConfiguration; - }; + parserExceptionHandler = (BuildContext context, RouteMatchList routeMatchList) { + onException(context, configuration.buildTopLevelGoRouterState(routeMatchList), this); + // Avoid updating GoRouterDelegate if onException is provided. + return routerDelegate.currentConfiguration; + }; } else { parserExceptionHandler = null; } @@ -309,8 +301,8 @@ class GoRouter implements RouterConfig { requestFocus: requestFocus, // wrap the returned Navigator to enable GoRouter.of(context).go() et al, // allowing the caller to wrap the navigator themselves - builderWithNav: (BuildContext context, Widget child) => - InheritedGoRouter(goRouter: this, child: child), + builderWithNav: + (BuildContext context, Widget child) => InheritedGoRouter(goRouter: this, child: child), ); assert(() { @@ -420,10 +412,7 @@ class GoRouter implements RouterConfig { /// Restore the RouteMatchList void restore(RouteMatchList matchList) { log('restoring ${matchList.uri}'); - routeInformationProvider.restore( - matchList.uri.toString(), - matchList: matchList, - ); + routeInformationProvider.restore(matchList.uri.toString(), matchList: matchList); } /// Navigate to a named route w/ optional parameters, e.g. @@ -436,16 +425,16 @@ class GoRouter implements RouterConfig { Object? extra, String? fragment, }) => - // Construct location with optional fragment - go( - namedLocation( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - fragment: fragment, - ), - extra: extra, - ); + // Construct location with optional fragment + go( + namedLocation( + name, + pathParameters: pathParameters, + queryParameters: queryParameters, + fragment: fragment, + ), + extra: extra, + ); /// Push a URI location onto the page stack w/ optional query parameters, e.g. /// `/family/f2/person/p1?color=blue`. @@ -473,11 +462,7 @@ class GoRouter implements RouterConfig { Map queryParameters = const {}, Object? extra, }) => push( - namedLocation( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - ), + namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters), extra: extra, ); @@ -490,10 +475,7 @@ class GoRouter implements RouterConfig { /// * [replace] which replaces the top-most page of the page stack but treats /// it as the same page. The page key will be reused. This will preserve the /// state and not run any page animation. - Future pushReplacement( - String location, { - Object? extra, - }) { + Future pushReplacement(String location, {Object? extra}) { log('pushReplacement $location'); return routeInformationProvider.pushReplacement( location, @@ -516,11 +498,7 @@ class GoRouter implements RouterConfig { Object? extra, }) { return pushReplacement( - namedLocation( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - ), + namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters), extra: extra, ); } @@ -562,11 +540,7 @@ class GoRouter implements RouterConfig { Object? extra, }) { return replace( - namedLocation( - name, - pathParameters: pathParameters, - queryParameters: queryParameters, - ), + namedLocation(name, pathParameters: pathParameters, queryParameters: queryParameters), extra: extra, ); } @@ -613,9 +587,7 @@ class GoRouter implements RouterConfig { /// The current GoRouter in the widget tree, if any. static GoRouter? maybeOf(BuildContext context) { final inherited = - context - .getElementForInheritedWidgetOfExactType() - ?.widget + context.getElementForInheritedWidgetOfExactType()?.widget as InheritedGoRouter?; if (inherited != null) { return inherited.goRouter; @@ -638,9 +610,7 @@ class GoRouter implements RouterConfig { // verified by assert() during the initialization. return initialLocation!; } - Uri platformDefaultUri = Uri.parse( - WidgetsBinding.instance.platformDispatcher.defaultRouteName, - ); + Uri platformDefaultUri = Uri.parse(WidgetsBinding.instance.platformDispatcher.defaultRouteName); if (platformDefaultUri.hasEmptyPath) { platformDefaultUri = platformDefaultUri.replace(path: '/'); } diff --git a/packages/go_router/lib/src/state.dart b/packages/go_router/lib/src/state.dart index 80554631915e..bd5755928be3 100644 --- a/packages/go_router/lib/src/state.dart +++ b/packages/go_router/lib/src/state.dart @@ -125,16 +125,14 @@ class GoRouterState { } final RouteSettings settings = route.settings; if (settings is Page) { - scope = context - .dependOnInheritedWidgetOfExactType(); + scope = context.dependOnInheritedWidgetOfExactType(); if (scope == null) { throw _noGoRouterStateError; } - final GoRouterState? state = scope.notifier! - ._createPageRouteAssociation( - route.settings as Page, - route, - ); + final GoRouterState? state = scope.notifier!._createPageRouteAssociation( + route.settings as Page, + route, + ); if (state != null) { return state; } @@ -204,8 +202,7 @@ class GoRouterState { /// Should not be used directly, consider using [GoRouterState.of] to access /// [GoRouterState] from the context. @internal -class GoRouterStateRegistryScope - extends InheritedNotifier { +class GoRouterStateRegistryScope extends InheritedNotifier { /// Creates a GoRouterStateRegistryScope. const GoRouterStateRegistryScope({ super.key, @@ -225,16 +222,12 @@ class GoRouterStateRegistry extends ChangeNotifier { /// A [Map] that maps a [Page] to a [GoRouterState]. @visibleForTesting - final Map, GoRouterState> registry = - , GoRouterState>{}; + final Map, GoRouterState> registry = , GoRouterState>{}; final Map, Page> _routePageAssociation = , Page>{}; - GoRouterState? _createPageRouteAssociation( - Page page, - ModalRoute route, - ) { + GoRouterState? _createPageRouteAssociation(Page page, ModalRoute route) { assert(route.settings == page); if (!registry.containsKey(page)) { return null; @@ -249,9 +242,7 @@ class GoRouterStateRegistry extends ChangeNotifier { route.completed.then((Object? result) { // Can't use `page` directly because Route.settings may have changed during // the lifetime of this route. - final Page associatedPage = _routePageAssociation.remove( - route, - )!; + final Page associatedPage = _routePageAssociation.remove(route)!; assert(registry.containsKey(associatedPage)); registry.remove(associatedPage); }); @@ -268,15 +259,12 @@ class GoRouterStateRegistry extends ChangeNotifier { /// Updates this registry with new records. void updateRegistry(Map, GoRouterState> newRegistry) { var shouldNotify = false; - final Set> pagesWithAssociation = _routePageAssociation.values - .toSet(); - for (final MapEntry, GoRouterState> entry - in newRegistry.entries) { + final Set> pagesWithAssociation = _routePageAssociation.values.toSet(); + for (final MapEntry, GoRouterState> entry in newRegistry.entries) { final GoRouterState? existingState = registry[entry.key]; if (existingState != null) { if (existingState != entry.value) { - shouldNotify = - shouldNotify || pagesWithAssociation.contains(entry.key); + shouldNotify = shouldNotify || pagesWithAssociation.contains(entry.key); registry[entry.key] = entry.value; } continue; diff --git a/packages/go_router/test/builder_test.dart b/packages/go_router/test/builder_test.dart index 46292b6157a2..75d1099a4345 100644 --- a/packages/go_router/test/builder_test.dart +++ b/packages/go_router/test/builder_test.dart @@ -39,9 +39,7 @@ void main() { pathParameters: const {}, ); - await tester.pumpWidget( - _BuilderTestWidget(routeConfiguration: config, matches: matches), - ); + await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches)); expect(find.byType(_DetailsScreen), findsOneWidget); }); @@ -92,9 +90,7 @@ void main() { pathParameters: const {}, ); - await tester.pumpWidget( - _BuilderTestWidget(routeConfiguration: config, matches: matches), - ); + await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches)); expect(find.byType(_DetailsScreen), findsOneWidget); }); @@ -129,16 +125,12 @@ void main() { pathParameters: const {}, ); - await tester.pumpWidget( - _BuilderTestWidget(routeConfiguration: config, matches: matches), - ); + await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches)); expect(find.byKey(rootNavigatorKey), findsOneWidget); }); - testWidgets('Builds a Navigator for ShellRoute', ( - WidgetTester tester, - ) async { + testWidgets('Builds a Navigator for ShellRoute', (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(debugLabel: 'root'); final shellNavigatorKey = GlobalKey(debugLabel: 'shell'); final RouteConfiguration config = createRouteConfiguration( @@ -185,9 +177,7 @@ void main() { pathParameters: const {}, ); - await tester.pumpWidget( - _BuilderTestWidget(routeConfiguration: config, matches: matches), - ); + await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches)); expect(find.byType(_HomeScreen, skipOffstage: false), findsOneWidget); expect(find.byType(_DetailsScreen), findsOneWidget); @@ -246,9 +236,7 @@ void main() { pathParameters: const {}, ); - await tester.pumpWidget( - _BuilderTestWidget(routeConfiguration: config, matches: matches), - ); + await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches)); // The Details screen should be visible, but the HomeScreen should be // offstage (underneath) the DetailsScreen. @@ -256,9 +244,7 @@ void main() { expect(find.byType(_DetailsScreen), findsOneWidget); }); - testWidgets('Uses the correct restorationScopeId for ShellRoute', ( - WidgetTester tester, - ) async { + testWidgets('Uses the correct restorationScopeId for ShellRoute', (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(debugLabel: 'root'); final shellNavigatorKey = GlobalKey(debugLabel: 'shell'); final RouteConfiguration config = createRouteConfiguration( @@ -306,16 +292,11 @@ void main() { pathParameters: const {}, ); - await tester.pumpWidget( - _BuilderTestWidget(routeConfiguration: config, matches: matches), - ); + await tester.pumpWidget(_BuilderTestWidget(routeConfiguration: config, matches: matches)); expect(find.byKey(rootNavigatorKey), findsOneWidget); expect(find.byKey(shellNavigatorKey), findsOneWidget); - expect( - (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, - 'scope1', - ); + expect((shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, 'scope1'); }); testWidgets('Uses the correct restorationScopeId for StatefulShellRoute', ( @@ -358,21 +339,17 @@ void main() { expect(find.byKey(rootNavigatorKey), findsOneWidget); expect(find.byKey(shellNavigatorKey), findsOneWidget); - expect( - (shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, - 'scope1', - ); + expect((shellNavigatorKey.currentWidget as Navigator?)?.restorationScopeId, 'scope1'); }); - testWidgets('GoRouter requestFocus defaults to true', ( - WidgetTester tester, - ) async { + testWidgets('GoRouter requestFocus defaults to true', (WidgetTester tester) async { final router = GoRouter( routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const Scaffold(body: Center(child: Text('Home'))), + builder: + (BuildContext context, GoRouterState state) => + const Scaffold(body: Center(child: Text('Home'))), ), ], ); @@ -381,21 +358,18 @@ void main() { addTearDown(() => router.dispose()); - final Navigator navigator = tester.widget( - find.byType(Navigator), - ); + final Navigator navigator = tester.widget(find.byType(Navigator)); expect(navigator.requestFocus, isTrue); }); - testWidgets('GoRouter requestFocus can be set to false', ( - WidgetTester tester, - ) async { + testWidgets('GoRouter requestFocus can be set to false', (WidgetTester tester) async { final router = GoRouter( routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const Scaffold(body: Center(child: Text('Home'))), + builder: + (BuildContext context, GoRouterState state) => + const Scaffold(body: Center(child: Text('Home'))), ), ], requestFocus: false, @@ -405,9 +379,7 @@ void main() { addTearDown(() => router.dispose()); - final Navigator navigator = tester.widget( - find.byType(Navigator), - ); + final Navigator navigator = tester.widget(find.byType(Navigator)); expect(navigator.requestFocus, isFalse); }); }); @@ -421,12 +393,7 @@ class _HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - body: Column( - children: [ - const Text('Home Screen'), - Expanded(child: child), - ], - ), + body: Column(children: [const Text('Home Screen'), Expanded(child: child)]), ); } } diff --git a/packages/go_router/test/configuration_test.dart b/packages/go_router/test/configuration_test.dart index 2e6e9cc39321..3960c73b7e60 100644 --- a/packages/go_router/test/configuration_test.dart +++ b/packages/go_router/test/configuration_test.dart @@ -26,19 +26,13 @@ void main() { ShellRoute( navigatorKey: a, builder: _mockShellBuilder, - routes: [ - GoRoute(path: 'b', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: 'b', builder: _mockScreenBuilder)], ), ShellRoute( navigatorKey: b, builder: _mockShellBuilder, routes: [ - GoRoute( - path: 'c', - parentNavigatorKey: a, - builder: _mockScreenBuilder, - ), + GoRoute(path: 'c', parentNavigatorKey: a, builder: _mockScreenBuilder), ], ), ], @@ -67,54 +61,12 @@ void main() { }, throwsAssertionError); }); - test( - 'throws when StatefulShellRoute sub-route uses incorrect parentNavigatorKey', - () { - final root = GlobalKey(debugLabel: 'root'); - final keyA = GlobalKey(debugLabel: 'A'); - final keyB = GlobalKey(debugLabel: 'B'); - - expect(() { - createRouteConfiguration( - navigatorKey: root, - routes: [ - StatefulShellRoute.indexedStack( - branches: [ - StatefulShellBranch( - navigatorKey: keyA, - routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'details', - builder: _mockScreenBuilder, - parentNavigatorKey: keyB, - ), - ], - ), - ], - ), - ], - builder: mockStackedShellBuilder, - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, throwsA(isA())); - }, - ); - - test( - 'does not throw when StatefulShellRoute sub-route uses correct parentNavigatorKeys', - () { - final root = GlobalKey(debugLabel: 'root'); - final keyA = GlobalKey(debugLabel: 'A'); + test('throws when StatefulShellRoute sub-route uses incorrect parentNavigatorKey', () { + final root = GlobalKey(debugLabel: 'root'); + final keyA = GlobalKey(debugLabel: 'A'); + final keyB = GlobalKey(debugLabel: 'B'); + expect(() { createRouteConfiguration( navigatorKey: root, routes: [ @@ -130,7 +82,7 @@ void main() { GoRoute( path: 'details', builder: _mockScreenBuilder, - parentNavigatorKey: keyA, + parentNavigatorKey: keyB, ), ], ), @@ -145,80 +97,103 @@ void main() { return null; }, ); - }, - ); + }, throwsA(isA())); + }); - test( - 'throws when a sub-route of StatefulShellRoute has a parentNavigatorKey', - () { - final root = GlobalKey(debugLabel: 'root'); - final someNavigatorKey = GlobalKey(); - expect(() { - createRouteConfiguration( - navigatorKey: root, - routes: [ - StatefulShellRoute.indexedStack( - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'details', - builder: _mockScreenBuilder, - parentNavigatorKey: someNavigatorKey, - ), - ], - ), - ], - ), - StatefulShellBranch( + test('does not throw when StatefulShellRoute sub-route uses correct parentNavigatorKeys', () { + final root = GlobalKey(debugLabel: 'root'); + final keyA = GlobalKey(debugLabel: 'A'); + + createRouteConfiguration( + navigatorKey: root, + routes: [ + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + navigatorKey: keyA, + routes: [ + GoRoute( + path: '/a', + builder: _mockScreenBuilder, routes: [ GoRoute( - path: '/b', + path: 'details', builder: _mockScreenBuilder, - parentNavigatorKey: someNavigatorKey, + parentNavigatorKey: keyA, ), ], ), ], - builder: mockStackedShellBuilder, ), ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, throwsAssertionError); - }, - ); + builder: mockStackedShellBuilder, + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }); + + test('throws when a sub-route of StatefulShellRoute has a parentNavigatorKey', () { + final root = GlobalKey(debugLabel: 'root'); + final someNavigatorKey = GlobalKey(); + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + StatefulShellRoute.indexedStack( + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'details', + builder: _mockScreenBuilder, + parentNavigatorKey: someNavigatorKey, + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: _mockScreenBuilder, + parentNavigatorKey: someNavigatorKey, + ), + ], + ), + ], + builder: mockStackedShellBuilder, + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); + }); test('throws when StatefulShellRoute has duplicate navigator keys', () { final root = GlobalKey(debugLabel: 'root'); final keyA = GlobalKey(debugLabel: 'A'); final shellRouteChildren = [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - parentNavigatorKey: keyA, - ), - GoRoute( - path: '/b', - builder: _mockScreenBuilder, - parentNavigatorKey: keyA, - ), + GoRoute(path: '/a', builder: _mockScreenBuilder, parentNavigatorKey: keyA), + GoRoute(path: '/b', builder: _mockScreenBuilder, parentNavigatorKey: keyA), ]; expect(() { createRouteConfiguration( navigatorKey: root, routes: [ StatefulShellRoute.indexedStack( - branches: [ - StatefulShellBranch(routes: shellRouteChildren), - ], + branches: [StatefulShellBranch(routes: shellRouteChildren)], builder: mockStackedShellBuilder, ), ], @@ -285,15 +260,11 @@ void main() { StatefulShellBranch( initialLocation: '/x', navigatorKey: sectionANavigatorKey, - routes: [ - GoRoute(path: '/a', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: '/a', builder: _mockScreenBuilder)], ), StatefulShellBranch( navigatorKey: sectionBNavigatorKey, - routes: [ - GoRoute(path: '/b', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: '/b', builder: _mockScreenBuilder)], ), ], builder: mockStackedShellBuilder, @@ -321,9 +292,7 @@ void main() { StatefulShellBranch( initialLocation: '/b', navigatorKey: sectionANavigatorKey, - routes: [ - GoRoute(path: '/a', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: '/a', builder: _mockScreenBuilder)], ), StatefulShellBranch( initialLocation: '/b', @@ -332,9 +301,7 @@ void main() { StatefulShellRoute.indexedStack( branches: [ StatefulShellBranch( - routes: [ - GoRoute(path: '/b', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: '/b', builder: _mockScreenBuilder)], ), ], builder: mockStackedShellBuilder, @@ -367,9 +334,7 @@ void main() { GoRoute( path: '/a', builder: _mockScreenBuilder, - routes: [ - GoRoute(path: 'detail', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: 'detail', builder: _mockScreenBuilder)], ), ], ), @@ -379,9 +344,7 @@ void main() { GoRoute( path: '/b', builder: _mockScreenBuilder, - routes: [ - GoRoute(path: 'detail', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: 'detail', builder: _mockScreenBuilder)], ), ], ), @@ -396,10 +359,7 @@ void main() { path: '/c', builder: _mockScreenBuilder, routes: [ - GoRoute( - path: 'detail', - builder: _mockScreenBuilder, - ), + GoRoute(path: 'detail', builder: _mockScreenBuilder), ], ), ], @@ -411,10 +371,7 @@ void main() { path: '/d', builder: _mockScreenBuilder, routes: [ - GoRoute( - path: 'detail', - builder: _mockScreenBuilder, - ), + GoRoute(path: 'detail', builder: _mockScreenBuilder), ], ), ], @@ -431,9 +388,7 @@ void main() { routes: [ ShellRoute( builder: _mockShellBuilder, - routes: [ - GoRoute(path: '/e', builder: _mockScreenBuilder), - ], + routes: [GoRoute(path: '/e', builder: _mockScreenBuilder)], ), ], ), @@ -479,14 +434,8 @@ void main() { ShellRoute( builder: _mockShellBuilder, routes: [ - GoRoute( - path: 'y1', - builder: _mockScreenBuilder, - ), - GoRoute( - path: 'y2', - builder: _mockScreenBuilder, - ), + GoRoute(path: 'y1', builder: _mockScreenBuilder), + GoRoute(path: 'y2', builder: _mockScreenBuilder), ], ), ], @@ -534,41 +483,34 @@ void main() { expect('/b1', initialLocation(branchB)); }); - test( - 'throws when there is a GoRoute ancestor with a different parentNavigatorKey', - () { - final root = GlobalKey(debugLabel: 'root'); - final shell = GlobalKey(debugLabel: 'shell'); - expect(() { - createRouteConfiguration( - navigatorKey: root, - routes: [ - ShellRoute( - navigatorKey: shell, - routes: [ - GoRoute( - path: '/', - builder: _mockScreenBuilder, - parentNavigatorKey: root, - routes: [ - GoRoute( - path: 'a', - builder: _mockScreenBuilder, - parentNavigatorKey: shell, - ), - ], - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, throwsAssertionError); - }, - ); + test('throws when there is a GoRoute ancestor with a different parentNavigatorKey', () { + final root = GlobalKey(debugLabel: 'root'); + final shell = GlobalKey(debugLabel: 'shell'); + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + ShellRoute( + navigatorKey: shell, + routes: [ + GoRoute( + path: '/', + builder: _mockScreenBuilder, + parentNavigatorKey: root, + routes: [ + GoRoute(path: 'a', builder: _mockScreenBuilder, parentNavigatorKey: shell), + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); + }); test('Does not throw with valid parentNavigatorKey configuration', () { final root = GlobalKey(debugLabel: 'root'); @@ -619,52 +561,45 @@ void main() { ); }); - test( - 'Does not throw with multiple nested GoRoutes using parentNavigatorKey in ShellRoute', - () { - final root = GlobalKey(debugLabel: 'root'); - final shell = GlobalKey(debugLabel: 'shell'); - createRouteConfiguration( - navigatorKey: root, - routes: [ - ShellRoute( - navigatorKey: shell, - routes: [ - GoRoute( - path: '/', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'a', - builder: _mockScreenBuilder, - parentNavigatorKey: root, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - parentNavigatorKey: root, - routes: [ - GoRoute( - path: 'c', - builder: _mockScreenBuilder, - parentNavigatorKey: root, - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - ); + test('Does not throw with multiple nested GoRoutes using parentNavigatorKey in ShellRoute', () { + final root = GlobalKey(debugLabel: 'root'); + final shell = GlobalKey(debugLabel: 'shell'); + createRouteConfiguration( + navigatorKey: root, + routes: [ + ShellRoute( + navigatorKey: shell, + routes: [ + GoRoute( + path: '/', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'a', + builder: _mockScreenBuilder, + parentNavigatorKey: root, + routes: [ + GoRoute( + path: 'b', + builder: _mockScreenBuilder, + parentNavigatorKey: root, + routes: [ + GoRoute(path: 'c', builder: _mockScreenBuilder, parentNavigatorKey: root), + ], + ), + ], + ), + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }); test('Throws when parentNavigatorKeys are overlapping', () { final root = GlobalKey(debugLabel: 'root'); @@ -712,51 +647,44 @@ void main() { ); }); - test( - 'Does not throw when parentNavigatorKeys are overlapping correctly', - () { - final root = GlobalKey(debugLabel: 'root'); - final shell = GlobalKey(debugLabel: 'shell'); - createRouteConfiguration( - navigatorKey: root, - routes: [ - ShellRoute( - navigatorKey: shell, - routes: [ - GoRoute( - path: '/', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'a', - builder: _mockScreenBuilder, - parentNavigatorKey: shell, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'b', - builder: _mockScreenBuilder, - parentNavigatorKey: root, - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, - ); + test('Does not throw when parentNavigatorKeys are overlapping correctly', () { + final root = GlobalKey(debugLabel: 'root'); + final shell = GlobalKey(debugLabel: 'shell'); + createRouteConfiguration( + navigatorKey: root, + routes: [ + ShellRoute( + navigatorKey: shell, + routes: [ + GoRoute( + path: '/', + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'a', + builder: _mockScreenBuilder, + parentNavigatorKey: shell, + routes: [ + GoRoute( + path: 'b', + builder: _mockScreenBuilder, + routes: [ + GoRoute(path: 'b', builder: _mockScreenBuilder, parentNavigatorKey: root), + ], + ), + ], + ), + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }); test('throws when a GoRoute with a different parentNavigatorKey ' 'exists between a GoRoute with a parentNavigatorKey and ' @@ -811,34 +739,29 @@ void main() { throwsA(isA()), ); }); - test( - 'does not throw when ShellRoute is the child of another ShellRoute', - () { - final root = GlobalKey(debugLabel: 'root'); - createRouteConfiguration( - routes: [ - ShellRoute( - builder: _mockShellBuilder, - routes: [ - ShellRoute( - builder: _mockShellBuilder, - routes: [ - GoRoute(path: '/a', builder: _mockScreenBuilder), - ], - ), - GoRoute(path: '/b', builder: _mockScreenBuilder), - ], - ), - GoRoute(path: '/c', builder: _mockScreenBuilder), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - navigatorKey: root, - ); - }, - ); + test('does not throw when ShellRoute is the child of another ShellRoute', () { + final root = GlobalKey(debugLabel: 'root'); + createRouteConfiguration( + routes: [ + ShellRoute( + builder: _mockShellBuilder, + routes: [ + ShellRoute( + builder: _mockShellBuilder, + routes: [GoRoute(path: '/a', builder: _mockScreenBuilder)], + ), + GoRoute(path: '/b', builder: _mockScreenBuilder), + ], + ), + GoRoute(path: '/c', builder: _mockScreenBuilder), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + navigatorKey: root, + ); + }); test('Does not throw with valid parentNavigatorKey configuration', () { final root = GlobalKey(debugLabel: 'root'); @@ -889,127 +812,101 @@ void main() { ); }); - test( - 'throws when ShellRoute contains a GoRoute with a parentNavigatorKey', - () { - final root = GlobalKey(debugLabel: 'root'); - expect(() { - createRouteConfiguration( - navigatorKey: root, - routes: [ - ShellRoute( - routes: [ - GoRoute( - path: '/a', - builder: _mockScreenBuilder, - parentNavigatorKey: root, - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ); - }, throwsAssertionError); - }, - ); + test('throws when ShellRoute contains a GoRoute with a parentNavigatorKey', () { + final root = GlobalKey(debugLabel: 'root'); + expect(() { + createRouteConfiguration( + navigatorKey: root, + routes: [ + ShellRoute( + routes: [ + GoRoute(path: '/a', builder: _mockScreenBuilder, parentNavigatorKey: root), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ); + }, throwsAssertionError); + }); - test( - 'All known route strings returned by debugKnownRoutes are correct', - () { - final root = GlobalKey(debugLabel: 'root'); - final shell = GlobalKey(debugLabel: 'shell'); + test('All known route strings returned by debugKnownRoutes are correct', () { + final root = GlobalKey(debugLabel: 'root'); + final shell = GlobalKey(debugLabel: 'shell'); - expect( - createRouteConfiguration( - navigatorKey: root, - routes: [ - GoRoute( - path: '/a', - parentNavigatorKey: root, - builder: _mockScreenBuilder, - routes: [ - ShellRoute( - navigatorKey: shell, - builder: _mockShellBuilder, - routes: [ - GoRoute( - path: 'b', - parentNavigatorKey: shell, - builder: _mockScreenBuilder, - ), - GoRoute( - path: 'c', - parentNavigatorKey: shell, - builder: _mockScreenBuilder, - ), - ], - ), - ], - ), - GoRoute( - path: '/d', - parentNavigatorKey: root, - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'e', - parentNavigatorKey: root, - builder: _mockScreenBuilder, - routes: [ - GoRoute( - path: 'f', - parentNavigatorKey: root, - builder: _mockScreenBuilder, - ), - ], - ), - ], - ), - GoRoute( - path: '/g', - builder: _mockScreenBuilder, - routes: [ - StatefulShellRoute.indexedStack( - builder: _mockIndexedStackShellBuilder, - branches: [ - StatefulShellBranch( - routes: [ - GoRoute(path: 'h', builder: _mockScreenBuilder), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute(path: 'i', builder: _mockScreenBuilder), - ], - ), - ], - ), - ], - ), - ], - redirectLimit: 10, - topRedirect: (BuildContext context, GoRouterState state) { - return null; - }, - ).debugKnownRoutes(), - 'Full paths for routes:\n' - '├─/a (Widget)\n' - '│ └─ (ShellRoute)\n' - '│ ├─/a/b (Widget)\n' - '│ └─/a/c (Widget)\n' - '├─/d (Widget)\n' - '│ └─/d/e (Widget)\n' - '│ └─/d/e/f (Widget)\n' - '└─/g (Widget)\n' - ' └─ (ShellRoute)\n' - ' ├─/g/h (Widget)\n' - ' └─/g/i (Widget)\n', - ); - }, - ); + expect( + createRouteConfiguration( + navigatorKey: root, + routes: [ + GoRoute( + path: '/a', + parentNavigatorKey: root, + builder: _mockScreenBuilder, + routes: [ + ShellRoute( + navigatorKey: shell, + builder: _mockShellBuilder, + routes: [ + GoRoute(path: 'b', parentNavigatorKey: shell, builder: _mockScreenBuilder), + GoRoute(path: 'c', parentNavigatorKey: shell, builder: _mockScreenBuilder), + ], + ), + ], + ), + GoRoute( + path: '/d', + parentNavigatorKey: root, + builder: _mockScreenBuilder, + routes: [ + GoRoute( + path: 'e', + parentNavigatorKey: root, + builder: _mockScreenBuilder, + routes: [ + GoRoute(path: 'f', parentNavigatorKey: root, builder: _mockScreenBuilder), + ], + ), + ], + ), + GoRoute( + path: '/g', + builder: _mockScreenBuilder, + routes: [ + StatefulShellRoute.indexedStack( + builder: _mockIndexedStackShellBuilder, + branches: [ + StatefulShellBranch( + routes: [GoRoute(path: 'h', builder: _mockScreenBuilder)], + ), + StatefulShellBranch( + routes: [GoRoute(path: 'i', builder: _mockScreenBuilder)], + ), + ], + ), + ], + ), + ], + redirectLimit: 10, + topRedirect: (BuildContext context, GoRouterState state) { + return null; + }, + ).debugKnownRoutes(), + 'Full paths for routes:\n' + '├─/a (Widget)\n' + '│ └─ (ShellRoute)\n' + '│ ├─/a/b (Widget)\n' + '│ └─/a/c (Widget)\n' + '├─/d (Widget)\n' + '│ └─/d/e (Widget)\n' + '│ └─/d/e/f (Widget)\n' + '└─/g (Widget)\n' + ' └─ (ShellRoute)\n' + ' ├─/g/h (Widget)\n' + ' └─/g/i (Widget)\n', + ); + }); group('normalizeUri', () { test('adds leading slash if missing', () { @@ -1021,10 +918,7 @@ void main() { }); test('removes trailing slash if length > 1', () { - expect( - RouteConfiguration.normalizeUri(Uri.parse('/foo/')).path, - '/foo', - ); + expect(RouteConfiguration.normalizeUri(Uri.parse('/foo/')).path, '/foo'); }); test('does not remove slash for root root', () { @@ -1039,9 +933,7 @@ void main() { }); test('handles hash fragments with authority', () { - final Uri uri = RouteConfiguration.normalizeUri( - Uri.parse('http://localhost:3000/#foo'), - ); + final Uri uri = RouteConfiguration.normalizeUri(Uri.parse('http://localhost:3000/#foo')); expect(uri.path, '/'); expect(uri.fragment, 'foo'); }); @@ -1071,11 +963,7 @@ class _MockScreen extends StatelessWidget { Widget _mockScreenBuilder(BuildContext context, GoRouterState state) => _MockScreen(key: state.pageKey); -Widget _mockShellBuilder( - BuildContext context, - GoRouterState state, - Widget child, -) => child; +Widget _mockShellBuilder(BuildContext context, GoRouterState state, Widget child) => child; Widget _mockIndexedStackShellBuilder( BuildContext context, diff --git a/packages/go_router/test/cupertino_test.dart b/packages/go_router/test/cupertino_test.dart index 12fa0ee6a2be..d6de929c75f4 100644 --- a/packages/go_router/test/cupertino_test.dart +++ b/packages/go_router/test/cupertino_test.dart @@ -11,20 +11,14 @@ import 'helpers/error_screen_helpers.dart'; void main() { group('isCupertinoApp', () { - testWidgets('returns [true] when CupertinoApp is present', ( - WidgetTester tester, - ) async { + testWidgets('returns [true] when CupertinoApp is present', (WidgetTester tester) async { final key = GlobalKey<_DummyStatefulWidgetState>(); - await tester.pumpWidget( - CupertinoApp(home: DummyStatefulWidget(key: key)), - ); + await tester.pumpWidget(CupertinoApp(home: DummyStatefulWidget(key: key))); final bool isCupertino = isCupertinoApp(key.currentContext! as Element); expect(isCupertino, true); }); - testWidgets('returns [false] when MaterialApp is present', ( - WidgetTester tester, - ) async { + testWidgets('returns [false] when MaterialApp is present', (WidgetTester tester) async { final key = GlobalKey<_DummyStatefulWidgetState>(); await tester.pumpWidget(MaterialApp(home: DummyStatefulWidget(key: key))); final bool isCupertino = isCupertinoApp(key.currentContext! as Element); @@ -55,9 +49,7 @@ void main() { group('GoRouterCupertinoErrorScreen', () { testWidgets( 'shows "page not found" by default', - testPageNotFound( - widget: const CupertinoApp(home: CupertinoErrorScreen(null)), - ), + testPageNotFound(widget: const CupertinoApp(home: CupertinoErrorScreen(null))), ); final exception = Exception('Something went wrong!'); diff --git a/packages/go_router/test/custom_transition_page_test.dart b/packages/go_router/test/custom_transition_page_test.dart index 0fae9d9a6048..a56eeb14c355 100644 --- a/packages/go_router/test/custom_transition_page_test.dart +++ b/packages/go_router/test/custom_transition_page_test.dart @@ -7,30 +7,23 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; void main() { - testWidgets( - 'CustomTransitionPage builds its child using transitionsBuilder', - (WidgetTester tester) async { - const child = HomeScreen(); - final transition = CustomTransitionPage( - transitionsBuilder: expectAsync4((_, __, ___, Widget child) => child), - child: child, - ); - final router = GoRouter( - routes: [ - GoRoute(path: '/', pageBuilder: (_, __) => transition), - ], - ); - addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); - expect(find.byWidget(child), findsOneWidget); - }, - ); - - testWidgets('NoTransitionPage does not apply any transition', ( + testWidgets('CustomTransitionPage builds its child using transitionsBuilder', ( WidgetTester tester, ) async { + const child = HomeScreen(); + final transition = CustomTransitionPage( + transitionsBuilder: expectAsync4((_, __, ___, Widget child) => child), + child: child, + ); + final router = GoRouter( + routes: [GoRoute(path: '/', pageBuilder: (_, __) => transition)], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); + expect(find.byWidget(child), findsOneWidget); + }); + + testWidgets('NoTransitionPage does not apply any transition', (WidgetTester tester) async { final showHomeValueNotifier = ValueNotifier(false); addTearDown(showHomeValueNotifier.dispose); await tester.pumpWidget( @@ -106,26 +99,22 @@ void main() { expect(homeScreenFinder, findsNothing); }); - testWidgets('Dismiss a screen by tapping a modal barrier', ( - WidgetTester tester, - ) async { + testWidgets('Dismiss a screen by tapping a modal barrier', (WidgetTester tester) async { const homeKey = ValueKey('home'); const dismissibleModalKey = ValueKey('dismissibleModal'); final router = GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, __) => const HomeScreen(key: homeKey), - ), + GoRoute(path: '/', builder: (_, __) => const HomeScreen(key: homeKey)), GoRoute( path: '/dismissible-modal', - pageBuilder: (_, GoRouterState state) => CustomTransitionPage( - key: state.pageKey, - barrierDismissible: true, - transitionsBuilder: (_, __, ___, Widget child) => child, - child: const DismissibleModal(key: dismissibleModalKey), - ), + pageBuilder: + (_, GoRouterState state) => CustomTransitionPage( + key: state.pageKey, + barrierDismissible: true, + transitionsBuilder: (_, __, ___, Widget child) => child, + child: const DismissibleModal(key: dismissibleModalKey), + ), ), ], ); @@ -150,21 +139,19 @@ void main() { final router = GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, __) => const HomeScreen(key: homeKey), - ), + GoRoute(path: '/', builder: (_, __) => const HomeScreen(key: homeKey)), GoRoute( path: '/login', - pageBuilder: (_, GoRouterState state) => CustomTransitionPage( - key: state.pageKey, - transitionDuration: transitionDuration, - reverseTransitionDuration: reverseTransitionDuration, - transitionsBuilder: - (_, Animation animation, ___, Widget child) => - FadeTransition(opacity: animation, child: child), - child: const LoginScreen(key: loginKey), - ), + pageBuilder: + (_, GoRouterState state) => CustomTransitionPage( + key: state.pageKey, + transitionDuration: transitionDuration, + reverseTransitionDuration: reverseTransitionDuration, + transitionsBuilder: + (_, Animation animation, ___, Widget child) => + FadeTransition(opacity: animation, child: child), + child: const LoginScreen(key: loginKey), + ), ), ], ); @@ -207,10 +194,6 @@ class DismissibleModal extends StatelessWidget { @override Widget build(BuildContext context) { - return const SizedBox( - width: 200, - height: 200, - child: Center(child: Text('Dismissible Modal')), - ); + return const SizedBox(width: 200, height: 200, child: Center(child: Text('Dismissible Modal'))); } } diff --git a/packages/go_router/test/delegate_test.dart b/packages/go_router/test/delegate_test.dart index 097feaf9e82b..bd2d8d34b06e 100644 --- a/packages/go_router/test/delegate_test.dart +++ b/packages/go_router/test/delegate_test.dart @@ -30,9 +30,7 @@ Future createGoRouter( return router; } -Future createGoRouterWithStatefulShellRoute( - WidgetTester tester, -) async { +Future createGoRouterWithStatefulShellRoute(WidgetTester tester) async { final router = GoRouter( initialLocation: '/', routes: [ @@ -46,14 +44,8 @@ Future createGoRouterWithStatefulShellRoute( path: '/c', builder: (_, __) => const DummyStatefulWidget(), routes: [ - GoRoute( - path: 'c1', - builder: (_, __) => const DummyStatefulWidget(), - ), - GoRoute( - path: 'c2', - builder: (_, __) => const DummyStatefulWidget(), - ), + GoRoute(path: 'c1', builder: (_, __) => const DummyStatefulWidget()), + GoRoute(path: 'c2', builder: (_, __) => const DummyStatefulWidget()), ], ), ], @@ -64,10 +56,7 @@ Future createGoRouterWithStatefulShellRoute( path: '/d', builder: (_, __) => const DummyStatefulWidget(), routes: [ - GoRoute( - path: 'd1', - builder: (_, __) => const DummyStatefulWidget(), - ), + GoRoute(path: 'd1', builder: (_, __) => const DummyStatefulWidget()), ], ), ], @@ -100,19 +89,21 @@ Future createGoRouterWithStatefulShellRouteAndPopScopes( routes: [ GoRoute( path: '/c', - builder: (_, __) => PopScope( - onPopInvokedWithResult: onPopBranch, - canPop: canPopBranch, - child: const Text('Home'), - ), + builder: + (_, __) => PopScope( + onPopInvokedWithResult: onPopBranch, + canPop: canPopBranch, + child: const Text('Home'), + ), routes: [ GoRoute( path: 'c1', - builder: (_, __) => PopScope( - onPopInvokedWithResult: onPopBranchSubRoute, - canPop: canPopBranchSubRoute, - child: const Text('SubRoute'), - ), + builder: + (_, __) => PopScope( + onPopInvokedWithResult: onPopBranchSubRoute, + canPop: canPopBranchSubRoute, + child: const Text('SubRoute'), + ), ), ], ), @@ -120,15 +111,12 @@ Future createGoRouterWithStatefulShellRouteAndPopScopes( ), ], builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) => PopScope( - onPopInvokedWithResult: onPopShellRouteBuilder, - canPop: canPopShellRouteBuilder, - child: navigationShell, - ), + (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) => + PopScope( + onPopInvokedWithResult: onPopShellRouteBuilder, + canPop: canPopShellRouteBuilder, + child: navigationShell, + ), ), ], ); @@ -140,9 +128,7 @@ Future createGoRouterWithStatefulShellRouteAndPopScopes( void main() { group('pop', () { - testWidgets('restore() update currentConfiguration in pop()', ( - WidgetTester tester, - ) async { + testWidgets('restore() update currentConfiguration in pop()', (WidgetTester tester) async { final valueNotifier = ValueNotifier(0); final GoRouter goRouter = await createGoRouter( tester, @@ -156,15 +142,7 @@ void main() { goRouter.pop(); valueNotifier.notifyListeners(); await tester.pumpAndSettle(); - expect( - goRouter - .routerDelegate - .currentConfiguration - .matches - .last - .matchedLocation, - '/', - ); + expect(goRouter.routerDelegate.currentConfiguration.matches.last.matchedLocation, '/'); addTearDown(valueNotifier.dispose); addTearDown(goRouter.dispose); @@ -175,19 +153,13 @@ void main() { ..push('/error'); await tester.pumpAndSettle(); expect(find.byType(ErrorScreen), findsOneWidget); - final RouteMatchBase last = - goRouter.routerDelegate.currentConfiguration.matches.last; + final RouteMatchBase last = goRouter.routerDelegate.currentConfiguration.matches.last; await goRouter.routerDelegate.popRoute(); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - expect( - goRouter.routerDelegate.currentConfiguration.matches.contains(last), - false, - ); + expect(goRouter.routerDelegate.currentConfiguration.matches.contains(last), false); }); - testWidgets('PopScope intercepts back button on root route', ( - WidgetTester tester, - ) async { + testWidgets('PopScope intercepts back button on root route', (WidgetTester tester) async { var didPop = false; final goRouter = GoRouter( @@ -195,13 +167,14 @@ void main() { routes: [ GoRoute( path: '/', - builder: (_, __) => PopScope( - onPopInvokedWithResult: (bool result, _) { - didPop = true; - }, - canPop: false, - child: const Text('Home'), - ), + builder: + (_, __) => PopScope( + onPopInvokedWithResult: (bool result, _) { + didPop = true; + }, + canPop: false, + child: const Text('Home'), + ), ), ], ); @@ -222,97 +195,91 @@ void main() { expect(find.text('Home'), findsOneWidget); }); - testWidgets( - 'PopScope intercepts back button on StatefulShellRoute builder route', - (WidgetTester tester) async { - var didPopShellRouteBuilder = false; - var didPopBranch = false; - var didPopBranchSubRoute = false; - - await createGoRouterWithStatefulShellRouteAndPopScopes( - tester, - canPopShellRouteBuilder: false, - onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, - onPopBranch: (_, __) => didPopBranch = true, - onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, - ); - - expect(find.text('Home'), findsOneWidget); - await tester.binding.handlePopRoute(); - await tester.pumpAndSettle(); - - // Verify that PopScope intercepted the back button - expect(didPopShellRouteBuilder, isTrue); - expect(didPopBranch, isFalse); - expect(didPopBranchSubRoute, isFalse); - - expect(find.text('Home'), findsOneWidget); - }, - ); + testWidgets('PopScope intercepts back button on StatefulShellRoute builder route', ( + WidgetTester tester, + ) async { + var didPopShellRouteBuilder = false; + var didPopBranch = false; + var didPopBranchSubRoute = false; - testWidgets( - 'PopScope intercepts back button on StatefulShellRoute branch route', - (WidgetTester tester) async { - var didPopShellRouteBuilder = false; - var didPopBranch = false; - var didPopBranchSubRoute = false; - - await createGoRouterWithStatefulShellRouteAndPopScopes( - tester, - canPopBranch: false, - onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, - onPopBranch: (_, __) => didPopBranch = true, - onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, - ); - - expect(find.text('Home'), findsOneWidget); - await tester.binding.handlePopRoute(); - await tester.pumpAndSettle(); - - // Verify that PopScope intercepted the back button - expect(didPopShellRouteBuilder, isFalse); - expect(didPopBranch, isTrue); - expect(didPopBranchSubRoute, isFalse); - - expect(find.text('Home'), findsOneWidget); - }, - ); + await createGoRouterWithStatefulShellRouteAndPopScopes( + tester, + canPopShellRouteBuilder: false, + onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, + onPopBranch: (_, __) => didPopBranch = true, + onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, + ); - testWidgets( - 'PopScope intercepts back button on StatefulShellRoute branch sub route', - (WidgetTester tester) async { - var didPopShellRouteBuilder = false; - var didPopBranch = false; - var didPopBranchSubRoute = false; - - final GoRouter goRouter = - await createGoRouterWithStatefulShellRouteAndPopScopes( - tester, - canPopBranchSubRoute: false, - onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, - onPopBranch: (_, __) => didPopBranch = true, - onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, - ); - - goRouter.push('/c/c1'); - await tester.pumpAndSettle(); - - expect(find.text('SubRoute'), findsOneWidget); - await tester.binding.handlePopRoute(); - await tester.pumpAndSettle(); - - // Verify that PopScope intercepted the back button - expect(didPopShellRouteBuilder, isFalse); - expect(didPopBranch, isFalse); - expect(didPopBranchSubRoute, isTrue); - - expect(find.text('SubRoute'), findsOneWidget); - }, - ); + expect(find.text('Home'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); - testWidgets('pops more than matches count should return false', ( + // Verify that PopScope intercepted the back button + expect(didPopShellRouteBuilder, isTrue); + expect(didPopBranch, isFalse); + expect(didPopBranchSubRoute, isFalse); + + expect(find.text('Home'), findsOneWidget); + }); + + testWidgets('PopScope intercepts back button on StatefulShellRoute branch route', ( WidgetTester tester, ) async { + var didPopShellRouteBuilder = false; + var didPopBranch = false; + var didPopBranchSubRoute = false; + + await createGoRouterWithStatefulShellRouteAndPopScopes( + tester, + canPopBranch: false, + onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, + onPopBranch: (_, __) => didPopBranch = true, + onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, + ); + + expect(find.text('Home'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + + // Verify that PopScope intercepted the back button + expect(didPopShellRouteBuilder, isFalse); + expect(didPopBranch, isTrue); + expect(didPopBranchSubRoute, isFalse); + + expect(find.text('Home'), findsOneWidget); + }); + + testWidgets('PopScope intercepts back button on StatefulShellRoute branch sub route', ( + WidgetTester tester, + ) async { + var didPopShellRouteBuilder = false; + var didPopBranch = false; + var didPopBranchSubRoute = false; + + final GoRouter goRouter = await createGoRouterWithStatefulShellRouteAndPopScopes( + tester, + canPopBranchSubRoute: false, + onPopShellRouteBuilder: (_, __) => didPopShellRouteBuilder = true, + onPopBranch: (_, __) => didPopBranch = true, + onPopBranchSubRoute: (_, __) => didPopBranchSubRoute = true, + ); + + goRouter.push('/c/c1'); + await tester.pumpAndSettle(); + + expect(find.text('SubRoute'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + + // Verify that PopScope intercepted the back button + expect(didPopShellRouteBuilder, isFalse); + expect(didPopBranch, isFalse); + expect(didPopBranchSubRoute, isTrue); + + expect(find.text('SubRoute'), findsOneWidget); + }); + + testWidgets('pops more than matches count should return false', (WidgetTester tester) async { final GoRouter goRouter = await createGoRouter(tester) ..push('/error'); await tester.pumpAndSettle(); @@ -354,9 +321,7 @@ void main() { expect(message, 'There is nothing to pop'); }); - testWidgets('poproute return false if nothing to pop', ( - WidgetTester tester, - ) async { + testWidgets('poproute return false if nothing to pop', (WidgetTester tester) async { final rootKey = GlobalKey(); final navKey = GlobalKey(); final GoRouter goRouter = await createRouter([ @@ -399,110 +364,77 @@ void main() { expect(goRouter.routerDelegate.currentConfiguration.matches.length, 3); expect( goRouter.routerDelegate.currentConfiguration.matches[1].pageKey, - isNot( - equals( - goRouter.routerDelegate.currentConfiguration.matches[2].pageKey, - ), - ), + isNot(equals(goRouter.routerDelegate.currentConfiguration.matches[2].pageKey)), ); }); - testWidgets( - 'It should successfully push a route from outside the the current ' - 'StatefulShellRoute', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouterWithStatefulShellRoute( - tester, - ); - goRouter.push('/c/c1'); - await tester.pumpAndSettle(); - goRouter.push('/a'); - await tester.pumpAndSettle(); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 3); - expect( - goRouter.routerDelegate.currentConfiguration.matches[1].pageKey, - isNot( - equals( - goRouter.routerDelegate.currentConfiguration.matches[2].pageKey, - ), - ), - ); - }, - ); + testWidgets('It should successfully push a route from outside the the current ' + 'StatefulShellRoute', (WidgetTester tester) async { + final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(tester); + goRouter.push('/c/c1'); + await tester.pumpAndSettle(); + goRouter.push('/a'); + await tester.pumpAndSettle(); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 3); + expect( + goRouter.routerDelegate.currentConfiguration.matches[1].pageKey, + isNot(equals(goRouter.routerDelegate.currentConfiguration.matches[2].pageKey)), + ); + }); - testWidgets( - 'It should successfully push a route that is a descendant of the current ' - 'StatefulShellRoute branch', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouterWithStatefulShellRoute( - tester, - ); - goRouter.push('/c/c1'); - await tester.pumpAndSettle(); - - goRouter.push('/c/c2'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final shellRouteMatch = - goRouter.routerDelegate.currentConfiguration.matches.last - as ShellRouteMatch; - expect(shellRouteMatch.matches.length, 2); - expect( - shellRouteMatch.matches[0].pageKey, - isNot(equals(shellRouteMatch.matches[1].pageKey)), - ); - }, - ); + testWidgets('It should successfully push a route that is a descendant of the current ' + 'StatefulShellRoute branch', (WidgetTester tester) async { + final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(tester); + goRouter.push('/c/c1'); + await tester.pumpAndSettle(); - testWidgets( - 'It should successfully push the root of the current StatefulShellRoute ' - 'branch upon itself', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouterWithStatefulShellRoute( - tester, - ); - goRouter.push('/c'); - await tester.pumpAndSettle(); - - goRouter.push('/c'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final shellRouteMatch = - goRouter.routerDelegate.currentConfiguration.matches.last - as ShellRouteMatch; - expect(shellRouteMatch.matches.length, 2); - expect( - shellRouteMatch.matches[0].pageKey, - isNot(equals(shellRouteMatch.matches[1].pageKey)), - ); - }, - ); + goRouter.push('/c/c2'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + final shellRouteMatch = + goRouter.routerDelegate.currentConfiguration.matches.last as ShellRouteMatch; + expect(shellRouteMatch.matches.length, 2); + expect(shellRouteMatch.matches[0].pageKey, isNot(equals(shellRouteMatch.matches[1].pageKey))); + }); + + testWidgets('It should successfully push the root of the current StatefulShellRoute ' + 'branch upon itself', (WidgetTester tester) async { + final GoRouter goRouter = await createGoRouterWithStatefulShellRoute(tester); + goRouter.push('/c'); + await tester.pumpAndSettle(); + + goRouter.push('/c'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + final shellRouteMatch = + goRouter.routerDelegate.currentConfiguration.matches.last as ShellRouteMatch; + expect(shellRouteMatch.matches.length, 2); + expect(shellRouteMatch.matches[0].pageKey, isNot(equals(shellRouteMatch.matches[1].pageKey))); + }); }); group('canPop', () { - testWidgets( - 'It should return false if there is only 1 match in the stack', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester); - - await tester.pumpAndSettle(); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - expect(goRouter.routerDelegate.canPop(), false); - }, - ); - testWidgets( - 'It should return true if there is more than 1 match in the stack', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester) - ..push('/a'); - - await tester.pumpAndSettle(); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - expect(goRouter.routerDelegate.canPop(), true); - }, - ); + testWidgets('It should return false if there is only 1 match in the stack', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester); + + await tester.pumpAndSettle(); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); + expect(goRouter.routerDelegate.canPop(), false); + }); + testWidgets('It should return true if there is more than 1 match in the stack', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester) + ..push('/a'); + + await tester.pumpAndSettle(); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + expect(goRouter.routerDelegate.canPop(), true); + }); testWidgets('It should return false if there are no matches in the stack', ( WidgetTester tester, ) async { @@ -516,9 +448,7 @@ void main() { }); group('pushReplacement', () { - testWidgets('It should replace the last match with the given one', ( - WidgetTester tester, - ) async { + testWidgets('It should replace the last match with the given one', (WidgetTester tester) async { final goRouter = GoRouter( initialLocation: '/', routes: [ @@ -533,8 +463,7 @@ void main() { goRouter.push('/page-0'); goRouter.routerDelegate.addListener(expectAsync0(() {})); - final RouteMatchBase first = - goRouter.routerDelegate.currentConfiguration.matches.first; + final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first; final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last; goRouter.pushReplacement('/page-1'); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); @@ -549,63 +478,46 @@ void main() { reason: 'The last match should have been removed', ); expect( - (goRouter.routerDelegate.currentConfiguration.last - as ImperativeRouteMatch) - .matches - .uri + (goRouter.routerDelegate.currentConfiguration.last as ImperativeRouteMatch).matches.uri .toString(), '/page-1', reason: 'The new location should have been pushed', ); }); - testWidgets( - 'It should return different pageKey when pushReplacement is called', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - expect( - goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, - isNotNull, - ); - - goRouter.push('/a'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final ValueKey prev = - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; - - goRouter.pushReplacement('/a'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - expect( - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, - isNot(equals(prev)), - ); - }, - ); + testWidgets('It should return different pageKey when pushReplacement is called', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); + expect(goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, isNotNull); + + goRouter.push('/a'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + final ValueKey prev = + goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; + + goRouter.pushReplacement('/a'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + expect( + goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, + isNot(equals(prev)), + ); + }); }); group('pushReplacementNamed', () { - testWidgets('It should replace the last match with the given one', ( - WidgetTester tester, - ) async { + testWidgets('It should replace the last match with the given one', (WidgetTester tester) async { final goRouter = GoRouter( initialLocation: '/', routes: [ GoRoute(path: '/', builder: (_, __) => const SizedBox()), - GoRoute( - path: '/page-0', - name: 'page0', - builder: (_, __) => const SizedBox(), - ), - GoRoute( - path: '/page-1', - name: 'page1', - builder: (_, __) => const SizedBox(), - ), + GoRoute(path: '/page-0', name: 'page0', builder: (_, __) => const SizedBox()), + GoRoute(path: '/page-1', name: 'page1', builder: (_, __) => const SizedBox()), ], ); addTearDown(goRouter.dispose); @@ -614,8 +526,7 @@ void main() { goRouter.pushNamed('page0'); goRouter.routerDelegate.addListener(expectAsync0(() {})); - final RouteMatchBase first = - goRouter.routerDelegate.currentConfiguration.matches.first; + final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first; final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last; goRouter.pushReplacementNamed('page1'); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); @@ -642,9 +553,7 @@ void main() { }); group('replace', () { - testWidgets('It should replace the last match with the given one', ( - WidgetTester tester, - ) async { + testWidgets('It should replace the last match with the given one', (WidgetTester tester) async { final goRouter = GoRouter( initialLocation: '/', routes: [ @@ -659,8 +568,7 @@ void main() { goRouter.push('/page-0'); goRouter.routerDelegate.addListener(expectAsync0(() {})); - final RouteMatchBase first = - goRouter.routerDelegate.currentConfiguration.matches.first; + final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first; final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last; goRouter.replace('/page-1'); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); @@ -675,96 +583,64 @@ void main() { reason: 'The last match should have been removed', ); expect( - (goRouter.routerDelegate.currentConfiguration.last - as ImperativeRouteMatch) - .matches - .uri + (goRouter.routerDelegate.currentConfiguration.last as ImperativeRouteMatch).matches.uri .toString(), '/page-1', reason: 'The new location should have been pushed', ); }); - testWidgets( - 'It should use the same pageKey when replace is called (with the same path)', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - expect( - goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, - isNotNull, - ); - - goRouter.push('/a'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final ValueKey prev = - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; - - goRouter.replace('/a'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - expect( - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, - prev, - ); - }, - ); + testWidgets('It should use the same pageKey when replace is called (with the same path)', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); + expect(goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, isNotNull); - testWidgets( - 'It should use the same pageKey when replace is called (with a different path)', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - expect( - goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, - isNotNull, - ); - - goRouter.push('/a'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final ValueKey prev = - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; - - goRouter.replace('/'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - expect( - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, - prev, - ); - }, - ); + goRouter.push('/a'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + final ValueKey prev = + goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; + + goRouter.replace('/a'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev); + }); + + testWidgets('It should use the same pageKey when replace is called (with a different path)', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); + expect(goRouter.routerDelegate.currentConfiguration.matches[0].pageKey, isNotNull); + + goRouter.push('/a'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + final ValueKey prev = + goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; + + goRouter.replace('/'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev); + }); }); group('replaceNamed', () { - Future createGoRouter( - WidgetTester tester, { - Listenable? refreshListenable, - }) async { + Future createGoRouter(WidgetTester tester, {Listenable? refreshListenable}) async { final router = GoRouter( initialLocation: '/', routes: [ - GoRoute( - path: '/', - name: 'home', - builder: (_, __) => const SizedBox(), - ), - GoRoute( - path: '/page-0', - name: 'page0', - builder: (_, __) => const SizedBox(), - ), - GoRoute( - path: '/page-1', - name: 'page1', - builder: (_, __) => const SizedBox(), - ), + GoRoute(path: '/', name: 'home', builder: (_, __) => const SizedBox()), + GoRoute(path: '/page-0', name: 'page0', builder: (_, __) => const SizedBox()), + GoRoute(path: '/page-1', name: 'page1', builder: (_, __) => const SizedBox()), ], ); addTearDown(router.dispose); @@ -772,16 +648,13 @@ void main() { return router; } - testWidgets('It should replace the last match with the given one', ( - WidgetTester tester, - ) async { + testWidgets('It should replace the last match with the given one', (WidgetTester tester) async { final GoRouter goRouter = await createGoRouter(tester); goRouter.pushNamed('page0'); goRouter.routerDelegate.addListener(expectAsync0(() {})); - final RouteMatchBase first = - goRouter.routerDelegate.currentConfiguration.matches.first; + final RouteMatchBase first = goRouter.routerDelegate.currentConfiguration.matches.first; final RouteMatch last = goRouter.routerDelegate.currentConfiguration.last; goRouter.replaceNamed('page1'); expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); @@ -796,76 +669,57 @@ void main() { reason: 'The last match should have been removed', ); expect( - (goRouter.routerDelegate.currentConfiguration.last - as ImperativeRouteMatch) - .matches - .uri + (goRouter.routerDelegate.currentConfiguration.last as ImperativeRouteMatch).matches.uri .toString(), '/page-1', reason: 'The new location should have been pushed', ); }); - testWidgets( - 'It should use the same pageKey when replace is called with the same path', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - expect( - goRouter.routerDelegate.currentConfiguration.matches.first.pageKey, - isNotNull, - ); - - goRouter.pushNamed('page0'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final ValueKey prev = - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; - - goRouter.replaceNamed('page0'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - expect( - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, - prev, - ); - }, - ); + testWidgets('It should use the same pageKey when replace is called with the same path', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); + expect(goRouter.routerDelegate.currentConfiguration.matches.first.pageKey, isNotNull); - testWidgets( - 'It should use a new pageKey when replace is called with a different path', - (WidgetTester tester) async { - final GoRouter goRouter = await createGoRouter(tester); - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); - expect( - goRouter.routerDelegate.currentConfiguration.matches.first.pageKey, - isNotNull, - ); - - goRouter.pushNamed('page0'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - final ValueKey prev = - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; - - goRouter.replaceNamed('home'); - await tester.pumpAndSettle(); - - expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); - expect( - goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, - prev, - ); - }, - ); + goRouter.pushNamed('page0'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + final ValueKey prev = + goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; + + goRouter.replaceNamed('page0'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev); + }); + + testWidgets('It should use a new pageKey when replace is called with a different path', ( + WidgetTester tester, + ) async { + final GoRouter goRouter = await createGoRouter(tester); + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 1); + expect(goRouter.routerDelegate.currentConfiguration.matches.first.pageKey, isNotNull); + + goRouter.pushNamed('page0'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + final ValueKey prev = + goRouter.routerDelegate.currentConfiguration.matches.last.pageKey; + + goRouter.replaceNamed('home'); + await tester.pumpAndSettle(); + + expect(goRouter.routerDelegate.currentConfiguration.matches.length, 2); + expect(goRouter.routerDelegate.currentConfiguration.matches.last.pageKey, prev); + }); }); - testWidgets('dispose unsubscribes from refreshListenable', ( - WidgetTester tester, - ) async { + testWidgets('dispose unsubscribes from refreshListenable', (WidgetTester tester) async { final refreshListenable = FakeRefreshListenable(); addTearDown(refreshListenable.dispose); diff --git a/packages/go_router/test/error_page_test.dart b/packages/go_router/test/error_page_test.dart index b5ac263c1c75..7637d34010f0 100644 --- a/packages/go_router/test/error_page_test.dart +++ b/packages/go_router/test/error_page_test.dart @@ -26,9 +26,7 @@ void main() { testWidgets( 'clicking the button should redirect to /', testClickingTheButtonRedirectsToRoot( - buttonFinder: find.byWidgetPredicate( - (Widget widget) => widget is GestureDetector, - ), + buttonFinder: find.byWidgetPredicate((Widget widget) => widget is GestureDetector), widget: widgetsAppBuilder(home: const ErrorScreen(null)), ), ); diff --git a/packages/go_router/test/exception_handling_test.dart b/packages/go_router/test/exception_handling_test.dart index 8578c6e87548..2c467f7c9839 100644 --- a/packages/go_router/test/exception_handling_test.dart +++ b/packages/go_router/test/exception_handling_test.dart @@ -16,10 +16,7 @@ void main() { try { GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), ], errorBuilder: (_, __) => const Text(''), onException: (_, __, ___) {}, @@ -33,10 +30,7 @@ void main() { try { GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), ], errorBuilder: (_, __) => const Text(''), errorPageBuilder: (_, __) => const MaterialPage(child: Text('')), @@ -50,10 +44,7 @@ void main() { try { GoRouter( routes: [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), ], onException: (_, __, ___) {}, errorPageBuilder: (_, __) => const MaterialPage(child: Text('')), @@ -70,13 +61,13 @@ void main() { [ GoRoute( path: '/error', - builder: (_, GoRouterState state) => - Text('redirected ${state.extra}'), + builder: (_, GoRouterState state) => Text('redirected ${state.extra}'), ), ], tester, - onException: (_, GoRouterState state, GoRouter router) => - router.go('/error', extra: state.uri.toString()), + onException: + (_, GoRouterState state, GoRouter router) => + router.go('/error', extra: state.uri.toString()), ); expect(find.text('redirected /'), findsOneWidget); @@ -94,8 +85,8 @@ void main() { ), ], tester, - onException: (_, GoRouterState state, GoRouter router) => - router.go('/error', extra: state.extra), + onException: + (_, GoRouterState state, GoRouter router) => router.go('/error', extra: state.extra), ); expect(find.text('extra: null'), findsOneWidget); @@ -106,12 +97,7 @@ void main() { testWidgets('stays on the same page if noop.', (WidgetTester tester) async { final GoRouter router = await createRouter( - [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), - ], + [GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home'))], tester, onException: (_, __, ___) {}, ); @@ -122,27 +108,20 @@ void main() { expect(find.text('home'), findsOneWidget); }); - testWidgets('can catch errors thrown in redirect callbacks', ( - WidgetTester tester, - ) async { + testWidgets('can catch errors thrown in redirect callbacks', (WidgetTester tester) async { var exceptionCaught = false; String? errorMessage; final GoRouter router = await createRouter( [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), GoRoute( path: '/error-page', - builder: (_, GoRouterState state) => - Text('error handled: ${state.extra}'), + builder: (_, GoRouterState state) => Text('error handled: ${state.extra}'), ), GoRoute( path: '/trigger-error', - builder: (_, GoRouterState state) => - const Text('should not reach here'), + builder: (_, GoRouterState state) => const Text('should not reach here'), ), ], tester, @@ -153,12 +132,11 @@ void main() { } return null; }, - onException: - (BuildContext context, GoRouterState state, GoRouter router) { - exceptionCaught = true; - errorMessage = 'Caught exception for ${state.uri}'; - router.go('/error-page', extra: errorMessage); - }, + onException: (BuildContext context, GoRouterState state, GoRouter router) { + exceptionCaught = true; + errorMessage = 'Caught exception for ${state.uri}'; + router.go('/error-page', extra: errorMessage); + }, ); expect(find.text('home'), findsOneWidget); @@ -171,10 +149,7 @@ void main() { // Verify the exception was caught and handled expect(exceptionCaught, isTrue); expect(errorMessage, isNotNull); - expect( - find.text('error handled: Caught exception for /trigger-error'), - findsOneWidget, - ); + expect(find.text('error handled: Caught exception for /trigger-error'), findsOneWidget); expect(find.text('should not reach here'), findsNothing); }); @@ -185,19 +160,14 @@ void main() { final GoRouter router = await createRouter( [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), GoRoute( path: '/error-page', - builder: (_, GoRouterState state) => - const Text('generic error handled'), + builder: (_, GoRouterState state) => const Text('generic error handled'), ), GoRoute( path: '/trigger-runtime-error', - builder: (_, GoRouterState state) => - const Text('should not reach here'), + builder: (_, GoRouterState state) => const Text('should not reach here'), ), ], tester, @@ -208,11 +178,10 @@ void main() { } return null; }, - onException: - (BuildContext context, GoRouterState state, GoRouter router) { - exceptionCaught = true; - router.go('/error-page'); - }, + onException: (BuildContext context, GoRouterState state, GoRouter router) { + exceptionCaught = true; + router.go('/error-page'); + }, ); expect(find.text('home'), findsOneWidget); diff --git a/packages/go_router/test/extension_test.dart b/packages/go_router/test/extension_test.dart index d65bf21b8298..90161d874260 100644 --- a/packages/go_router/test/extension_test.dart +++ b/packages/go_router/test/extension_test.dart @@ -8,23 +8,12 @@ import 'package:go_router/go_router.dart'; void main() { group('replaceNamed', () { - Future createGoRouter( - WidgetTester tester, { - Listenable? refreshListenable, - }) async { + Future createGoRouter(WidgetTester tester, {Listenable? refreshListenable}) async { final router = GoRouter( initialLocation: '/', routes: [ - GoRoute( - path: '/', - name: 'home', - builder: (_, __) => const _MyWidget(), - ), - GoRoute( - path: '/page-0/:tab', - name: 'page-0', - builder: (_, __) => const SizedBox(), - ), + GoRoute(path: '/', name: 'home', builder: (_, __) => const _MyWidget()), + GoRoute(path: '/page-0/:tab', name: 'page-0', builder: (_, __) => const SizedBox()), ], ); addTearDown(router.dispose); @@ -32,9 +21,7 @@ void main() { return router; } - testWidgets('Passes GoRouter parameters through context call.', ( - WidgetTester tester, - ) async { + testWidgets('Passes GoRouter parameters through context call.', (WidgetTester tester) async { final GoRouter router = await createGoRouter(tester); await tester.tap(find.text('Settings')); await tester.pumpAndSettle(); @@ -52,11 +39,12 @@ class _MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return ElevatedButton( - onPressed: () => context.replaceNamed( - 'page-0', - pathParameters: {'tab': 'settings'}, - queryParameters: {'search': 'notification'}, - ), + onPressed: + () => context.replaceNamed( + 'page-0', + pathParameters: {'tab': 'settings'}, + queryParameters: {'search': 'notification'}, + ), child: const Text('Settings'), ); } diff --git a/packages/go_router/test/extra_codec_test.dart b/packages/go_router/test/extra_codec_test.dart index 67d832fdfa1c..06e6e0ffc696 100644 --- a/packages/go_router/test/extra_codec_test.dart +++ b/packages/go_router/test/extra_codec_test.dart @@ -12,9 +12,7 @@ import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'test_helpers.dart'; void main() { - testWidgets('router rebuild with extra codec works', ( - WidgetTester tester, - ) async { + testWidgets('router rebuild with extra codec works', (WidgetTester tester) async { const initialString = 'some string'; const empty = 'empty'; final router = GoRouter( diff --git a/packages/go_router/test/go_route_test.dart b/packages/go_router/test/go_route_test.dart index a741577c5806..e6acd8d63bc6 100644 --- a/packages/go_router/test/go_route_test.dart +++ b/packages/go_router/test/go_route_test.dart @@ -21,9 +21,7 @@ void main() { GoRoute(path: '/', redirect: (_, __) => '/a'); }); - testWidgets('ShellRoute can use parent navigator key', ( - WidgetTester tester, - ) async { + testWidgets('ShellRoute can use parent navigator key', (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(); final shellNavigatorKey = GlobalKey(); @@ -32,12 +30,7 @@ void main() { navigatorKey: shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( - body: Column( - children: [ - const Text('Screen A'), - Expanded(child: child), - ], - ), + body: Column(children: [const Text('Screen A'), Expanded(child: child)]), ); }, routes: [ @@ -49,17 +42,13 @@ void main() { routes: [ ShellRoute( parentNavigatorKey: rootNavigatorKey, - builder: - (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - body: Column( - children: [ - const Text('Screen D'), - Expanded(child: child), - ], - ), - ); - }, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Column( + children: [const Text('Screen D'), Expanded(child: child)], + ), + ); + }, routes: [ GoRoute( path: 'c', @@ -75,21 +64,14 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/b/c', - navigatorKey: rootNavigatorKey, - ); + await createRouter(routes, tester, initialLocation: '/b/c', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen D'), findsOneWidget); expect(find.text('Screen C'), findsOneWidget); }); - testWidgets('StatefulShellRoute can use parent navigator key', ( - WidgetTester tester, - ) async { + testWidgets('StatefulShellRoute can use parent navigator key', (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(); final shellNavigatorKey = GlobalKey(); @@ -98,12 +80,7 @@ void main() { navigatorKey: shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( - body: Column( - children: [ - const Text('Screen A'), - Expanded(child: child), - ], - ), + body: Column(children: [const Text('Screen A'), Expanded(child: child)]), ); }, routes: [ @@ -117,10 +94,7 @@ void main() { parentNavigatorKey: rootNavigatorKey, builder: (_, __, StatefulNavigationShell navigationShell) { return Column( - children: [ - const Text('Screen D'), - Expanded(child: navigationShell), - ], + children: [const Text('Screen D'), Expanded(child: navigationShell)], ); }, branches: [ @@ -142,12 +116,7 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/b/c', - navigatorKey: rootNavigatorKey, - ); + await createRouter(routes, tester, initialLocation: '/b/c', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen D'), findsOneWidget); @@ -166,9 +135,7 @@ void main() { ShellRoute( parentNavigatorKey: key2, builder: (_, __, Widget child) => child, - routes: [ - GoRoute(path: '1', builder: (_, __) => const Text('/route/1')), - ], + routes: [GoRoute(path: '1', builder: (_, __) => const Text('/route/1'))], ), ], ); @@ -188,9 +155,7 @@ void main() { GoRoute( path: 'route', redirect: (_, __) => '/route/1', - routes: [ - GoRoute(path: '1', builder: (_, __) => const Text('/route/1')), - ], + routes: [GoRoute(path: '1', builder: (_, __) => const Text('/route/1'))], ), ], ), @@ -217,9 +182,7 @@ void main() { GoRoute( path: 'route', redirect: (_, __) => '/route', - routes: [ - GoRoute(path: '1', builder: (_, __) => const Text('/route/1')), - ], + routes: [GoRoute(path: '1', builder: (_, __) => const Text('/route/1'))], ), ], ), @@ -232,9 +195,7 @@ void main() { expect(tester.takeException(), isAssertionError); }); - testWidgets('redirects to a valid route based on fragment.', ( - WidgetTester tester, - ) async { + testWidgets('redirects to a valid route based on fragment.', (WidgetTester tester) async { final GoRouter router = await createRouter([ GoRoute( path: '/', @@ -254,8 +215,7 @@ void main() { routes: [ GoRoute( path: '1', - builder: (_, __) => - const Text('/route/1'), // Renders "/route/1" text + builder: (_, __) => const Text('/route/1'), // Renders "/route/1" text ), ], ), @@ -266,14 +226,8 @@ void main() { expect(find.text('home'), findsOneWidget); // Generate a location string for the named route "route" with fragment "2" - final String locationWithFragment = router.namedLocation( - 'route', - fragment: '2', - ); - expect( - locationWithFragment, - '/route#2', - ); // Expect the generated location to be "/route#2" + final String locationWithFragment = router.namedLocation('route', fragment: '2'); + expect(locationWithFragment, '/route#2'); // Expect the generated location to be "/route#2" // Navigate to the named route "route" with fragment "1" router.goNamed('route', fragment: '1'); @@ -286,35 +240,34 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets( - 'throw if sub route does not conform with parent navigator key', - (WidgetTester tester) async { - final key1 = GlobalKey(); - final key2 = GlobalKey(); - var hasError = false; - try { - ShellRoute( - navigatorKey: key1, - builder: (_, __, Widget child) => child, - routes: [ - GoRoute( - path: '/', - redirect: (_, __) => '/route', - routes: [ - GoRoute( - parentNavigatorKey: key2, - path: 'route', - builder: (_, __) => const Text('/route/1'), - ), - ], - ), - ], - ); - } on AssertionError catch (_) { - hasError = true; - } - expect(hasError, isTrue); - }, - ); + testWidgets('throw if sub route does not conform with parent navigator key', ( + WidgetTester tester, + ) async { + final key1 = GlobalKey(); + final key2 = GlobalKey(); + var hasError = false; + try { + ShellRoute( + navigatorKey: key1, + builder: (_, __, Widget child) => child, + routes: [ + GoRoute( + path: '/', + redirect: (_, __) => '/route', + routes: [ + GoRoute( + parentNavigatorKey: key2, + path: 'route', + builder: (_, __) => const Text('/route/1'), + ), + ], + ), + ], + ); + } on AssertionError catch (_) { + hasError = true; + } + expect(hasError, isTrue); + }); }); } diff --git a/packages/go_router/test/go_router_state_test.dart b/packages/go_router/test/go_router_state_test.dart index 2624084dea1b..39cba7c0c40e 100644 --- a/packages/go_router/test/go_router_state_test.dart +++ b/packages/go_router/test/go_router_state_test.dart @@ -75,9 +75,7 @@ void main() { expect(find.text('1 /a', skipOffstage: false), findsOneWidget); }); - testWidgets('path parameter persists after page is popped', ( - WidgetTester tester, - ) async { + testWidgets('path parameter persists after page is popped', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', @@ -94,9 +92,7 @@ void main() { builder: (_, __) { return Builder( builder: (BuildContext context) { - return Text( - '2 ${GoRouterState.of(context).pathParameters['id']}', - ); + return Text('2 ${GoRouterState.of(context).pathParameters['id']}'); }, ); }, @@ -118,9 +114,7 @@ void main() { expect(find.text('2 123'), findsOneWidget); }); - testWidgets('registry retains GoRouterState for exiting route', ( - WidgetTester tester, - ) async { + testWidgets('registry retains GoRouterState for exiting route', (WidgetTester tester) async { final key = UniqueKey(); final routes = [ GoRoute( @@ -146,17 +140,12 @@ void main() { ], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(tester.widget(find.byKey(key)).data, '/a'); - final GoRouterStateRegistry registry = tester - .widget( - find.byType(GoRouterStateRegistryScope), - ) - .notifier!; + final GoRouterStateRegistry registry = + tester + .widget(find.byType(GoRouterStateRegistryScope)) + .notifier!; expect(registry.registry.length, 2); router.go('/'); await tester.pump(); @@ -170,9 +159,7 @@ void main() { expect(find.byKey(key), findsNothing); }); - testWidgets('imperative pop clears out registry', ( - WidgetTester tester, - ) async { + testWidgets('imperative pop clears out registry', (WidgetTester tester) async { final key = UniqueKey(); final nav = GlobalKey(); final routes = [ @@ -199,18 +186,12 @@ void main() { ], ), ]; - await createRouter( - routes, - tester, - initialLocation: '/a', - navigatorKey: nav, - ); + await createRouter(routes, tester, initialLocation: '/a', navigatorKey: nav); expect(tester.widget(find.byKey(key)).data, '/a'); - final GoRouterStateRegistry registry = tester - .widget( - find.byType(GoRouterStateRegistryScope), - ) - .notifier!; + final GoRouterStateRegistry registry = + tester + .widget(find.byType(GoRouterStateRegistryScope)) + .notifier!; expect(registry.registry.length, 2); nav.currentState!.pop(); await tester.pump(); @@ -224,41 +205,36 @@ void main() { expect(find.byKey(key), findsNothing); }); - testWidgets( - 'GoRouterState look up should be resilient when there is a nested navigator.', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/', - builder: (_, __) { - return Scaffold( - appBar: AppBar(), - body: Navigator( - pages: >[ - MaterialPage( - child: Builder( - builder: (BuildContext context) { - return Center( - child: Text( - GoRouterState.of(context).uri.toString(), - ), - ); - }, - ), + testWidgets('GoRouterState look up should be resilient when there is a nested navigator.', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + path: '/', + builder: (_, __) { + return Scaffold( + appBar: AppBar(), + body: Navigator( + pages: >[ + MaterialPage( + child: Builder( + builder: (BuildContext context) { + return Center(child: Text(GoRouterState.of(context).uri.toString())); + }, ), - ], - onPopPage: (Route route, Object? result) { - throw UnimplementedError(); - }, - ), - ); - }, - ), - ]; - await createRouter(routes, tester); - expect(find.text('/'), findsOneWidget); - }, - ); + ), + ], + onPopPage: (Route route, Object? result) { + throw UnimplementedError(); + }, + ), + ); + }, + ), + ]; + await createRouter(routes, tester); + expect(find.text('/'), findsOneWidget); + }); testWidgets('GoRouterState topRoute accessible from StatefulShellRoute', ( WidgetTester tester, @@ -270,12 +246,7 @@ void main() { navigatorKey: shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( - body: Column( - children: [ - const Text('Screen 0'), - Expanded(child: child), - ], - ), + body: Column(children: [const Text('Screen 0'), Expanded(child: child)]), ); }, routes: [ @@ -288,27 +259,21 @@ void main() { routes: [ StatefulShellRoute.indexedStack( parentNavigatorKey: rootNavigatorKey, - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - final String? routeName = GoRouterState.of( - context, - ).topRoute?.name; - final String title = switch (routeName) { - 'a' => 'A', - 'b' => 'B', - _ => 'Unknown', - }; - return Column( - children: [ - Text(title), - Expanded(child: navigationShell), - ], - ); - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + final String? routeName = GoRouterState.of(context).topRoute?.name; + final String title = switch (routeName) { + 'a' => 'A', + 'b' => 'B', + _ => 'Unknown', + }; + return Column( + children: [Text(title), Expanded(child: navigationShell)], + ); + }, branches: [ StatefulShellBranch( routes: [ diff --git a/packages/go_router/test/go_router_test.dart b/packages/go_router/test/go_router_test.dart index d47fee16665a..996a889acb50 100644 --- a/packages/go_router/test/go_router_test.dart +++ b/packages/go_router/test/go_router_test.dart @@ -43,8 +43,7 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), ]; @@ -55,27 +54,23 @@ void main() { expect(find.byType(HomeScreen), findsOneWidget); }); - testWidgets( - 'If there is more than one route to match, use the first match', - (WidgetTester tester) async { - final routes = [ - GoRoute(name: '1', path: '/', builder: dummy), - GoRoute(name: '2', path: '/', builder: dummy), - ]; - - final GoRouter router = await createRouter(routes, tester); - router.go('/'); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect((matches.first.route as GoRoute).name, '1'); - expect(find.byType(DummyScreen), findsOneWidget); - }, - ); - - testWidgets('pushReplacement and replace when only one matches', ( + testWidgets('If there is more than one route to match, use the first match', ( WidgetTester tester, ) async { + final routes = [ + GoRoute(name: '1', path: '/', builder: dummy), + GoRoute(name: '2', path: '/', builder: dummy), + ]; + + final GoRouter router = await createRouter(routes, tester); + router.go('/'); + final List matches = router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect((matches.first.route as GoRoute).name, '1'); + expect(find.byType(DummyScreen), findsOneWidget); + }); + + testWidgets('pushReplacement and replace when only one matches', (WidgetTester tester) async { final routes = [ GoRoute(name: '1', path: '/', builder: dummy), GoRoute(name: '2', path: '/a', builder: dummy), @@ -122,13 +117,11 @@ void main() { final GoRouter router = await createRouter( routes, tester, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); router.go('/foo'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); }); @@ -137,80 +130,66 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/login'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('match 2nd top level route with subroutes', ( - WidgetTester tester, - ) async { + testWidgets('match 2nd top level route with subroutes', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'page1', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), ], ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/login'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('match top level route when location has trailing /', ( - WidgetTester tester, - ) async { + testWidgets('match top level route when location has trailing /', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/login/'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); @@ -220,19 +199,14 @@ void main() { WidgetTester tester, ) async { final routes = [ - GoRoute( - path: '/profile', - builder: dummy, - redirect: (_, __) => '/profile/foo', - ), + GoRoute(path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), GoRoute(path: '/profile/:kind', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('/profile/'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/profile/foo'); expect(find.byType(DummyScreen), findsOneWidget); @@ -242,142 +216,106 @@ void main() { WidgetTester tester, ) async { final routes = [ - GoRoute( - path: '/profile', - builder: dummy, - redirect: (_, __) => '/profile/foo', - ), + GoRoute(path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), GoRoute(path: '/profile/:kind', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('/profile/?bar=baz'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/profile/foo'); expect(find.byType(DummyScreen), findsOneWidget); }); - testWidgets( - 'match top level route when location has scheme/host and has trailing /', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), - ]; - - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/?bar=baz'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/'); - expect(find.byType(HomeScreen), findsOneWidget); - }, - ); - - testWidgets( - 'match top level route when location has scheme/host and has trailing / (2)', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), - GoRoute( - path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), - ), - ]; + testWidgets('match top level route when location has scheme/host and has trailing /', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), + ), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/login/'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/login'); - expect(find.byType(LoginScreen), findsOneWidget); - }, - ); + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/?bar=baz'); + await tester.pumpAndSettle(); + final List matches = router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/'); + expect(find.byType(HomeScreen), findsOneWidget); + }); - testWidgets( - 'match top level route when location has scheme/host and has trailing / (3)', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/profile', - builder: dummy, - redirect: (_, __) => '/profile/foo', - ), - GoRoute(path: '/profile/:kind', builder: dummy), - ]; + testWidgets('match top level route when location has scheme/host and has trailing / (2)', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), + ), + GoRoute( + path: '/login', + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), + ), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/profile/'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/profile/foo'); - expect(find.byType(DummyScreen), findsOneWidget); - }, - ); + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/login/'); + await tester.pumpAndSettle(); + final List matches = router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/login'); + expect(find.byType(LoginScreen), findsOneWidget); + }); - testWidgets( - 'match top level route when location has scheme/host and has trailing / (4)', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/profile', - builder: dummy, - redirect: (_, __) => '/profile/foo', - ), - GoRoute(path: '/profile/:kind', builder: dummy), - ]; + testWidgets('match top level route when location has scheme/host and has trailing / (3)', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute(path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), + GoRoute(path: '/profile/:kind', builder: dummy), + ]; - final GoRouter router = await createRouter(routes, tester); - router.go('https://www.domain.com/profile/?bar=baz'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(matches.first.matchedLocation, '/profile/foo'); - expect(find.byType(DummyScreen), findsOneWidget); - }, - ); + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/profile/'); + await tester.pumpAndSettle(); + final List matches = router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/profile/foo'); + expect(find.byType(DummyScreen), findsOneWidget); + }); - testWidgets('repeatedly pops imperative route does not crash', ( + testWidgets('match top level route when location has scheme/host and has trailing / (4)', ( WidgetTester tester, ) async { + final routes = [ + GoRoute(path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), + GoRoute(path: '/profile/:kind', builder: dummy), + ]; + + final GoRouter router = await createRouter(routes, tester); + router.go('https://www.domain.com/profile/?bar=baz'); + await tester.pumpAndSettle(); + final List matches = router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(matches.first.matchedLocation, '/profile/foo'); + expect(find.byType(DummyScreen), findsOneWidget); + }); + + testWidgets('repeatedly pops imperative route does not crash', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/123369. final home = UniqueKey(); final settings = UniqueKey(); final dialog = UniqueKey(); final navKey = GlobalKey(); final routes = [ - GoRoute( - path: '/', - builder: (_, __) => DummyScreen(key: home), - ), - GoRoute( - path: '/settings', - builder: (_, __) => DummyScreen(key: settings), - ), + GoRoute(path: '/', builder: (_, __) => DummyScreen(key: home)), + GoRoute(path: '/settings', builder: (_, __) => DummyScreen(key: settings)), ]; - final GoRouter router = await createRouter( - routes, - tester, - navigatorKey: navKey, - ); + final GoRouter router = await createRouter(routes, tester, navigatorKey: navKey); expect(find.byKey(home), findsOneWidget); router.push('/settings'); @@ -385,10 +323,7 @@ void main() { expect(find.byKey(home), findsNothing); expect(find.byKey(settings), findsOneWidget); - showDialog( - context: navKey.currentContext!, - builder: (_) => DummyScreen(key: dialog), - ); + showDialog(context: navKey.currentContext!, builder: (_) => DummyScreen(key: dialog)); await tester.pumpAndSettle(); expect(find.byKey(dialog), findsOneWidget); @@ -397,10 +332,7 @@ void main() { expect(find.byKey(dialog), findsNothing); expect(find.byKey(settings), findsOneWidget); - showDialog( - context: navKey.currentContext!, - builder: (_) => DummyScreen(key: dialog), - ); + showDialog(context: navKey.currentContext!, builder: (_) => DummyScreen(key: dialog)); await tester.pumpAndSettle(); expect(find.byKey(dialog), findsOneWidget); @@ -410,9 +342,7 @@ void main() { expect(find.byKey(settings), findsOneWidget); }); - testWidgets('android back button pop in correct order', ( - WidgetTester tester, - ) async { + testWidgets('android back button pop in correct order', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/141906. final routes = [ GoRoute( @@ -420,12 +350,9 @@ void main() { builder: (_, __) => const Text('home'), routes: [ ShellRoute( - builder: - (BuildContext context, GoRouterState state, Widget child) { - return Column( - children: [const Text('shell'), child], - ); - }, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Column(children: [const Text('shell'), child]); + }, routes: [ GoRoute( path: 'page', @@ -449,11 +376,7 @@ void main() { ], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/page', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/page'); expect(find.text('shell'), findsOneWidget); expect(find.text('page'), findsOneWidget); @@ -471,34 +394,22 @@ void main() { expect(find.text('pageless'), findsNothing); }); - testWidgets('can correctly pop stacks of repeated pages', ( - WidgetTester tester, - ) async { + testWidgets('can correctly pop stacks of repeated pages', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/#132229. final navKey = GlobalKey(); final routes = [ - GoRoute( - path: '/', - pageBuilder: (_, __) => - const MaterialPage(child: HomeScreen()), - ), + GoRoute(path: '/', pageBuilder: (_, __) => const MaterialPage(child: HomeScreen())), GoRoute( path: '/page1', - pageBuilder: (_, __) => - const MaterialPage(child: Page1Screen()), + pageBuilder: (_, __) => const MaterialPage(child: Page1Screen()), ), GoRoute( path: '/page2', - pageBuilder: (_, __) => - const MaterialPage(child: Page2Screen()), + pageBuilder: (_, __) => const MaterialPage(child: Page2Screen()), ), ]; - final GoRouter router = await createRouter( - routes, - tester, - navigatorKey: navKey, - ); + final GoRouter router = await createRouter(routes, tester, navigatorKey: navKey); expect(find.byType(HomeScreen), findsOneWidget); router.push('/page1'); @@ -514,8 +425,7 @@ void main() { router.pop(); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches.length, 4); expect(find.byType(HomeScreen), findsNothing); expect(find.byType(Page1Screen), findsOneWidget); @@ -526,13 +436,11 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -541,8 +449,7 @@ void main() { final GoRouter router = await createRouter(routes, tester); router.go('/login'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches.length, 2); expect(matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); @@ -554,25 +461,23 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person/:pid', - builder: (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: + (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), GoRoute( path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -580,8 +485,7 @@ void main() { final GoRouter router = await createRouter(routes, tester); { - final RouteMatchList matches = - router.routerDelegate.currentConfiguration; + final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(1)); expect(matches.uri.toString(), '/'); expect(find.byType(HomeScreen), findsOneWidget); @@ -590,8 +494,7 @@ void main() { router.go('/login'); await tester.pumpAndSettle(); { - final RouteMatchList matches = - router.routerDelegate.currentConfiguration; + final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches.length, 2); expect(matches.matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); @@ -602,8 +505,7 @@ void main() { router.go('/family/f2'); await tester.pumpAndSettle(); { - final RouteMatchList matches = - router.routerDelegate.currentConfiguration; + final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches.length, 2); expect(matches.matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); @@ -614,8 +516,7 @@ void main() { router.go('/family/f2/person/p1'); await tester.pumpAndSettle(); { - final RouteMatchList matches = - router.routerDelegate.currentConfiguration; + final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches.length, 3); expect(matches.matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); @@ -626,34 +527,27 @@ void main() { } }); - testWidgets('return first matching route if too many subroutes', ( - WidgetTester tester, - ) async { + testWidgets('return first matching route if too many subroutes', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'foo/bar', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen(''), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen(''), ), GoRoute( path: 'bar', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: 'foo', - builder: (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => const Page2Screen(), routes: [ GoRoute( path: 'bar', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -664,8 +558,7 @@ void main() { final GoRouter router = await createRouter(routes, tester); router.go('/bar'); await tester.pumpAndSettle(); - List matches = - router.routerDelegate.currentConfiguration.matches; + List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(2)); expect(find.byType(Page1Screen), findsOneWidget); @@ -720,10 +613,7 @@ void main() { name: 'family', path: 'family/:fid', builder: (BuildContext context, GoRouterState state) { - expect( - state.uri.toString(), - anyOf(['/family/f2', '/family/f2/person/p1']), - ); + expect(state.uri.toString(), anyOf(['/family/f2', '/family/f2/person/p1'])); expect(state.matchedLocation, '/family/f2'); expect(state.name, 'family'); expect(state.path, 'family/:fid'); @@ -743,16 +633,10 @@ void main() { expect(state.name, 'person'); expect(state.path, 'person/:pid'); expect(state.fullPath, '/family/:fid/person/:pid'); - expect(state.pathParameters, { - 'fid': 'f2', - 'pid': 'p1', - }); + expect(state.pathParameters, {'fid': 'f2', 'pid': 'p1'}); expect(state.error, null); expect(state.extra! as int, 4); - return PersonScreen( - state.pathParameters['fid']!, - state.pathParameters['pid']!, - ); + return PersonScreen(state.pathParameters['fid']!, state.pathParameters['pid']!); }, ), ], @@ -776,14 +660,14 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family/:fid', caseSensitive: false, - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -791,8 +675,7 @@ void main() { const loc = '/FaMiLy/f2'; router.go(loc); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; // NOTE: match the lower case, since location is canonicalized to match the // path case whereas the location can be any case; so long as the path @@ -810,13 +693,13 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family/:fid', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -832,8 +715,7 @@ void main() { const loc = '/family/f2'; router.go(loc); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(router.routerDelegate.currentConfiguration.uri.toString(), loc); @@ -841,24 +723,19 @@ void main() { expect(find.byType(FamilyScreen), findsOne); }); - testWidgets('supports routes with a different case', ( - WidgetTester tester, - ) async { + testWidgets('supports routes with a different case', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/abc', - builder: (BuildContext context, GoRouterState state) => - const SizedBox(key: Key('abc')), + builder: (BuildContext context, GoRouterState state) => const SizedBox(key: Key('abc')), ), GoRoute( path: '/ABC', - builder: (BuildContext context, GoRouterState state) => - const SizedBox(key: Key('ABC')), + builder: (BuildContext context, GoRouterState state) => const SizedBox(key: Key('ABC')), ), ]; @@ -877,29 +754,25 @@ void main() { expect(find.byKey(const Key('ABC')), findsOne); }); - testWidgets( - 'If there is more than one route to match, use the first match.', - (WidgetTester tester) async { - final routes = [ - GoRoute(path: '/', builder: dummy), - GoRoute(path: '/page1', builder: dummy), - GoRoute(path: '/page1', builder: dummy), - GoRoute(path: '/:ok', builder: dummy), - ]; - - final GoRouter router = await createRouter(routes, tester); - router.go('/user'); - await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; - expect(matches, hasLength(1)); - expect(find.byType(DummyScreen), findsOneWidget); - }, - ); - - testWidgets('Handles the Android back button correctly', ( + testWidgets('If there is more than one route to match, use the first match.', ( WidgetTester tester, ) async { + final routes = [ + GoRoute(path: '/', builder: dummy), + GoRoute(path: '/page1', builder: dummy), + GoRoute(path: '/page1', builder: dummy), + GoRoute(path: '/:ok', builder: dummy), + ]; + + final GoRouter router = await createRouter(routes, tester); + router.go('/user'); + await tester.pumpAndSettle(); + final List matches = router.routerDelegate.currentConfiguration.matches; + expect(matches, hasLength(1)); + expect(find.byType(DummyScreen), findsOneWidget); + }); + + testWidgets('Handles the Android back button correctly', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', @@ -935,10 +808,7 @@ void main() { final routes = [ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('Shell')), body: child); }, routes: [ GoRoute( @@ -1008,18 +878,15 @@ void main() { 'Handles the Android back button when parentNavigatorKey is set to the root navigator', (WidgetTester tester) async { final log = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - return null; - }); - - Future verify( - AsyncCallback test, - List expectations, - ) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); + + Future verify(AsyncCallback test, List expectations) async { log.clear(); await test(); expect(log, expectations); @@ -1037,12 +904,7 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/a', - navigatorKey: rootNavigatorKey, - ); + await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsOneWidget); await tester.runAsync(() async { @@ -1057,13 +919,13 @@ void main() { WidgetTester tester, ) async { final log = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); Future verify(AsyncCallback test, List expectations) async { log.clear(); @@ -1083,10 +945,7 @@ void main() { ), ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('Shell')), body: child); }, routes: [ GoRoute( @@ -1099,12 +958,7 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/b', - navigatorKey: rootNavigatorKey, - ); + await createRouter(routes, tester, initialLocation: '/b', navigatorKey: rootNavigatorKey); expect(find.text('Screen B'), findsOneWidget); await tester.runAsync(() async { @@ -1115,9 +969,7 @@ void main() { }); }); - testWidgets('does not crash when inherited widget changes', ( - WidgetTester tester, - ) async { + testWidgets('does not crash when inherited widget changes', (WidgetTester tester) async { final notifier = ValueNotifier('initial'); addTearDown(notifier.dispose); @@ -1125,10 +977,8 @@ void main() { GoRoute( path: '/', pageBuilder: (BuildContext context, GoRouterState state) { - final String value = context - .dependOnInheritedWidgetOfExactType()! - .notifier! - .value; + final String value = + context.dependOnInheritedWidgetOfExactType()!.notifier!.value; return MaterialPage(key: state.pageKey, child: Text(value)); }, ), @@ -1154,13 +1004,13 @@ void main() { 'Handles the Android back button when a second Shell has a GoRoute with parentNavigator key', (WidgetTester tester) async { final log = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); Future verify(AsyncCallback test, List expectations) async { log.clear(); @@ -1176,10 +1026,7 @@ void main() { ShellRoute( navigatorKey: shellNavigatorKeyA, builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('Shell')), body: child); }, routes: [ GoRoute( @@ -1190,17 +1037,9 @@ void main() { routes: [ ShellRoute( navigatorKey: shellNavigatorKeyB, - builder: - ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); - }, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold(appBar: AppBar(title: const Text('Shell')), body: child); + }, routes: [ GoRoute( path: 'b', @@ -1217,12 +1056,7 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/a/b', - navigatorKey: rootNavigatorKey, - ); + await createRouter(routes, tester, initialLocation: '/a/b', navigatorKey: rootNavigatorKey); expect(find.text('Screen B'), findsOneWidget); // The first pop should not exit the app. @@ -1247,68 +1081,63 @@ void main() { final log = []; setUp(() { GoRouter.optionURLReflectsImperativeAPIs = false; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.navigation, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.navigation, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); }); tearDown(() { GoRouter.optionURLReflectsImperativeAPIs = false; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.navigation, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.navigation, + null, + ); log.clear(); }); - testWidgets( - 'on push shell route with optionURLReflectImperativeAPIs = true', - (WidgetTester tester) async { - GoRouter.optionURLReflectsImperativeAPIs = true; - final routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - routes: [ - ShellRoute( - builder: - (BuildContext context, GoRouterState state, Widget child) => - child, - routes: [ - GoRoute( - path: 'c', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - ), - ], - ), - ], - ), - ]; - - final GoRouter router = await createRouter(routes, tester); - - log.clear(); - router.push('/c?foo=bar'); - final codec = RouteMatchListCodec(router.configuration); - await tester.pumpAndSettle(); - expect(log, [ - isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/c?foo=bar', - false, - codec.encode(router.routerDelegate.currentConfiguration), - ), - ]); - GoRouter.optionURLReflectsImperativeAPIs = false; - }, - ); - - testWidgets('on push with optionURLReflectImperativeAPIs = true', ( + testWidgets('on push shell route with optionURLReflectImperativeAPIs = true', ( WidgetTester tester, ) async { + GoRouter.optionURLReflectsImperativeAPIs = true; + final routes = [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), + routes: [ + ShellRoute( + builder: (BuildContext context, GoRouterState state, Widget child) => child, + routes: [ + GoRoute( + path: 'c', + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), + ), + ], + ), + ], + ), + ]; + + final GoRouter router = await createRouter(routes, tester); + + log.clear(); + router.push('/c?foo=bar'); + final codec = RouteMatchListCodec(router.configuration); + await tester.pumpAndSettle(); + expect(log, [ + isMethodCall('selectMultiEntryHistory', arguments: null), + IsRouteUpdateCall( + '/c?foo=bar', + false, + codec.encode(router.routerDelegate.currentConfiguration), + ), + ]); + GoRouter.optionURLReflectsImperativeAPIs = false; + }); + + testWidgets('on push with optionURLReflectImperativeAPIs = true', (WidgetTester tester) async { GoRouter.optionURLReflectsImperativeAPIs = true; final routes = [ GoRoute(path: '/', builder: (_, __) => const DummyScreen()), @@ -1346,11 +1175,7 @@ void main() { await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/', - false, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); @@ -1359,28 +1184,18 @@ void main() { GoRoute( path: '/', builder: (_, __) => const DummyScreen(), - routes: [ - GoRoute(path: 'settings', builder: (_, __) => const DummyScreen()), - ], + routes: [GoRoute(path: 'settings', builder: (_, __) => const DummyScreen())], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/settings', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/settings'); final codec = RouteMatchListCodec(router.configuration); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/', - false, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); @@ -1394,10 +1209,7 @@ void main() { path: 'settings', builder: (_, __) => const DummyScreen(), routes: [ - GoRoute( - path: 'profile', - builder: (_, __) => const DummyScreen(), - ), + GoRoute(path: 'profile', builder: (_, __) => const DummyScreen()), ], ), ], @@ -1416,11 +1228,7 @@ void main() { await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/', - false, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); @@ -1430,62 +1238,39 @@ void main() { path: '/', builder: (_, __) => const DummyScreen(), routes: [ - GoRoute( - path: 'settings/:id', - builder: (_, __) => const DummyScreen(), - ), + GoRoute(path: 'settings/:id', builder: (_, __) => const DummyScreen()), ], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/settings/123', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/settings/123'); final codec = RouteMatchListCodec(router.configuration); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/', - false, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); - testWidgets('on pop with path parameters case 2', ( - WidgetTester tester, - ) async { + testWidgets('on pop with path parameters case 2', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), - routes: [ - GoRoute(path: ':id', builder: (_, __) => const DummyScreen()), - ], + routes: [GoRoute(path: ':id', builder: (_, __) => const DummyScreen())], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/123/', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/123/'); final codec = RouteMatchListCodec(router.configuration); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/', - false, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); @@ -1502,10 +1287,9 @@ void main() { }, routes: [ ShellRoute( - builder: - (BuildContext context, GoRouterState state, Widget child) { - return Scaffold(appBar: AppBar(), body: child); - }, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold(appBar: AppBar(), body: child); + }, routes: [ GoRoute( path: 'b', @@ -1537,11 +1321,7 @@ void main() { expect(find.text('Screen C'), findsOneWidget); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/b/c', - true, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/b/c', true, codec.encode(router.routerDelegate.currentConfiguration)), ]); log.clear(); @@ -1551,17 +1331,11 @@ void main() { expect(find.text('Home'), findsOneWidget); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/', - false, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); - testWidgets('can handle route information update from browser', ( - WidgetTester tester, - ) async { + testWidgets('can handle route information update from browser', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', @@ -1569,8 +1343,9 @@ void main() { routes: [ GoRoute( path: 'settings', - builder: (_, GoRouterState state) => - DummyScreen(key: ValueKey('settings-${state.extra}')), + builder: + (_, GoRouterState state) => + DummyScreen(key: ValueKey('settings-${state.extra}')), ), ], ), @@ -1591,8 +1366,7 @@ void main() { final arguments = log.last.arguments as Map; // Stores the state after the last push. This should contain the encoded // RouteMatchList. - final Object? state = - (log.last.arguments as Map)['state']; + final Object? state = (log.last.arguments as Map)['state']; final location = (arguments['location'] ?? arguments['uri']!) as String; router.go('/'); @@ -1615,16 +1389,11 @@ void main() { expect(find.byKey(const ValueKey('home')), findsOneWidget); }); - testWidgets('works correctly with async redirect', ( - WidgetTester tester, - ) async { + testWidgets('works correctly with async redirect', (WidgetTester tester) async { final login = UniqueKey(); final routes = [ GoRoute(path: '/', builder: (_, __) => const DummyScreen()), - GoRoute( - path: '/login', - builder: (_, __) => DummyScreen(key: login), - ), + GoRoute(path: '/login', builder: (_, __) => DummyScreen(key: login)), ]; final completer = Completer(); final GoRouter router = await createRouter( @@ -1648,11 +1417,7 @@ void main() { expect(tester.takeException(), isNull); expect(log, [ isMethodCall('selectMultiEntryHistory', arguments: null), - IsRouteUpdateCall( - '/login', - true, - codec.encode(router.routerDelegate.currentConfiguration), - ), + IsRouteUpdateCall('/login', true, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); }); @@ -1663,8 +1428,7 @@ void main() { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), ]; @@ -1691,9 +1455,7 @@ void main() { testWidgets('match no routes', (WidgetTester tester) async { await expectLater(() async { - final routes = [ - GoRoute(name: 'home', path: '/', builder: dummy), - ]; + final routes = [GoRoute(name: 'home', path: '/', builder: dummy)]; final GoRouter router = await createRouter(routes, tester); router.goNamed('work'); }, throwsA(isAssertionError)); @@ -1704,14 +1466,12 @@ void main() { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'login', path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; @@ -1724,14 +1484,12 @@ void main() { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'login', path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -1746,23 +1504,18 @@ void main() { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( name: 'person', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { - expect(state.pathParameters, { - 'fid': 'f2', - 'pid': 'p1', - }); + expect(state.pathParameters, {'fid': 'f2', 'pid': 'p1'}); return const PersonScreen('dummy', 'dummy'); }, ), @@ -1773,10 +1526,7 @@ void main() { ]; final GoRouter router = await createRouter(routes, tester); - router.goNamed( - 'person', - pathParameters: {'fid': 'f2', 'pid': 'p1'}, - ); + router.goNamed('person', pathParameters: {'fid': 'f2', 'pid': 'p1'}); }); testWidgets('too few params', (WidgetTester tester) async { @@ -1784,20 +1534,19 @@ void main() { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( name: 'person', path: 'person/:pid', - builder: (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: + (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), @@ -1816,23 +1565,18 @@ void main() { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'family', path: 'family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( name: 'PeRsOn', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { - expect(state.pathParameters, { - 'fid': 'f2', - 'pid': 'p1', - }); + expect(state.pathParameters, {'fid': 'f2', 'pid': 'p1'}); return const PersonScreen('dummy', 'dummy'); }, ), @@ -1844,10 +1588,7 @@ void main() { final GoRouter router = await createRouter(routes, tester); expect(() { - router.goNamed( - 'person', - pathParameters: {'fid': 'f2', 'pid': 'p1'}, - ); + router.goNamed('person', pathParameters: {'fid': 'f2', 'pid': 'p1'}); }, throwsAssertionError); }); @@ -1856,8 +1597,7 @@ void main() { GoRoute( name: 'family', path: '/family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), ), ]; await expectLater(() async { @@ -1871,16 +1611,12 @@ void main() { GoRoute( name: 'family', path: '/family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), ), ]; await expectLater(() async { final GoRouter router = await createRouter(routes, tester); - router.goNamed( - 'family', - pathParameters: {'fid': 'f2', 'pid': 'p1'}, - ); + router.goNamed('family', pathParameters: {'fid': 'f2', 'pid': 'p1'}); }, throwsA(isAssertionError)); }); @@ -1889,34 +1625,28 @@ void main() { GoRoute(path: '/', builder: dummy, redirect: (_, __) => '/family/f2'), GoRoute( path: '/family/:fid', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), routes: [ GoRoute( name: 'person', path: 'person:pid', - builder: (BuildContext context, GoRouterState state) => - PersonScreen( - state.pathParameters['fid']!, - state.pathParameters['pid']!, - ), + builder: + (BuildContext context, GoRouterState state) => + PersonScreen(state.pathParameters['fid']!, state.pathParameters['pid']!), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); - router.goNamed( - 'person', - pathParameters: {'fid': 'f2', 'pid': 'p1'}, - ); + router.goNamed('person', pathParameters: {'fid': 'f2', 'pid': 'p1'}); await tester.pumpAndSettle(); expect(find.byType(PersonScreen), findsOneWidget); }); - testWidgets('preserve path param spaces and slashes', ( - WidgetTester tester, - ) async { + testWidgets('preserve path param spaces and slashes', (WidgetTester tester) async { const param1 = 'param w/ spaces and slashes'; final routes = [ GoRoute( @@ -1942,9 +1672,7 @@ void main() { expect(matches.pathParameters['param1'], param1); }); - testWidgets('preserve query param spaces and slashes', ( - WidgetTester tester, - ) async { + testWidgets('preserve query param spaces and slashes', (WidgetTester tester) async { const param1 = 'param w/ spaces and slashes'; final routes = [ GoRoute( @@ -1975,13 +1703,11 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -1997,13 +1723,11 @@ void main() { final routes = [ GoRoute( path: '/home', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -2023,22 +1747,17 @@ void main() { final routes = [ GoRoute( path: '/home', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( name: 'person', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { - expect(state.pathParameters, { - 'fid': fid, - 'pid': pid, - }); + expect(state.pathParameters, {'fid': fid, 'pid': pid}); return const PersonScreen('dummy', 'dummy'); }, ), @@ -2048,11 +1767,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/home', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/home'); router.go('./family/$fid'); await tester.pumpAndSettle(); @@ -2070,20 +1785,16 @@ void main() { final routes = [ GoRoute( path: '/home', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'family', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person', builder: (BuildContext context, GoRouterState state) { - expect(state.uri.queryParameters, { - 'pid': pid, - }); + expect(state.uri.queryParameters, {'pid': pid}); return const PersonScreen('dummy', 'dummy'); }, ), @@ -2093,11 +1804,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/home', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/home'); router.go('./family?fid=$fid'); await tester.pumpAndSettle(); @@ -2114,18 +1821,17 @@ void main() { final routes = [ GoRoute( path: '/home', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'family/:fid', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person/:pid', - builder: (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: + (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), @@ -2137,15 +1843,13 @@ void main() { routes, tester, initialLocation: '/home', - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); router.go('./family/person/$pid'); await tester.pumpAndSettle(); expect(find.byType(TestErrorScreen), findsOneWidget); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); }); @@ -2153,18 +1857,17 @@ void main() { final routes = [ GoRoute( path: '/home', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'family', - builder: (BuildContext context, GoRouterState state) => - const FamilyScreen('dummy'), + builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: [ GoRoute( path: 'person', - builder: (BuildContext context, GoRouterState state) => - const PersonScreen('dummy', 'dummy'), + builder: + (BuildContext context, GoRouterState state) => + const PersonScreen('dummy', 'dummy'), ), ], ), @@ -2176,22 +1879,18 @@ void main() { routes, tester, initialLocation: '/home', - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); router.go('person'); await tester.pumpAndSettle(); expect(find.byType(TestErrorScreen), findsOneWidget); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); }); - testWidgets('preserve path param spaces and slashes', ( - WidgetTester tester, - ) async { + testWidgets('preserve path param spaces and slashes', (WidgetTester tester) async { const param1 = 'param w/ spaces and slashes'; final routes = [ GoRoute( @@ -2209,11 +1908,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/home', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/home'); final loc = 'page1/${Uri.encodeComponent(param1)}'; router.go('./$loc'); @@ -2224,9 +1919,7 @@ void main() { expect(matches.pathParameters['param1'], param1); }); - testWidgets('preserve query param spaces and slashes', ( - WidgetTester tester, - ) async { + testWidgets('preserve query param spaces and slashes', (WidgetTester tester) async { const param1 = 'param w/ spaces and slashes'; final routes = [ GoRoute( @@ -2244,16 +1937,10 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/home', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/home'); - final loc = Uri( - path: 'page1', - queryParameters: {'param1': param1}, - ).toString(); + final loc = + Uri(path: 'page1', queryParameters: {'param1': param1}).toString(); router.go('./$loc'); await tester.pumpAndSettle(); @@ -2269,18 +1956,15 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -2296,10 +1980,7 @@ void main() { }, ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/login', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login'); expect(redirected, isTrue); redirected = false; @@ -2307,10 +1988,7 @@ void main() { await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/login', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login'); expect(redirected, isTrue); }); @@ -2321,18 +1999,16 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), GoRoute( path: '/trigger-error', - builder: (BuildContext context, GoRouterState state) => - const Text('should not reach here'), + builder: + (BuildContext context, GoRouterState state) => const Text('should not reach here'), ), ]; @@ -2345,10 +2021,9 @@ void main() { } return null; }, - onException: - (BuildContext context, GoRouterState state, GoRouter router) { - exceptionCaught = true; - }, + onException: (BuildContext context, GoRouterState state, GoRouter router) { + exceptionCaught = true; + }, ); expect(find.byType(HomeScreen), findsOneWidget); @@ -2365,22 +2040,18 @@ void main() { expect(find.text('should not reach here'), findsNothing); }); - testWidgets('context extension methods work in redirects', ( - WidgetTester tester, - ) async { + testWidgets('context extension methods work in redirects', (WidgetTester tester) async { String? capturedNamedLocation; final routes = [ GoRoute( path: '/', name: 'home', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', name: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; @@ -2396,21 +2067,17 @@ void main() { expect(capturedNamedLocation, '/login'); }); - testWidgets('redirect can redirect to same path', ( - WidgetTester tester, - ) async { + testWidgets('redirect can redirect to same path', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', // Return same location. redirect: (_, GoRouterState state) => state.uri.toString(), - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), @@ -2429,33 +2096,25 @@ void main() { // Directly set the url through platform message. await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/dummy', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); }); - testWidgets('top-level redirect w/ named routes', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect w/ named routes', (WidgetTester tester) async { final routes = [ GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'dummy', path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( name: 'login', path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -2464,34 +2123,27 @@ void main() { final GoRouter router = await createRouter( routes, tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/login' - ? null - : state.namedLocation('login'), - ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/login', + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/login' ? null : state.namedLocation('login'), ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login'); }); testWidgets('route-level redirect', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/login', ), GoRoute( path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -2500,25 +2152,18 @@ void main() { final GoRouter router = await createRouter(routes, tester); router.go('/dummy'); await tester.pump(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/login', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login'); }); - testWidgets('top-level redirect take priority over route level', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect take priority over route level', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) { // should never be reached. assert(false); @@ -2527,13 +2172,11 @@ void main() { ), GoRoute( path: 'dummy2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -2552,36 +2195,27 @@ void main() { await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/login', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login'); expect(redirected, isTrue); }); - testWidgets('route-level redirect w/ named routes', ( - WidgetTester tester, - ) async { + testWidgets('route-level redirect w/ named routes', (WidgetTester tester) async { final routes = [ GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'dummy', path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - redirect: (BuildContext context, GoRouterState state) => - state.namedLocation('login'), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), + redirect: (BuildContext context, GoRouterState state) => state.namedLocation('login'), ), GoRoute( name: 'login', path: 'login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), @@ -2590,28 +2224,22 @@ void main() { final GoRouter router = await createRouter(routes, tester); router.go('/dummy'); await tester.pump(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/login', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login'); }); testWidgets('multiple mixed redirect', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy1', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: 'dummy2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/', ), ], @@ -2621,8 +2249,9 @@ void main() { final GoRouter router = await createRouter( routes, tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/dummy1' ? '/dummy2' : null, + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/dummy1' ? '/dummy2' : null, ); router.go('/dummy1'); await tester.pump(); @@ -2633,22 +2262,19 @@ void main() { final GoRouter router = await createRouter( [], tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' - ? '/login' - : state.matchedLocation == '/login' - ? '/' - : null, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' + ? '/login' + : state.matchedLocation == '/login' + ? '/' + : null, + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); @@ -2667,17 +2293,13 @@ void main() { ), ], tester, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); @@ -2691,56 +2313,45 @@ void main() { ), ], tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' ? '/login' : null, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' ? '/login' : null, + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); - testWidgets('top-level redirect loop w/ query params', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect loop w/ query params', (WidgetTester tester) async { final GoRouter router = await createRouter( [], tester, - redirect: (BuildContext context, GoRouterState state) => - state.matchedLocation == '/' - ? '/login?from=${state.uri}' - : state.matchedLocation == '/login' - ? '/' - : null, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: + (BuildContext context, GoRouterState state) => + state.matchedLocation == '/' + ? '/login?from=${state.uri}' + : state.matchedLocation == '/login' + ? '/' + : null, + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); - testWidgets('expect null path/fullPath on top-level redirect', ( - WidgetTester tester, - ) async { + testWidgets('expect null path/fullPath on top-level redirect', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/dummy', @@ -2749,11 +2360,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/dummy', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/dummy'); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); }); @@ -2761,13 +2368,11 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; @@ -2787,25 +2392,20 @@ void main() { }, ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('top-level redirect state contains path parameters', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect state contains path parameters', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), routes: [ GoRoute( path: ':id', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), @@ -2824,8 +2424,7 @@ void main() { }, ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(2)); }); @@ -2847,21 +2446,14 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: loc, - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: loc); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(find.byType(HomeScreen), findsOneWidget); }); - testWidgets('sub-sub-route-level redirect params', ( - WidgetTester tester, - ) async { + testWidgets('sub-sub-route-level redirect params', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', @@ -2869,8 +2461,7 @@ void main() { routes: [ GoRoute( path: 'family/:fid', - builder: (BuildContext c, GoRouterState s) => - FamilyScreen(s.pathParameters['fid']!), + builder: (BuildContext c, GoRouterState s) => FamilyScreen(s.pathParameters['fid']!), routes: [ GoRoute( path: 'person/:pid', @@ -2879,10 +2470,9 @@ void main() { expect(s.pathParameters['pid'], 'p1'); return null; }, - builder: (BuildContext c, GoRouterState s) => PersonScreen( - s.pathParameters['fid']!, - s.pathParameters['pid']!, - ), + builder: + (BuildContext c, GoRouterState s) => + PersonScreen(s.pathParameters['fid']!, s.pathParameters['pid']!), ), ], ), @@ -2896,14 +2486,11 @@ void main() { initialLocation: '/family/f2/person/p1', ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches.length, 3); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); expect(find.byType(FamilyScreen, skipOffstage: false), findsOneWidget); - final PersonScreen page = tester.widget( - find.byType(PersonScreen), - ); + final PersonScreen page = tester.widget(find.byType(PersonScreen)); expect(page.fid, 'f2'); expect(page.pid, 'p1'); }); @@ -2912,20 +2499,15 @@ void main() { final GoRouter router = await createRouter( [], tester, - redirect: (BuildContext context, GoRouterState state) => - '/${state.uri}+', - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + redirect: (BuildContext context, GoRouterState state) => '/${state.uri}+', + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), redirectLimit: 10, ); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); @@ -2976,8 +2558,7 @@ void main() { GoRoute( name: 'home', path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( name: 'login', @@ -3022,19 +2603,16 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/other', routes: [ GoRoute( path: 'dummy2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) { assert(false); return '/other2'; @@ -3044,13 +2622,11 @@ void main() { ), GoRoute( path: 'other', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: 'other2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), @@ -3062,37 +2638,30 @@ void main() { await sendPlatformUrl('/dummy/dummy2', tester); await tester.pumpAndSettle(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/other', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/other'); }); - testWidgets('redirect when go to a shell route', ( - WidgetTester tester, - ) async { + testWidgets('redirect when go to a shell route', (WidgetTester tester) async { final routes = [ ShellRoute( redirect: (BuildContext context, GoRouterState state) => '/dummy', - builder: (BuildContext context, GoRouterState state, Widget child) => - Scaffold(appBar: AppBar(), body: child), + builder: + (BuildContext context, GoRouterState state, Widget child) => + Scaffold(appBar: AppBar(), body: child), routes: [ GoRoute( path: '/other', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/other2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), GoRoute( path: '/dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ]; @@ -3101,34 +2670,27 @@ void main() { for (final shellRoute in ['/other', '/other2']) { router.go(shellRoute); await tester.pump(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/dummy', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); } }); - testWidgets('redirect when go to a stateful shell route', ( - WidgetTester tester, - ) async { + testWidgets('redirect when go to a stateful shell route', (WidgetTester tester) async { final routes = [ StatefulShellRoute.indexedStack( redirect: (BuildContext context, GoRouterState state) => '/dummy', - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/other', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), @@ -3136,8 +2698,7 @@ void main() { routes: [ GoRoute( path: '/other2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), @@ -3145,8 +2706,7 @@ void main() { ), GoRoute( path: '/dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ]; @@ -3155,10 +2715,7 @@ void main() { for (final shellRoute in ['/other', '/other2']) { router.go(shellRoute); await tester.pump(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/dummy', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); } }); }); @@ -3168,35 +2725,25 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/dummy', - ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/dummy', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/dummy'); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); }); testWidgets('initial location with extra', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'dummy', @@ -3214,10 +2761,7 @@ void main() { initialLocation: '/dummy', initialExtra: 'extra', ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/dummy', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); expect(find.byKey(const ValueKey('extra')), findsOneWidget); }); @@ -3225,8 +2769,7 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/dummy', @@ -3235,44 +2778,32 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/dummy', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/dummy'); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); }); - testWidgets( - 'does not take precedence over platformDispatcher.defaultRouteName', - (WidgetTester tester) async { - TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = - '/dummy'; + testWidgets('does not take precedence over platformDispatcher.defaultRouteName', ( + WidgetTester tester, + ) async { + TestWidgetsFlutterBinding.instance.platformDispatcher.defaultRouteNameTestValue = '/dummy'; - final routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - routes: [ - GoRoute( - path: 'dummy', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - ), - ], - ), - ]; + final routes = [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), + routes: [ + GoRoute( + path: 'dummy', + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), + ), + ], + ), + ]; - final GoRouter router = await createRouter(routes, tester); - expect(router.routeInformationProvider.value.uri.path, '/dummy'); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }, - ); + final GoRouter router = await createRouter(routes, tester); + expect(router.routeInformationProvider.value.uri.path, '/dummy'); + TestWidgetsFlutterBinding.instance.platformDispatcher.clearDefaultRouteNameTestValue(); + }); test('throws assertion if initialExtra is set w/o initialLocation', () { expect( @@ -3292,61 +2823,36 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), ]; - testWidgets( - 'When platformDispatcher.defaultRouteName is deep-link Uri with ' - 'scheme, authority, no path', - (WidgetTester tester) async { - TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = - 'https://domain.com'; - final GoRouter router = await createRouter(routes, tester); - expect(router.routeInformationProvider.value.uri.path, '/'); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }, - ); + testWidgets('When platformDispatcher.defaultRouteName is deep-link Uri with ' + 'scheme, authority, no path', (WidgetTester tester) async { + TestWidgetsFlutterBinding.instance.platformDispatcher.defaultRouteNameTestValue = + 'https://domain.com'; + final GoRouter router = await createRouter(routes, tester); + expect(router.routeInformationProvider.value.uri.path, '/'); + TestWidgetsFlutterBinding.instance.platformDispatcher.clearDefaultRouteNameTestValue(); + }); - testWidgets( - 'When platformDispatcher.defaultRouteName is deep-link Uri with ' - 'scheme, authority, no path, but trailing slash', - (WidgetTester tester) async { - TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = - 'https://domain.com/'; - final GoRouter router = await createRouter(routes, tester); - expect(router.routeInformationProvider.value.uri.path, '/'); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }, - ); + testWidgets('When platformDispatcher.defaultRouteName is deep-link Uri with ' + 'scheme, authority, no path, but trailing slash', (WidgetTester tester) async { + TestWidgetsFlutterBinding.instance.platformDispatcher.defaultRouteNameTestValue = + 'https://domain.com/'; + final GoRouter router = await createRouter(routes, tester); + expect(router.routeInformationProvider.value.uri.path, '/'); + TestWidgetsFlutterBinding.instance.platformDispatcher.clearDefaultRouteNameTestValue(); + }); - testWidgets( - 'When platformDispatcher.defaultRouteName is deep-link Uri with ' - 'scheme, authority, no path, and query parameters', - (WidgetTester tester) async { - TestWidgetsFlutterBinding - .instance - .platformDispatcher - .defaultRouteNameTestValue = - 'https://domain.com?param=1'; - final GoRouter router = await createRouter(routes, tester); - expect( - router.routeInformationProvider.value.uri.toString(), - 'https://domain.com/?param=1', - ); - TestWidgetsFlutterBinding.instance.platformDispatcher - .clearDefaultRouteNameTestValue(); - }, - ); + testWidgets('When platformDispatcher.defaultRouteName is deep-link Uri with ' + 'scheme, authority, no path, and query parameters', (WidgetTester tester) async { + TestWidgetsFlutterBinding.instance.platformDispatcher.defaultRouteNameTestValue = + 'https://domain.com?param=1'; + final GoRouter router = await createRouter(routes, tester); + expect(router.routeInformationProvider.value.uri.toString(), 'https://domain.com/?param=1'); + TestWidgetsFlutterBinding.instance.platformDispatcher.clearDefaultRouteNameTestValue(); + }); }); group('params', () { @@ -3354,13 +2860,13 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family/:fid', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), ), ]; @@ -3369,8 +2875,7 @@ void main() { final loc = '/family/$fid'; router.go(loc); await tester.pumpAndSettle(); - final RouteMatchList matches = - router.routerDelegate.currentConfiguration; + final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(router.routerDelegate.currentConfiguration.uri.toString(), loc); expect(matches.matches, hasLength(1)); @@ -3383,13 +2888,13 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.uri.queryParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.uri.queryParameters['fid']!), ), ]; @@ -3398,8 +2903,7 @@ void main() { final loc = '/family?fid=$fid'; router.go(loc); await tester.pumpAndSettle(); - final RouteMatchList matches = - router.routerDelegate.currentConfiguration; + final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(router.routerDelegate.currentConfiguration.uri.toString(), loc); expect(matches.matches, hasLength(1)); @@ -3408,9 +2912,7 @@ void main() { } }); - testWidgets('preserve path param spaces and slashes', ( - WidgetTester tester, - ) async { + testWidgets('preserve path param spaces and slashes', (WidgetTester tester) async { const param1 = 'param w/ spaces and slashes'; final routes = [ GoRoute( @@ -3432,9 +2934,7 @@ void main() { expect(matches.pathParameters['param1'], param1); }); - testWidgets('preserve query param spaces and slashes', ( - WidgetTester tester, - ) async { + testWidgets('preserve query param spaces and slashes', (WidgetTester tester) async { const param1 = 'param w/ spaces and slashes'; final routes = [ GoRoute( @@ -3458,8 +2958,7 @@ void main() { router.go(loc); await tester.pumpAndSettle(); - final RouteMatchList matches2 = - router.routerDelegate.currentConfiguration; + final RouteMatchList matches2 = router.routerDelegate.currentConfiguration; expect(find.byType(DummyScreen), findsOneWidget); expect(matches2.uri.queryParameters['param1'], param1); }); @@ -3467,11 +2966,9 @@ void main() { test('error: duplicate path param', () { try { GoRouter( - routes: [ - GoRoute(path: '/:id/:blah/:bam/:id/:blah', builder: dummy), - ], - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + routes: [GoRoute(path: '/:id/:blah/:bam/:id/:blah', builder: dummy)], + errorBuilder: + (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), initialLocation: '/0/1/2/0/1', ); expect(false, true); @@ -3528,15 +3025,17 @@ void main() { GoRoute(path: '/', builder: dummy), GoRoute( path: '/family', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.uri.queryParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.uri.queryParameters['fid']!), ), GoRoute( path: '/person', - builder: (BuildContext context, GoRouterState state) => PersonScreen( - state.uri.queryParameters['fid']!, - state.uri.queryParameters['pid']!, - ), + builder: + (BuildContext context, GoRouterState state) => PersonScreen( + state.uri.queryParameters['fid']!, + state.uri.queryParameters['pid']!, + ), ), ], tester); @@ -3549,9 +3048,7 @@ void main() { ); expect(page1.fid, 'f2'); - final PersonScreen page2 = tester.widget( - find.byType(PersonScreen), - ); + final PersonScreen page2 = tester.widget(find.byType(PersonScreen)); expect(page2.fid, 'f2'); expect(page2.pid, 'p1'); }); @@ -3561,15 +3058,17 @@ void main() { GoRoute(path: '/', builder: dummy), GoRoute( path: '/family', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen((state.extra! as Map)['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen((state.extra! as Map)['fid']!), ), GoRoute( path: '/person', - builder: (BuildContext context, GoRouterState state) => PersonScreen( - (state.extra! as Map)['fid']!, - (state.extra! as Map)['pid']!, - ), + builder: + (BuildContext context, GoRouterState state) => PersonScreen( + (state.extra! as Map)['fid']!, + (state.extra! as Map)['pid']!, + ), ), ], tester); @@ -3582,9 +3081,7 @@ void main() { ); expect(page1.fid, 'f2'); - final PersonScreen page2 = tester.widget( - find.byType(PersonScreen), - ); + final PersonScreen page2 = tester.widget(find.byType(PersonScreen)); expect(page2.fid, 'f2'); expect(page2.pid, 'p1'); }); @@ -3593,13 +3090,13 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family/:fid', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), routes: [ GoRoute( path: 'person/:pid', @@ -3637,22 +3134,20 @@ void main() { StatefulNavigationShell? routeState; final routes = [ StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), @@ -3660,13 +3155,13 @@ void main() { routes: [ GoRoute( path: '/family', - builder: (BuildContext context, GoRouterState state) => - const Text('Families'), + builder: (BuildContext context, GoRouterState state) => const Text('Families'), routes: [ GoRoute( path: ':fid', - builder: (BuildContext context, GoRouterState state) => - FamilyScreen(state.pathParameters['fid']!), + builder: + (BuildContext context, GoRouterState state) => + FamilyScreen(state.pathParameters['fid']!), routes: [ GoRoute( path: 'person/:pid', @@ -3687,11 +3182,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); const fid = 'f1'; const pid = 'p2'; const loc = '/family/$fid/person/$pid'; @@ -3729,22 +3220,20 @@ void main() { Object? latestExtra; final routes = [ StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), @@ -3764,12 +3253,7 @@ void main() { ]; final expectedExtra = Object(); - await createRouter( - routes, - tester, - initialLocation: '/b', - initialExtra: expectedExtra, - ); + await createRouter(routes, tester, initialLocation: '/b', initialExtra: expectedExtra); expect(latestExtra, expectedExtra); routeState!.goBranch(0); await tester.pumpAndSettle(); @@ -3794,8 +3278,7 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'page', @@ -3803,9 +3286,7 @@ void main() { builder: (BuildContext context, GoRouterState state) { expect(state.uri.queryParametersAll, queryParametersAll); expectLocationWithQueryParams(state.uri.toString()); - return DummyScreen( - queryParametersAll: state.uri.queryParametersAll, - ); + return DummyScreen(queryParametersAll: state.uri.queryParametersAll); }, ), ]; @@ -3820,13 +3301,10 @@ void main() { }, ); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); - expectLocationWithQueryParams( - router.routerDelegate.currentConfiguration.uri.toString(), - ); + expectLocationWithQueryParams(router.routerDelegate.currentConfiguration.uri.toString()); expect( tester.widget(find.byType(DummyScreen)), isA().having( @@ -3854,8 +3332,7 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'page', @@ -3872,13 +3349,10 @@ void main() { router.go('/page?q1=v1&q2=v2&q2=v3'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); - expectLocationWithQueryParams( - router.routerDelegate.currentConfiguration.uri.toString(), - ); + expectLocationWithQueryParams(router.routerDelegate.currentConfiguration.uri.toString()); expect( tester.widget(find.byType(DummyScreen)), isA().having( @@ -3889,9 +3363,7 @@ void main() { ); }); - testWidgets('goRouter should rebuild widget if ', ( - WidgetTester tester, - ) async { + testWidgets('goRouter should rebuild widget if ', (WidgetTester tester) async { const Map queryParametersAll = >{ 'q1': ['v1'], 'q2': ['v2', 'v3'], @@ -3905,8 +3377,7 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'page', @@ -3923,13 +3394,10 @@ void main() { router.go('/page?q1=v1&q2=v2&q2=v3'); await tester.pumpAndSettle(); - final List matches = - router.routerDelegate.currentConfiguration.matches; + final List matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); - expectLocationWithQueryParams( - router.routerDelegate.currentConfiguration.uri.toString(), - ); + expectLocationWithQueryParams(router.routerDelegate.currentConfiguration.uri.toString()); expect( tester.widget(find.byType(DummyScreen)), isA().having( @@ -3946,14 +3414,12 @@ void main() { GoRoute( path: '/', name: 'home', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: key), + builder: (BuildContext context, GoRouterState state) => DummyStatefulWidget(key: key), ), GoRoute( path: '/page1', name: 'page1', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), ]; @@ -3963,19 +3429,11 @@ void main() { const location = '/page1'; const extra = 'Hello'; - testWidgets('calls [namedLocation] on closest GoRouter', ( - WidgetTester tester, - ) async { + testWidgets('calls [namedLocation] on closest GoRouter', (WidgetTester tester) async { final router = GoRouterNamedLocationSpy(routes: routes); addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); - key.currentContext!.namedLocation( - name, - pathParameters: params, - queryParameters: queryParams, - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); + key.currentContext!.namedLocation(name, pathParameters: params, queryParameters: queryParams); expect(router.name, name); expect(router.pathParameters, params); expect(router.queryParameters, queryParams); @@ -3984,22 +3442,16 @@ void main() { testWidgets('calls [go] on closest GoRouter', (WidgetTester tester) async { final router = GoRouterGoSpy(routes: routes); addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); key.currentContext!.go(location, extra: extra); expect(router.myLocation, location); expect(router.extra, extra); }); - testWidgets('calls [goNamed] on closest GoRouter', ( - WidgetTester tester, - ) async { + testWidgets('calls [goNamed] on closest GoRouter', (WidgetTester tester) async { final router = GoRouterGoNamedSpy(routes: routes); addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); key.currentContext!.goNamed( name, pathParameters: params, @@ -4012,14 +3464,10 @@ void main() { expect(router.extra, extra); }); - testWidgets('calls [push] on closest GoRouter', ( - WidgetTester tester, - ) async { + testWidgets('calls [push] on closest GoRouter', (WidgetTester tester) async { final router = GoRouterPushSpy(routes: routes); addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); key.currentContext!.push(location, extra: extra); expect(router.myLocation, location); expect(router.extra, extra); @@ -4044,14 +3492,10 @@ void main() { expect(router.extra, extra); }); - testWidgets('calls [pushNamed] on closest GoRouter', ( - WidgetTester tester, - ) async { + testWidgets('calls [pushNamed] on closest GoRouter', (WidgetTester tester) async { final router = GoRouterPushNamedSpy(routes: routes); addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); key.currentContext!.pushNamed( name, pathParameters: params, @@ -4093,22 +3537,16 @@ void main() { testWidgets('calls [pop] on closest GoRouter', (WidgetTester tester) async { final router = GoRouterPopSpy(routes: routes); addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); key.currentContext!.pop(); expect(router.popped, true); expect(router.poppedResult, null); }); - testWidgets('calls [pop] on closest GoRouter with result', ( - WidgetTester tester, - ) async { + testWidgets('calls [pop] on closest GoRouter with result', (WidgetTester tester) async { final router = GoRouterPopSpy(routes: routes); addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Example'), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Example')); key.currentContext!.pop('result'); expect(router.popped, true); expect(router.poppedResult, 'result'); @@ -4186,53 +3624,47 @@ void main() { expect(result, isTrue); }); - testWidgets( - 'Pops from the correct Navigator when the Android back button is pressed', - (WidgetTester tester) async { - final routes = [ - ShellRoute( - builder: (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - body: Column( - children: [ - const Text('Screen A'), - Expanded(child: child), - ], + testWidgets('Pops from the correct Navigator when the Android back button is pressed', ( + WidgetTester tester, + ) async { + final routes = [ + ShellRoute( + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Column(children: [const Text('Screen A'), Expanded(child: child)]), + ); + }, + routes: [ + GoRoute( + path: '/b', + builder: (BuildContext context, GoRouterState state) { + return const Scaffold(body: Text('Screen B')); + }, + routes: [ + GoRoute( + path: 'c', + builder: (BuildContext context, GoRouterState state) { + return const Scaffold(body: Text('Screen C')); + }, ), - ); - }, - routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) { - return const Scaffold(body: Text('Screen B')); - }, - routes: [ - GoRoute( - path: 'c', - builder: (BuildContext context, GoRouterState state) { - return const Scaffold(body: Text('Screen C')); - }, - ), - ], - ), - ], - ), - ]; + ], + ), + ], + ), + ]; - await createRouter(routes, tester, initialLocation: '/b/c'); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsOneWidget); + await createRouter(routes, tester, initialLocation: '/b/c'); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsOneWidget); - await simulateAndroidBackButton(tester); - await tester.pumpAndSettle(); + await simulateAndroidBackButton(tester); + await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen B'), findsOneWidget); - expect(find.text('Screen C'), findsNothing); - }, - ); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen B'), findsOneWidget); + expect(find.text('Screen C'), findsNothing); + }); testWidgets('Pops from the correct navigator when a sub-route is placed on ' 'the root Navigator', (WidgetTester tester) async { @@ -4244,12 +3676,7 @@ void main() { navigatorKey: shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( - body: Column( - children: [ - const Text('Screen A'), - Expanded(child: child), - ], - ), + body: Column(children: [const Text('Screen A'), Expanded(child: child)]), ); }, routes: [ @@ -4272,12 +3699,7 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/b/c', - navigatorKey: rootNavigatorKey, - ); + await createRouter(routes, tester, initialLocation: '/b/c', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsOneWidget); @@ -4306,8 +3728,7 @@ void main() { routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), @@ -4315,8 +3736,7 @@ void main() { routes: [ GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ], ), @@ -4339,16 +3759,13 @@ void main() { expect(find.text('Screen B'), findsOneWidget); }); - testWidgets('Builds StatefulShellRoute as a sub-route', ( - WidgetTester tester, - ) async { + testWidgets('Builds StatefulShellRoute as a sub-route', (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(); final routes = [ GoRoute( path: '/root', - builder: (BuildContext context, GoRouterState state) => - const Text('Root'), + builder: (BuildContext context, GoRouterState state) => const Text('Root'), routes: [ StatefulShellRoute.indexedStack( builder: @@ -4362,8 +3779,8 @@ void main() { routes: [ GoRoute( path: 'a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: + (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), @@ -4371,8 +3788,8 @@ void main() { routes: [ GoRoute( path: 'b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: + (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ], ), @@ -4397,298 +3814,271 @@ void main() { expect(find.text('Screen B'), findsOneWidget); }); - testWidgets( - 'Navigation with goBranch is correctly handled in StatefulShellRoute', - (WidgetTester tester) async { - final rootNavigatorKey = GlobalKey(); - final statefulWidgetKey = GlobalKey(); - StatefulNavigationShell? routeState; - - final routes = [ - StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), - ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: '/c', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen C'), - ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: '/d', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen D'), - ), - ], - ), - ], - ), - ]; - - await createRouter( - routes, - tester, - initialLocation: '/a', - navigatorKey: rootNavigatorKey, - ); - statefulWidgetKey.currentState?.increment(); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsNothing); - expect(find.text('Screen D'), findsNothing); - - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B'), findsOneWidget); - expect(find.text('Screen C'), findsNothing); - expect(find.text('Screen D'), findsNothing); - - routeState!.goBranch(2); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsOneWidget); - expect(find.text('Screen D'), findsNothing); - - routeState!.goBranch(3); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen C'), findsNothing); - expect(find.text('Screen D'), findsOneWidget); - - expect(() { - // Verify that navigation to unknown index fails - routeState!.goBranch(4); - }, throwsA(isA())); - }, - ); - - testWidgets( - 'Navigates to correct nested navigation tree in StatefulShellRoute ' - 'and maintains state', - (WidgetTester tester) async { - final rootNavigatorKey = GlobalKey(); - final statefulWidgetKey = GlobalKey(); - StatefulNavigationShell? routeState; - - final routes = [ - StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), - routes: [ - GoRoute( - path: 'detailA', - builder: (BuildContext context, GoRouterState state) => - Column( - children: [ - const Text('Screen A Detail'), - DummyStatefulWidget(key: statefulWidgetKey), - ], - ), - ), - ], - ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - ), - ], - ), - ], - ), - ]; - - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a/detailA', - navigatorKey: rootNavigatorKey, - ); - statefulWidgetKey.currentState?.increment(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsOneWidget); - - routeState!.goBranch(0); - await tester.pumpAndSettle(); - expect(statefulWidgetKey.currentState?.counter, equals(1)); - - router.go('/a'); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen A Detail'), findsNothing); - router.go('/a/detailA'); - await tester.pumpAndSettle(); - expect(statefulWidgetKey.currentState?.counter, equals(0)); - }, - ); - - testWidgets( - 'Navigates to correct nested navigation tree in StatefulShellRoute ' - 'and maintains path parameters', - (WidgetTester tester) async { - StatefulNavigationShell? routeState; - - final routes = [ - GoRoute( - path: '/:id', - builder: (_, __) => const Placeholder(), - routes: [ - StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: 'a', - builder: (BuildContext context, GoRouterState state) => - Text('a id is ${state.pathParameters['id']}'), - ), - ], - ), - StatefulShellBranch( - routes: [ - GoRoute( - path: 'b', - builder: (BuildContext context, GoRouterState state) => - Text('b id is ${state.pathParameters['id']}'), - ), - ], - ), - ], - ), - ], - ), - ]; - - await createRouter(routes, tester, initialLocation: '/123/a'); - expect(find.text('a id is 123'), findsOneWidget); - - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('b id is 123'), findsOneWidget); - }, - ); - - testWidgets('Maintains state for nested StatefulShellRoute', ( + testWidgets('Navigation with goBranch is correctly handled in StatefulShellRoute', ( WidgetTester tester, ) async { final rootNavigatorKey = GlobalKey(); final statefulWidgetKey = GlobalKey(); - StatefulNavigationShell? routeState1; - StatefulNavigationShell? routeState2; + StatefulNavigationShell? routeState; final routes = [ StatefulShellRoute.indexedStack( - builder: - ( + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/c', + builder: (BuildContext context, GoRouterState state) => const Text('Screen C'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/d', + builder: (BuildContext context, GoRouterState state) => const Text('Screen D'), + ), + ], + ), + ], + ), + ]; + + await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); + statefulWidgetKey.currentState?.increment(); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsNothing); + expect(find.text('Screen D'), findsNothing); + + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B'), findsOneWidget); + expect(find.text('Screen C'), findsNothing); + expect(find.text('Screen D'), findsNothing); + + routeState!.goBranch(2); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsOneWidget); + expect(find.text('Screen D'), findsNothing); + + routeState!.goBranch(3); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen C'), findsNothing); + expect(find.text('Screen D'), findsOneWidget); + + expect(() { + // Verify that navigation to unknown index fails + routeState!.goBranch(4); + }, throwsA(isA())); + }); + + testWidgets('Navigates to correct nested navigation tree in StatefulShellRoute ' + 'and maintains state', (WidgetTester tester) async { + final rootNavigatorKey = GlobalKey(); + final statefulWidgetKey = GlobalKey(); + StatefulNavigationShell? routeState; + + final routes = [ + StatefulShellRoute.indexedStack( + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), + routes: [ + GoRoute( + path: 'detailA', + builder: + (BuildContext context, GoRouterState state) => Column( + children: [ + const Text('Screen A Detail'), + DummyStatefulWidget(key: statefulWidgetKey), + ], + ), + ), + ], + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b', + builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), + ), + ], + ), + ], + ), + ]; + + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a/detailA', + navigatorKey: rootNavigatorKey, + ); + statefulWidgetKey.currentState?.increment(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsOneWidget); + + routeState!.goBranch(0); + await tester.pumpAndSettle(); + expect(statefulWidgetKey.currentState?.counter, equals(1)); + + router.go('/a'); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen A Detail'), findsNothing); + router.go('/a/detailA'); + await tester.pumpAndSettle(); + expect(statefulWidgetKey.currentState?.counter, equals(0)); + }); + + testWidgets('Navigates to correct nested navigation tree in StatefulShellRoute ' + 'and maintains path parameters', (WidgetTester tester) async { + StatefulNavigationShell? routeState; + + final routes = [ + GoRoute( + path: '/:id', + builder: (_, __) => const Placeholder(), + routes: [ + StatefulShellRoute.indexedStack( + builder: ( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) { - routeState1 = navigationShell; + routeState = navigationShell; return navigationShell; }, + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: 'a', + builder: + (BuildContext context, GoRouterState state) => + Text('a id is ${state.pathParameters['id']}'), + ), + ], + ), + StatefulShellBranch( + routes: [ + GoRoute( + path: 'b', + builder: + (BuildContext context, GoRouterState state) => + Text('b id is ${state.pathParameters['id']}'), + ), + ], + ), + ], + ), + ], + ), + ]; + + await createRouter(routes, tester, initialLocation: '/123/a'); + expect(find.text('a id is 123'), findsOneWidget); + + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('b id is 123'), findsOneWidget); + }); + + testWidgets('Maintains state for nested StatefulShellRoute', (WidgetTester tester) async { + final rootNavigatorKey = GlobalKey(); + final statefulWidgetKey = GlobalKey(); + StatefulNavigationShell? routeState1; + StatefulNavigationShell? routeState2; + + final routes = [ + StatefulShellRoute.indexedStack( + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState1 = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState2 = navigationShell; - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState2 = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', builder: - (BuildContext context, GoRouterState state) => - const Text('Screen A'), + (BuildContext context, GoRouterState state) => const Text('Screen A'), routes: [ GoRoute( path: 'detailA', builder: - (BuildContext context, GoRouterState state) => - Column( - children: [ - const Text('Screen A Detail'), - DummyStatefulWidget( - key: statefulWidgetKey, - ), - ], - ), + (BuildContext context, GoRouterState state) => Column( + children: [ + const Text('Screen A Detail'), + DummyStatefulWidget(key: statefulWidgetKey), + ], + ), ), ], ), @@ -4699,8 +4089,7 @@ void main() { GoRoute( path: '/b', builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B'), + (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ], ), @@ -4709,8 +4098,7 @@ void main() { GoRoute( path: '/c', builder: - (BuildContext context, GoRouterState state) => - const Text('Screen C'), + (BuildContext context, GoRouterState state) => const Text('Screen C'), ), ], ), @@ -4722,8 +4110,7 @@ void main() { routes: [ GoRoute( path: '/d', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen D'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen D'), ), ], ), @@ -4761,103 +4148,99 @@ void main() { expect(statefulWidgetKey.currentState?.counter, equals(1)); }); - testWidgets( - 'Pops from the correct Navigator in a StatefulShellRoute when the ' - 'Android back button is pressed', - (WidgetTester tester) async { - final rootNavigatorKey = GlobalKey(); - final sectionANavigatorKey = GlobalKey(); - final sectionBNavigatorKey = GlobalKey(); - StatefulNavigationShell? routeState; + testWidgets('Pops from the correct Navigator in a StatefulShellRoute when the ' + 'Android back button is pressed', (WidgetTester tester) async { + final rootNavigatorKey = GlobalKey(); + final sectionANavigatorKey = GlobalKey(); + final sectionBNavigatorKey = GlobalKey(); + StatefulNavigationShell? routeState; - final routes = [ - StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - StatefulShellBranch( - navigatorKey: sectionANavigatorKey, - routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), - routes: [ - GoRoute( - path: 'detailA', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A Detail'), - ), - ], - ), - ], - ), - StatefulShellBranch( - navigatorKey: sectionBNavigatorKey, - routes: [ - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), - routes: [ - GoRoute( - path: 'detailB', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B Detail'), - ), - ], - ), - ], - ), - ], - ), - ]; + final routes = [ + StatefulShellRoute.indexedStack( + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, + branches: [ + StatefulShellBranch( + navigatorKey: sectionANavigatorKey, + routes: [ + GoRoute( + path: '/a', + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), + routes: [ + GoRoute( + path: 'detailA', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen A Detail'), + ), + ], + ), + ], + ), + StatefulShellBranch( + navigatorKey: sectionBNavigatorKey, + routes: [ + GoRoute( + path: '/b', + builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), + routes: [ + GoRoute( + path: 'detailB', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B Detail'), + ), + ], + ), + ], + ), + ], + ), + ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a/detailA', - navigatorKey: rootNavigatorKey, - ); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Detail'), findsNothing); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a/detailA', + navigatorKey: rootNavigatorKey, + ); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Detail'), findsNothing); - router.go('/b/detailB'); - await tester.pumpAndSettle(); + router.go('/b/detailB'); + await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Detail'), findsOneWidget); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Detail'), findsOneWidget); - await simulateAndroidBackButton(tester); - await tester.pumpAndSettle(); + await simulateAndroidBackButton(tester); + await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsOneWidget); - expect(find.text('Screen B Detail'), findsNothing); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsOneWidget); + expect(find.text('Screen B Detail'), findsNothing); - routeState!.goBranch(0); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen A Detail'), findsOneWidget); + routeState!.goBranch(0); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen A Detail'), findsOneWidget); - await simulateAndroidBackButton(tester); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen A Detail'), findsNothing); - }, - ); + await simulateAndroidBackButton(tester); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen A Detail'), findsNothing); + }); testWidgets('Maintains extra navigation information when navigating ' 'between branches in StatefulShellRoute', (WidgetTester tester) async { @@ -4866,22 +4249,20 @@ void main() { final routes = [ StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), @@ -4889,8 +4270,9 @@ void main() { routes: [ GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - Text('Screen B - ${state.extra}'), + builder: + (BuildContext context, GoRouterState state) => + Text('Screen B - ${state.extra}'), ), ], ), @@ -4923,35 +4305,30 @@ void main() { }); testWidgets('Pushed non-descendant routes are correctly restored when ' - 'navigating between branches in StatefulShellRoute', ( - WidgetTester tester, - ) async { + 'navigating between branches in StatefulShellRoute', (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(); StatefulNavigationShell? routeState; final routes = [ GoRoute( path: '/common', - builder: (BuildContext context, GoRouterState state) => - Text('Common - ${state.extra}'), + builder: (BuildContext context, GoRouterState state) => Text('Common - ${state.extra}'), ), StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), @@ -4959,8 +4336,7 @@ void main() { routes: [ GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ], ), @@ -4998,25 +4374,13 @@ void main() { expect(find.text('Screen B'), findsOneWidget); }); - testWidgets('Preloads routes correctly in a StatefulShellRoute', ( - WidgetTester tester, - ) async { + testWidgets('Preloads routes correctly in a StatefulShellRoute', (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(); - final statefulWidgetKeyA = GlobalKey( - debugLabel: 'A', - ); - final statefulWidgetKeyB = GlobalKey( - debugLabel: 'B', - ); - final statefulWidgetKeyC = GlobalKey( - debugLabel: 'C', - ); - final statefulWidgetKeyD = GlobalKey( - debugLabel: 'D', - ); - final statefulWidgetKeyE = GlobalKey( - debugLabel: 'E', - ); + final statefulWidgetKeyA = GlobalKey(debugLabel: 'A'); + final statefulWidgetKeyB = GlobalKey(debugLabel: 'B'); + final statefulWidgetKeyC = GlobalKey(debugLabel: 'C'); + final statefulWidgetKeyD = GlobalKey(debugLabel: 'D'); + final statefulWidgetKeyE = GlobalKey(debugLabel: 'E'); final routes = [ StatefulShellRoute.indexedStack( @@ -5026,8 +4390,9 @@ void main() { routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyA), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyA), ), ], ), @@ -5035,8 +4400,9 @@ void main() { routes: [ GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyB), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyB), ), ], ), @@ -5050,8 +4416,9 @@ void main() { routes: [ GoRoute( path: '/c', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyC), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyC), ), ], ), @@ -5060,8 +4427,9 @@ void main() { routes: [ GoRoute( path: '/d', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyD), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyD), ), ], ), @@ -5071,13 +4439,13 @@ void main() { routes: [ GoRoute( path: '/e', - builder: (BuildContext context, GoRouterState state) => - const Text('E'), + builder: (BuildContext context, GoRouterState state) => const Text('E'), routes: [ GoRoute( path: 'details', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyE), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyE), ), ], ), @@ -5109,18 +4477,10 @@ void main() { WidgetTester tester, ) async { final rootNavigatorKey = GlobalKey(); - final statefulWidgetKeyA = GlobalKey( - debugLabel: 'A', - ); - final statefulWidgetKeyB = GlobalKey( - debugLabel: 'B', - ); - final statefulWidgetKeyC = GlobalKey( - debugLabel: 'C', - ); - final statefulWidgetKeyD = GlobalKey( - debugLabel: 'D', - ); + final statefulWidgetKeyA = GlobalKey(debugLabel: 'A'); + final statefulWidgetKeyB = GlobalKey(debugLabel: 'B'); + final statefulWidgetKeyC = GlobalKey(debugLabel: 'C'); + final statefulWidgetKeyD = GlobalKey(debugLabel: 'D'); final routes = [ StatefulShellRoute.indexedStack( @@ -5163,8 +4523,9 @@ void main() { routes: [ GoRoute( path: '/c', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyC), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyC), ), ], ), @@ -5172,8 +4533,9 @@ void main() { routes: [ GoRoute( path: '/d', - builder: (BuildContext context, GoRouterState state) => - DummyStatefulWidget(key: statefulWidgetKeyD), + builder: + (BuildContext context, GoRouterState state) => + DummyStatefulWidget(key: statefulWidgetKeyD), ), ], ), @@ -5181,12 +4543,7 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/c', - navigatorKey: rootNavigatorKey, - ); + await createRouter(routes, tester, initialLocation: '/c', navigatorKey: rootNavigatorKey); expect(statefulWidgetKeyA.currentState?.counter, equals(0)); expect(statefulWidgetKeyB.currentState?.counter, equals(0)); expect(statefulWidgetKeyC.currentState?.counter, equals(0)); @@ -5200,22 +4557,20 @@ void main() { final routes = [ StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), @@ -5223,18 +4578,19 @@ void main() { routes: [ GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), routes: [ GoRoute( path: 'details1', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B Detail1'), + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B Detail1'), ), GoRoute( path: 'details2', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen B Detail2'), + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B Detail2'), ), ], ), @@ -5245,13 +4601,11 @@ void main() { GoRoute(path: '/c', redirect: (_, __) => '/c/main2'), GoRoute( path: '/c/main1', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen C1'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen C1'), ), GoRoute( path: '/c/main2', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen C2'), + builder: (BuildContext context, GoRouterState state) => const Text('Screen C2'), ), ], ), @@ -5265,164 +4619,160 @@ void main() { tester, initialLocation: '/a', navigatorKey: rootNavigatorKey, - redirect: (_, GoRouterState state) { - if (state.uri.toString().startsWith('/b')) { - return redirectDestinationBranchB; - } - return null; - }, + redirect: (_, GoRouterState state) { + if (state.uri.toString().startsWith('/b')) { + return redirectDestinationBranchB; + } + return null; + }, + ); + expect(find.text('Screen A'), findsOneWidget); + expect(find.text('Screen B Detail'), findsNothing); + + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B Detail1'), findsOneWidget); + + routeState!.goBranch(2); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B Detail1'), findsNothing); + expect(find.text('Screen C2'), findsOneWidget); + + redirectDestinationBranchB = '/b/details2'; + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B Detail2'), findsOneWidget); + expect(find.text('Screen C2'), findsNothing); + }); + + testWidgets('Pushed top-level route is correctly handled by StatefulShellRoute', ( + WidgetTester tester, + ) async { + final rootNavigatorKey = GlobalKey(); + final nestedNavigatorKey = GlobalKey(); + StatefulNavigationShell? routeState; + + final routes = [ + // First level shell + StatefulShellRoute.indexedStack( + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/a', + builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), + ), + ], + ), + StatefulShellBranch( + routes: [ + // Second level / nested shell + StatefulShellRoute.indexedStack( + builder: + ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) => navigationShell, + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: '/b1', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B1'), + ), + ], + ), + StatefulShellBranch( + navigatorKey: nestedNavigatorKey, + routes: [ + GoRoute( + path: '/b2', + builder: + (BuildContext context, GoRouterState state) => + const Text('Screen B2'), + ), + GoRoute( + path: '/b2-modal', + // We pass an explicit parentNavigatorKey here, to + // properly test the logic in RouteBuilder, i.e. + // routes with parentNavigatorKeys under the shell + // should not be stripped. + parentNavigatorKey: nestedNavigatorKey, + builder: + (BuildContext context, GoRouterState state) => + const Text('Nested Modal'), + ), + ], + ), + ], + ), + ], + ), + ], + ), + GoRoute( + path: '/top-modal', + parentNavigatorKey: rootNavigatorKey, + builder: (BuildContext context, GoRouterState state) => const Text('Top Modal'), + ), + ]; + + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a', + navigatorKey: rootNavigatorKey, ); expect(find.text('Screen A'), findsOneWidget); - expect(find.text('Screen B Detail'), findsNothing); routeState!.goBranch(1); await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B Detail1'), findsOneWidget); + expect(find.text('Screen B1'), findsOneWidget); - routeState!.goBranch(2); + // Navigate nested (second level) shell to second branch + router.go('/b2'); await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B Detail1'), findsNothing); - expect(find.text('Screen C2'), findsOneWidget); + expect(find.text('Screen B2'), findsOneWidget); - redirectDestinationBranchB = '/b/details2'; - routeState!.goBranch(1); + // Push route over second branch of nested (second level) shell + router.push('/b2-modal'); await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B Detail2'), findsOneWidget); - expect(find.text('Screen C2'), findsNothing); - }); - - testWidgets( - 'Pushed top-level route is correctly handled by StatefulShellRoute', - (WidgetTester tester) async { - final rootNavigatorKey = GlobalKey(); - final nestedNavigatorKey = GlobalKey(); - StatefulNavigationShell? routeState; - - final routes = [ - // First level shell - StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Text('Screen A'), - ), - ], - ), - StatefulShellBranch( - routes: [ - // Second level / nested shell - StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) => navigationShell, - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/b1', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B1'), - ), - ], - ), - StatefulShellBranch( - navigatorKey: nestedNavigatorKey, - routes: [ - GoRoute( - path: '/b2', - builder: - (BuildContext context, GoRouterState state) => - const Text('Screen B2'), - ), - GoRoute( - path: '/b2-modal', - // We pass an explicit parentNavigatorKey here, to - // properly test the logic in RouteBuilder, i.e. - // routes with parentNavigatorKeys under the shell - // should not be stripped. - parentNavigatorKey: nestedNavigatorKey, - builder: - (BuildContext context, GoRouterState state) => - const Text('Nested Modal'), - ), - ], - ), - ], - ), - ], - ), - ], - ), - GoRoute( - path: '/top-modal', - parentNavigatorKey: rootNavigatorKey, - builder: (BuildContext context, GoRouterState state) => - const Text('Top Modal'), - ), - ]; - - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - navigatorKey: rootNavigatorKey, - ); - expect(find.text('Screen A'), findsOneWidget); - - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen B1'), findsOneWidget); - - // Navigate nested (second level) shell to second branch - router.go('/b2'); - await tester.pumpAndSettle(); - expect(find.text('Screen B2'), findsOneWidget); + expect(find.text('Nested Modal'), findsOneWidget); - // Push route over second branch of nested (second level) shell - router.push('/b2-modal'); - await tester.pumpAndSettle(); - expect(find.text('Nested Modal'), findsOneWidget); - - // Push top-level route while on second branch - router.push('/top-modal'); - await tester.pumpAndSettle(); - expect(find.text('Top Modal'), findsOneWidget); + // Push top-level route while on second branch + router.push('/top-modal'); + await tester.pumpAndSettle(); + expect(find.text('Top Modal'), findsOneWidget); - // Return to shell and first branch - router.go('/a'); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsOneWidget); + // Return to shell and first branch + router.go('/a'); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsOneWidget); - // Switch to second branch, which should only contain 'Nested Modal' - // (in the nested shell) - routeState!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen A'), findsNothing); - expect(find.text('Screen B1'), findsNothing); - expect(find.text('Screen B2'), findsNothing); - expect(find.text('Top Modal'), findsNothing); - expect(find.text('Nested Modal'), findsOneWidget); - }, - ); + // Switch to second branch, which should only contain 'Nested Modal' + // (in the nested shell) + routeState!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A'), findsNothing); + expect(find.text('Screen B1'), findsNothing); + expect(find.text('Screen B2'), findsNothing); + expect(find.text('Top Modal'), findsNothing); + expect(find.text('Nested Modal'), findsOneWidget); + }); testWidgets( 'Obsolete branches in StatefulShellRoute are cleaned up after route ' @@ -5431,9 +4781,7 @@ void main() { skip: true, (WidgetTester tester) async { final rootNavigatorKey = GlobalKey(debugLabel: 'root'); - final statefulShellKey = GlobalKey( - debugLabel: 'shell', - ); + final statefulShellKey = GlobalKey(debugLabel: 'shell'); StatefulNavigationShell? routeState; StatefulShellBranch makeBranch(String name) => StatefulShellBranch( navigatorKey: GlobalKey(debugLabel: 'branch-$name'), @@ -5442,8 +4790,7 @@ void main() { routes: [ GoRoute( path: '/$name', - builder: (BuildContext context, GoRouterState state) => - Text('Screen $name'), + builder: (BuildContext context, GoRouterState state) => Text('Screen $name'), ), ], ); @@ -5451,15 +4798,14 @@ void main() { List createRoutes(bool includeCRoute) => [ StatefulShellRoute.indexedStack( key: statefulShellKey, - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return navigationShell; + }, branches: [ makeBranch('a'), makeBranch('b'), @@ -5468,9 +4814,7 @@ void main() { ), ]; - final config = ValueNotifier( - RoutingConfig(routes: createRoutes(true)), - ); + final config = ValueNotifier(RoutingConfig(routes: createRoutes(true))); addTearDown(config.dispose); await createRouterWithRoutingConfig( navigatorKey: rootNavigatorKey, @@ -5481,8 +4825,9 @@ void main() { ); await tester.pumpAndSettle(); - bool hasLoadedBranch(String name) => routeState!.debugLoadedBranches - .any((StatefulShellBranch e) => e.initialLocation == '/$name'); + bool hasLoadedBranch(String name) => routeState!.debugLoadedBranches.any( + (StatefulShellBranch e) => e.initialLocation == '/$name', + ); expect(hasLoadedBranch('a'), isTrue); expect(hasLoadedBranch('b'), isTrue); @@ -5501,77 +4846,65 @@ void main() { group('Imperative navigation', () { group('canPop', () { - testWidgets( - 'It should return false if Navigator.canPop() returns false.', - (WidgetTester tester) async { - final navigatorKey = GlobalKey(); - final router = GoRouter( - initialLocation: '/', - navigatorKey: navigatorKey, - routes: [ - GoRoute( - path: '/', - builder: (BuildContext context, _) { - return Scaffold( - body: TextButton( - onPressed: () async { - navigatorKey.currentState!.push( - MaterialPageRoute( - builder: (BuildContext context) { - return const Scaffold( - body: Text('pageless route'), - ); - }, - ), - ); - }, - child: const Text('Push'), - ), - ); - }, - ), - GoRoute(path: '/a', builder: (_, __) => const DummyScreen()), - ], - ); - addTearDown(router.dispose); - - await tester.pumpWidget( - MaterialApp.router( - routeInformationProvider: router.routeInformationProvider, - routeInformationParser: router.routeInformationParser, - routerDelegate: router.routerDelegate, + testWidgets('It should return false if Navigator.canPop() returns false.', ( + WidgetTester tester, + ) async { + final navigatorKey = GlobalKey(); + final router = GoRouter( + initialLocation: '/', + navigatorKey: navigatorKey, + routes: [ + GoRoute( + path: '/', + builder: (BuildContext context, _) { + return Scaffold( + body: TextButton( + onPressed: () async { + navigatorKey.currentState!.push( + MaterialPageRoute( + builder: (BuildContext context) { + return const Scaffold(body: Text('pageless route')); + }, + ), + ); + }, + child: const Text('Push'), + ), + ); + }, ), - ); + GoRoute(path: '/a', builder: (_, __) => const DummyScreen()), + ], + ); + addTearDown(router.dispose); + + await tester.pumpWidget( + MaterialApp.router( + routeInformationProvider: router.routeInformationProvider, + routeInformationParser: router.routeInformationParser, + routerDelegate: router.routerDelegate, + ), + ); - expect(router.canPop(), false); + expect(router.canPop(), false); - await tester.tap(find.text('Push')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Push')); + await tester.pumpAndSettle(); - expect( - find.text('pageless route', skipOffstage: false), - findsOneWidget, - ); - expect(router.canPop(), true); - }, - ); + expect(find.text('pageless route', skipOffstage: false), findsOneWidget); + expect(router.canPop(), true); + }); - testWidgets('It checks if ShellRoute navigators can pop', ( - WidgetTester tester, - ) async { + testWidgets('It checks if ShellRoute navigators can pop', (WidgetTester tester) async { final shellNavigatorKey = GlobalKey(); final router = GoRouter( initialLocation: '/a', routes: [ ShellRoute( navigatorKey: shellNavigatorKey, - builder: - (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('Shell')), - body: child, - ); - }, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold(appBar: AppBar(title: const Text('Shell')), body: child); + }, routes: [ GoRoute( path: '/a', @@ -5582,9 +4915,7 @@ void main() { shellNavigatorKey.currentState!.push( MaterialPageRoute( builder: (BuildContext context) { - return const Scaffold( - body: Text('pageless route'), - ); + return const Scaffold(body: Text('pageless route')); }, ), ); @@ -5614,10 +4945,7 @@ void main() { await tester.tap(find.text('Push')); await tester.pumpAndSettle(); - expect( - find.text('pageless route', skipOffstage: false), - findsOneWidget, - ); + expect(find.text('pageless route', skipOffstage: false), findsOneWidget); expect(router.canPop(), true); }); @@ -5653,9 +4981,7 @@ void main() { GoRoute( path: 'detail', builder: (BuildContext context, _) { - return const Scaffold( - body: Text('Screen B detail'), - ); + return const Scaffold(body: Text('Screen B detail')); }, ), ], @@ -5681,19 +5007,14 @@ void main() { router.go('/b/detail'); await tester.pumpAndSettle(); - expect( - find.text('Screen B detail', skipOffstage: false), - findsOneWidget, - ); + expect(find.text('Screen B detail', skipOffstage: false), findsOneWidget); expect(router.canPop(), true); // Verify that it is actually the StatefulShellRoute that reports // canPop = true expect(rootNavigatorKey.currentState?.canPop(), false); }); - testWidgets('Pageless route should include in can pop', ( - WidgetTester tester, - ) async { + testWidgets('Pageless route should include in can pop', (WidgetTester tester) async { final root = GlobalKey(debugLabel: 'root'); final shell = GlobalKey(debugLabel: 'shell'); @@ -5702,22 +5023,14 @@ void main() { routes: [ ShellRoute( navigatorKey: shell, - builder: - (BuildContext context, GoRouterState state, Widget child) { - return Scaffold( - body: Center( - child: Column( - children: [ - const Text('Shell'), - Expanded(child: child), - ], - ), - ), - ); - }, - routes: [ - GoRoute(path: '/', builder: (_, __) => const Text('A Screen')), - ], + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Center( + child: Column(children: [const Text('Shell'), Expanded(child: child)]), + ), + ); + }, + routes: [GoRoute(path: '/', builder: (_, __) => const Text('A Screen'))], ), ], ); @@ -5728,10 +5041,7 @@ void main() { expect(router.canPop(), isFalse); expect(find.text('A Screen'), findsOneWidget); expect(find.text('Shell'), findsOneWidget); - showDialog( - context: root.currentContext!, - builder: (_) => const Text('A dialog'), - ); + showDialog(context: root.currentContext!, builder: (_) => const Text('A dialog')); await tester.pumpAndSettle(); expect(find.text('A dialog'), findsOneWidget); expect(router.canPop(), isTrue); @@ -5739,94 +5049,14 @@ void main() { }); group('pop', () { - testWidgets( - 'Should pop from the correct navigator when parentNavigatorKey is set', - (WidgetTester tester) async { - final root = GlobalKey(debugLabel: 'root'); - final shell = GlobalKey(debugLabel: 'shell'); - - final router = GoRouter( - initialLocation: '/a/b', - navigatorKey: root, - routes: [ - GoRoute( - path: '/', - builder: (BuildContext context, _) { - return const Scaffold(body: Text('Home')); - }, - routes: [ - ShellRoute( - navigatorKey: shell, - builder: - ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - body: Center( - child: Column( - children: [ - const Text('Shell'), - Expanded(child: child), - ], - ), - ), - ); - }, - routes: [ - GoRoute( - path: 'a', - builder: (_, __) => const Text('A Screen'), - routes: [ - GoRoute( - parentNavigatorKey: root, - path: 'b', - builder: (_, __) => const Text('B Screen'), - ), - ], - ), - ], - ), - ], - ), - ], - ); - addTearDown(router.dispose); - - await tester.pumpWidget( - MaterialApp.router( - routeInformationProvider: router.routeInformationProvider, - routeInformationParser: router.routeInformationParser, - routerDelegate: router.routerDelegate, - ), - ); - - expect(router.canPop(), isTrue); - expect(find.text('B Screen'), findsOneWidget); - expect(find.text('A Screen'), findsNothing); - expect(find.text('Shell'), findsNothing); - expect(find.text('Home'), findsNothing); - router.pop(); - await tester.pumpAndSettle(); - expect(find.text('A Screen'), findsOneWidget); - expect(find.text('Shell'), findsOneWidget); - expect(router.canPop(), isTrue); - router.pop(); - await tester.pumpAndSettle(); - expect(find.text('Home'), findsOneWidget); - expect(find.text('Shell'), findsNothing); - }, - ); - - testWidgets('Should pop dialog if it is present', ( + testWidgets('Should pop from the correct navigator when parentNavigatorKey is set', ( WidgetTester tester, ) async { final root = GlobalKey(debugLabel: 'root'); final shell = GlobalKey(debugLabel: 'shell'); final router = GoRouter( - initialLocation: '/a', + initialLocation: '/a/b', navigatorKey: root, routes: [ GoRoute( @@ -5837,27 +5067,26 @@ void main() { routes: [ ShellRoute( navigatorKey: shell, - builder: - ( - BuildContext context, - GoRouterState state, - Widget child, - ) { - return Scaffold( - body: Center( - child: Column( - children: [ - const Text('Shell'), - Expanded(child: child), - ], - ), - ), - ); - }, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Center( + child: Column( + children: [const Text('Shell'), Expanded(child: child)], + ), + ), + ); + }, routes: [ GoRoute( path: 'a', builder: (_, __) => const Text('A Screen'), + routes: [ + GoRoute( + parentNavigatorKey: root, + path: 'b', + builder: (_, __) => const Text('B Screen'), + ), + ], ), ], ), @@ -5867,6 +5096,65 @@ void main() { ); addTearDown(router.dispose); + await tester.pumpWidget( + MaterialApp.router( + routeInformationProvider: router.routeInformationProvider, + routeInformationParser: router.routeInformationParser, + routerDelegate: router.routerDelegate, + ), + ); + + expect(router.canPop(), isTrue); + expect(find.text('B Screen'), findsOneWidget); + expect(find.text('A Screen'), findsNothing); + expect(find.text('Shell'), findsNothing); + expect(find.text('Home'), findsNothing); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('A Screen'), findsOneWidget); + expect(find.text('Shell'), findsOneWidget); + expect(router.canPop(), isTrue); + router.pop(); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); + expect(find.text('Shell'), findsNothing); + }); + + testWidgets('Should pop dialog if it is present', (WidgetTester tester) async { + final root = GlobalKey(debugLabel: 'root'); + final shell = GlobalKey(debugLabel: 'shell'); + + final router = GoRouter( + initialLocation: '/a', + navigatorKey: root, + routes: [ + GoRoute( + path: '/', + builder: (BuildContext context, _) { + return const Scaffold(body: Text('Home')); + }, + routes: [ + ShellRoute( + navigatorKey: shell, + builder: (BuildContext context, GoRouterState state, Widget child) { + return Scaffold( + body: Center( + child: Column( + children: [const Text('Shell'), Expanded(child: child)], + ), + ), + ); + }, + routes: [ + GoRoute(path: 'a', builder: (_, __) => const Text('A Screen')), + ], + ), + ], + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); expect(router.canPop(), isTrue); @@ -5890,9 +5178,7 @@ void main() { expect(result, isTrue); }); - testWidgets('Triggers a Hero inside a ShellRoute', ( - WidgetTester tester, - ) async { + testWidgets('Triggers a Hero inside a ShellRoute', (WidgetTester tester) async { final heroKey = UniqueKey(); const kHeroTag = 'hero'; @@ -5923,11 +5209,7 @@ void main() { ], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); // check that flightShuttleBuilder widget is not yet present expect(find.byKey(heroKey), findsNothing); @@ -5950,12 +5232,7 @@ void main() { WidgetTester tester, ) async { const key = Key('key'); - final routes = [ - GoRoute( - path: '/', - builder: (_, __) => const SizedBox(key: key), - ), - ]; + final routes = [GoRoute(path: '/', builder: (_, __) => const SizedBox(key: key))]; final GoRouter router = await createRouter(routes, tester); final Element context = tester.element(find.byKey(key)); @@ -5979,12 +5256,7 @@ void main() { WidgetTester tester, ) async { const key = Key('key'); - final routes = [ - GoRoute( - path: '/', - builder: (_, __) => const SizedBox(key: key), - ), - ]; + final routes = [GoRoute(path: '/', builder: (_, __) => const SizedBox(key: key))]; final GoRouter router = await createRouter(routes, tester); final Element context = tester.element(find.byKey(key)); @@ -5992,30 +5264,25 @@ void main() { expect(foundRouter, router); }); - testWidgets( - 'It should return null if there is no go router in the widget tree', - (WidgetTester tester) async { - const key = Key('key'); - await tester.pumpWidget(const SizedBox(key: key)); + testWidgets('It should return null if there is no go router in the widget tree', ( + WidgetTester tester, + ) async { + const key = Key('key'); + await tester.pumpWidget(const SizedBox(key: key)); - final Element context = tester.element(find.byKey(key)); - expect(GoRouter.maybeOf(context), isNull); - }, - ); + final Element context = tester.element(find.byKey(key)); + expect(GoRouter.maybeOf(context), isNull); + }); }); group('state restoration', () { testWidgets('Restores state correctly', (WidgetTester tester) async { - final statefulWidgetKeyA = - GlobalKey(); + final statefulWidgetKeyA = GlobalKey(); final routes = [ GoRoute( path: '/a', - pageBuilder: createPageBuilder( - restorationId: 'screenA', - child: const Text('Screen A'), - ), + pageBuilder: createPageBuilder(restorationId: 'screenA', child: const Text('Screen A')), routes: [ GoRoute( path: 'detail', @@ -6036,12 +5303,7 @@ void main() { ), ]; - await createRouter( - routes, - tester, - initialLocation: '/a/detail', - restorationScopeId: 'test', - ); + await createRouter(routes, tester, initialLocation: '/a/detail', restorationScopeId: 'test'); await tester.pumpAndSettle(); statefulWidgetKeyA.currentState?.increment(); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); @@ -6058,29 +5320,22 @@ void main() { WidgetTester tester, ) async { final rootNavigatorKey = GlobalKey(); - final statefulWidgetKeyA = - GlobalKey(); - final statefulWidgetKeyB = - GlobalKey(); - final statefulWidgetKeyC = - GlobalKey(); + final statefulWidgetKeyA = GlobalKey(); + final statefulWidgetKeyB = GlobalKey(); + final statefulWidgetKeyC = GlobalKey(); StatefulNavigationShell? routeState; final routes = [ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', - pageBuilder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeState = navigationShell; - return MaterialPage( - restorationId: 'shellWidget', - child: navigationShell, - ); - }, + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeState = navigationShell; + return MaterialPage(restorationId: 'shellWidget', child: navigationShell); + }, branches: [ StatefulShellBranch( restorationScopeId: 'branchA', @@ -6215,178 +5470,170 @@ void main() { expect(statefulWidgetKeyC.currentState?.counter, equals(0)); }); - testWidgets( - 'Restores state of imperative routes in StatefulShellRoute correctly', - (WidgetTester tester) async { - final rootNavigatorKey = GlobalKey(); - final statefulWidgetKeyA = - GlobalKey(); - final statefulWidgetKeyB = - GlobalKey(); - StatefulNavigationShell? routeStateRoot; - StatefulNavigationShell? routeStateNested; + testWidgets('Restores state of imperative routes in StatefulShellRoute correctly', ( + WidgetTester tester, + ) async { + final rootNavigatorKey = GlobalKey(); + final statefulWidgetKeyA = GlobalKey(); + final statefulWidgetKeyB = GlobalKey(); + StatefulNavigationShell? routeStateRoot; + StatefulNavigationShell? routeStateNested; - final routes = [ - StatefulShellRoute.indexedStack( - restorationScopeId: 'shell', - pageBuilder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeStateRoot = navigationShell; - return MaterialPage( - restorationId: 'shellWidget', - child: navigationShell, - ); - }, - branches: [ - StatefulShellBranch( - restorationScopeId: 'branchA', - routes: [ - GoRoute( - path: '/a', - pageBuilder: createPageBuilder( - restorationId: 'screenA', - child: const Text('Screen A'), - ), - routes: [ - GoRoute( - path: 'detailA', - pageBuilder: createPageBuilder( - restorationId: 'screenADetail', - child: Column( - children: [ - const Text('Screen A Detail'), - DummyRestorableStatefulWidget( - key: statefulWidgetKeyA, - restorationId: 'counterA', - ), - ], - ), - ), - ), - ], + final routes = [ + StatefulShellRoute.indexedStack( + restorationScopeId: 'shell', + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeStateRoot = navigationShell; + return MaterialPage(restorationId: 'shellWidget', child: navigationShell); + }, + branches: [ + StatefulShellBranch( + restorationScopeId: 'branchA', + routes: [ + GoRoute( + path: '/a', + pageBuilder: createPageBuilder( + restorationId: 'screenA', + child: const Text('Screen A'), ), - ], - ), - StatefulShellBranch( - restorationScopeId: 'branchB', - routes: [ - StatefulShellRoute.indexedStack( - restorationScopeId: 'branchB-nested-shell', - pageBuilder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - routeStateNested = navigationShell; - return MaterialPage( - restorationId: 'shellWidget-nested', - child: navigationShell, - ); - }, - branches: [ - StatefulShellBranch( - restorationScopeId: 'branchB-nested', - routes: [ - GoRoute( - path: '/b', - pageBuilder: createPageBuilder( - restorationId: 'screenB', - child: const Text('Screen B'), + routes: [ + GoRoute( + path: 'detailA', + pageBuilder: createPageBuilder( + restorationId: 'screenADetail', + child: Column( + children: [ + const Text('Screen A Detail'), + DummyRestorableStatefulWidget( + key: statefulWidgetKeyA, + restorationId: 'counterA', ), - routes: [ - GoRoute( - path: 'detailB', - pageBuilder: createPageBuilder( - restorationId: 'screenBDetail', - child: Column( - children: [ - const Text('Screen B Detail'), - DummyRestorableStatefulWidget( - key: statefulWidgetKeyB, - restorationId: 'counterB', - ), - ], - ), + ], + ), + ), + ), + ], + ), + ], + ), + StatefulShellBranch( + restorationScopeId: 'branchB', + routes: [ + StatefulShellRoute.indexedStack( + restorationScopeId: 'branchB-nested-shell', + pageBuilder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + routeStateNested = navigationShell; + return MaterialPage( + restorationId: 'shellWidget-nested', + child: navigationShell, + ); + }, + branches: [ + StatefulShellBranch( + restorationScopeId: 'branchB-nested', + routes: [ + GoRoute( + path: '/b', + pageBuilder: createPageBuilder( + restorationId: 'screenB', + child: const Text('Screen B'), + ), + routes: [ + GoRoute( + path: 'detailB', + pageBuilder: createPageBuilder( + restorationId: 'screenBDetail', + child: Column( + children: [ + const Text('Screen B Detail'), + DummyRestorableStatefulWidget( + key: statefulWidgetKeyB, + restorationId: 'counterB', + ), + ], ), ), - ], - ), - ], - ), - StatefulShellBranch( - restorationScopeId: 'branchC-nested', - routes: [ - GoRoute( - path: '/c', - pageBuilder: createPageBuilder( - restorationId: 'screenC', - child: const Text('Screen C'), ), + ], + ), + ], + ), + StatefulShellBranch( + restorationScopeId: 'branchC-nested', + routes: [ + GoRoute( + path: '/c', + pageBuilder: createPageBuilder( + restorationId: 'screenC', + child: const Text('Screen C'), ), - ], - ), - ], - ), - ], - ), - ], - ), - ]; + ), + ], + ), + ], + ), + ], + ), + ], + ), + ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a/detailA', - navigatorKey: rootNavigatorKey, - restorationScopeId: 'test', - ); - await tester.pumpAndSettle(); - statefulWidgetKeyA.currentState?.increment(); - expect(statefulWidgetKeyA.currentState?.counter, equals(1)); + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/a/detailA', + navigatorKey: rootNavigatorKey, + restorationScopeId: 'test', + ); + await tester.pumpAndSettle(); + statefulWidgetKeyA.currentState?.increment(); + expect(statefulWidgetKeyA.currentState?.counter, equals(1)); - routeStateRoot!.goBranch(1); - await tester.pumpAndSettle(); + routeStateRoot!.goBranch(1); + await tester.pumpAndSettle(); - router.go('/b/detailB'); - await tester.pumpAndSettle(); - statefulWidgetKeyB.currentState?.increment(); - expect(statefulWidgetKeyB.currentState?.counter, equals(1)); + router.go('/b/detailB'); + await tester.pumpAndSettle(); + statefulWidgetKeyB.currentState?.increment(); + expect(statefulWidgetKeyB.currentState?.counter, equals(1)); - routeStateRoot!.goBranch(0); - await tester.pumpAndSettle(); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Pushed Detail'), findsNothing); + routeStateRoot!.goBranch(0); + await tester.pumpAndSettle(); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Pushed Detail'), findsNothing); - await tester.restartAndRestore(); + await tester.restartAndRestore(); - await tester.pumpAndSettle(); - expect(find.text('Screen A Detail'), findsOneWidget); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Pushed Detail'), findsNothing); - expect(statefulWidgetKeyA.currentState?.counter, equals(1)); + await tester.pumpAndSettle(); + expect(find.text('Screen A Detail'), findsOneWidget); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Pushed Detail'), findsNothing); + expect(statefulWidgetKeyA.currentState?.counter, equals(1)); - routeStateRoot!.goBranch(1); - await tester.pumpAndSettle(); - expect(find.text('Screen A Detail'), findsNothing); - expect(find.text('Screen B'), findsNothing); - expect(find.text('Screen B Detail'), findsOneWidget); - expect(statefulWidgetKeyB.currentState?.counter, equals(1)); + routeStateRoot!.goBranch(1); + await tester.pumpAndSettle(); + expect(find.text('Screen A Detail'), findsNothing); + expect(find.text('Screen B'), findsNothing); + expect(find.text('Screen B Detail'), findsOneWidget); + expect(statefulWidgetKeyB.currentState?.counter, equals(1)); - routeStateNested!.goBranch(1); - await tester.pumpAndSettle(); - routeStateNested!.goBranch(0); - await tester.pumpAndSettle(); + routeStateNested!.goBranch(1); + await tester.pumpAndSettle(); + routeStateNested!.goBranch(0); + await tester.pumpAndSettle(); - expect(find.text('Screen B Detail'), findsOneWidget); - expect(statefulWidgetKeyB.currentState?.counter, equals(1)); - }, - ); + expect(find.text('Screen B Detail'), findsOneWidget); + expect(statefulWidgetKeyB.currentState?.counter, equals(1)); + }); }); ///Regression tests for https://github.com/flutter/flutter/issues/132557 @@ -6398,39 +5645,31 @@ void main() { routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), ], ), throwsA(const TypeMatcher()), ); }); - testWidgets('Test override using routeInformationProvider', ( - WidgetTester tester, - ) async { - tester.binding.platformDispatcher.defaultRouteNameTestValue = - '/some-route'; - final String platformRoute = - WidgetsBinding.instance.platformDispatcher.defaultRouteName; + testWidgets('Test override using routeInformationProvider', (WidgetTester tester) async { + tester.binding.platformDispatcher.defaultRouteNameTestValue = '/some-route'; + final String platformRoute = WidgetsBinding.instance.platformDispatcher.defaultRouteName; const expectedInitialRoute = '/kyc'; expect(platformRoute != expectedInitialRoute, isTrue); final routes = [ GoRoute( path: '/abc', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), GoRoute( path: '/bcd', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), ]; @@ -6440,146 +5679,127 @@ void main() { overridePlatformDefaultLocation: true, initialLocation: expectedInitialRoute, ); - expect( - router.routeInformationProvider.value.uri.toString(), - expectedInitialRoute, - ); + expect(router.routeInformationProvider.value.uri.toString(), expectedInitialRoute); }); }); - testWidgets( - 'test the pathParameters in redirect when the Router is recreated', - (WidgetTester tester) async { - final router = GoRouter( - initialLocation: '/foo', - routes: [ - GoRoute( - path: '/foo', - builder: dummy, - routes: [ - GoRoute( - path: ':id', - redirect: (_, GoRouterState state) { - expect(state.pathParameters['id'], isNotNull); - return null; - }, - builder: dummy, - ), - ], - ), - ], - ); - addTearDown(router.dispose); - await tester.pumpWidget( - MaterialApp.router(key: UniqueKey(), routerConfig: router), - ); - router.push('/foo/123'); - await tester.pump(); // wait reportRouteInformation - await tester.pumpWidget( - MaterialApp.router(key: UniqueKey(), routerConfig: router), - ); - }, - ); - - testWidgets( - 'should return the current GoRouterState when router.currentState is called', - (WidgetTester tester) async { - final routes = [ - GoRoute( - name: 'home', - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), - GoRoute( - name: 'books', - path: '/books', - builder: (BuildContext context, GoRouterState state) => - const Text('books'), - ), + testWidgets('test the pathParameters in redirect when the Router is recreated', ( + WidgetTester tester, + ) async { + final router = GoRouter( + initialLocation: '/foo', + routes: [ GoRoute( - name: 'boats', - path: '/boats', - builder: (BuildContext context, GoRouterState state) => - const Text('boats'), - ), - ShellRoute( - builder: (BuildContext context, GoRouterState state, Widget child) => - child, - routes: [ + path: '/foo', + builder: dummy, + routes: [ GoRoute( - name: 'tulips', - path: '/tulips', - builder: (BuildContext context, GoRouterState state) => - const Text('tulips'), + path: ':id', + redirect: (_, GoRouterState state) { + expect(state.pathParameters['id'], isNotNull); + return null; + }, + builder: dummy, ), ], ), - ]; + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(key: UniqueKey(), routerConfig: router)); + router.push('/foo/123'); + await tester.pump(); // wait reportRouteInformation + await tester.pumpWidget(MaterialApp.router(key: UniqueKey(), routerConfig: router)); + }); - final GoRouter router = await createRouter(routes, tester); - await tester.pumpAndSettle(); + testWidgets('should return the current GoRouterState when router.currentState is called', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + name: 'home', + path: '/', + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), + ), + GoRoute( + name: 'books', + path: '/books', + builder: (BuildContext context, GoRouterState state) => const Text('books'), + ), + GoRoute( + name: 'boats', + path: '/boats', + builder: (BuildContext context, GoRouterState state) => const Text('boats'), + ), + ShellRoute( + builder: (BuildContext context, GoRouterState state, Widget child) => child, + routes: [ + GoRoute( + name: 'tulips', + path: '/tulips', + builder: (BuildContext context, GoRouterState state) => const Text('tulips'), + ), + ], + ), + ]; - GoRouterState? state = router.state; - expect(state.name, 'home'); - expect(state.fullPath, '/'); + final GoRouter router = await createRouter(routes, tester); + await tester.pumpAndSettle(); - router.go('/books'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'books'); - expect(state.fullPath, '/books'); + GoRouterState? state = router.state; + expect(state.name, 'home'); + expect(state.fullPath, '/'); - router.push('/boats'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'boats'); - expect(state.fullPath, '/boats'); + router.go('/books'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'books'); + expect(state.fullPath, '/books'); - router.pop(); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'books'); - expect(state.fullPath, '/books'); + router.push('/boats'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'boats'); + expect(state.fullPath, '/boats'); - router.go('/tulips'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'tulips'); - expect(state.fullPath, '/tulips'); + router.pop(); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'books'); + expect(state.fullPath, '/books'); - router.go('/books'); - router.push('/tulips'); - await tester.pumpAndSettle(); - state = router.state; - expect(state.name, 'tulips'); - expect(state.fullPath, '/tulips'); - }, - ); + router.go('/tulips'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'tulips'); + expect(state.fullPath, '/tulips'); - testWidgets('should allow route paths without leading /', ( - WidgetTester tester, - ) async { + router.go('/books'); + router.push('/tulips'); + await tester.pumpAndSettle(); + state = router.state; + expect(state.name, 'tulips'); + expect(state.fullPath, '/tulips'); + }); + + testWidgets('should allow route paths without leading /', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', // root cannot be empty (existing assert) - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'child-route', - builder: (BuildContext context, GoRouterState state) => - const Text('/child-route'), + builder: (BuildContext context, GoRouterState state) => const Text('/child-route'), routes: [ GoRoute( path: 'grand-child-route', - builder: (BuildContext context, GoRouterState state) => - const Text('/grand-child-route'), + builder: + (BuildContext context, GoRouterState state) => const Text('/grand-child-route'), ), GoRoute( path: 'redirected-grand-child-route', - redirect: (BuildContext context, GoRouterState state) => - '/child-route', + redirect: (BuildContext context, GoRouterState state) => '/child-route', ), ], ), @@ -6605,29 +5825,24 @@ void main() { expect(find.text('/child-route'), findsOneWidget); }); - testWidgets('should allow route paths with leading /', ( - WidgetTester tester, - ) async { + testWidgets('should allow route paths with leading /', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: '/child-route', - builder: (BuildContext context, GoRouterState state) => - const Text('/child-route'), + builder: (BuildContext context, GoRouterState state) => const Text('/child-route'), routes: [ GoRoute( path: '/grand-child-route', - builder: (BuildContext context, GoRouterState state) => - const Text('/grand-child-route'), + builder: + (BuildContext context, GoRouterState state) => const Text('/grand-child-route'), ), GoRoute( path: '/redirected-grand-child-route', - redirect: (BuildContext context, GoRouterState state) => - '/child-route', + redirect: (BuildContext context, GoRouterState state) => '/child-route', ), ], ), @@ -6655,11 +5870,7 @@ void main() { } class TestInheritedNotifier extends InheritedNotifier> { - const TestInheritedNotifier({ - super.key, - required super.notifier, - required super.child, - }); + const TestInheritedNotifier({super.key, required super.notifier, required super.child}); } class IsRouteUpdateCall extends Matcher { diff --git a/packages/go_router/test/imperative_api_test.dart b/packages/go_router/test/imperative_api_test.dart index b56d0eefa565..d86b6f6f2e1a 100644 --- a/packages/go_router/test/imperative_api_test.dart +++ b/packages/go_router/test/imperative_api_test.dart @@ -16,28 +16,15 @@ void main() { final routes = [ ShellRoute( builder: (_, __, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('shell')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell')), body: child); }, routes: [ - GoRoute( - path: '/a', - builder: (_, __) => DummyScreen(key: a), - ), - GoRoute( - path: '/b', - builder: (_, __) => DummyScreen(key: b), - ), + GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), + GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), ], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsOneWidget); @@ -54,30 +41,15 @@ void main() { final a = UniqueKey(); final b = UniqueKey(); final routes = [ - GoRoute( - path: '/a', - builder: (_, __) => DummyScreen(key: a), - ), + GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), ShellRoute( builder: (_, __, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('shell')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell')), body: child); }, - routes: [ - GoRoute( - path: '/b', - builder: (_, __) => DummyScreen(key: b), - ), - ], + routes: [GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b))], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell'), findsNothing); expect(find.byKey(a), findsOneWidget); @@ -89,39 +61,25 @@ void main() { expect(find.byKey(b), findsOneWidget); }); - testWidgets('shell route reflect imperative push', ( - WidgetTester tester, - ) async { + testWidgets('shell route reflect imperative push', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/125752. final home = UniqueKey(); final a = UniqueKey(); final routes = [ ShellRoute( builder: (_, GoRouterState state, Widget child) { - return Scaffold( - appBar: AppBar(title: Text('location: ${state.uri.path}')), - body: child, - ); + return Scaffold(appBar: AppBar(title: Text('location: ${state.uri.path}')), body: child); }, routes: [ GoRoute( path: '/', builder: (_, __) => DummyScreen(key: home), - routes: [ - GoRoute( - path: 'a', - builder: (_, __) => DummyScreen(key: a), - ), - ], + routes: [GoRoute(path: 'a', builder: (_, __) => DummyScreen(key: a))], ), ], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('location: /a'), findsOneWidget); expect(find.byKey(a), findsOneWidget); @@ -139,47 +97,25 @@ void main() { expect(find.byKey(home), findsNothing); }); - testWidgets('push shell route in another shell route', ( - WidgetTester tester, - ) async { + testWidgets('push shell route in another shell route', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/120791. final b = UniqueKey(); final a = UniqueKey(); final routes = [ ShellRoute( builder: (_, __, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('shell1')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell1')), body: child); }, - routes: [ - GoRoute( - path: '/a', - builder: (_, __) => DummyScreen(key: a), - ), - ], + routes: [GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a))], ), ShellRoute( builder: (_, __, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('shell2')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell2')), body: child); }, - routes: [ - GoRoute( - path: '/b', - builder: (_, __) => DummyScreen(key: b), - ), - ], + routes: [GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b))], ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell1'), findsOneWidget); expect(find.byKey(a), findsOneWidget); @@ -192,37 +128,20 @@ void main() { expect(find.byKey(b), findsOneWidget); }); - testWidgets('push inside or outside shell route', ( - WidgetTester tester, - ) async { + testWidgets('push inside or outside shell route', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/120665. final inside = UniqueKey(); final outside = UniqueKey(); final routes = [ ShellRoute( builder: (_, __, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('shell')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell')), body: child); }, - routes: [ - GoRoute( - path: '/in', - builder: (_, __) => DummyScreen(key: inside), - ), - ], - ), - GoRoute( - path: '/out', - builder: (_, __) => DummyScreen(key: outside), + routes: [GoRoute(path: '/in', builder: (_, __) => DummyScreen(key: inside))], ), + GoRoute(path: '/out', builder: (_, __) => DummyScreen(key: outside)), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/out', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/out'); expect(find.text('shell'), findsNothing); expect(find.byKey(outside), findsOneWidget); @@ -250,42 +169,21 @@ void main() { final routes = [ ShellRoute( builder: (_, __, Widget child) { - return Scaffold( - appBar: AppBar(title: const Text('shell')), - body: child, - ); + return Scaffold(appBar: AppBar(title: const Text('shell')), body: child); }, routes: [ - GoRoute( - path: '/a', - builder: (_, __) => DummyScreen(key: a), - ), - GoRoute( - path: '/c', - builder: (_, __) => DummyScreen(key: c), - ), + GoRoute(path: '/a', builder: (_, __) => DummyScreen(key: a)), + GoRoute(path: '/c', builder: (_, __) => DummyScreen(key: c)), ], ), GoRoute( path: '/d', builder: (_, __) => DummyScreen(key: d), - routes: [ - GoRoute( - path: 'e', - builder: (_, __) => DummyScreen(key: e), - ), - ], - ), - GoRoute( - path: '/b', - builder: (_, __) => DummyScreen(key: b), + routes: [GoRoute(path: 'e', builder: (_, __) => DummyScreen(key: e))], ), + GoRoute(path: '/b', builder: (_, __) => DummyScreen(key: b)), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/a', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); expect(find.text('shell'), findsOneWidget); expect(find.byKey(a), findsOneWidget); diff --git a/packages/go_router/test/information_provider_test.dart b/packages/go_router/test/information_provider_test.dart index 5028e882f8ee..5376ddc68a1c 100644 --- a/packages/go_router/test/information_provider_test.dart +++ b/packages/go_router/test/information_provider_test.dart @@ -12,9 +12,7 @@ const String newRoute = '/new'; void main() { group('GoRouteInformationProvider', () { - testWidgets('notifies its listeners when set by the app', ( - WidgetTester tester, - ) async { + testWidgets('notifies its listeners when set by the app', (WidgetTester tester) async { late final provider = GoRouteInformationProvider( initialLocation: initialRoute, initialExtra: null, @@ -24,18 +22,14 @@ void main() { provider.go(newRoute); }); - testWidgets('notifies its listeners when set by the platform', ( - WidgetTester tester, - ) async { + testWidgets('notifies its listeners when set by the platform', (WidgetTester tester) async { late final provider = GoRouteInformationProvider( initialLocation: initialRoute, initialExtra: null, ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); - provider.didPushRouteInformation( - RouteInformation(uri: Uri.parse(newRoute)), - ); + provider.didPushRouteInformation(RouteInformation(uri: Uri.parse(newRoute))); }); testWidgets('didPushRouteInformation maintains uri scheme and host', ( @@ -51,18 +45,14 @@ void main() { ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); - provider.didPushRouteInformation( - RouteInformation(uri: Uri.parse(expectedUriString)), - ); + provider.didPushRouteInformation(RouteInformation(uri: Uri.parse(expectedUriString))); expect(provider.value.uri.scheme, 'https'); expect(provider.value.uri.host, 'www.example.com'); expect(provider.value.uri.path, '/some/path'); expect(provider.value.uri.toString(), expectedUriString); }); - testWidgets('didPushRoute maintains uri scheme and host', ( - WidgetTester tester, - ) async { + testWidgets('didPushRoute maintains uri scheme and host', (WidgetTester tester) async { const expectedScheme = 'https'; const expectedHost = 'www.example.com'; const expectedPath = '/some/path'; @@ -73,9 +63,7 @@ void main() { ); addTearDown(provider.dispose); provider.addListener(expectAsync0(() {})); - provider.didPushRouteInformation( - RouteInformation(uri: Uri.parse(expectedUriString)), - ); + provider.didPushRouteInformation(RouteInformation(uri: Uri.parse(expectedUriString))); expect(provider.value.uri.scheme, 'https'); expect(provider.value.uri.host, 'www.example.com'); expect(provider.value.uri.path, '/some/path'); @@ -101,9 +89,7 @@ void main() { expect(systemChannelsMock.uriIsNeglected[newRoute], true); }); - testWidgets('Route is NOT neglected when routerNeglect is false', ( - WidgetTester tester, - ) async { + testWidgets('Route is NOT neglected when routerNeglect is false', (WidgetTester tester) async { final systemChannelsMock = _SystemChannelsNavigationMock(); late final provider = GoRouteInformationProvider( initialLocation: initialRoute, @@ -123,19 +109,18 @@ void main() { class _SystemChannelsNavigationMock { _SystemChannelsNavigationMock() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.navigation, ( - MethodCall methodCall, - ) async { - if (methodCall.method == 'routeInformationUpdated' && - methodCall.arguments is Map) { - final args = methodCall.arguments as Map; - final String? uri = - args['location'] as String? ?? args['uri'] as String?; - uriIsNeglected[uri ?? ''] = args['replace'] as bool; - } - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.navigation, + (MethodCall methodCall) async { + if (methodCall.method == 'routeInformationUpdated' && + methodCall.arguments is Map) { + final args = methodCall.arguments as Map; + final String? uri = args['location'] as String? ?? args['uri'] as String?; + uriIsNeglected[uri ?? ''] = args['replace'] as bool; + } + return null; + }, + ); } Map uriIsNeglected = {}; diff --git a/packages/go_router/test/inherited_test.dart b/packages/go_router/test/inherited_test.dart index 96e3f9a063c1..bdbf288ccdd2 100644 --- a/packages/go_router/test/inherited_test.dart +++ b/packages/go_router/test/inherited_test.dart @@ -13,9 +13,7 @@ void main() { group('updateShouldNotify', () { test('does not update when goRouter does not change', () { final goRouter = GoRouter( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Page1()), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Page1())], ); final bool shouldNotify = setupInheritedGoRouterChange( oldGoRouter: goRouter, @@ -26,14 +24,10 @@ void main() { test('does not update even when goRouter changes', () { final oldGoRouter = GoRouter( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Page1()), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Page1())], ); final newGoRouter = GoRouter( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Page2()), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Page2())], ); final bool shouldNotify = setupInheritedGoRouterChange( oldGoRouter: oldGoRouter, @@ -47,10 +41,7 @@ void main() { final goRouter = GoRouter( routes: [GoRoute(path: '/', builder: (_, __) => const Page1())], ); - final inheritedGoRouter = InheritedGoRouter( - goRouter: goRouter, - child: Container(), - ); + final inheritedGoRouter = InheritedGoRouter(goRouter: goRouter, child: Container()); final properties = DiagnosticPropertiesBuilder(); inheritedGoRouter.debugFillProperties(properties); expect(properties.properties.length, 1); @@ -58,14 +49,10 @@ void main() { expect(properties.properties.first.value, goRouter); }); - testWidgets("mediates Widget's access to GoRouter.", ( - WidgetTester tester, - ) async { + testWidgets("mediates Widget's access to GoRouter.", (WidgetTester tester) async { final router = MockGoRouter(); await tester.pumpWidget( - MaterialApp( - home: InheritedGoRouter(goRouter: router, child: const _MyWidget()), - ), + MaterialApp(home: InheritedGoRouter(goRouter: router, child: const _MyWidget())), ); await tester.tap(find.text('My Page')); expect(router.latestPushedName, 'my_page'); @@ -101,18 +88,9 @@ void main() { }); } -bool setupInheritedGoRouterChange({ - required GoRouter oldGoRouter, - required GoRouter newGoRouter, -}) { - final oldInheritedGoRouter = InheritedGoRouter( - goRouter: oldGoRouter, - child: Container(), - ); - final newInheritedGoRouter = InheritedGoRouter( - goRouter: newGoRouter, - child: Container(), - ); +bool setupInheritedGoRouterChange({required GoRouter oldGoRouter, required GoRouter newGoRouter}) { + final oldInheritedGoRouter = InheritedGoRouter(goRouter: oldGoRouter, child: Container()); + final newInheritedGoRouter = InheritedGoRouter(goRouter: newGoRouter, child: Container()); return newInheritedGoRouter.updateShouldNotify(oldInheritedGoRouter); } @@ -145,9 +123,7 @@ class _MyWidget extends StatelessWidget { class MockGoRouter extends GoRouter { MockGoRouter() : super.routingConfig( - routingConfig: const ConstantRoutingConfig( - RoutingConfig(routes: []), - ), + routingConfig: const ConstantRoutingConfig(RoutingConfig(routes: [])), ); late String latestPushedName; diff --git a/packages/go_router/test/logging_test.dart b/packages/go_router/test/logging_test.dart index 6d8098aa105c..76c4d7fb9db6 100644 --- a/packages/go_router/test/logging_test.dart +++ b/packages/go_router/test/logging_test.dart @@ -30,23 +30,20 @@ void main() { logger.info('message'); }); - testWidgets( - 'It should not log anything the if debugLogDiagnostics is false', - (WidgetTester tester) async { - testDeveloperLog = expectAsync1((LogRecord data) {}, count: 0); - final StreamSubscription subscription = Logger.root.onRecord - .listen(expectAsync1((LogRecord data) {}, count: 0)); - addTearDown(subscription.cancel); - GoRouter( - routes: [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), - ], - ); - }, - ); + testWidgets('It should not log anything the if debugLogDiagnostics is false', ( + WidgetTester tester, + ) async { + testDeveloperLog = expectAsync1((LogRecord data) {}, count: 0); + final StreamSubscription subscription = Logger.root.onRecord.listen( + expectAsync1((LogRecord data) {}, count: 0), + ); + addTearDown(subscription.cancel); + GoRouter( + routes: [ + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), + ], + ); + }); testWidgets( 'It should log the known routes and the initial route if debugLogDiagnostics is true', @@ -61,10 +58,7 @@ void main() { GoRouter( debugLogDiagnostics: true, routes: [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), ], ); @@ -90,10 +84,7 @@ void main() { GoRouter( debugLogDiagnostics: true, routes: [ - GoRoute( - path: '/', - builder: (_, GoRouterState state) => const Text('home'), - ), + GoRoute(path: '/', builder: (_, GoRouterState state) => const Text('home')), ], ); diff --git a/packages/go_router/test/match_test.dart b/packages/go_router/test/match_test.dart index 1b12d2e71d7c..bcf1d6de3cdc 100644 --- a/packages/go_router/test/match_test.dart +++ b/packages/go_router/test/match_test.dart @@ -117,11 +117,7 @@ void main() { path: 'c', builder: _builder, routes: [ - GoRoute( - parentNavigatorKey: root, - path: 'd', - builder: _builder, - ), + GoRoute(parentNavigatorKey: root, path: 'd', builder: _builder), ], ), ], @@ -142,26 +138,13 @@ void main() { rootNavigatorKey: root, ); expect(matches.length, 4); - expect( - matches[0].route, - isA().having((GoRoute route) => route.path, 'path', '/'), - ); + expect(matches[0].route, isA().having((GoRoute route) => route.path, 'path', '/')); expect( matches[1].route, - isA().having( - (ShellRoute route) => route.navigatorKey, - 'navigator key', - shell1, - ), - ); - expect( - matches[2].route, - isA().having((GoRoute route) => route.path, 'path', 'b'), - ); - expect( - matches[3].route, - isA().having((GoRoute route) => route.path, 'path', 'd'), + isA().having((ShellRoute route) => route.navigatorKey, 'navigator key', shell1), ); + expect(matches[2].route, isA().having((GoRoute route) => route.path, 'path', 'b')); + expect(matches[3].route, isA().having((GoRoute route) => route.path, 'path', 'd')); }); group('ImperativeRouteMatch', () { @@ -196,63 +179,30 @@ void main() { final completer2 = Completer(); test('can equal and has', () async { - var match1 = ImperativeRouteMatch( - pageKey: key1, - matches: matchList1, - completer: completer1, - ); - var match2 = ImperativeRouteMatch( - pageKey: key1, - matches: matchList1, - completer: completer1, - ); + var match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1); + var match2 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1); expect(match1 == match2, isTrue); expect(match1.hashCode == match2.hashCode, isTrue); - match1 = ImperativeRouteMatch( - pageKey: key1, - matches: matchList1, - completer: completer1, - ); - match2 = ImperativeRouteMatch( - pageKey: key2, - matches: matchList1, - completer: completer1, - ); + match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1); + match2 = ImperativeRouteMatch(pageKey: key2, matches: matchList1, completer: completer1); expect(match1 == match2, isFalse); expect(match1.hashCode == match2.hashCode, isFalse); - match1 = ImperativeRouteMatch( - pageKey: key1, - matches: matchList1, - completer: completer1, - ); - match2 = ImperativeRouteMatch( - pageKey: key1, - matches: matchList2, - completer: completer1, - ); + match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1); + match2 = ImperativeRouteMatch(pageKey: key1, matches: matchList2, completer: completer1); expect(match1 == match2, isFalse); expect(match1.hashCode == match2.hashCode, isFalse); - match1 = ImperativeRouteMatch( - pageKey: key1, - matches: matchList1, - completer: completer1, - ); - match2 = ImperativeRouteMatch( - pageKey: key1, - matches: matchList1, - completer: completer2, - ); + match1 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer1); + match2 = ImperativeRouteMatch(pageKey: key1, matches: matchList1, completer: completer2); expect(match1 == match2, isFalse); expect(match1.hashCode == match2.hashCode, isFalse); }); }); } -Widget _builder(BuildContext context, GoRouterState state) => - const Placeholder(); +Widget _builder(BuildContext context, GoRouterState state) => const Placeholder(); Widget _shellBuilder(BuildContext context, GoRouterState state, Widget child) => const Placeholder(); diff --git a/packages/go_router/test/matching_test.dart b/packages/go_router/test/matching_test.dart index 23d217935617..379fb4311637 100644 --- a/packages/go_router/test/matching_test.dart +++ b/packages/go_router/test/matching_test.dart @@ -12,22 +12,15 @@ import 'package:go_router/src/match.dart'; import 'test_helpers.dart'; void main() { - testWidgets('RouteMatchList toString prints the fullPath', ( - WidgetTester tester, - ) async { + testWidgets('RouteMatchList toString prints the fullPath', (WidgetTester tester) async { final routes = [ GoRoute( path: '/page-0', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/page-0', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/page-0'); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.toString(), contains('/page-0')); @@ -36,8 +29,7 @@ void main() { test('RouteMatchList compares', () async { final route = GoRoute( path: '/page-0', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ); final params1 = {}; final List match1 = RouteMatchBase.match( @@ -55,17 +47,9 @@ void main() { pathParameters: params2, ); - final matches1 = RouteMatchList( - matches: match1, - uri: Uri.parse(''), - pathParameters: params1, - ); + final matches1 = RouteMatchList(matches: match1, uri: Uri.parse(''), pathParameters: params1); - final matches2 = RouteMatchList( - matches: match2, - uri: Uri.parse(''), - pathParameters: params2, - ); + final matches2 = RouteMatchList(matches: match2, uri: Uri.parse(''), pathParameters: params2); final matches3 = RouteMatchList( matches: match2, @@ -82,13 +66,11 @@ void main() { routes: [ GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Placeholder(), + builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), ], redirectLimit: 0, diff --git a/packages/go_router/test/material_test.dart b/packages/go_router/test/material_test.dart index 9a56c9ed2141..c862e903b14f 100644 --- a/packages/go_router/test/material_test.dart +++ b/packages/go_router/test/material_test.dart @@ -11,22 +11,16 @@ import 'helpers/error_screen_helpers.dart'; void main() { group('isMaterialApp', () { - testWidgets('returns [true] when MaterialApp is present', ( - WidgetTester tester, - ) async { + testWidgets('returns [true] when MaterialApp is present', (WidgetTester tester) async { final key = GlobalKey<_DummyStatefulWidgetState>(); await tester.pumpWidget(MaterialApp(home: DummyStatefulWidget(key: key))); final bool isMaterial = isMaterialApp(key.currentContext! as Element); expect(isMaterial, true); }); - testWidgets('returns [false] when CupertinoApp is present', ( - WidgetTester tester, - ) async { + testWidgets('returns [false] when CupertinoApp is present', (WidgetTester tester) async { final key = GlobalKey<_DummyStatefulWidgetState>(); - await tester.pumpWidget( - CupertinoApp(home: DummyStatefulWidget(key: key)), - ); + await tester.pumpWidget(CupertinoApp(home: DummyStatefulWidget(key: key))); final bool isMaterial = isMaterialApp(key.currentContext! as Element); expect(isMaterial, false); }); @@ -55,9 +49,7 @@ void main() { group('GoRouterMaterialErrorScreen', () { testWidgets( 'shows "page not found" by default', - testPageNotFound( - widget: const MaterialApp(home: MaterialErrorScreen(null)), - ), + testPageNotFound(widget: const MaterialApp(home: MaterialErrorScreen(null))), ); final exception = Exception('Something went wrong!'); diff --git a/packages/go_router/test/name_case_test.dart b/packages/go_router/test/name_case_test.dart index 672cdefdd2ce..84010a7e7307 100644 --- a/packages/go_router/test/name_case_test.dart +++ b/packages/go_router/test/name_case_test.dart @@ -12,19 +12,13 @@ void main() { final router = GoRouter( routes: [ GoRoute(path: '/', name: 'Name', builder: (_, __) => const ScreenA()), - GoRoute( - path: '/path', - name: 'name', - builder: (_, __) => const ScreenB(), - ), + GoRoute(path: '/path', name: 'name', builder: (_, __) => const ScreenB()), ], ); addTearDown(router.dispose); // run MaterialApp, initial screen path is '/' -> ScreenA - await tester.pumpWidget( - MaterialApp.router(routerConfig: router, title: 'GoRouter Testcase'), - ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router, title: 'GoRouter Testcase')); // go to ScreenB router.goNamed('name'); diff --git a/packages/go_router/test/on_enter_test.dart b/packages/go_router/test/on_enter_test.dart index 2fb09cc051f3..77d858b93ccf 100644 --- a/packages/go_router/test/on_enter_test.dart +++ b/packages/go_router/test/on_enter_test.dart @@ -18,27 +18,24 @@ void main() { return Future.delayed(Duration.zero).then((_) => router.dispose()); }); - testWidgets('Should set current/next state correctly', ( - WidgetTester tester, - ) async { + testWidgets('Should set current/next state correctly', (WidgetTester tester) async { GoRouterState? capturedCurrentState; GoRouterState? capturedNextState; var onEnterCallCount = 0; router = GoRouter( initialLocation: '/', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - onEnterCallCount++; - capturedCurrentState = current; - capturedNextState = next; - return const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + onEnterCallCount++; + capturedCurrentState = current; + capturedNextState = next; + return const Allow(); + }, routes: [ GoRoute( path: '/', @@ -58,27 +55,22 @@ void main() { expect(capturedCurrentState?.uri.path, capturedNextState?.uri.path); }); - testWidgets('Should block navigation when onEnter returns false', ( - WidgetTester tester, - ) async { + testWidgets('Should block navigation when onEnter returns false', (WidgetTester tester) async { final navigationAttempts = []; var currentPath = '/'; router = GoRouter( initialLocation: '/', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationAttempts.add(next.uri.path); - currentPath = current.uri.path; - return next.uri.path.contains('blocked') - ? const Block.stop() - : const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationAttempts.add(next.uri.path); + currentPath = current.uri.path; + return next.uri.path.contains('blocked') ? const Block.stop() : const Allow(); + }, routes: [ GoRoute( path: '/', @@ -96,75 +88,61 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); final GoRouteInformationParser parser = router.routeInformationParser; - final RouteMatchList beforeBlockedNav = - router.routerDelegate.currentConfiguration; + final RouteMatchList beforeBlockedNav = router.routerDelegate.currentConfiguration; // Try blocked route - final RouteMatchList blockedMatch = await parser - .parseRouteInformationWithDependencies( - RouteInformation( - uri: Uri.parse('/blocked'), - state: RouteInformationState(type: NavigatingType.go), - ), - context, - ); + final RouteMatchList blockedMatch = await parser.parseRouteInformationWithDependencies( + RouteInformation( + uri: Uri.parse('/blocked'), + state: RouteInformationState(type: NavigatingType.go), + ), + context, + ); await tester.pumpAndSettle(); - expect( - blockedMatch.uri.toString(), - equals(beforeBlockedNav.uri.toString()), - ); + expect(blockedMatch.uri.toString(), equals(beforeBlockedNav.uri.toString())); expect(currentPath, equals('/')); expect(navigationAttempts, contains('/blocked')); // Try allowed route - final RouteMatchList allowedMatch = await parser - .parseRouteInformationWithDependencies( - RouteInformation( - uri: Uri.parse('/allowed'), - state: RouteInformationState(type: NavigatingType.go), - ), - context, - ); + final RouteMatchList allowedMatch = await parser.parseRouteInformationWithDependencies( + RouteInformation( + uri: Uri.parse('/allowed'), + state: RouteInformationState(type: NavigatingType.go), + ), + context, + ); expect(allowedMatch.uri.path, equals('/allowed')); expect(navigationAttempts, contains('/allowed')); await tester.pumpAndSettle(); }); - testWidgets('Should allow navigation when onEnter returns true', ( - WidgetTester tester, - ) async { + testWidgets('Should allow navigation when onEnter returns true', (WidgetTester tester) async { var onEnterCallCount = 0; router = GoRouter( initialLocation: '/home', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - onEnterCallCount++; - return next.uri.path.contains('block') - ? const Block.stop() - : const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + onEnterCallCount++; + return next.uri.path.contains('block') ? const Block.stop() : const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), routes: [ GoRoute( path: 'allowed', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Allowed'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Allowed'))), ), GoRoute( path: 'block', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Blocked'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Blocked'))), ), ], ), @@ -189,121 +167,99 @@ void main() { expect(onEnterCallCount, greaterThan(0)); }); - testWidgets( - 'Should trigger onException when the redirection limit is exceeded', - (WidgetTester tester) async { - final completer = Completer(); - Object? capturedError; + testWidgets('Should trigger onException when the redirection limit is exceeded', ( + WidgetTester tester, + ) async { + final completer = Completer(); + Object? capturedError; - router = GoRouter( - initialLocation: '/start', - redirectLimit: 2, - onException: - (BuildContext context, GoRouterState state, GoRouter goRouter) { - capturedError = state.error; - goRouter.go('/fallback'); - completer.complete(); - }, - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - if (next.uri.path == '/recursive') { - return Block.then(() => goRouter.push('/recursive')); - } - return const Allow(); - }, - routes: [ - GoRoute( - path: '/start', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Start'))), - ), - GoRoute( - path: '/recursive', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Recursive'))), - ), - GoRoute( - path: '/fallback', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Fallback'))), - ), - ], - ); + router = GoRouter( + initialLocation: '/start', + redirectLimit: 2, + onException: (BuildContext context, GoRouterState state, GoRouter goRouter) { + capturedError = state.error; + goRouter.go('/fallback'); + completer.complete(); + }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + if (next.uri.path == '/recursive') { + return Block.then(() => goRouter.push('/recursive')); + } + return const Allow(); + }, + routes: [ + GoRoute( + path: '/start', + builder: (_, __) => const Scaffold(body: Center(child: Text('Start'))), + ), + GoRoute( + path: '/recursive', + builder: (_, __) => const Scaffold(body: Center(child: Text('Recursive'))), + ), + GoRoute( + path: '/fallback', + builder: (_, __) => const Scaffold(body: Center(child: Text('Fallback'))), + ), + ], + ); - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); - router.go('/recursive'); - await completer.future; - await tester.pumpAndSettle(); + router.go('/recursive'); + await completer.future; + await tester.pumpAndSettle(); - expect(capturedError, isNotNull); - expect( - capturedError.toString(), - contains('Too many onEnter calls detected'), - ); - expect(find.text('Fallback'), findsOneWidget); - }, - ); + expect(capturedError, isNotNull); + expect(capturedError.toString(), contains('Too many onEnter calls detected')); + expect(find.text('Fallback'), findsOneWidget); + }); - testWidgets('Should handle `go` usage in onEnter', ( - WidgetTester tester, - ) async { + testWidgets('Should handle `go` usage in onEnter', (WidgetTester tester) async { var isAuthenticatedResult = false; - Future isAuthenticated() => - Future.value(isAuthenticatedResult); + Future isAuthenticated() => Future.value(isAuthenticatedResult); final paramsSink = StreamController<({String current, String next})>(); - final Stream<({String current, String next})> paramsStream = paramsSink - .stream - .asBroadcastStream(); + final Stream<({String current, String next})> paramsStream = + paramsSink.stream.asBroadcastStream(); router = GoRouter( initialLocation: '/home', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - final bool isProtected = next.uri.toString().contains( - 'protected', - ); - paramsSink.add(( - current: current.uri.toString(), - next: next.uri.toString(), - )); - - if (!isProtected) { - return const Allow(); - } - if (await isAuthenticated()) { - return const Allow(); - } - return Block.then(() => router.go('/sign-in')); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + final bool isProtected = next.uri.toString().contains('protected'); + paramsSink.add((current: current.uri.toString(), next: next.uri.toString())); + + if (!isProtected) { + return const Allow(); + } + if (await isAuthenticated()) { + return const Allow(); + } + return Block.then(() => router.go('/sign-in')); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/protected', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Protected'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Protected'))), ), GoRoute( path: '/sign-in', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Sign-in'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Sign-in'))), ), ], ); @@ -333,65 +289,58 @@ void main() { await paramsSink.close(); }); - testWidgets('Should handle `goNamed` usage in onEnter', ( - WidgetTester tester, - ) async { + testWidgets('Should handle `goNamed` usage in onEnter', (WidgetTester tester) async { final navigationAttempts = []; router = GoRouter( initialLocation: '/home', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationAttempts.add(next.uri.path); - - if (next.uri.path == '/requires-auth') { - return Block.then( - () => goRouter.goNamed( - 'login-page', - queryParameters: { - 'from': next.uri.toString(), - }, - ), - ); - } - return const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationAttempts.add(next.uri.path); + + if (next.uri.path == '/requires-auth') { + return Block.then( + () => goRouter.goNamed( + 'login-page', + queryParameters: {'from': next.uri.toString()}, + ), + ); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/requires-auth', - builder: (_, __) => const Scaffold( - body: Center(child: Text('Authenticated Content')), - ), + builder: (_, __) => const Scaffold(body: Center(child: Text('Authenticated Content'))), ), GoRoute( path: '/login', name: 'login-page', - builder: (_, GoRouterState state) => Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - 'Login Page - From: ${state.uri.queryParameters['from'] ?? 'unknown'}', - ), - ElevatedButton( - onPressed: () => router.go('/home'), - child: const Text('Go Home'), + builder: + (_, GoRouterState state) => Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + 'Login Page - From: ${state.uri.queryParameters['from'] ?? 'unknown'}', + ), + ElevatedButton( + onPressed: () => router.go('/home'), + child: const Text('Go Home'), + ), + ], ), - ], + ), ), - ), - ), ), ], ); @@ -407,66 +356,55 @@ void main() { expect(find.text('Login Page - From: /requires-auth'), findsOneWidget); }); - testWidgets('Should handle `push` usage in onEnter', ( - WidgetTester tester, - ) async { + testWidgets('Should handle `push` usage in onEnter', (WidgetTester tester) async { const isAuthenticatedResult = false; - Future isAuthenticated() => - Future.value(isAuthenticatedResult); + Future isAuthenticated() => Future.value(isAuthenticatedResult); final paramsSink = StreamController<({String current, String next})>(); - final Stream<({String current, String next})> paramsStream = paramsSink - .stream - .asBroadcastStream(); + final Stream<({String current, String next})> paramsStream = + paramsSink.stream.asBroadcastStream(); router = GoRouter( initialLocation: '/home', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - final bool isProtected = next.uri.toString().contains( - 'protected', - ); - paramsSink.add(( - current: current.uri.toString(), - next: next.uri.toString(), - )); - if (!isProtected) { - return const Allow(); - } - if (await isAuthenticated()) { - return const Allow(); - } - await router.push('/sign-in').then((bool? isLoggedIn) { - if (isLoggedIn ?? false) { - router.go(next.uri.toString()); - } - }); + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + final bool isProtected = next.uri.toString().contains('protected'); + paramsSink.add((current: current.uri.toString(), next: next.uri.toString())); + if (!isProtected) { + return const Allow(); + } + if (await isAuthenticated()) { + return const Allow(); + } + await router.push('/sign-in').then((bool? isLoggedIn) { + if (isLoggedIn ?? false) { + router.go(next.uri.toString()); + } + }); - return const Block.stop(); - }, + return const Block.stop(); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/protected', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Protected'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Protected'))), ), GoRoute( path: '/sign-in', - builder: (_, __) => Scaffold( - appBar: AppBar(title: const Text('Sign in')), - body: const Center(child: Text('Sign-in')), - ), + builder: + (_, __) => Scaffold( + appBar: AppBar(title: const Text('Sign in')), + body: const Center(child: Text('Sign-in')), + ), ), ], ); @@ -495,44 +433,38 @@ void main() { await paramsSink.close(); }); - testWidgets('Should handle `replace` usage in onEnter', ( - WidgetTester tester, - ) async { + testWidgets('Should handle `replace` usage in onEnter', (WidgetTester tester) async { final navigationHistory = []; router = GoRouter( initialLocation: '/home', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationHistory.add('Entering: ${next.uri.path}'); - - if (next.uri.path == '/old-page') { - navigationHistory.add('Replacing with /new-version'); - await goRouter.replace('/new-version'); - return const Block.stop(); - } - return const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationHistory.add('Entering: ${next.uri.path}'); + + if (next.uri.path == '/old-page') { + navigationHistory.add('Replacing with /new-version'); + await goRouter.replace('/new-version'); + return const Block.stop(); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/old-page', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Old Page'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Old Page'))), ), GoRoute( path: '/new-version', - builder: (_, __) => - const Scaffold(body: Center(child: Text('New Version'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('New Version'))), ), ], ); @@ -555,57 +487,52 @@ void main() { expect(find.text('Home'), findsOneWidget); }); - testWidgets('Should handle `pushReplacement` usage in onEnter', ( - WidgetTester tester, - ) async { + testWidgets('Should handle `pushReplacement` usage in onEnter', (WidgetTester tester) async { final navigationLog = []; router = GoRouter( initialLocation: '/home', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - navigationLog.add('Entering: ${next.uri.path}'); - - if (next.uri.path == '/outdated') { - navigationLog.add('Push replacing with /updated'); - await goRouter.pushReplacement('/updated'); - return const Block.stop(); - } - return const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + navigationLog.add('Entering: ${next.uri.path}'); + + if (next.uri.path == '/outdated') { + navigationLog.add('Push replacing with /updated'); + await goRouter.pushReplacement('/updated'); + return const Block.stop(); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/outdated', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Outdated'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Outdated'))), ), GoRoute( path: '/updated', - builder: (_, __) => Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Updated'), - ElevatedButton( - onPressed: () => - router.go('/home'), // Use go instead of pop - child: const Text('Go Home'), + builder: + (_, __) => Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Updated'), + ElevatedButton( + onPressed: () => router.go('/home'), // Use go instead of pop + child: const Text('Go Home'), + ), + ], ), - ], + ), ), - ), - ), ), ], ); @@ -630,243 +557,225 @@ void main() { expect(find.text('Home'), findsOneWidget); }); - testWidgets( - 'onEnter should handle protected route redirection with query parameters', - (WidgetTester tester) async { - // Test setup - var isAuthenticatedResult = false; - Future isAuthenticated() => - Future.value(isAuthenticatedResult); - - // Stream to capture onEnter calls - final paramsSink = StreamController<({String current, String next})>(); - // Use broadcast stream for potentially multiple listeners/expects if needed, - // although expectLater handles one listener well. - final Stream<({String current, String next})> paramsStream = paramsSink - .stream - .asBroadcastStream(); - - // Helper to navigate after sign-in button press - void goToRedirect(GoRouter router, GoRouterState state) { - final String? redirect = state.uri.queryParameters['redirectTo']; - // Use null check and Uri.tryParse for safety - if (redirect != null && Uri.tryParse(redirect) != null) { - // Decode potentially encoded URI component - router.go(Uri.decodeComponent(redirect)); - } else { - // Fallback if redirectTo is missing or invalid - router.go('/home'); - } - } - - router = GoRouter( - initialLocation: '/home', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - // Renamed parameter to avoid shadowing router variable - ) async { - // Log the navigation attempt state URIs - paramsSink.add(( - current: current.uri.toString(), - next: next.uri.toString(), - )); - - final isNavigatingToProtected = next.uri.path == '/protected'; - - // Allow navigation if not going to the protected route - if (!isNavigatingToProtected) { - return const Allow(); - } - - // Allow navigation if authenticated - if (await isAuthenticated()) { - return const Allow(); - } - - // If unauthenticated and going to protected route: - // 1. Redirect to sign-in using pushNamed, passing the intended destination - await goRouter.pushNamed( - 'sign-in', // Return type likely void or not needed - queryParameters: { - 'redirectTo': next.uri.toString(), // Pass the full next URI - }, - ); - // 2. Block the original navigation to '/protected' - return const Block.stop(); - }, - routes: [ - GoRoute( - path: '/home', - name: 'home', // Good practice to name routes - builder: (_, __) => const Scaffold( - body: Center(child: Text('Home Screen')), - ), // Unique text - ), - GoRoute( - path: '/protected', - name: 'protected', // Good practice to name routes - builder: (_, __) => const Scaffold( - body: Center(child: Text('Protected Screen')), - ), // Unique text - ), - GoRoute( - path: '/sign-in', - name: 'sign-in', - builder: (_, GoRouterState state) => Scaffold( - appBar: AppBar( - title: const Text('Sign In Screen Title'), // Unique text - ), - body: Center( - child: ElevatedButton( - child: const Text('Sign In Button'), // Unique text - onPressed: () => goToRedirect(router, state), - ), - ), - ), - ), - ], - ); - - // Expect the stream of onEnter calls to emit events in this specific order - // We use unawaited because expectLater returns a Future that completes - // when the expectation is met or fails, but we want the test execution - // (pumping widgets, triggering actions) to proceed concurrently. - unawaited( - expectLater( - paramsStream, - emitsInOrder([ - // 1. Initial Load to '/home' - equals((current: '/home', next: '/home')), - // 2. Attempt go('/protected') -> onEnter blocks - equals((current: '/home', next: '/protected')), - // 3. onEnter runs for the push('/sign-in?redirectTo=...') triggered internally - equals(( - current: '/home', - next: '/sign-in?redirectTo=%2Fprotected', - )), - // 4. Tap button -> go('/protected') -> onEnter allows access - equals(( - current: - // State when button is tapped - '/sign-in?redirectTo=%2Fprotected', - // Target of the 'go' call - next: '/protected', - )), - ]), - ), - ); - - // Initial widget pump - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - // Let initial navigation and builds complete - await tester.pumpAndSettle(); - // Verify initial screen - expect(find.text('Home Screen'), findsOneWidget); - - // Trigger navigation to protected route (user is not authenticated) - router.go('/protected'); - // Allow navigation/redirection to complete - await tester.pumpAndSettle(); - - // Verify state after redirection to sign-in - expect( - router.state.uri.toString(), - equals('/sign-in?redirectTo=%2Fprotected'), - ); - // Verify app bar title - expect(find.text('Sign In Screen Title'), findsOneWidget); - // Verify button exists - expect( - find.widgetWithText(ElevatedButton, 'Sign In Button'), - findsOneWidget, - ); - // BackButton appears because sign-in was pushed onto the stack - expect(find.byType(BackButton), findsOneWidget); - - // Simulate successful authentication - isAuthenticatedResult = true; - - // Trigger navigation back to protected route by tapping the sign-in button - await tester.tap(find.widgetWithText(ElevatedButton, 'Sign In Button')); - // Allow navigation to protected route to complete - await tester.pumpAndSettle(); - - // Verify final state - expect(router.state.uri.toString(), equals('/protected')); - // Verify final screen - expect(find.text('Protected Screen'), findsOneWidget); - // Verify sign-in screen is gone - expect(find.text('Sign In Screen Title'), findsNothing); - - // Close the stream controller - await paramsSink.close(); - }, - ); - - testWidgets('Should handle sequential navigation steps in onEnter', ( + testWidgets('onEnter should handle protected route redirection with query parameters', ( WidgetTester tester, ) async { - final navigationChain = []; - final navigationComplete = Completer(); + // Test setup + var isAuthenticatedResult = false; + Future isAuthenticated() => Future.value(isAuthenticatedResult); + + // Stream to capture onEnter calls + final paramsSink = StreamController<({String current, String next})>(); + // Use broadcast stream for potentially multiple listeners/expects if needed, + // although expectLater handles one listener well. + final Stream<({String current, String next})> paramsStream = + paramsSink.stream.asBroadcastStream(); + + // Helper to navigate after sign-in button press + void goToRedirect(GoRouter router, GoRouterState state) { + final String? redirect = state.uri.queryParameters['redirectTo']; + // Use null check and Uri.tryParse for safety + if (redirect != null && Uri.tryParse(redirect) != null) { + // Decode potentially encoded URI component + router.go(Uri.decodeComponent(redirect)); + } else { + // Fallback if redirectTo is missing or invalid + router.go('/home'); + } + } router = GoRouter( - initialLocation: '/start', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - final String targetPath = next.uri.path; - navigationChain.add('Entering: $targetPath'); - - // Execute a simpler navigation sequence - if (targetPath == '/multi-step') { - // Step 1: Go to a different route - navigationChain.add('Step 1: Go to /step-one'); - // We're blocking the original navigation and deferring the go - return Block.then(() => goRouter.go('/step-one')); - } + initialLocation: '/home', + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + // Renamed parameter to avoid shadowing router variable + ) async { + // Log the navigation attempt state URIs + paramsSink.add((current: current.uri.toString(), next: next.uri.toString())); + + final isNavigatingToProtected = next.uri.path == '/protected'; + + // Allow navigation if not going to the protected route + if (!isNavigatingToProtected) { + return const Allow(); + } - // When we reach step-one, mark test as complete - if (targetPath == '/step-one') { - navigationComplete.complete(); - } + // Allow navigation if authenticated + if (await isAuthenticated()) { + return const Allow(); + } - return const Allow(); + // If unauthenticated and going to protected route: + // 1. Redirect to sign-in using pushNamed, passing the intended destination + await goRouter.pushNamed( + 'sign-in', // Return type likely void or not needed + queryParameters: { + 'redirectTo': next.uri.toString(), // Pass the full next URI }, + ); + // 2. Block the original navigation to '/protected' + return const Block.stop(); + }, routes: [ GoRoute( - path: '/start', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Start'))), + path: '/home', + name: 'home', // Good practice to name routes + builder: + (_, __) => const Scaffold(body: Center(child: Text('Home Screen'))), // Unique text ), GoRoute( - path: '/multi-step', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Multi Step'))), + path: '/protected', + name: 'protected', // Good practice to name routes + builder: + (_, __) => + const Scaffold(body: Center(child: Text('Protected Screen'))), // Unique text ), GoRoute( - path: '/step-one', - builder: (_, __) => Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Step One'), - ElevatedButton( - onPressed: () => router.go('/start'), - child: const Text('Go Back to Start'), - ), - ], + path: '/sign-in', + name: 'sign-in', + builder: + (_, GoRouterState state) => Scaffold( + appBar: AppBar( + title: const Text('Sign In Screen Title'), // Unique text + ), + body: Center( + child: ElevatedButton( + child: const Text('Sign In Button'), // Unique text + onPressed: () => goToRedirect(router, state), + ), + ), + ), + ), + ], + ); + + // Expect the stream of onEnter calls to emit events in this specific order + // We use unawaited because expectLater returns a Future that completes + // when the expectation is met or fails, but we want the test execution + // (pumping widgets, triggering actions) to proceed concurrently. + unawaited( + expectLater( + paramsStream, + emitsInOrder([ + // 1. Initial Load to '/home' + equals((current: '/home', next: '/home')), + // 2. Attempt go('/protected') -> onEnter blocks + equals((current: '/home', next: '/protected')), + // 3. onEnter runs for the push('/sign-in?redirectTo=...') triggered internally + equals((current: '/home', next: '/sign-in?redirectTo=%2Fprotected')), + // 4. Tap button -> go('/protected') -> onEnter allows access + equals(( + current: + // State when button is tapped + '/sign-in?redirectTo=%2Fprotected', + // Target of the 'go' call + next: '/protected', + )), + ]), + ), + ); + + // Initial widget pump + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + // Let initial navigation and builds complete + await tester.pumpAndSettle(); + // Verify initial screen + expect(find.text('Home Screen'), findsOneWidget); + + // Trigger navigation to protected route (user is not authenticated) + router.go('/protected'); + // Allow navigation/redirection to complete + await tester.pumpAndSettle(); + + // Verify state after redirection to sign-in + expect(router.state.uri.toString(), equals('/sign-in?redirectTo=%2Fprotected')); + // Verify app bar title + expect(find.text('Sign In Screen Title'), findsOneWidget); + // Verify button exists + expect(find.widgetWithText(ElevatedButton, 'Sign In Button'), findsOneWidget); + // BackButton appears because sign-in was pushed onto the stack + expect(find.byType(BackButton), findsOneWidget); + + // Simulate successful authentication + isAuthenticatedResult = true; + + // Trigger navigation back to protected route by tapping the sign-in button + await tester.tap(find.widgetWithText(ElevatedButton, 'Sign In Button')); + // Allow navigation to protected route to complete + await tester.pumpAndSettle(); + + // Verify final state + expect(router.state.uri.toString(), equals('/protected')); + // Verify final screen + expect(find.text('Protected Screen'), findsOneWidget); + // Verify sign-in screen is gone + expect(find.text('Sign In Screen Title'), findsNothing); + + // Close the stream controller + await paramsSink.close(); + }); + + testWidgets('Should handle sequential navigation steps in onEnter', ( + WidgetTester tester, + ) async { + final navigationChain = []; + final navigationComplete = Completer(); + + router = GoRouter( + initialLocation: '/start', + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + final String targetPath = next.uri.path; + navigationChain.add('Entering: $targetPath'); + + // Execute a simpler navigation sequence + if (targetPath == '/multi-step') { + // Step 1: Go to a different route + navigationChain.add('Step 1: Go to /step-one'); + // We're blocking the original navigation and deferring the go + return Block.then(() => goRouter.go('/step-one')); + } + + // When we reach step-one, mark test as complete + if (targetPath == '/step-one') { + navigationComplete.complete(); + } + + return const Allow(); + }, + routes: [ + GoRoute( + path: '/start', + builder: (_, __) => const Scaffold(body: Center(child: Text('Start'))), + ), + GoRoute( + path: '/multi-step', + builder: (_, __) => const Scaffold(body: Center(child: Text('Multi Step'))), + ), + GoRoute( + path: '/step-one', + builder: + (_, __) => Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Step One'), + ElevatedButton( + onPressed: () => router.go('/start'), + child: const Text('Go Back to Start'), + ), + ], + ), + ), ), - ), - ), ), ], ); @@ -908,37 +817,33 @@ void main() { // to avoid triggering the exception when navigating to the fallback route. router = GoRouter( initialLocation: '/error', - onException: - (BuildContext context, GoRouterState state, GoRouter goRouter) { - capturedError = state.error; - // Navigate to a safe fallback route. - goRouter.go('/fallback'); - completer.complete(); - }, - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - // If the navigation target is '/fallback', allow it without throwing. - if (next.uri.path == '/fallback') { - return const Allow(); - } - // For any other target, throw an exception. - throw Exception('onEnter error triggered'); - }, + onException: (BuildContext context, GoRouterState state, GoRouter goRouter) { + capturedError = state.error; + // Navigate to a safe fallback route. + goRouter.go('/fallback'); + completer.complete(); + }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + // If the navigation target is '/fallback', allow it without throwing. + if (next.uri.path == '/fallback') { + return const Allow(); + } + // For any other target, throw an exception. + throw Exception('onEnter error triggered'); + }, routes: [ GoRoute( path: '/error', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Error Page'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Error Page'))), ), GoRoute( path: '/fallback', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Fallback Page'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Fallback Page'))), ), ], ); @@ -959,9 +864,7 @@ void main() { expect(find.text('Fallback Page'), findsOneWidget); }); - testWidgets('onEnter has priority over deprecated redirect', ( - WidgetTester tester, - ) async { + testWidgets('onEnter has priority over deprecated redirect', (WidgetTester tester) async { var redirectCallCount = 0; var onEnterCallCount = 0; var lastOnEnterBlocked = false; @@ -1032,10 +935,7 @@ void main() { routes: [ GoRoute(path: '/page1', builder: (_, __) => const Text('Page 1')), GoRoute(path: '/page2', builder: (_, __) => const Text('Page 2')), - GoRoute( - path: '/protected', - builder: (_, __) => const Text('Protected'), - ), + GoRoute(path: '/protected', builder: (_, __) => const Text('Protected')), ], onEnter: (_, GoRouterState current, GoRouterState next, ___) async { capturedCurrentPath = current.uri.path; @@ -1070,9 +970,7 @@ void main() { expect(capturedNextPath, equals('/protected')); }); - testWidgets('pop does not call onEnter but restore does', ( - WidgetTester tester, - ) async { + testWidgets('pop does not call onEnter but restore does', (WidgetTester tester) async { var onEnterCount = 0; router = GoRouter( @@ -1086,10 +984,7 @@ void main() { path: '/a', builder: (_, __) => const Scaffold(body: Text('A')), routes: [ - GoRoute( - path: 'b', - builder: (_, __) => const Scaffold(body: Text('B')), - ), + GoRoute(path: 'b', builder: (_, __) => const Scaffold(body: Text('B'))), ], ), ], @@ -1114,9 +1009,7 @@ void main() { // Explicit restore would call onEnter (tested separately in integration) }); - testWidgets('restore navigation calls onEnter for re-validation', ( - WidgetTester tester, - ) async { + testWidgets('restore navigation calls onEnter for re-validation', (WidgetTester tester) async { var onEnterCount = 0; var allowNavigation = true; @@ -1131,14 +1024,8 @@ void main() { return const Allow(); }, routes: [ - GoRoute( - path: '/home', - builder: (_, __) => const Scaffold(body: Text('Home')), - ), - GoRoute( - path: '/protected', - builder: (_, __) => const Scaffold(body: Text('Protected')), - ), + GoRoute(path: '/home', builder: (_, __) => const Scaffold(body: Text('Home'))), + GoRoute(path: '/protected', builder: (_, __) => const Scaffold(body: Text('Protected'))), ], ); @@ -1157,17 +1044,16 @@ void main() { final GoRouteInformationParser parser = router.routeInformationParser; // Create a restore navigation to protected route - final RouteMatchList restoredMatch = await parser - .parseRouteInformationWithDependencies( - RouteInformation( - uri: Uri.parse('/protected'), - state: RouteInformationState( - type: NavigatingType.restore, - baseRouteMatchList: router.routerDelegate.currentConfiguration, - ), - ), - context, - ); + final RouteMatchList restoredMatch = await parser.parseRouteInformationWithDependencies( + RouteInformation( + uri: Uri.parse('/protected'), + state: RouteInformationState( + type: NavigatingType.restore, + baseRouteMatchList: router.routerDelegate.currentConfiguration, + ), + ), + context, + ); // onEnter should be called again for restore expect(onEnterCount, 3); @@ -1175,17 +1061,16 @@ void main() { // Now simulate session expired - block on restore allowNavigation = false; - final RouteMatchList blockedRestore = await parser - .parseRouteInformationWithDependencies( - RouteInformation( - uri: Uri.parse('/protected'), - state: RouteInformationState( - type: NavigatingType.restore, - baseRouteMatchList: router.routerDelegate.currentConfiguration, - ), - ), - context, - ); + final RouteMatchList blockedRestore = await parser.parseRouteInformationWithDependencies( + RouteInformation( + uri: Uri.parse('/protected'), + state: RouteInformationState( + type: NavigatingType.restore, + baseRouteMatchList: router.routerDelegate.currentConfiguration, + ), + ), + context, + ); // onEnter called again but blocks this time expect(onEnterCount, 4); @@ -1193,49 +1078,42 @@ void main() { expect(blockedRestore.uri.path, equals('/protected')); }); - testWidgets( - 'goNamed supports fragment (hash) and preserves it in state.uri', - (WidgetTester tester) async { - router = GoRouter( - initialLocation: '/', - routes: [ - GoRoute( - path: '/', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Root'))), - ), - GoRoute( - path: '/article/:id', - name: 'article', - builder: (_, GoRouterState state) { - return Scaffold( - body: Center( - child: Text( - 'article=${state.pathParameters['id']};frag=${state.uri.fragment}', - ), - ), - ); - }, - ), - ], - ); + testWidgets('goNamed supports fragment (hash) and preserves it in state.uri', ( + WidgetTester tester, + ) async { + router = GoRouter( + initialLocation: '/', + routes: [ + GoRoute(path: '/', builder: (_, __) => const Scaffold(body: Center(child: Text('Root')))), + GoRoute( + path: '/article/:id', + name: 'article', + builder: (_, GoRouterState state) { + return Scaffold( + body: Center( + child: Text('article=${state.pathParameters['id']};frag=${state.uri.fragment}'), + ), + ); + }, + ), + ], + ); - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); - // Navigate with a fragment - router.goNamed( - 'article', - pathParameters: {'id': '42'}, - fragment: 'section-2', - ); - await tester.pumpAndSettle(); + // Navigate with a fragment + router.goNamed( + 'article', + pathParameters: {'id': '42'}, + fragment: 'section-2', + ); + await tester.pumpAndSettle(); - expect(router.state.uri.path, '/article/42'); - expect(router.state.uri.fragment, 'section-2'); - expect(find.text('article=42;frag=section-2'), findsOneWidget); - }, - ); + expect(router.state.uri.path, '/article/42'); + expect(router.state.uri.fragment, 'section-2'); + expect(find.text('article=42;frag=section-2'), findsOneWidget); + }); testWidgets('relative "./" navigation resolves against current location', ( WidgetTester tester, @@ -1245,13 +1123,11 @@ void main() { routes: [ GoRoute( path: '/parent', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Parent'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Parent'))), routes: [ GoRoute( path: 'child', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Child'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Child'))), ), ], ), @@ -1278,22 +1154,17 @@ void main() { router = GoRouter( initialLocation: '/', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - seenNextPaths.add(next.uri.path); - return const Allow(); // don't block; let route-level redirect run - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + seenNextPaths.add(next.uri.path); + return const Allow(); // don't block; let route-level redirect run + }, routes: [ - GoRoute( - path: '/', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Root'))), - ), + GoRoute(path: '/', builder: (_, __) => const Scaffold(body: Center(child: Text('Root')))), GoRoute( path: '/old', builder: (_, __) => const SizedBox.shrink(), @@ -1302,8 +1173,7 @@ void main() { ), GoRoute( path: '/new', - builder: (_, __) => - const Scaffold(body: Center(child: Text('New'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('New'))), ), ], ); @@ -1323,61 +1193,55 @@ void main() { expect(find.text('New'), findsOneWidget); }); - testWidgets( - 'Allow(then) error is reported but does not revert navigation', - (WidgetTester tester) async { - // Capture FlutterError.reportError calls - FlutterErrorDetails? reported; - final void Function(FlutterErrorDetails)? oldHandler = - FlutterError.onError; - FlutterError.onError = (FlutterErrorDetails details) { - reported = details; - }; - addTearDown(() => FlutterError.onError = oldHandler); + testWidgets('Allow(then) error is reported but does not revert navigation', ( + WidgetTester tester, + ) async { + // Capture FlutterError.reportError calls + FlutterErrorDetails? reported; + final void Function(FlutterErrorDetails)? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + reported = details; + }; + addTearDown(() => FlutterError.onError = oldHandler); - router = GoRouter( - initialLocation: '/home', - onEnter: (_, __, GoRouterState next, ___) async { - if (next.uri.path == '/boom') { - // Allow, but run a failing "then" callback - return Allow(then: () => throw StateError('then blew up')); - } - return const Allow(); - }, - routes: [ - GoRoute( - path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), - ), - GoRoute( - path: '/boom', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Boom'))), - ), - ], - ); + router = GoRouter( + initialLocation: '/home', + onEnter: (_, __, GoRouterState next, ___) async { + if (next.uri.path == '/boom') { + // Allow, but run a failing "then" callback + return Allow(then: () => throw StateError('then blew up')); + } + return const Allow(); + }, + routes: [ + GoRoute( + path: '/home', + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), + ), + GoRoute( + path: '/boom', + builder: (_, __) => const Scaffold(body: Center(child: Text('Boom'))), + ), + ], + ); - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); - expect(find.text('Home'), findsOneWidget); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); - router.go('/boom'); - await tester.pumpAndSettle(); // commits nav + runs deferred microtask + router.go('/boom'); + await tester.pumpAndSettle(); // commits nav + runs deferred microtask - // Navigation should be committed - expect(router.state.uri.path, equals('/boom')); - expect(find.text('Boom'), findsOneWidget); + // Navigation should be committed + expect(router.state.uri.path, equals('/boom')); + expect(find.text('Boom'), findsOneWidget); - // Error from deferred callback should be reported (but not crash) - expect(reported, isNotNull); - expect(reported!.exception.toString(), contains('then blew up')); - }, - ); + // Error from deferred callback should be reported (but not crash) + expect(reported, isNotNull); + expect(reported!.exception.toString(), contains('then blew up')); + }); - testWidgets('Hard-stop vs chaining resets onEnter history', ( - WidgetTester tester, - ) async { + testWidgets('Hard-stop vs chaining resets onEnter history', (WidgetTester tester) async { // With redirectLimit=1: // - Block.stop() resets history so repeated attempts don't hit the limit. // - Block.then(() => go(...)) keeps history and will exceed the limit. @@ -1407,18 +1271,15 @@ void main() { routes: [ GoRoute( path: '/start', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Start'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Start'))), ), GoRoute( path: '/blocked-once', - builder: (_, __) => - const Scaffold(body: Center(child: Text('BlockedOnce'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('BlockedOnce'))), ), GoRoute( path: '/chain', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Chain'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Chain'))), ), ], ); @@ -1456,10 +1317,7 @@ void main() { router = GoRouter( initialLocation: '/home', routes: [ - GoRoute( - path: '/home', - builder: (_, __) => const Scaffold(body: Text('Home')), - ), + GoRoute(path: '/home', builder: (_, __) => const Scaffold(body: Text('Home'))), GoRoute( path: '/has-route-redirect', builder: (_, __) => const Scaffold(body: Text('Never shown')), @@ -1492,10 +1350,7 @@ void main() { await tester.pumpAndSettle(); // Verify execution order: onEnter -> legacy -> route-level - expect( - calls, - containsAllInOrder(['onEnter', 'legacy', 'route-level']), - ); + expect(calls, containsAllInOrder(['onEnter', 'legacy', 'route-level'])); expect(router.state.uri.path, '/redirected'); expect(find.text('Redirected'), findsOneWidget); @@ -1518,37 +1373,92 @@ void main() { ); // Verify restore also follows same order - expect( - calls, - containsAllInOrder(['onEnter', 'legacy', 'route-level']), + expect(calls, containsAllInOrder(['onEnter', 'legacy', 'route-level'])); + }); + testWidgets('onEnter blocking prevents stale state restoration (pop case)', ( + WidgetTester tester, + ) async { + // This test reproduces https://github.com/flutter/flutter/issues/178853 + // 1. Push A -> B + // 2. Pop B -> A (simulating system back) + // 3. Go A -> Blocked + // 4. onEnter blocks + // 5. Ensure we stay on A and don't "restore" B (stale state) + + router = GoRouter( + initialLocation: '/home', + onEnter: + (_, __, GoRouterState next, ___) => + next.uri.path == '/blocked' ? const Block.stop() : const Allow(), + routes: [ + GoRoute(path: '/home', builder: (_, __) => const Scaffold(body: Text('Home'))), + GoRoute(path: '/allowed', builder: (_, __) => const Scaffold(body: Text('Allowed'))), + GoRoute(path: '/blocked', builder: (_, __) => const Scaffold(body: Text('Blocked'))), + ], ); + + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); + + // 1. Push allowed + router.push('/allowed'); + await tester.pumpAndSettle(); + expect(find.text('Allowed'), findsOneWidget); + + // 2. Pop (simulating system back / imperative pop) + final NavigatorState navigator = tester.state(find.byType(Navigator).last); + navigator.pop(); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); + + // 3. Attempt blocked navigation + router.go('/blocked'); + await tester.pumpAndSettle(); + + // 4. Verify blocking worked + expect(find.text('Blocked'), findsNothing); + + // 5. Verify we didn't restore the popped route (Allowed) + expect(find.text('Allowed'), findsNothing); + expect(find.text('Home'), findsOneWidget); }); - testWidgets( - 'onEnter blocking prevents stale state restoration (pop case)', - (WidgetTester tester) async { - // This test reproduces https://github.com/flutter/flutter/issues/178853 - // 1. Push A -> B - // 2. Pop B -> A (simulating system back) - // 3. Go A -> Blocked - // 4. onEnter blocks - // 5. Ensure we stay on A and don't "restore" B (stale state) + + group('with refreshListenable', () { + testWidgets('Block.then(router.go) navigates after refreshListenable fires', ( + WidgetTester tester, + ) async { + final isAuthenticated = ValueNotifier(true); + addTearDown(isAuthenticated.dispose); router = GoRouter( initialLocation: '/home', - onEnter: (_, __, GoRouterState next, ___) => - next.uri.path == '/blocked' ? const Block.stop() : const Allow(), + refreshListenable: isAuthenticated, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) { + // Public routes — always allow + if (next.uri.path == '/login') { + return const Allow(); + } + + // Protected routes — require auth + if (!isAuthenticated.value) { + return Block.then(() => goRouter.go('/login')); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => const Scaffold(body: Text('Home')), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( - path: '/allowed', - builder: (_, __) => const Scaffold(body: Text('Allowed')), - ), - GoRoute( - path: '/blocked', - builder: (_, __) => const Scaffold(body: Text('Blocked')), + path: '/login', + builder: (_, __) => const Scaffold(body: Center(child: Text('Login'))), ), ], ); @@ -1557,140 +1467,63 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Home'), findsOneWidget); - // 1. Push allowed - router.push('/allowed'); - await tester.pumpAndSettle(); - expect(find.text('Allowed'), findsOneWidget); - - // 2. Pop (simulating system back / imperative pop) - final NavigatorState navigator = tester.state( - find.byType(Navigator).last, - ); - navigator.pop(); - await tester.pumpAndSettle(); - expect(find.text('Home'), findsOneWidget); - - // 3. Attempt blocked navigation - router.go('/blocked'); + // Toggle auth off — refreshListenable fires, guard blocks and + // calls router.go('/login') in Block.then callback. + isAuthenticated.value = false; await tester.pumpAndSettle(); - // 4. Verify blocking worked - expect(find.text('Blocked'), findsNothing); - - // 5. Verify we didn't restore the popped route (Allowed) - expect(find.text('Allowed'), findsNothing); - expect(find.text('Home'), findsOneWidget); - }, - ); - - group('with refreshListenable', () { - testWidgets( - 'Block.then(router.go) navigates after refreshListenable fires', - (WidgetTester tester) async { - final isAuthenticated = ValueNotifier(true); - addTearDown(isAuthenticated.dispose); - - router = GoRouter( - initialLocation: '/home', - refreshListenable: isAuthenticated, - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) { - // Public routes — always allow - if (next.uri.path == '/login') { - return const Allow(); - } - - // Protected routes — require auth - if (!isAuthenticated.value) { - return Block.then(() => goRouter.go('/login')); - } - return const Allow(); - }, - routes: [ - GoRoute( - path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), - ), - GoRoute( - path: '/login', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Login'))), - ), - ], - ); - - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); - expect(find.text('Home'), findsOneWidget); - - // Toggle auth off — refreshListenable fires, guard blocks and - // calls router.go('/login') in Block.then callback. - isAuthenticated.value = false; - await tester.pumpAndSettle(); + // The callback navigation must commit. + expect(router.state.uri.path, equals('/login')); + expect(find.text('Login'), findsOneWidget); + }); - // The callback navigation must commit. - expect(router.state.uri.path, equals('/login')); - expect(find.text('Login'), findsOneWidget); - }, - ); + testWidgets('Block.then(router.goNamed) navigates after refreshListenable fires', ( + WidgetTester tester, + ) async { + final isAuthenticated = ValueNotifier(true); + addTearDown(isAuthenticated.dispose); - testWidgets( - 'Block.then(router.goNamed) navigates after refreshListenable fires', - (WidgetTester tester) async { - final isAuthenticated = ValueNotifier(true); - addTearDown(isAuthenticated.dispose); + router = GoRouter( + initialLocation: '/home', + refreshListenable: isAuthenticated, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) { + if (next.uri.path == '/login') { + return const Allow(); + } - router = GoRouter( - initialLocation: '/home', - refreshListenable: isAuthenticated, - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) { - if (next.uri.path == '/login') { - return const Allow(); - } - - if (!isAuthenticated.value) { - return Block.then(() => goRouter.goNamed('login')); - } - return const Allow(); - }, - routes: [ - GoRoute( - path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), - ), - GoRoute( - path: '/login', - name: 'login', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Login'))), - ), - ], - ); + if (!isAuthenticated.value) { + return Block.then(() => goRouter.goNamed('login')); + } + return const Allow(); + }, + routes: [ + GoRoute( + path: '/home', + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), + ), + GoRoute( + path: '/login', + name: 'login', + builder: (_, __) => const Scaffold(body: Center(child: Text('Login'))), + ), + ], + ); - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); - expect(find.text('Home'), findsOneWidget); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); - isAuthenticated.value = false; - await tester.pumpAndSettle(); + isAuthenticated.value = false; + await tester.pumpAndSettle(); - expect(router.state.uri.path, equals('/login')); - expect(find.text('Login'), findsOneWidget); - }, - ); + expect(router.state.uri.path, equals('/login')); + expect(find.text('Login'), findsOneWidget); + }); testWidgets( 'Block.then(router.go) navigates after multiple rapid refreshListenable emissions', @@ -1701,32 +1534,29 @@ void main() { router = GoRouter( initialLocation: '/home', refreshListenable: authState, - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) { - if (next.uri.path == '/login') { - return const Allow(); - } - - if (authState.value > 2) { - return Block.then(() => goRouter.go('/login')); - } - return const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) { + if (next.uri.path == '/login') { + return const Allow(); + } + + if (authState.value > 2) { + return Block.then(() => goRouter.go('/login')); + } + return const Allow(); + }, routes: [ GoRoute( path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), ), GoRoute( path: '/login', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Login'))), + builder: (_, __) => const Scaffold(body: Center(child: Text('Login'))), ), ], ); @@ -1746,107 +1576,99 @@ void main() { }, ); - testWidgets( - 'Allow.then(router.go) navigates after refreshListenable fires', - (WidgetTester tester) async { - final shouldRedirect = ValueNotifier(false); - addTearDown(shouldRedirect.dispose); + testWidgets('Allow.then(router.go) navigates after refreshListenable fires', ( + WidgetTester tester, + ) async { + final shouldRedirect = ValueNotifier(false); + addTearDown(shouldRedirect.dispose); - router = GoRouter( - initialLocation: '/home', - refreshListenable: shouldRedirect, - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) { - if (next.uri.path == '/dashboard') { - return const Allow(); - } - - if (shouldRedirect.value && next.uri.path == '/home') { - return Allow(then: () => goRouter.go('/dashboard')); - } - return const Allow(); - }, - routes: [ - GoRoute( - path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), - ), - GoRoute( - path: '/dashboard', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Dashboard'))), - ), - ], - ); + router = GoRouter( + initialLocation: '/home', + refreshListenable: shouldRedirect, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) { + if (next.uri.path == '/dashboard') { + return const Allow(); + } - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); - expect(find.text('Home'), findsOneWidget); + if (shouldRedirect.value && next.uri.path == '/home') { + return Allow(then: () => goRouter.go('/dashboard')); + } + return const Allow(); + }, + routes: [ + GoRoute( + path: '/home', + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), + ), + GoRoute( + path: '/dashboard', + builder: (_, __) => const Scaffold(body: Center(child: Text('Dashboard'))), + ), + ], + ); - shouldRedirect.value = true; - await tester.pumpAndSettle(); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); - expect(router.state.uri.path, equals('/dashboard')); - expect(find.text('Dashboard'), findsOneWidget); - }, - ); + shouldRedirect.value = true; + await tester.pumpAndSettle(); - testWidgets( - 'Block.then error is reported after refreshListenable fires', - (WidgetTester tester) async { - final trigger = ValueNotifier(false); - addTearDown(trigger.dispose); + expect(router.state.uri.path, equals('/dashboard')); + expect(find.text('Dashboard'), findsOneWidget); + }); - FlutterErrorDetails? reported; - final void Function(FlutterErrorDetails)? oldHandler = - FlutterError.onError; - FlutterError.onError = (FlutterErrorDetails details) { - reported = details; - }; - addTearDown(() => FlutterError.onError = oldHandler); + testWidgets('Block.then error is reported after refreshListenable fires', ( + WidgetTester tester, + ) async { + final trigger = ValueNotifier(false); + addTearDown(trigger.dispose); - router = GoRouter( - initialLocation: '/home', - refreshListenable: trigger, - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) { - if (trigger.value && next.uri.path == '/home') { - return Block.then(() => throw StateError('callback error')); - } - return const Allow(); - }, - routes: [ - GoRoute( - path: '/home', - builder: (_, __) => - const Scaffold(body: Center(child: Text('Home'))), - ), - ], - ); + FlutterErrorDetails? reported; + final void Function(FlutterErrorDetails)? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + reported = details; + }; + addTearDown(() => FlutterError.onError = oldHandler); - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); - expect(find.text('Home'), findsOneWidget); + router = GoRouter( + initialLocation: '/home', + refreshListenable: trigger, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) { + if (trigger.value && next.uri.path == '/home') { + return Block.then(() => throw StateError('callback error')); + } + return const Allow(); + }, + routes: [ + GoRoute( + path: '/home', + builder: (_, __) => const Scaffold(body: Center(child: Text('Home'))), + ), + ], + ); - trigger.value = true; - await tester.pumpAndSettle(); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); - // Error should be reported (not swallowed) - expect(reported, isNotNull); - expect(reported!.exception.toString(), contains('callback error')); - }, - ); + trigger.value = true; + await tester.pumpAndSettle(); + + // Error should be reported (not swallowed) + expect(reported, isNotNull); + expect(reported!.exception.toString(), contains('callback error')); + }); }); // Tests for onEnter interaction with chained redirects. @@ -1866,16 +1688,15 @@ void main() { router = GoRouter( initialLocation: '/', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - onEnterCallCount++; - return const Allow(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + onEnterCallCount++; + return const Allow(); + }, redirect: (BuildContext context, GoRouterState state) { redirectCallCount++; if (state.matchedLocation == '/') { @@ -1905,86 +1726,77 @@ void main() { expect(redirectCallCount, 3); }); - testWidgets( - 'onEnter called once when route-level triggers top-level redirect', - (WidgetTester tester) async { - // Route-level on /src: /src -> /dst - // Top-level: /dst -> /final - // onEnter should be called exactly once. - var onEnterCallCount = 0; + testWidgets('onEnter called once when route-level triggers top-level redirect', ( + WidgetTester tester, + ) async { + // Route-level on /src: /src -> /dst + // Top-level: /dst -> /final + // onEnter should be called exactly once. + var onEnterCallCount = 0; - router = GoRouter( - initialLocation: '/src', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - onEnterCallCount++; - return const Allow(); - }, - redirect: (BuildContext context, GoRouterState state) { - if (state.matchedLocation == '/dst') { - return '/final'; - } - return null; - }, - routes: [ - GoRoute( - path: '/', - builder: (_, __) => const Text('Home'), - routes: [ - GoRoute( - path: 'src', - builder: (_, __) => const Text('Src'), - redirect: (BuildContext context, GoRouterState state) => - '/dst', - ), - ], - ), - GoRoute(path: '/dst', builder: (_, __) => const Text('Dst')), - GoRoute(path: '/final', builder: (_, __) => const Text('Final')), - ], - ); + router = GoRouter( + initialLocation: '/src', + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + onEnterCallCount++; + return const Allow(); + }, + redirect: (BuildContext context, GoRouterState state) { + if (state.matchedLocation == '/dst') { + return '/final'; + } + return null; + }, + routes: [ + GoRoute( + path: '/', + builder: (_, __) => const Text('Home'), + routes: [ + GoRoute( + path: 'src', + builder: (_, __) => const Text('Src'), + redirect: (BuildContext context, GoRouterState state) => '/dst', + ), + ], + ), + GoRoute(path: '/dst', builder: (_, __) => const Text('Dst')), + GoRoute(path: '/final', builder: (_, __) => const Text('Final')), + ], + ); - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pumpAndSettle(); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); - // Chain should resolve to /final. - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/final', - ); - expect(find.text('Final'), findsOneWidget); - // onEnter should be called exactly once for the initial navigation. - expect(onEnterCallCount, 1); - }, - ); + // Chain should resolve to /final. + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final'); + expect(find.text('Final'), findsOneWidget); + // onEnter should be called exactly once for the initial navigation. + expect(onEnterCallCount, 1); + }); - testWidgets('onEnter block prevents redirect chain evaluation', ( - WidgetTester tester, - ) async { + testWidgets('onEnter block prevents redirect chain evaluation', (WidgetTester tester) async { // onEnter blocks navigation to /a. // Top-level redirect: /a -> /b (should never be evaluated). var redirectCallCount = 0; router = GoRouter( initialLocation: '/', - onEnter: - ( - BuildContext context, - GoRouterState current, - GoRouterState next, - GoRouter goRouter, - ) async { - // Block all navigation except to /. - if (next.uri.path == '/') { - return const Allow(); - } - return const Block.stop(); - }, + onEnter: ( + BuildContext context, + GoRouterState current, + GoRouterState next, + GoRouter goRouter, + ) async { + // Block all navigation except to /. + if (next.uri.path == '/') { + return const Allow(); + } + return const Block.stop(); + }, redirect: (BuildContext context, GoRouterState state) { redirectCallCount++; if (state.matchedLocation == '/a') { diff --git a/packages/go_router/test/on_exit_test.dart b/packages/go_router/test/on_exit_test.dart index 56f5c6119698..dc0ae6acb8a7 100644 --- a/packages/go_router/test/on_exit_test.dart +++ b/packages/go_router/test/on_exit_test.dart @@ -18,13 +18,11 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), routes: [ GoRoute( path: '1', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { return allow; }, @@ -33,11 +31,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/1', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.pop(); @@ -57,24 +51,18 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), ), GoRoute( path: '/1', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { return allow; }, ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/1', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.go('/'); @@ -94,13 +82,11 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), routes: [ GoRoute( path: '1', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) async { return allow.future; }, @@ -109,11 +95,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/1', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.pop(); @@ -141,24 +123,18 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), ), GoRoute( path: '/1', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) async { return allow.future; }, ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/1', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/1'); expect(find.byKey(page1), findsOneWidget); router.go('/'); @@ -179,16 +155,13 @@ void main() { expect(find.byKey(home), findsOneWidget); }); - testWidgets('android back button respects the last route.', ( - WidgetTester tester, - ) async { + testWidgets('android back button respects the last route.', (WidgetTester tester) async { var allow = false; final home = UniqueKey(); final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), onExit: (BuildContext context, GoRouterState state) { return allow; }, @@ -205,16 +178,13 @@ void main() { expect(await router.routerDelegate.popRoute(), false); }); - testWidgets('android back button respects the last route. async', ( - WidgetTester tester, - ) async { + testWidgets('android back button respects the last route. async', (WidgetTester tester) async { var allow = false; final home = UniqueKey(); final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), onExit: (BuildContext context, GoRouterState state) async { return allow; }, @@ -242,8 +212,7 @@ void main() { routes: [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), onExit: (BuildContext context, GoRouterState state) { return allow; }, @@ -275,13 +244,11 @@ void main() { final routes = [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: home), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: home), routes: [ GoRoute( path: '1', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), onExit: (BuildContext context, GoRouterState state) { onExitState1 = state; return true; @@ -289,8 +256,7 @@ void main() { routes: [ GoRoute( path: '2', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page2), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page2), onExit: (BuildContext context, GoRouterState state) { onExitState2 = state; return true; @@ -298,8 +264,7 @@ void main() { routes: [ GoRoute( path: '3', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page3), + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page3), onExit: (BuildContext context, GoRouterState state) { onExitState3 = state; return true; @@ -313,11 +278,7 @@ void main() { ), ]; - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/1/2/3', - ); + final GoRouter router = await createRouter(routes, tester, initialLocation: '/1/2/3'); expect(find.byKey(page3), findsOneWidget); router.pop(); @@ -337,219 +298,208 @@ void main() { expect(onExitState1.uri.toString(), '/1'); }); - testWidgets( - 'It should provide the correct path parameters to the onExit callback', - (WidgetTester tester) async { - final page0 = UniqueKey(); - final page1 = UniqueKey(); - final page2 = UniqueKey(); - final page3 = UniqueKey(); - late final GoRouterState onExitState1; - late final GoRouterState onExitState2; - late final GoRouterState onExitState3; - final routes = [ - GoRoute( - path: '/route-0/:id0', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page0), - ), - GoRoute( - path: '/route-1/:id1', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), - onExit: (BuildContext context, GoRouterState state) { - onExitState1 = state; - return true; - }, - ), - GoRoute( - path: '/route-2/:id2', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page2), - onExit: (BuildContext context, GoRouterState state) { - onExitState2 = state; - return true; - }, - ), - GoRoute( - path: '/route-3/:id3', - builder: (BuildContext context, GoRouterState state) { - return DummyScreen(key: page3); - }, - onExit: (BuildContext context, GoRouterState state) { - onExitState3 = state; - return true; - }, - ), - ]; - - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/route-0/0?param0=0', - ); - unawaited(router.push('/route-1/1?param1=1')); - unawaited(router.push('/route-2/2?param2=2')); - unawaited(router.push('/route-3/3?param3=3')); - - await tester.pumpAndSettle(); - expect(find.byKey(page3), findsOne); - - router.pop(); - await tester.pumpAndSettle(); - expect(find.byKey(page2), findsOne); - expect(onExitState3.uri.toString(), '/route-3/3?param3=3'); - expect(onExitState3.pathParameters, const {'id3': '3'}); - expect(onExitState3.fullPath, '/route-3/:id3'); - - router.pop(); - await tester.pumpAndSettle(); - expect(find.byKey(page1), findsOne); - expect(onExitState2.uri.toString(), '/route-2/2?param2=2'); - expect(onExitState2.pathParameters, const {'id2': '2'}); - expect(onExitState2.fullPath, '/route-2/:id2'); - - router.pop(); - await tester.pumpAndSettle(); - expect(find.byKey(page0), findsOne); - expect(onExitState1.uri.toString(), '/route-1/1?param1=1'); - expect(onExitState1.pathParameters, const {'id1': '1'}); - expect(onExitState1.fullPath, '/route-1/:id1'); - }, - ); - - testWidgets( - 'It should provide the correct path parameters to the onExit callback during a go', - (WidgetTester tester) async { - final page0 = UniqueKey(); - final page1 = UniqueKey(); - final page2 = UniqueKey(); - final page3 = UniqueKey(); - late final GoRouterState onExitState0; - late final GoRouterState onExitState1; - late final GoRouterState onExitState2; - final routes = [ - GoRoute( - path: '/route-0/:id0', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page0), - onExit: (BuildContext context, GoRouterState state) { - onExitState0 = state; - return true; - }, - ), - GoRoute( - path: '/route-1/:id1', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page1), - onExit: (BuildContext context, GoRouterState state) { - onExitState1 = state; - return true; - }, - ), - GoRoute( - path: '/route-2/:id2', - builder: (BuildContext context, GoRouterState state) => - DummyScreen(key: page2), - onExit: (BuildContext context, GoRouterState state) { - onExitState2 = state; - return true; - }, - ), - GoRoute( - path: '/route-3/:id3', - builder: (BuildContext context, GoRouterState state) { - return DummyScreen(key: page3); - }, - ), - ]; - - final GoRouter router = await createRouter( - routes, - tester, - initialLocation: '/route-0/0?param0=0', - ); - expect(find.byKey(page0), findsOne); - - router.go('/route-1/1?param1=1'); - await tester.pumpAndSettle(); - expect(find.byKey(page1), findsOne); - expect(onExitState0.uri.toString(), '/route-0/0?param0=0'); - expect(onExitState0.pathParameters, const {'id0': '0'}); - expect(onExitState0.fullPath, '/route-0/:id0'); - - router.go('/route-2/2?param2=2'); - await tester.pumpAndSettle(); - expect(find.byKey(page2), findsOne); - expect(onExitState1.uri.toString(), '/route-1/1?param1=1'); - expect(onExitState1.pathParameters, const {'id1': '1'}); - expect(onExitState1.fullPath, '/route-1/:id1'); - - router.go('/route-3/3?param3=3'); - await tester.pumpAndSettle(); - expect(find.byKey(page3), findsOne); - expect(onExitState2.uri.toString(), '/route-2/2?param2=2'); - expect(onExitState2.pathParameters, const {'id2': '2'}); - expect(onExitState2.fullPath, '/route-2/:id2'); - }, - ); + testWidgets('It should provide the correct path parameters to the onExit callback', ( + WidgetTester tester, + ) async { + final page0 = UniqueKey(); + final page1 = UniqueKey(); + final page2 = UniqueKey(); + final page3 = UniqueKey(); + late final GoRouterState onExitState1; + late final GoRouterState onExitState2; + late final GoRouterState onExitState3; + final routes = [ + GoRoute( + path: '/route-0/:id0', + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page0), + ), + GoRoute( + path: '/route-1/:id1', + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), + onExit: (BuildContext context, GoRouterState state) { + onExitState1 = state; + return true; + }, + ), + GoRoute( + path: '/route-2/:id2', + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page2), + onExit: (BuildContext context, GoRouterState state) { + onExitState2 = state; + return true; + }, + ), + GoRoute( + path: '/route-3/:id3', + builder: (BuildContext context, GoRouterState state) { + return DummyScreen(key: page3); + }, + onExit: (BuildContext context, GoRouterState state) { + onExitState3 = state; + return true; + }, + ), + ]; - // Regression test: pop() with onExit + async redirect must not restore - // stale configuration. - testWidgets( - 'pop does not call restore with stale config when route has onExit', - (WidgetTester tester) async { - final homeKey = UniqueKey(); - final detailKey = UniqueKey(); - - final GoRouter router = await createRouter( - [ - GoRoute( - path: '/', - builder: (_, __) => DummyScreen(key: homeKey), - routes: [ - GoRoute( - path: 'detail', - onExit: (_, __) => true, - builder: (_, __) => DummyScreen(key: detailKey), - ), - ], - ), - ], - tester, - initialLocation: '/detail', - redirect: (_, GoRouterState state) async { - // Async redirect — completes in a later microtask. - await Future.delayed(Duration.zero); - return null; + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/route-0/0?param0=0', + ); + unawaited(router.push('/route-1/1?param1=1')); + unawaited(router.push('/route-2/2?param2=2')); + unawaited(router.push('/route-3/3?param3=3')); + + await tester.pumpAndSettle(); + expect(find.byKey(page3), findsOne); + + router.pop(); + await tester.pumpAndSettle(); + expect(find.byKey(page2), findsOne); + expect(onExitState3.uri.toString(), '/route-3/3?param3=3'); + expect(onExitState3.pathParameters, const {'id3': '3'}); + expect(onExitState3.fullPath, '/route-3/:id3'); + + router.pop(); + await tester.pumpAndSettle(); + expect(find.byKey(page1), findsOne); + expect(onExitState2.uri.toString(), '/route-2/2?param2=2'); + expect(onExitState2.pathParameters, const {'id2': '2'}); + expect(onExitState2.fullPath, '/route-2/:id2'); + + router.pop(); + await tester.pumpAndSettle(); + expect(find.byKey(page0), findsOne); + expect(onExitState1.uri.toString(), '/route-1/1?param1=1'); + expect(onExitState1.pathParameters, const {'id1': '1'}); + expect(onExitState1.fullPath, '/route-1/:id1'); + }); + + testWidgets('It should provide the correct path parameters to the onExit callback during a go', ( + WidgetTester tester, + ) async { + final page0 = UniqueKey(); + final page1 = UniqueKey(); + final page2 = UniqueKey(); + final page3 = UniqueKey(); + late final GoRouterState onExitState0; + late final GoRouterState onExitState1; + late final GoRouterState onExitState2; + final routes = [ + GoRoute( + path: '/route-0/:id0', + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page0), + onExit: (BuildContext context, GoRouterState state) { + onExitState0 = state; + return true; + }, + ), + GoRoute( + path: '/route-1/:id1', + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page1), + onExit: (BuildContext context, GoRouterState state) { + onExitState1 = state; + return true; + }, + ), + GoRoute( + path: '/route-2/:id2', + builder: (BuildContext context, GoRouterState state) => DummyScreen(key: page2), + onExit: (BuildContext context, GoRouterState state) { + onExitState2 = state; + return true; + }, + ), + GoRoute( + path: '/route-3/:id3', + builder: (BuildContext context, GoRouterState state) { + return DummyScreen(key: page3); }, - ); - - await tester.pumpAndSettle(); - expect(find.byKey(detailKey), findsOneWidget); - - router.pop(); - await tester.pumpAndSettle(); - - // The detail route should be gone after pop. - expect( - find.byKey(detailKey), - findsNothing, - reason: - 'Route with onExit should be properly popped ' - 'even when async redirect is present', - ); - expect(find.byKey(homeKey), findsOneWidget); - }, - ); + ), + ]; - // Verify that pop is correctly cancelled when onExit returns false. - testWidgets('pop is cancelled when onExit returns false', ( + final GoRouter router = await createRouter( + routes, + tester, + initialLocation: '/route-0/0?param0=0', + ); + expect(find.byKey(page0), findsOne); + + router.go('/route-1/1?param1=1'); + await tester.pumpAndSettle(); + expect(find.byKey(page1), findsOne); + expect(onExitState0.uri.toString(), '/route-0/0?param0=0'); + expect(onExitState0.pathParameters, const {'id0': '0'}); + expect(onExitState0.fullPath, '/route-0/:id0'); + + router.go('/route-2/2?param2=2'); + await tester.pumpAndSettle(); + expect(find.byKey(page2), findsOne); + expect(onExitState1.uri.toString(), '/route-1/1?param1=1'); + expect(onExitState1.pathParameters, const {'id1': '1'}); + expect(onExitState1.fullPath, '/route-1/:id1'); + + router.go('/route-3/3?param3=3'); + await tester.pumpAndSettle(); + expect(find.byKey(page3), findsOne); + expect(onExitState2.uri.toString(), '/route-2/2?param2=2'); + expect(onExitState2.pathParameters, const {'id2': '2'}); + expect(onExitState2.fullPath, '/route-2/:id2'); + }); + + // Regression test: pop() with onExit + async redirect must not restore + // stale configuration. + testWidgets('pop does not call restore with stale config when route has onExit', ( WidgetTester tester, ) async { final homeKey = UniqueKey(); final detailKey = UniqueKey(); + final GoRouter router = await createRouter( + [ + GoRoute( + path: '/', + builder: (_, __) => DummyScreen(key: homeKey), + routes: [ + GoRoute( + path: 'detail', + onExit: (_, __) => true, + builder: (_, __) => DummyScreen(key: detailKey), + ), + ], + ), + ], + tester, + initialLocation: '/detail', + redirect: (_, GoRouterState state) async { + // Async redirect — completes in a later microtask. + await Future.delayed(Duration.zero); + return null; + }, + ); + + await tester.pumpAndSettle(); + expect(find.byKey(detailKey), findsOneWidget); + + router.pop(); + await tester.pumpAndSettle(); + + // The detail route should be gone after pop. + expect( + find.byKey(detailKey), + findsNothing, + reason: + 'Route with onExit should be properly popped ' + 'even when async redirect is present', + ); + expect(find.byKey(homeKey), findsOneWidget); + }); + + // Verify that pop is correctly cancelled when onExit returns false. + testWidgets('pop is cancelled when onExit returns false', (WidgetTester tester) async { + final homeKey = UniqueKey(); + final detailKey = UniqueKey(); + final GoRouter router = await createRouter( [ GoRoute( diff --git a/packages/go_router/test/parser_test.dart b/packages/go_router/test/parser_test.dart index d6d4d18e6adf..c1510eb44d0a 100644 --- a/packages/go_router/test/parser_test.dart +++ b/packages/go_router/test/parser_test.dart @@ -22,26 +22,18 @@ void main() { int redirectLimit = 5, GoRouterRedirect? redirect, }) async { - final router = GoRouter( - routes: routes, - redirectLimit: redirectLimit, - redirect: redirect, - ); + final router = GoRouter(routes: routes, redirectLimit: redirectLimit, redirect: redirect); addTearDown(router.dispose); await tester.pumpWidget(MaterialApp.router(routerConfig: router)); return router.routeInformationParser; } - testWidgets('GoRouteInformationParser can parse route', ( - WidgetTester tester, - ) async { + testWidgets('GoRouteInformationParser can parse route', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', builder: (_, __) => const Placeholder(), - routes: [ - GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), - ], + routes: [GoRoute(path: 'abc', builder: (_, __) => const Placeholder())], ), ]; final GoRouteInformationParser parser = await createParser( @@ -53,11 +45,10 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('/'), - context, - ); + RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('/'), + context, + ); List matches = matchesObj.matches; expect(matches.length, 1); expect(matchesObj.uri.toString(), '/'); @@ -81,48 +72,40 @@ void main() { expect(matches[1].route, routes[0].routes[0]); }); - testWidgets( - 'GoRouteInformationParser can handle empty path for non http uri', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); + testWidgets('GoRouteInformationParser can handle empty path for non http uri', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [GoRoute(path: 'abc', builder: (_, __) => const Placeholder())], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); - final BuildContext context = tester.element(find.byType(Router)); + final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('elbaapp://domain'), - context, - ); - final List matches = matchesObj.matches; - expect(matches.length, 1); - expect(matchesObj.uri.toString(), 'elbaapp://domain/'); - }, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('elbaapp://domain'), + context, + ); + final List matches = matchesObj.matches; + expect(matches.length, 1); + expect(matchesObj.uri.toString(), 'elbaapp://domain/'); + }); - testWidgets('GoRouteInformationParser cleans up uri', ( - WidgetTester tester, - ) async { + testWidgets('GoRouteInformationParser cleans up uri', (WidgetTester tester) async { final routes = [ GoRoute( path: '/', builder: (_, __) => const Placeholder(), - routes: [ - GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), - ], + routes: [GoRoute(path: 'abc', builder: (_, __) => const Placeholder())], ), ]; final GoRouteInformationParser parser = await createParser( @@ -134,11 +117,10 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('http://domain/abc/?query=bde'), - context, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('http://domain/abc/?query=bde'), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 2); expect(matchesObj.uri.toString(), 'http://domain/abc?query=bde'); @@ -151,11 +133,8 @@ void main() { const expectedHost = 'www.example.com'; const expectedQuery = 'abc=def'; const expectedFragment = 'abc'; - const expectedUriString = - '$expectedScheme://$expectedHost/?$expectedQuery#$expectedFragment'; - final routes = [ - GoRoute(path: '/', builder: (_, __) => const Placeholder()), - ]; + const expectedUriString = '$expectedScheme://$expectedHost/?$expectedQuery#$expectedFragment'; + final routes = [GoRoute(path: '/', builder: (_, __) => const Placeholder())]; final GoRouteInformationParser parser = await createParser( tester, routes: routes, @@ -165,11 +144,10 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation(expectedUriString), - context, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation(expectedUriString), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 1); expect(matchesObj.uri.toString(), expectedUriString); @@ -197,9 +175,7 @@ void main() { GoRoute( path: '/', builder: (_, __) => const Placeholder(), - routes: [ - GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), - ], + routes: [GoRoute(path: 'abc', builder: (_, __) => const Placeholder())], ), ]; final GoRouteInformationParser parser = await createParser( @@ -211,11 +187,10 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation(expectedUriString), - context, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation(expectedUriString), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 2); expect(matchesObj.uri.toString(), expectedUriString); @@ -241,40 +216,28 @@ void main() { GoRoute( path: '/', builder: (_, __) => const Placeholder(), - routes: [ - GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), - ], + routes: [GoRoute(path: 'abc', builder: (_, __) => const Placeholder())], ), ]; GoRouter.optionURLReflectsImperativeAPIs = true; - final GoRouter router = await createRouter( - routes, - tester, - navigatorKey: navKey, - ); + final GoRouter router = await createRouter(routes, tester, navigatorKey: navKey); // Generate RouteMatchList with imperative route match router.go('/abc'); await tester.pumpAndSettle(); router.push('/'); await tester.pumpAndSettle(); - final RouteMatchList matchList = - router.routerDelegate.currentConfiguration; + final RouteMatchList matchList = router.routerDelegate.currentConfiguration; expect(matchList.uri.toString(), '/abc'); expect(matchList.matches.length, 3); - final RouteInformation restoredRouteInformation = router - .routeInformationParser - .restoreRouteInformation(matchList)!; + final RouteInformation restoredRouteInformation = + router.routeInformationParser.restoreRouteInformation(matchList)!; expect(restoredRouteInformation.uri.path, '/'); // Can restore back to original RouteMatchList. - final RouteMatchList parsedRouteMatch = await router - .routeInformationParser - .parseRouteInformationWithDependencies( - restoredRouteInformation, - navKey.currentContext!, - ); + final RouteMatchList parsedRouteMatch = await router.routeInformationParser + .parseRouteInformationWithDependencies(restoredRouteInformation, navKey.currentContext!); expect(parsedRouteMatch.uri.toString(), '/abc'); expect(parsedRouteMatch.matches.length, 3); @@ -288,21 +251,9 @@ void main() { path: '/', builder: (_, __) => const Placeholder(), routes: [ - GoRoute( - path: 'abc', - name: 'lowercase', - builder: (_, __) => const Placeholder(), - ), - GoRoute( - path: 'efg', - name: 'camelCase', - builder: (_, __) => const Placeholder(), - ), - GoRoute( - path: 'hij', - name: 'snake_case', - builder: (_, __) => const Placeholder(), - ), + GoRoute(path: 'abc', name: 'lowercase', builder: (_, __) => const Placeholder()), + GoRoute(path: 'efg', name: 'camelCase', builder: (_, __) => const Placeholder()), + GoRoute(path: 'hij', name: 'snake_case', builder: (_, __) => const Placeholder()), ], ), ]; @@ -321,10 +272,7 @@ void main() { // With query parameters expect(configuration.namedLocation('lowercase'), '/abc'); expect( - configuration.namedLocation( - 'lowercase', - queryParameters: const {'q': '1'}, - ), + configuration.namedLocation('lowercase', queryParameters: const {'q': '1'}), '/abc?q=1', ); expect( @@ -336,42 +284,35 @@ void main() { ); }); - test( - 'GoRouteInformationParser can retrieve route by name with query parameters', - () async { - final routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: 'abc', - name: 'routeName', - builder: (_, __) => const Placeholder(), - ), - ], - ), - ]; + test('GoRouteInformationParser can retrieve route by name with query parameters', () async { + final routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute(path: 'abc', name: 'routeName', builder: (_, __) => const Placeholder()), + ], + ), + ]; - final RouteConfiguration configuration = createRouteConfiguration( - routes: routes, - redirectLimit: 100, - topRedirect: (_, __) => null, - navigatorKey: GlobalKey(), - ); + final RouteConfiguration configuration = createRouteConfiguration( + routes: routes, + redirectLimit: 100, + topRedirect: (_, __) => null, + navigatorKey: GlobalKey(), + ); - expect( - configuration.namedLocation( - 'routeName', - queryParameters: const { - 'q1': 'v1', - 'q2': ['v2', 'v3'], - }, - ), - '/abc?q1=v1&q2=v2&q2=v3', - ); - }, - ); + expect( + configuration.namedLocation( + 'routeName', + queryParameters: const { + 'q1': 'v1', + 'q2': ['v2', 'v3'], + }, + ), + '/abc?q1=v1&q2=v2&q2=v3', + ); + }); testWidgets('GoRouteInformationParser returns error when unknown route', ( WidgetTester tester, @@ -380,9 +321,7 @@ void main() { GoRoute( path: '/', builder: (_, __) => const Placeholder(), - routes: [ - GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), - ], + routes: [GoRoute(path: 'abc', builder: (_, __) => const Placeholder())], ), ]; final GoRouteInformationParser parser = await createParser( @@ -394,52 +333,42 @@ void main() { final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('/def'), - context, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('/def'), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 0); expect(matchesObj.uri.toString(), '/def'); expect(matchesObj.extra, isNull); - expect( - matchesObj.error!.toString(), - 'GoException: no routes for location: /def', - ); + expect(matchesObj.error!.toString(), 'GoException: no routes for location: /def'); }); - testWidgets( - 'GoRouteInformationParser calls redirector with correct uri when unknown route', - (WidgetTester tester) async { - String? lastRedirectLocation; - final routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute(path: 'abc', builder: (_, __) => const Placeholder()), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, GoRouterState state) { - lastRedirectLocation = state.uri.toString(); - return null; - }, - ); + testWidgets('GoRouteInformationParser calls redirector with correct uri when unknown route', ( + WidgetTester tester, + ) async { + String? lastRedirectLocation; + final routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [GoRoute(path: 'abc', builder: (_, __) => const Placeholder())], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, GoRouterState state) { + lastRedirectLocation = state.uri.toString(); + return null; + }, + ); - final BuildContext context = tester.element(find.byType(Router)); - await parser.parseRouteInformationWithDependencies( - createRouteInformation('/def'), - context, - ); - expect(lastRedirectLocation, '/def'); - }, - ); + final BuildContext context = tester.element(find.byType(Router)); + await parser.parseRouteInformationWithDependencies(createRouteInformation('/def'), context); + expect(lastRedirectLocation, '/def'); + }); testWidgets('GoRouteInformationParser can work with route parameters', ( WidgetTester tester, @@ -449,10 +378,7 @@ void main() { path: '/', builder: (_, __) => const Placeholder(), routes: [ - GoRoute( - path: ':uid/family/:fid', - builder: (_, __) => const Placeholder(), - ), + GoRoute(path: ':uid/family/:fid', builder: (_, __) => const Placeholder()), ], ), ]; @@ -464,11 +390,10 @@ void main() { ); final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('/123/family/456'), - context, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('/123/family/456'), + context, + ); final List matches = matchesObj.matches; expect(matches.length, 2); @@ -482,144 +407,128 @@ void main() { expect(matches[1].matchedLocation, '/123/family/456'); }); - testWidgets( - 'GoRouteInformationParser processes top level redirect when there is no match', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: ':uid/family/:fid', - builder: (_, __) => const Placeholder(), - ), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (BuildContext context, GoRouterState state) { - if (state.uri.toString() != '/123/family/345') { - return '/123/family/345'; - } - return null; - }, - ); - - final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('/random/uri'), - context, - ); - final List matches = matchesObj.matches; + testWidgets('GoRouteInformationParser processes top level redirect when there is no match', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute(path: ':uid/family/:fid', builder: (_, __) => const Placeholder()), + ], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (BuildContext context, GoRouterState state) { + if (state.uri.toString() != '/123/family/345') { + return '/123/family/345'; + } + return null; + }, + ); - expect(matches.length, 2); - expect(matchesObj.uri.toString(), '/123/family/345'); - expect(matches[0].matchedLocation, '/'); + final BuildContext context = tester.element(find.byType(Router)); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('/random/uri'), + context, + ); + final List matches = matchesObj.matches; - expect(matches[1].matchedLocation, '/123/family/345'); - }, - ); + expect(matches.length, 2); + expect(matchesObj.uri.toString(), '/123/family/345'); + expect(matches[0].matchedLocation, '/'); - testWidgets( - 'GoRouteInformationParser can do route level redirect when there is a match', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/', - builder: (_, __) => const Placeholder(), - routes: [ - GoRoute( - path: ':uid/family/:fid', - builder: (_, __) => const Placeholder(), - ), - GoRoute( - path: 'redirect', - redirect: (_, __) => '/123/family/345', - builder: (_, __) => throw UnimplementedError(), - ), - ], - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); + expect(matches[1].matchedLocation, '/123/family/345'); + }); - final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('/redirect'), - context, - ); - final List matches = matchesObj.matches; + testWidgets('GoRouteInformationParser can do route level redirect when there is a match', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + path: '/', + builder: (_, __) => const Placeholder(), + routes: [ + GoRoute(path: ':uid/family/:fid', builder: (_, __) => const Placeholder()), + GoRoute( + path: 'redirect', + redirect: (_, __) => '/123/family/345', + builder: (_, __) => throw UnimplementedError(), + ), + ], + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); - expect(matches.length, 2); - expect(matchesObj.uri.toString(), '/123/family/345'); - expect(matches[0].matchedLocation, '/'); + final BuildContext context = tester.element(find.byType(Router)); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('/redirect'), + context, + ); + final List matches = matchesObj.matches; - expect(matches[1].matchedLocation, '/123/family/345'); - }, - ); + expect(matches.length, 2); + expect(matchesObj.uri.toString(), '/123/family/345'); + expect(matches[0].matchedLocation, '/'); - testWidgets( - 'GoRouteInformationParser throws an exception when route is malformed', - (WidgetTester tester) async { - final routes = [ - GoRoute(path: '/abc', builder: (_, __) => const Placeholder()), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); + expect(matches[1].matchedLocation, '/123/family/345'); + }); - final BuildContext context = tester.element(find.byType(Router)); - expect(() async { - await parser.parseRouteInformationWithDependencies( - createRouteInformation('::Not valid URI::'), - context, - ); - }, throwsA(isA())); - }, - ); + testWidgets('GoRouteInformationParser throws an exception when route is malformed', ( + WidgetTester tester, + ) async { + final routes = [GoRoute(path: '/abc', builder: (_, __) => const Placeholder())]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); - testWidgets( - 'GoRouteInformationParser returns an error if a redirect is detected.', - (WidgetTester tester) async { - final routes = [ - GoRoute( - path: '/abc', - builder: (_, __) => const Placeholder(), - redirect: (BuildContext context, GoRouterState state) => - state.uri.toString(), - ), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirect: (_, __) => null, + final BuildContext context = tester.element(find.byType(Router)); + expect(() async { + await parser.parseRouteInformationWithDependencies( + createRouteInformation('::Not valid URI::'), + context, ); + }, throwsA(isA())); + }); - final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('/abd'), - context, - ); - final List matches = matchesObj.matches; + testWidgets('GoRouteInformationParser returns an error if a redirect is detected.', ( + WidgetTester tester, + ) async { + final routes = [ + GoRoute( + path: '/abc', + builder: (_, __) => const Placeholder(), + redirect: (BuildContext context, GoRouterState state) => state.uri.toString(), + ), + ]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirect: (_, __) => null, + ); - expect(matches, hasLength(0)); - expect(matchesObj.error, isNotNull); - }, - ); + final BuildContext context = tester.element(find.byType(Router)); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('/abd'), + context, + ); + final List matches = matchesObj.matches; + + expect(matches, hasLength(0)); + expect(matchesObj.error, isNotNull); + }); testWidgets('Creates a match for ShellRoute', (WidgetTester tester) async { final routes = [ @@ -650,11 +559,10 @@ void main() { ); final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('/a'), - context, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('/a'), + context, + ); final List matches = matchesObj.matches; expect(matches, hasLength(1)); @@ -663,29 +571,25 @@ void main() { expect(matchesObj.error, isNull); }); - testWidgets( - 'GoRouteInformationParser can handle path without leading slash', - (WidgetTester tester) async { - final routes = [ - GoRoute(path: '/abc', builder: (_, __) => const Placeholder()), - ]; - final GoRouteInformationParser parser = await createParser( - tester, - routes: routes, - redirectLimit: 100, - redirect: (_, __) => null, - ); + testWidgets('GoRouteInformationParser can handle path without leading slash', ( + WidgetTester tester, + ) async { + final routes = [GoRoute(path: '/abc', builder: (_, __) => const Placeholder())]; + final GoRouteInformationParser parser = await createParser( + tester, + routes: routes, + redirectLimit: 100, + redirect: (_, __) => null, + ); - final BuildContext context = tester.element(find.byType(Router)); + final BuildContext context = tester.element(find.byType(Router)); - final RouteMatchList matchesObj = await parser - .parseRouteInformationWithDependencies( - createRouteInformation('abc'), - context, - ); - final List matches = matchesObj.matches; - expect(matches.length, 1); - expect(matchesObj.uri.toString(), '/abc'); - }, - ); + final RouteMatchList matchesObj = await parser.parseRouteInformationWithDependencies( + createRouteInformation('abc'), + context, + ); + final List matches = matchesObj.matches; + expect(matches.length, 1); + expect(matchesObj.uri.toString(), '/abc'); + }); } diff --git a/packages/go_router/test/path_utils_test.dart b/packages/go_router/test/path_utils_test.dart index 6dbf91102676..28553408c1df 100644 --- a/packages/go_router/test/path_utils_test.dart +++ b/packages/go_router/test/path_utils_test.dart @@ -9,11 +9,7 @@ void main() { test('patternToRegExp without path parameter', () async { const pattern = '/settings/detail'; final pathParameter = []; - final RegExp regex = patternToRegExp( - pattern, - pathParameter, - caseSensitive: true, - ); + final RegExp regex = patternToRegExp(pattern, pathParameter, caseSensitive: true); expect(pathParameter.isEmpty, isTrue); expect(regex.hasMatch('/settings/detail'), isTrue); expect(regex.hasMatch('/settings/'), isFalse); @@ -26,21 +22,14 @@ void main() { test('patternToRegExp with path parameter', () async { const pattern = '/user/:id/book/:bookId'; final pathParameter = []; - final RegExp regex = patternToRegExp( - pattern, - pathParameter, - caseSensitive: true, - ); + final RegExp regex = patternToRegExp(pattern, pathParameter, caseSensitive: true); expect(pathParameter.length, 2); expect(pathParameter[0], 'id'); expect(pathParameter[1], 'bookId'); final RegExpMatch? match = regex.firstMatch('/user/123/book/456/'); expect(match, isNotNull); - final Map parameterValues = extractPathParameters( - pathParameter, - match!, - ); + final Map parameterValues = extractPathParameters(pathParameter, match!); expect(parameterValues.length, 2); expect(parameterValues[pathParameter[0]], '123'); expect(parameterValues[pathParameter[1]], '456'); @@ -54,20 +43,13 @@ void main() { test('patternToPath without path parameter', () async { const pattern = '/settings/detail'; final pathParameter = []; - final RegExp regex = patternToRegExp( - pattern, - pathParameter, - caseSensitive: true, - ); + final RegExp regex = patternToRegExp(pattern, pathParameter, caseSensitive: true); const url = '/settings/detail'; final RegExpMatch? match = regex.firstMatch(url); expect(match, isNotNull); - final Map parameterValues = extractPathParameters( - pathParameter, - match!, - ); + final Map parameterValues = extractPathParameters(pathParameter, match!); final String restoredUrl = patternToPath(pattern, parameterValues); expect(url, restoredUrl); @@ -76,20 +58,13 @@ void main() { test('patternToPath with path parameter', () async { const pattern = '/user/:id/book/:bookId'; final pathParameter = []; - final RegExp regex = patternToRegExp( - pattern, - pathParameter, - caseSensitive: true, - ); + final RegExp regex = patternToRegExp(pattern, pathParameter, caseSensitive: true); const url = '/user/123/book/456'; final RegExpMatch? match = regex.firstMatch(url); expect(match, isNotNull); - final Map parameterValues = extractPathParameters( - pathParameter, - match!, - ); + final Map parameterValues = extractPathParameters(pathParameter, match!); final String restoredUrl = patternToPath(pattern, parameterValues); expect(url, restoredUrl); @@ -111,10 +86,7 @@ void main() { test('concatenateUris', () { void verify(String pathA, String pathB, String expected) { - final result = concatenateUris( - Uri.parse(pathA), - Uri.parse(pathB), - ).toString(); + final result = concatenateUris(Uri.parse(pathA), Uri.parse(pathB)).toString(); expect(result, expected); } @@ -134,8 +106,7 @@ void main() { }); test('canonicalUri', () { - void verify(String path, String expected) => - expect(canonicalUri(path), expected); + void verify(String path, String expected) => expect(canonicalUri(path), expected); verify('/a', '/a'); verify('/a/', '/a'); verify('/', '/'); diff --git a/packages/go_router/test/rebuild_test.dart b/packages/go_router/test/rebuild_test.dart index b0379459c8d3..981aab6cc290 100644 --- a/packages/go_router/test/rebuild_test.dart +++ b/packages/go_router/test/rebuild_test.dart @@ -9,14 +9,9 @@ import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { - testWidgets('GoRouter.push does not trigger unnecessary rebuilds', ( - WidgetTester tester, - ) async { + testWidgets('GoRouter.push does not trigger unnecessary rebuilds', (WidgetTester tester) async { final routes = [ - GoRoute( - path: '/', - builder: (BuildContext context, __) => const HomePage(), - ), + GoRoute(path: '/', builder: (BuildContext context, __) => const HomePage()), GoRoute( path: '/1', builder: (BuildContext context, __) { diff --git a/packages/go_router/test/redirect_chain_test.dart b/packages/go_router/test/redirect_chain_test.dart index 7eee12809189..41a262b16bdd 100644 --- a/packages/go_router/test/redirect_chain_test.dart +++ b/packages/go_router/test/redirect_chain_test.dart @@ -27,18 +27,15 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Page2Screen(), + builder: (BuildContext context, GoRouterState state) => const Page2Screen(), ), ], tester, @@ -60,30 +57,24 @@ void main() { expect(redirectLog, ['/', '/a', '/b']); }); - testWidgets('top-level redirect chain with three hops', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect chain with three hops', (WidgetTester tester) async { final GoRouter router = await createRouter( [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/step1', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/step2', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/step3', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -97,10 +88,7 @@ void main() { }, ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/step3', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/step3'); expect(find.byType(LoginScreen), findsOneWidget); }); @@ -109,18 +97,15 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -143,26 +128,21 @@ void main() { expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('top-level redirect chain loop detection', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect chain loop detection', (WidgetTester tester) async { // Redirect loop: / -> /a -> /b -> /a (loop) await createRouter( [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], tester, @@ -174,35 +154,25 @@ void main() { _ => null, }; }, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); - expect( - (screen.ex as GoException).message, - startsWith('redirect loop detected'), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); + expect((screen.ex as GoException).message, startsWith('redirect loop detected')); }); - testWidgets('top-level redirect chain loop to initial location', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect chain loop to initial location', (WidgetTester tester) async { // Redirect loop returning to initial location: / -> /a -> / await createRouter( [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], tester, @@ -213,42 +183,31 @@ void main() { _ => null, }; }, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); - expect( - (screen.ex as GoException).message, - startsWith('redirect loop detected'), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); + expect((screen.ex as GoException).message, startsWith('redirect loop detected')); }); - testWidgets('top-level redirect chain into route-level redirect', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect chain into route-level redirect', (WidgetTester tester) async { // Top-level: / -> /intermediate // Route-level on /intermediate: /intermediate -> /final final GoRouter router = await createRouter( [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/intermediate', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/final', ), GoRoute( path: '/final', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -260,16 +219,11 @@ void main() { }, ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/final', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final'); expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets('route-level redirect triggers top-level redirect', ( - WidgetTester tester, - ) async { + testWidgets('route-level redirect triggers top-level redirect', (WidgetTester tester) async { // Route-level on /src: /src -> /dst // Top-level: /dst -> /final final topRedirectLog = []; @@ -277,26 +231,22 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'src', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/dst', ), ], ), GoRoute( path: '/dst', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/final', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -310,10 +260,7 @@ void main() { }, ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/final', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final'); expect(find.byType(LoginScreen), findsOneWidget); // Top-level redirect was evaluated on /dst (after route-level redirect). expect(topRedirectLog, contains('/dst')); @@ -328,13 +275,11 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -347,42 +292,33 @@ void main() { }, ); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/login', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/login'); expect(find.byType(LoginScreen), findsOneWidget); // Redirect is called twice: once for /, once for /login. expect(callCount, 2); }); - testWidgets('top-level redirect chain respects redirect limit', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect chain respects redirect limit', (WidgetTester tester) async { // Endless chain: /0 -> /1 -> /2 -> ... with a low limit. await createRouter( [ for (int i = 0; i <= 20; i++) GoRoute( path: '/$i', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], tester, initialLocation: '/0', redirect: (BuildContext context, GoRouterState state) { - final RegExpMatch? match = RegExp( - r'^/(\d+)$', - ).firstMatch(state.matchedLocation); + final RegExpMatch? match = RegExp(r'^/(\d+)$').firstMatch(state.matchedLocation); if (match != null) { final int current = int.parse(match.group(1)!); return '/${current + 1}'; } return null; }, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); expect(find.byType(TestErrorScreen), findsOneWidget); @@ -397,18 +333,15 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -427,53 +360,43 @@ void main() { expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets( - 'top-level redirect chain fails when exceeding redirect limit', - (WidgetTester tester) async { - // Chain of 2 redirects: / -> /a -> /b. With limit=1, the second - // redirect exceeds the limit and should error. - await createRouter( - [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), - GoRoute( - path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), - ), - GoRoute( - path: '/b', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), - ), - ], - tester, - redirect: (BuildContext context, GoRouterState state) { - return switch (state.matchedLocation) { - '/' => '/a', - '/a' => '/b', - _ => null, - }; - }, - redirectLimit: 1, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), - ); - - // 2 redirects with limit=1 should error. - expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); - expect( - (screen.ex as GoException).message, - startsWith('too many redirects'), - ); - }, - ); + testWidgets('top-level redirect chain fails when exceeding redirect limit', ( + WidgetTester tester, + ) async { + // Chain of 2 redirects: / -> /a -> /b. With limit=1, the second + // redirect exceeds the limit and should error. + await createRouter( + [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), + ), + GoRoute( + path: '/a', + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), + ), + GoRoute( + path: '/b', + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), + ), + ], + tester, + redirect: (BuildContext context, GoRouterState state) { + return switch (state.matchedLocation) { + '/' => '/a', + '/a' => '/b', + _ => null, + }; + }, + redirectLimit: 1, + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), + ); + + // 2 redirects with limit=1 should error. + expect(find.byType(TestErrorScreen), findsOneWidget); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); + expect((screen.ex as GoException).message, startsWith('too many redirects')); + }); testWidgets('top-level and route-level redirects share redirect limit', ( WidgetTester tester, @@ -486,25 +409,21 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/b', ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/c', ), GoRoute( path: '/c', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -515,41 +434,30 @@ void main() { return null; }, redirectLimit: 2, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); // Combined chain of 3 redirects exceeds the shared limit of 2. expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); - expect( - (screen.ex as GoException).message, - startsWith('too many redirects'), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); + expect((screen.ex as GoException).message, startsWith('too many redirects')); }); - testWidgets('async top-level redirect chain loop detection', ( - WidgetTester tester, - ) async { + testWidgets('async top-level redirect chain loop detection', (WidgetTester tester) async { // Async redirect loop: / -> /a -> /b -> /a (loop) await createRouter( [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], tester, @@ -562,25 +470,17 @@ void main() { _ => null, }; }, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); await tester.pumpAndSettle(); expect(find.byType(TestErrorScreen), findsOneWidget); - final TestErrorScreen screen = tester.widget( - find.byType(TestErrorScreen), - ); - expect( - (screen.ex as GoException).message, - startsWith('redirect loop detected'), - ); + final TestErrorScreen screen = tester.widget(find.byType(TestErrorScreen)); + expect((screen.ex as GoException).message, startsWith('redirect loop detected')); }); - testWidgets('async top-level redirect into route-level redirect', ( - WidgetTester tester, - ) async { + testWidgets('async top-level redirect into route-level redirect', (WidgetTester tester) async { // Async top-level: / -> /mid (async) // Route-level on /mid: /mid -> /final (sync) // Exercises the async boundary between top-level and route-level @@ -589,19 +489,16 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/mid', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/final', ), GoRoute( path: '/final', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -616,10 +513,7 @@ void main() { await tester.pumpAndSettle(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/final', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final'); expect(find.byType(LoginScreen), findsOneWidget); }); @@ -632,13 +526,11 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'src', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) async { await Future.delayed(Duration.zero); return '/dst'; @@ -648,13 +540,11 @@ void main() { ), GoRoute( path: '/dst', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/final', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -669,10 +559,7 @@ void main() { await tester.pumpAndSettle(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/final', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final'); expect(find.byType(LoginScreen), findsOneWidget); }); @@ -685,26 +572,22 @@ void main() { [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: [ GoRoute( path: 'src', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/dst', ), ], ), GoRoute( path: '/dst', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/final', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, @@ -720,139 +603,122 @@ void main() { await tester.pumpAndSettle(); - expect( - router.routerDelegate.currentConfiguration.uri.toString(), - '/final', - ); + expect(router.routerDelegate.currentConfiguration.uri.toString(), '/final'); expect(find.byType(LoginScreen), findsOneWidget); }); - testWidgets( - 'context disposal during async top-level redirect does not crash', - (WidgetTester tester) async { - // Simulate context disposal while an async top-level redirect is - // in flight. The router should handle this gracefully — not navigate - // to /target after the context is unmounted. - final redirectStarted = Completer(); - final proceedRedirect = Completer(); - - final router = GoRouter( - routes: [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - ), - GoRoute( - path: '/target', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), - ), - ], - redirect: (BuildContext context, GoRouterState state) async { - if (state.matchedLocation == '/') { + testWidgets('context disposal during async top-level redirect does not crash', ( + WidgetTester tester, + ) async { + // Simulate context disposal while an async top-level redirect is + // in flight. The router should handle this gracefully — not navigate + // to /target after the context is unmounted. + final redirectStarted = Completer(); + final proceedRedirect = Completer(); + + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), + ), + GoRoute( + path: '/target', + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), + ), + ], + redirect: (BuildContext context, GoRouterState state) async { + if (state.matchedLocation == '/') { + redirectStarted.complete(); + await proceedRedirect.future; + return '/target'; + } + return null; + }, + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), + ); + addTearDown(router.dispose); + + // Mount the router. + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pump(); + + // Wait for the redirect to start. + await redirectStarted.future; + + // Unmount the MaterialApp.router, which disposes the router context. + await tester.pumpWidget(const SizedBox.shrink()); + + // Let the redirect complete after context is unmounted. + proceedRedirect.complete(); + await tester.pumpAndSettle(); + + // The router should NOT have navigated to /target. + expect(find.byType(LoginScreen), findsNothing); + }); + + testWidgets('context disposal during async route-level redirect does not crash', ( + WidgetTester tester, + ) async { + // Same as above but for route-level async redirects. + final redirectStarted = Completer(); + final proceedRedirect = Completer(); + + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), + redirect: (BuildContext context, GoRouterState state) async { redirectStarted.complete(); await proceedRedirect.future; return '/target'; - } - return null; - }, - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), - ); - addTearDown(router.dispose); - - // Mount the router. - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pump(); - - // Wait for the redirect to start. - await redirectStarted.future; - - // Unmount the MaterialApp.router, which disposes the router context. - await tester.pumpWidget(const SizedBox.shrink()); - - // Let the redirect complete after context is unmounted. - proceedRedirect.complete(); - await tester.pumpAndSettle(); - - // The router should NOT have navigated to /target. - expect(find.byType(LoginScreen), findsNothing); - }, - ); - - testWidgets( - 'context disposal during async route-level redirect does not crash', - (WidgetTester tester) async { - // Same as above but for route-level async redirects. - final redirectStarted = Completer(); - final proceedRedirect = Completer(); - - final router = GoRouter( - routes: [ - GoRoute( - path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), - redirect: (BuildContext context, GoRouterState state) async { - redirectStarted.complete(); - await proceedRedirect.future; - return '/target'; - }, - ), - GoRoute( - path: '/target', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), - ), - ], - errorBuilder: (BuildContext context, GoRouterState state) => - TestErrorScreen(state.error!), - ); - addTearDown(router.dispose); + }, + ), + GoRoute( + path: '/target', + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), + ), + ], + errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), + ); + addTearDown(router.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: router)); - await tester.pump(); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pump(); - await redirectStarted.future; + await redirectStarted.future; - // Unmount the MaterialApp.router. - await tester.pumpWidget(const SizedBox.shrink()); + // Unmount the MaterialApp.router. + await tester.pumpWidget(const SizedBox.shrink()); - // Let the redirect complete after context is unmounted. - proceedRedirect.complete(); - await tester.pumpAndSettle(); + // Let the redirect complete after context is unmounted. + proceedRedirect.complete(); + await tester.pumpAndSettle(); - // The router should NOT have navigated to /target. - expect(find.byType(LoginScreen), findsNothing); - }, - ); + // The router should NOT have navigated to /target. + expect(find.byType(LoginScreen), findsNothing); + }); - testWidgets('top-level redirect chain works with router.go()', ( - WidgetTester tester, - ) async { + testWidgets('top-level redirect chain works with router.go()', (WidgetTester tester) async { // Start at /, no redirect from /. Navigate to /a which chains to /c. final GoRouter router = await createRouter( [ GoRoute( path: '/', - builder: (BuildContext context, GoRouterState state) => - const HomeScreen(), + builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/a', - builder: (BuildContext context, GoRouterState state) => - const DummyScreen(), + builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: '/b', - builder: (BuildContext context, GoRouterState state) => - const Page1Screen(), + builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: '/c', - builder: (BuildContext context, GoRouterState state) => - const LoginScreen(), + builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], tester, diff --git a/packages/go_router/test/request_focus.dart b/packages/go_router/test/request_focus.dart index f17cd2d25cee..7f5c7e95f70e 100644 --- a/packages/go_router/test/request_focus.dart +++ b/packages/go_router/test/request_focus.dart @@ -16,11 +16,7 @@ void main() { initialLocation: '/', routes: [ GoRoute(path: '/', name: 'home', builder: (_, __) => const Text('A')), - GoRoute( - path: '/second', - name: 'second', - builder: (_, __) => Text('B', key: innerKey), - ), + GoRoute(path: '/second', name: 'second', builder: (_, __) => Text('B', key: innerKey)), ], requestFocus: false, ); diff --git a/packages/go_router/test/route_data_test.dart b/packages/go_router/test/route_data_test.dart index 9a0089080e0f..b635b5f70a17 100644 --- a/packages/go_router/test/route_data_test.dart +++ b/packages/go_router/test/route_data_test.dart @@ -13,24 +13,21 @@ class _GoRouteDataBuild extends GoRouteData { const _GoRouteDataBuild(); @override - Widget build(BuildContext context, GoRouterState state) => - const SizedBox(key: Key('build')); + Widget build(BuildContext context, GoRouterState state) => const SizedBox(key: Key('build')); } class _RelativeGoRouteDataBuild extends RelativeGoRouteData { const _RelativeGoRouteDataBuild(); @override - Widget build(BuildContext context, GoRouterState state) => - const SizedBox(key: Key('build')); + Widget build(BuildContext context, GoRouterState state) => const SizedBox(key: Key('build')); } class _ShellRouteDataRedirectPage extends ShellRouteData { const _ShellRouteDataRedirectPage(); @override - FutureOr redirect(BuildContext context, GoRouterState state) => - '/build-page'; + FutureOr redirect(BuildContext context, GoRouterState state) => '/build-page'; } class _ShellRouteDataBuilder extends ShellRouteData { @@ -73,10 +70,7 @@ final GoRoute _relativeGoRouteDataBuild = RelativeGoRouteData.$route( final ShellRoute _shellRouteDataBuilder = ShellRouteData.$route( factory: (GoRouterState state) => const _ShellRouteDataBuilder(), routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => const _GoRouteDataBuild(), - ), + GoRouteData.$route(path: '/child', factory: (GoRouterState state) => const _GoRouteDataBuild()), ], ); @@ -100,21 +94,15 @@ class _ShellRouteDataPageBuilder extends ShellRouteData { const _ShellRouteDataPageBuilder(); @override - Page pageBuilder( - BuildContext context, - GoRouterState state, - Widget navigator, - ) => MaterialPage( - child: SizedBox(key: const Key('page-builder'), child: navigator), - ); + Page pageBuilder(BuildContext context, GoRouterState state, Widget navigator) => + MaterialPage(child: SizedBox(key: const Key('page-builder'), child: navigator)); } class _StatefulShellRouteDataRedirectPage extends StatefulShellRouteData { const _StatefulShellRouteDataRedirectPage(); @override - FutureOr redirect(BuildContext context, GoRouterState state) => - '/build-page'; + FutureOr redirect(BuildContext context, GoRouterState state) => '/build-page'; } final GoRoute _goRouteDataBuildPage = GoRouteData.$route( @@ -130,10 +118,7 @@ final GoRoute _relativeGoRouteDataBuildPage = RelativeGoRouteData.$route( final ShellRoute _shellRouteDataPageBuilder = ShellRouteData.$route( factory: (GoRouterState state) => const _ShellRouteDataPageBuilder(), routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => const _GoRouteDataBuild(), - ), + GoRouteData.$route(path: '/child', factory: (GoRouterState state) => const _GoRouteDataBuild()), ], ); @@ -156,27 +141,23 @@ class _StatefulShellRouteDataBuilder extends StatefulShellRouteData { const _StatefulShellRouteDataBuilder(); @override - Widget builder( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigator, - ) => SizedBox(key: const Key('builder'), child: navigator); + Widget builder(BuildContext context, GoRouterState state, StatefulNavigationShell navigator) => + SizedBox(key: const Key('builder'), child: navigator); } -final StatefulShellRoute _statefulShellRouteDataBuilder = - StatefulShellRouteData.$route( - factory: (GoRouterState state) => const _StatefulShellRouteDataBuilder(), - branches: [ - StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => const _GoRouteDataBuild(), - ), - ], +final StatefulShellRoute _statefulShellRouteDataBuilder = StatefulShellRouteData.$route( + factory: (GoRouterState state) => const _StatefulShellRouteDataBuilder(), + branches: [ + StatefulShellBranchData.$branch( + routes: [ + GoRouteData.$route( + path: '/child', + factory: (GoRouterState state) => const _GoRouteDataBuild(), ), ], - ); + ), + ], +); class _StatefulShellRouteDataPageBuilder extends StatefulShellRouteData { const _StatefulShellRouteDataPageBuilder(); @@ -186,41 +167,35 @@ class _StatefulShellRouteDataPageBuilder extends StatefulShellRouteData { BuildContext context, GoRouterState state, StatefulNavigationShell navigator, - ) => MaterialPage( - child: SizedBox(key: const Key('page-builder'), child: navigator), - ); + ) => MaterialPage(child: SizedBox(key: const Key('page-builder'), child: navigator)); } -final StatefulShellRoute _statefulShellRouteDataPageBuilder = - StatefulShellRouteData.$route( - factory: (GoRouterState state) => - const _StatefulShellRouteDataPageBuilder(), - branches: [ - StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => const _GoRouteDataBuild(), - ), - ], +final StatefulShellRoute _statefulShellRouteDataPageBuilder = StatefulShellRouteData.$route( + factory: (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(), + branches: [ + StatefulShellBranchData.$branch( + routes: [ + GoRouteData.$route( + path: '/child', + factory: (GoRouterState state) => const _GoRouteDataBuild(), ), ], - ); + ), + ], +); class _GoRouteDataRedirectPage extends GoRouteData { const _GoRouteDataRedirectPage(); @override - FutureOr redirect(BuildContext context, GoRouterState state) => - '/build-page'; + FutureOr redirect(BuildContext context, GoRouterState state) => '/build-page'; } class _RelativeGoRouteDataRedirectPage extends RelativeGoRouteData { const _RelativeGoRouteDataRedirectPage(); @override - FutureOr redirect(BuildContext context, GoRouterState state) => - '/build-page'; + FutureOr redirect(BuildContext context, GoRouterState state) => '/build-page'; } final GoRoute _goRouteDataRedirect = GoRouteData.$route( @@ -275,65 +250,53 @@ void main() { expect(find.byKey(const Key('buildPage')), findsNothing); }); - testWidgets( - 'It should build the page from the overridden buildPage method', - (WidgetTester tester) async { - final goRouter = GoRouter( - initialLocation: '/build-page', - routes: _routes, - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('build')), findsNothing); - expect(find.byKey(const Key('buildPage')), findsOneWidget); - }, - ); - - testWidgets( - 'It should build a go route with the default case sensitivity', - (WidgetTester tester) async { - final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route( - path: '/path', - factory: (GoRouterState state) => const _GoRouteDataBuild(), - ); - - expect(routeWithDefaultCaseSensitivity.caseSensitive, true); - }, - ); + testWidgets('It should build the page from the overridden buildPage method', ( + WidgetTester tester, + ) async { + final goRouter = GoRouter(initialLocation: '/build-page', routes: _routes); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('build')), findsNothing); + expect(find.byKey(const Key('buildPage')), findsOneWidget); + }); - testWidgets( - 'It should build a go route with the overridden case sensitivity', - (WidgetTester tester) async { - final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route( - path: '/path', - caseSensitive: false, - factory: (GoRouterState state) => const _GoRouteDataBuild(), - ); + testWidgets('It should build a go route with the default case sensitivity', ( + WidgetTester tester, + ) async { + final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route( + path: '/path', + factory: (GoRouterState state) => const _GoRouteDataBuild(), + ); - expect(routeWithDefaultCaseSensitivity.caseSensitive, false); - }, - ); + expect(routeWithDefaultCaseSensitivity.caseSensitive, true); + }); - testWidgets('It should throw because there is no code generated', ( + testWidgets('It should build a go route with the overridden case sensitivity', ( WidgetTester tester, ) async { + final GoRoute routeWithDefaultCaseSensitivity = GoRouteData.$route( + path: '/path', + caseSensitive: false, + factory: (GoRouterState state) => const _GoRouteDataBuild(), + ); + + expect(routeWithDefaultCaseSensitivity.caseSensitive, false); + }); + + testWidgets('It should throw because there is no code generated', (WidgetTester tester) async { final errors = []; - FlutterError.onError = (FlutterErrorDetails details) => - errors.add(details); + FlutterError.onError = (FlutterErrorDetails details) => errors.add(details); const errorText = 'Should be generated'; - Future expectUnimplementedError( - void Function(BuildContext) onTap, - ) async { + Future expectUnimplementedError(void Function(BuildContext) onTap) async { await tester.pumpWidget( MaterialApp( home: Builder( - builder: (BuildContext context) => GestureDetector( - child: const Text('Tap'), - onTap: () => onTap(context), - ), + builder: + (BuildContext context) => + GestureDetector(child: const Text('Tap'), onTap: () => onTap(context)), ), ), ); @@ -373,79 +336,60 @@ void main() { testWidgets('It should build the page from the overridden build method', ( WidgetTester tester, ) async { - final goRouter = GoRouter( - initialLocation: '/build', - routes: _relativeRoutes, - ); + final goRouter = GoRouter(initialLocation: '/build', routes: _relativeRoutes); addTearDown(goRouter.dispose); await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); expect(find.byKey(const Key('build')), findsOneWidget); expect(find.byKey(const Key('buildPage')), findsNothing); }); - testWidgets( - 'It should build the page from the overridden buildPage method', - (WidgetTester tester) async { - final goRouter = GoRouter( - initialLocation: '/build-page', - routes: _relativeRoutes, - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('build')), findsNothing); - expect(find.byKey(const Key('buildPage')), findsOneWidget); - }, - ); + testWidgets('It should build the page from the overridden buildPage method', ( + WidgetTester tester, + ) async { + final goRouter = GoRouter(initialLocation: '/build-page', routes: _relativeRoutes); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('build')), findsNothing); + expect(find.byKey(const Key('buildPage')), findsOneWidget); + }); - testWidgets( - 'It should build a go route with the default case sensitivity', - (WidgetTester tester) async { - final GoRoute routeWithDefaultCaseSensitivity = - RelativeGoRouteData.$route( - path: 'path', - factory: (GoRouterState state) => - const _RelativeGoRouteDataBuild(), - ); - - expect(routeWithDefaultCaseSensitivity.caseSensitive, true); - }, - ); + testWidgets('It should build a go route with the default case sensitivity', ( + WidgetTester tester, + ) async { + final GoRoute routeWithDefaultCaseSensitivity = RelativeGoRouteData.$route( + path: 'path', + factory: (GoRouterState state) => const _RelativeGoRouteDataBuild(), + ); - testWidgets( - 'It should build a go route with the overridden case sensitivity', - (WidgetTester tester) async { - final GoRoute routeWithDefaultCaseSensitivity = - RelativeGoRouteData.$route( - path: 'path', - caseSensitive: false, - factory: (GoRouterState state) => - const _RelativeGoRouteDataBuild(), - ); - - expect(routeWithDefaultCaseSensitivity.caseSensitive, false); - }, - ); + expect(routeWithDefaultCaseSensitivity.caseSensitive, true); + }); - testWidgets('It should throw because there is no code generated', ( + testWidgets('It should build a go route with the overridden case sensitivity', ( WidgetTester tester, ) async { + final GoRoute routeWithDefaultCaseSensitivity = RelativeGoRouteData.$route( + path: 'path', + caseSensitive: false, + factory: (GoRouterState state) => const _RelativeGoRouteDataBuild(), + ); + + expect(routeWithDefaultCaseSensitivity.caseSensitive, false); + }); + + testWidgets('It should throw because there is no code generated', (WidgetTester tester) async { final errors = []; - FlutterError.onError = (FlutterErrorDetails details) => - errors.add(details); + FlutterError.onError = (FlutterErrorDetails details) => errors.add(details); const errorText = 'Should be generated'; - Future expectUnimplementedError( - void Function(BuildContext) onTap, - ) async { + Future expectUnimplementedError(void Function(BuildContext) onTap) async { await tester.pumpWidget( MaterialApp( home: Builder( - builder: (BuildContext context) => GestureDetector( - child: const Text('Tap'), - onTap: () => onTap(context), - ), + builder: + (BuildContext context) => + GestureDetector(child: const Text('Tap'), onTap: () => onTap(context)), ), ), ); @@ -509,25 +453,23 @@ void main() { initialLocation: '/child/test', routes: [ ShellRouteData.$route( - factory: (GoRouterState state) => - const _ShellRouteDataWithKey(Key('under-shell')), + factory: (GoRouterState state) => const _ShellRouteDataWithKey(Key('under-shell')), routes: [ GoRouteData.$route( path: '/child', - factory: (GoRouterState state) => - const _GoRouteDataBuildWithKey(Key('under')), + factory: (GoRouterState state) => const _GoRouteDataBuildWithKey(Key('under')), routes: [ ShellRouteData.$route( - factory: (GoRouterState state) => - const _ShellRouteDataWithKey(Key('above-shell')), + factory: + (GoRouterState state) => const _ShellRouteDataWithKey(Key('above-shell')), navigatorKey: inner, parentNavigatorKey: root, routes: [ GoRouteData.$route( parentNavigatorKey: inner, path: 'test', - factory: (GoRouterState state) => - const _GoRouteDataBuildWithKey(Key('above')), + factory: + (GoRouterState state) => const _GoRouteDataBuildWithKey(Key('above')), ), ], ), @@ -555,19 +497,18 @@ void main() { expect(find.byKey(const Key('above')), findsNothing); }); - testWidgets( - 'It should build the page from the overridden buildPage method', - (WidgetTester tester) async { - final goRouter = GoRouter( - initialLocation: '/child', - routes: [_shellRouteDataPageBuilder], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('builder')), findsNothing); - expect(find.byKey(const Key('page-builder')), findsOneWidget); - }, - ); + testWidgets('It should build the page from the overridden buildPage method', ( + WidgetTester tester, + ) async { + final goRouter = GoRouter( + initialLocation: '/child', + routes: [_shellRouteDataPageBuilder], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('builder')), findsNothing); + expect(find.byKey(const Key('page-builder')), findsOneWidget); + }); testWidgets('It should redirect using the overridden redirect method', ( WidgetTester tester, @@ -597,26 +538,24 @@ void main() { expect(find.byKey(const Key('page-builder')), findsNothing); }); - testWidgets( - 'It should build the page from the overridden buildPage method', - (WidgetTester tester) async { - final goRouter = GoRouter( - initialLocation: '/child', - routes: [_statefulShellRouteDataPageBuilder], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('builder')), findsNothing); - expect(find.byKey(const Key('page-builder')), findsOneWidget); - }, - ); + testWidgets('It should build the page from the overridden buildPage method', ( + WidgetTester tester, + ) async { + final goRouter = GoRouter( + initialLocation: '/child', + routes: [_statefulShellRouteDataPageBuilder], + ); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('builder')), findsNothing); + expect(find.byKey(const Key('page-builder')), findsOneWidget); + }); test('Can assign parent navigator key', () { final key = GlobalKey(); final StatefulShellRoute route = StatefulShellRouteData.$route( parentNavigatorKey: key, - factory: (GoRouterState state) => - const _StatefulShellRouteDataPageBuilder(), + factory: (GoRouterState state) => const _StatefulShellRouteDataPageBuilder(), branches: [ StatefulShellBranchData.$branch( routes: [ @@ -657,46 +596,41 @@ void main() { expect(find.byKey(const Key('buildPage')), findsOneWidget); }); - testWidgets( - 'It should redirect using the overridden StatefulShellRoute redirect method', - (WidgetTester tester) async { - final goRouter = GoRouter( - initialLocation: '/child', - routes: [ - _goRouteDataBuildPage, - StatefulShellRouteData.$route( - factory: (GoRouterState state) => - const _StatefulShellRouteDataRedirectPage(), - branches: [ - StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route( - path: '/child', - factory: (GoRouterState state) => const _GoRouteDataBuild(), - ), - ], - ), - ], - ), - ], - ); - addTearDown(goRouter.dispose); - await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); - expect(find.byKey(const Key('build')), findsNothing); - expect(find.byKey(const Key('buildPage')), findsOneWidget); - }, - ); - - testWidgets('It should redirect using the overridden redirect method', ( + testWidgets('It should redirect using the overridden StatefulShellRoute redirect method', ( WidgetTester tester, ) async { final goRouter = GoRouter( - initialLocation: '/redirect-with-state', - routes: _routes, + initialLocation: '/child', + routes: [ + _goRouteDataBuildPage, + StatefulShellRouteData.$route( + factory: (GoRouterState state) => const _StatefulShellRouteDataRedirectPage(), + branches: [ + StatefulShellBranchData.$branch( + routes: [ + GoRouteData.$route( + path: '/child', + factory: (GoRouterState state) => const _GoRouteDataBuild(), + ), + ], + ), + ], + ), + ], ); addTearDown(goRouter.dispose); await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); expect(find.byKey(const Key('build')), findsNothing); + expect(find.byKey(const Key('buildPage')), findsOneWidget); + }); + + testWidgets('It should redirect using the overridden redirect method', ( + WidgetTester tester, + ) async { + final goRouter = GoRouter(initialLocation: '/redirect-with-state', routes: _routes); + addTearDown(goRouter.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); + expect(find.byKey(const Key('build')), findsNothing); expect(find.byKey(const Key('buildPage')), findsNothing); }); test('TypedGoRoute with default parameters', () { @@ -714,11 +648,7 @@ void main() { name: 'name', caseSensitive: false, routes: >[ - TypedGoRoute( - path: 'sub-path', - name: 'subName', - caseSensitive: false, - ), + TypedGoRoute(path: 'sub-path', name: 'subName', caseSensitive: false), ], ); @@ -729,38 +659,21 @@ void main() { expect( typedGoRoute.routes.single, isA>() - .having( - (TypedGoRoute route) => route.path, - 'path', - 'sub-path', - ) - .having( - (TypedGoRoute route) => route.name, - 'name', - 'subName', - ) - .having( - (TypedGoRoute route) => route.caseSensitive, - 'caseSensitive', - false, - ), + .having((TypedGoRoute route) => route.path, 'path', 'sub-path') + .having((TypedGoRoute route) => route.name, 'name', 'subName') + .having((TypedGoRoute route) => route.caseSensitive, 'caseSensitive', false), ); }); test('CustomParameterCodec with required parameters', () { - const customParameterCodec = CustomParameterCodec( - encode: toBase64, - decode: fromBase64, - ); + const customParameterCodec = CustomParameterCodec(encode: toBase64, decode: fromBase64); expect(customParameterCodec.encode, toBase64); expect(customParameterCodec.decode, fromBase64); }); test('TypedRelativeGoRoute with default parameters', () { - const typedGoRoute = TypedRelativeGoRoute( - path: 'path', - ); + const typedGoRoute = TypedRelativeGoRoute(path: 'path'); expect(typedGoRoute.path, 'path'); expect(typedGoRoute.caseSensitive, true); @@ -772,10 +685,7 @@ void main() { path: 'path', caseSensitive: false, routes: >[ - TypedRelativeGoRoute( - path: 'sub-path', - caseSensitive: false, - ), + TypedRelativeGoRoute(path: 'sub-path', caseSensitive: false), ], ); @@ -791,8 +701,7 @@ void main() { 'sub-path', ) .having( - (TypedRelativeGoRoute route) => - route.caseSensitive, + (TypedRelativeGoRoute route) => route.caseSensitive, 'caseSensitive', false, ), @@ -800,9 +709,7 @@ void main() { }); test('TypedQueryParameter stores the name', () { - const TypedQueryParameter parameter = TypedQueryParameter( - name: 'customName', - ); + const TypedQueryParameter parameter = TypedQueryParameter(name: 'customName'); expect(parameter.name, 'customName'); }); diff --git a/packages/go_router/test/routing_config_test.dart b/packages/go_router/test/routing_config_test.dart index 762526ad3f3d..c07605d432bb 100644 --- a/packages/go_router/test/routing_config_test.dart +++ b/packages/go_router/test/routing_config_test.dart @@ -13,9 +13,7 @@ void main() { testWidgets('routing config works', (WidgetTester tester) async { final config = ValueNotifier( RoutingConfig( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Text('home')), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Text('home'))], redirect: (_, __) => '/', ), ); @@ -28,14 +26,10 @@ void main() { expect(find.text('home'), findsOneWidget); }); - testWidgets('routing config works after builder changes', ( - WidgetTester tester, - ) async { + testWidgets('routing config works after builder changes', (WidgetTester tester) async { final config = ValueNotifier( RoutingConfig( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Text('home')), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Text('home'))], ), ); addTearDown(config.dispose); @@ -43,22 +37,16 @@ void main() { expect(find.text('home'), findsOneWidget); config.value = RoutingConfig( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Text('home1')), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Text('home1'))], ); await tester.pumpAndSettle(); expect(find.text('home1'), findsOneWidget); }); - testWidgets('routing config works after routing changes', ( - WidgetTester tester, - ) async { + testWidgets('routing config works after routing changes', (WidgetTester tester) async { final config = ValueNotifier( RoutingConfig( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Text('home')), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Text('home'))], ), ); addTearDown(config.dispose); @@ -83,9 +71,7 @@ void main() { expect(find.text('/abc'), findsOneWidget); }); - testWidgets('routing config works after routing changes case 2', ( - WidgetTester tester, - ) async { + testWidgets('routing config works after routing changes case 2', (WidgetTester tester) async { final config = ValueNotifier( RoutingConfig( routes: [ @@ -107,28 +93,20 @@ void main() { expect(find.text('/abc'), findsOneWidget); config.value = RoutingConfig( - routes: [ - GoRoute(path: '/', builder: (_, __) => const Text('home')), - ], + routes: [GoRoute(path: '/', builder: (_, __) => const Text('home'))], ); await tester.pumpAndSettle(); expect(find.text('error'), findsOneWidget); }); - testWidgets('routing config works after routing changes case 3', ( - WidgetTester tester, - ) async { + testWidgets('routing config works after routing changes case 3', (WidgetTester tester) async { final key = GlobalKey<_StatefulTestState>(debugLabel: 'testState'); final rootNavigatorKey = GlobalKey(debugLabel: 'root'); final config = ValueNotifier( RoutingConfig( routes: [ - GoRoute( - path: '/', - builder: (_, __) => - StatefulTest(key: key, child: const Text('home')), - ), + GoRoute(path: '/', builder: (_, __) => StatefulTest(key: key, child: const Text('home'))), ], ), ); @@ -144,10 +122,7 @@ void main() { config.value = RoutingConfig( routes: [ - GoRoute( - path: '/', - builder: (_, __) => StatefulTest(key: key, child: const Text('home')), - ), + GoRoute(path: '/', builder: (_, __) => StatefulTest(key: key, child: const Text('home'))), GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')), ], ); @@ -169,11 +144,8 @@ void main() { routes: [ ShellRoute( navigatorKey: shellNavigatorKey, - routes: [ - GoRoute(path: '/', builder: (_, __) => const Text('home')), - ], - builder: (_, __, Widget widget) => - StatefulTest(key: key, child: widget), + routes: [GoRoute(path: '/', builder: (_, __) => const Text('home'))], + builder: (_, __, Widget widget) => StatefulTest(key: key, child: widget), ), ], ), @@ -196,8 +168,7 @@ void main() { GoRoute(path: '/', builder: (_, __) => const Text('home')), GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')), ], - builder: (_, __, Widget widget) => - StatefulTest(key: key, child: widget), + builder: (_, __, Widget widget) => StatefulTest(key: key, child: widget), ), ], ); @@ -207,18 +178,12 @@ void main() { }, ); - testWidgets('routing config works with named route', ( - WidgetTester tester, - ) async { + testWidgets('routing config works with named route', (WidgetTester tester) async { final config = ValueNotifier( RoutingConfig( routes: [ GoRoute(path: '/', builder: (_, __) => const Text('home')), - GoRoute( - path: '/abc', - name: 'abc', - builder: (_, __) => const Text('/abc'), - ), + GoRoute(path: '/abc', name: 'abc', builder: (_, __) => const Text('/abc')), ], ), ); @@ -237,16 +202,8 @@ void main() { config.value = RoutingConfig( routes: [ - GoRoute( - path: '/', - name: 'home', - builder: (_, __) => const Text('home'), - ), - GoRoute( - path: '/abc', - name: 'def', - builder: (_, __) => const Text('def'), - ), + GoRoute(path: '/', name: 'home', builder: (_, __) => const Text('home')), + GoRoute(path: '/abc', name: 'def', builder: (_, __) => const Text('def')), ], ); await tester.pumpAndSettle(); diff --git a/packages/go_router/test/shell_route_observers_test.dart b/packages/go_router/test/shell_route_observers_test.dart index 8d95373796f6..bf09bce5c844 100644 --- a/packages/go_router/test/shell_route_observers_test.dart +++ b/packages/go_router/test/shell_route_observers_test.dart @@ -28,50 +28,42 @@ void main() { expect(shell.observers!.length, 1); }); - testWidgets( - 'GoRouter observers should be notified when navigating within ShellRoute', - (WidgetTester tester) async { - final observer = MockObserver(); + testWidgets('GoRouter observers should be notified when navigating within ShellRoute', ( + WidgetTester tester, + ) async { + final observer = MockObserver(); - final root = GlobalKey(debugLabel: 'root'); - await createRouter( - [ - GoRoute(path: '/', builder: (_, __) => const Text('Home')), - ShellRoute( - builder: (_, __, Widget child) => child, - routes: [ - GoRoute(path: '/test1', builder: (_, __) => const Text('Test1')), - ], - ), - StatefulShellRoute.indexedStack( - builder: (_, __, Widget child) => child, - branches: [ - StatefulShellBranch( - routes: [ - GoRoute( - path: '/test2', - builder: (_, __) => const Text('Test2'), - ), - ], - ), - ], - ), - ], - tester, - navigatorKey: root, - observers: [observer], - ); - await tester.pumpAndSettle(); + final root = GlobalKey(debugLabel: 'root'); + await createRouter( + [ + GoRoute(path: '/', builder: (_, __) => const Text('Home')), + ShellRoute( + builder: (_, __, Widget child) => child, + routes: [GoRoute(path: '/test1', builder: (_, __) => const Text('Test1'))], + ), + StatefulShellRoute.indexedStack( + builder: (_, __, Widget child) => child, + branches: [ + StatefulShellBranch( + routes: [GoRoute(path: '/test2', builder: (_, __) => const Text('Test2'))], + ), + ], + ), + ], + tester, + navigatorKey: root, + observers: [observer], + ); + await tester.pumpAndSettle(); - root.currentContext!.push('/test1'); - await tester.pumpAndSettle(); - expect(observer.getCallCount('/test1'), 1); + root.currentContext!.push('/test1'); + await tester.pumpAndSettle(); + expect(observer.getCallCount('/test1'), 1); - root.currentContext!.push('/test2'); - await tester.pumpAndSettle(); - expect(observer.getCallCount('/test2'), 1); - }, - ); + root.currentContext!.push('/test2'); + await tester.pumpAndSettle(); + expect(observer.getCallCount('/test2'), 1); + }); } class MockObserver extends NavigatorObserver { diff --git a/packages/go_router/test/shell_route_system_back_test.dart b/packages/go_router/test/shell_route_system_back_test.dart index 3d7ef89654ca..ac2fca2f6db5 100644 --- a/packages/go_router/test/shell_route_system_back_test.dart +++ b/packages/go_router/test/shell_route_system_back_test.dart @@ -138,9 +138,7 @@ class _TestAppState extends State<_TestApp> { GoRoute( path: 'comment', builder: (BuildContext context, GoRouterState state) { - return Scaffold( - appBar: AppBar(title: const Text('Comment')), - ); + return Scaffold(appBar: AppBar(title: const Text('Comment'))); }, ), ], diff --git a/packages/go_router/test/stateful_shell_route_system_back_test.dart b/packages/go_router/test/stateful_shell_route_system_back_test.dart index 834af97b01b4..a97fdd4dd038 100644 --- a/packages/go_router/test/stateful_shell_route_system_back_test.dart +++ b/packages/go_router/test/stateful_shell_route_system_back_test.dart @@ -117,14 +117,13 @@ class _TestAppState extends State<_TestApp> { }, routes: [ StatefulShellRoute.indexedStack( - builder: - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - return navigationShell; - }, + builder: ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, + ) { + return navigationShell; + }, branches: [ StatefulShellBranch( routes: [ @@ -147,9 +146,7 @@ class _TestAppState extends State<_TestApp> { GoRoute( path: 'comment', builder: (BuildContext context, GoRouterState state) { - return Scaffold( - appBar: AppBar(title: const Text('Comment')), - ); + return Scaffold(appBar: AppBar(title: const Text('Comment'))); }, ), ], diff --git a/packages/go_router/test/test_helpers.dart b/packages/go_router/test/test_helpers.dart index 6a0b84960157..2789c3cef3fd 100644 --- a/packages/go_router/test/test_helpers.dart +++ b/packages/go_router/test/test_helpers.dart @@ -17,27 +17,18 @@ Future createGoRouter(WidgetTester tester) async { initialLocation: '/', routes: [ GoRoute(path: '/', builder: (_, __) => const DummyStatefulWidget()), - GoRoute( - path: '/error', - builder: (_, __) => TestErrorScreen(TestFailure('Exception')), - ), + GoRoute(path: '/error', builder: (_, __) => TestErrorScreen(TestFailure('Exception'))), ], ); await tester.pumpWidget(MaterialApp.router(routerConfig: goRouter)); return goRouter; } -Widget fakeNavigationBuilder( - BuildContext context, - GoRouterState state, - Widget child, -) => child; +Widget fakeNavigationBuilder(BuildContext context, GoRouterState state, Widget child) => child; class GoRouterNamedLocationSpy extends GoRouter { GoRouterNamedLocationSpy({required List routes}) - : super.routingConfig( - routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), - ); + : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? name; Map? pathParameters; @@ -61,9 +52,7 @@ class GoRouterNamedLocationSpy extends GoRouter { class GoRouterGoSpy extends GoRouter { GoRouterGoSpy({required List routes}) - : super.routingConfig( - routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), - ); + : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? myLocation; Object? extra; @@ -77,9 +66,7 @@ class GoRouterGoSpy extends GoRouter { class GoRouterGoNamedSpy extends GoRouter { GoRouterGoNamedSpy({required List routes}) - : super.routingConfig( - routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), - ); + : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? name; Map? pathParameters; @@ -105,9 +92,7 @@ class GoRouterGoNamedSpy extends GoRouter { class GoRouterPushSpy extends GoRouter { GoRouterPushSpy({required List routes}) - : super.routingConfig( - routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), - ); + : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? myLocation; Object? extra; @@ -122,9 +107,7 @@ class GoRouterPushSpy extends GoRouter { class GoRouterPushNamedSpy extends GoRouter { GoRouterPushNamedSpy({required List routes}) - : super.routingConfig( - routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), - ); + : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); String? name; Map? pathParameters; @@ -148,9 +131,7 @@ class GoRouterPushNamedSpy extends GoRouter { class GoRouterPopSpy extends GoRouter { GoRouterPopSpy({required List routes}) - : super.routingConfig( - routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes)), - ); + : super.routingConfig(routingConfig: ConstantRoutingConfig(RoutingConfig(routes: routes))); bool popped = false; Object? poppedResult; @@ -196,9 +177,7 @@ Future createRouter( addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( - restorationScopeId: restorationScopeId != null - ? '$restorationScopeId-root' - : null, + restorationScopeId: restorationScopeId != null ? '$restorationScopeId-root' : null, routerConfig: goRouter, ), ); @@ -231,9 +210,7 @@ Future createRouterWithRoutingConfig( addTearDown(goRouter.dispose); await tester.pumpWidget( MaterialApp.router( - restorationScopeId: restorationScopeId != null - ? '$restorationScopeId-root' - : null, + restorationScopeId: restorationScopeId != null ? '$restorationScopeId-root' : null, routerConfig: goRouter, ), ); @@ -282,10 +259,7 @@ class PersonScreen extends DummyScreen { } class DummyScreen extends StatelessWidget { - const DummyScreen({ - this.queryParametersAll = const {}, - super.key, - }); + const DummyScreen({this.queryParametersAll = const {}, super.key}); final Map queryParametersAll; @@ -324,8 +298,7 @@ class DummyRestorableStatefulWidget extends StatefulWidget { State createState() => DummyRestorableStatefulWidgetState(); } -class DummyRestorableStatefulWidgetState - extends State +class DummyRestorableStatefulWidgetState extends State with RestorationMixin { final RestorableInt _counter = RestorableInt(0); @@ -356,9 +329,7 @@ class DummyRestorableStatefulWidgetState } Future simulateAndroidBackButton(WidgetTester tester) async { - final ByteData message = const JSONMethodCodec().encodeMethodCall( - const MethodCall('popRoute'), - ); + final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/navigation', message, @@ -370,21 +341,17 @@ Future simulateIosBackGesture(WidgetTester tester) async { await tester.dragFrom(const Offset(0, 300), const Offset(500, 300)); } -GoRouterPageBuilder createPageBuilder({ - String? restorationId, - required Widget child, -}) => +GoRouterPageBuilder createPageBuilder({String? restorationId, required Widget child}) => (BuildContext context, GoRouterState state) => MaterialPage(restorationId: restorationId, child: child); -StatefulShellRouteBuilder mockStackedShellBuilder = - ( - BuildContext context, - GoRouterState state, - StatefulNavigationShell navigationShell, - ) { - return navigationShell; - }; +StatefulShellRouteBuilder mockStackedShellBuilder = ( + BuildContext context, + GoRouterState state, + StatefulNavigationShell navigationShell, +) { + return navigationShell; +}; /// A routing config that is never going to change. class ConstantRoutingConfig extends ValueListenable { @@ -411,11 +378,7 @@ RouteConfiguration createRouteConfiguration({ }) { return RouteConfiguration( ConstantRoutingConfig( - RoutingConfig( - routes: routes, - redirect: topRedirect, - redirectLimit: redirectLimit, - ), + RoutingConfig(routes: routes, redirect: topRedirect, redirectLimit: redirectLimit), ), navigatorKey: navigatorKey, ); @@ -429,8 +392,8 @@ class SimpleDependencyProvider extends InheritedNotifier { }) : super(notifier: dependency); static SimpleDependency of(BuildContext context) { - final SimpleDependencyProvider result = context - .dependOnInheritedWidgetOfExactType()!; + final SimpleDependencyProvider result = + context.dependOnInheritedWidgetOfExactType()!; return result.notifier!; } } diff --git a/packages/go_router/tool/run_tests.dart b/packages/go_router/tool/run_tests.dart index 0c1e0f907a22..6c602ef10f75 100644 --- a/packages/go_router/tool/run_tests.dart +++ b/packages/go_router/tool/run_tests.dart @@ -19,9 +19,7 @@ import 'package:path/path.dart' as p; // that references `go_router`, and running `dart fix --compare-to-golden` // on the temp directory. Future main(List args) async { - final Directory goRouterPackageRoot = File.fromUri( - Platform.script, - ).parent.parent; + final Directory goRouterPackageRoot = File.fromUri(Platform.script).parent.parent; final Directory testTempDir = await Directory.systemTemp.createTemp(); @@ -34,10 +32,7 @@ Future main(List args) async { // Copy the test_fixes folder to the temporary testFixesTargetDir. // // This also creates the proper pubspec.yaml in the temp directory. - await _prepareTemplate( - packageRoot: goRouterPackageRoot, - testTempDir: testTempDir, - ); + await _prepareTemplate(packageRoot: goRouterPackageRoot, testTempDir: testTempDir); // Run dart pub get in the temp directory to set it up. final int pubGetStatusCode = await _runProcess('dart', [ @@ -71,8 +66,7 @@ Future _prepareTemplate({ // The pubspec.yaml file to create. final targetPubspecFile = File(p.join(testTempDir.path, 'pubspec.yaml')); - final targetYaml = - ''' + final targetYaml = ''' name: test_fixes publish_to: "none" version: 1.0.0 @@ -98,11 +92,7 @@ Future _streamOutput(Future processFuture) async { return process; } -Future _runProcess( - String command, - List arguments, { - String? workingDirectory, -}) async { +Future _runProcess(String command, List arguments, {String? workingDirectory}) async { final Process process = await _streamOutput( Process.start(command, arguments, workingDirectory: workingDirectory), ); diff --git a/packages/go_router_builder/example/lib/all_extension_types.dart b/packages/go_router_builder/example/lib/all_extension_types.dart index eb357df56d45..97d870b70b30 100644 --- a/packages/go_router_builder/example/lib/all_extension_types.dart +++ b/packages/go_router_builder/example/lib/all_extension_types.dart @@ -14,28 +14,16 @@ part 'all_extension_types.g.dart'; @TypedGoRoute( path: '/', routes: >[ - TypedGoRoute( - path: 'big-int-route/:requiredBigIntField', - ), + TypedGoRoute(path: 'big-int-route/:requiredBigIntField'), TypedGoRoute(path: 'bool-route/:requiredBoolField'), - TypedGoRoute( - path: 'date-time-route/:requiredDateTimeField', - ), - TypedGoRoute( - path: 'double-route/:requiredDoubleField', - ), + TypedGoRoute(path: 'date-time-route/:requiredDateTimeField'), + TypedGoRoute(path: 'double-route/:requiredDoubleField'), TypedGoRoute(path: 'int-route/:requiredIntField'), TypedGoRoute(path: 'num-route/:requiredNumField'), - TypedGoRoute( - path: 'double-route/:requiredDoubleField', - ), + TypedGoRoute(path: 'double-route/:requiredDoubleField'), TypedGoRoute(path: 'enum-route/:requiredEnumField'), - TypedGoRoute( - path: 'enhanced-enum-route/:requiredEnumField', - ), - TypedGoRoute( - path: 'string-route/:requiredStringField', - ), + TypedGoRoute(path: 'enhanced-enum-route/:requiredEnumField'), + TypedGoRoute(path: 'string-route/:requiredStringField'), TypedGoRoute(path: 'uri-route/:requiredUriField'), ], ) @@ -49,21 +37,27 @@ class AllTypesBaseRoute extends GoRouteData with $AllTypesBaseRoute { } extension type const BigIntExtension(BigInt value) {} + extension type const BoolExtension(bool value) {} + extension type const DateTimeExtension(DateTime value) {} + extension type const DoubleExtension(double value) {} + extension type const IntExtension(int value) {} + extension type const NumExtension(num value) {} + extension type const StringExtension(String value) {} + extension type const UriExtension(Uri value) {} + extension type const PersonDetailsExtension(PersonDetails value) {} + extension type const SportDetailsExtension(SportDetails value) {} class BigIntExtensionRoute extends GoRouteData with $BigIntExtensionRoute { - const BigIntExtensionRoute({ - required this.requiredBigIntField, - this.bigIntField, - }); + const BigIntExtensionRoute({required this.requiredBigIntField, this.bigIntField}); final BigIntExtension requiredBigIntField; final BigIntExtension? bigIntField; @@ -109,10 +103,7 @@ class BoolExtensionRoute extends GoRouteData with $BoolExtensionRoute { } class DateTimeExtensionRoute extends GoRouteData with $DateTimeExtensionRoute { - const DateTimeExtensionRoute({ - required this.requiredDateTimeField, - this.dateTimeField, - }); + const DateTimeExtensionRoute({required this.requiredDateTimeField, this.dateTimeField}); final DateTimeExtension requiredDateTimeField; final DateTimeExtension? dateTimeField; @@ -213,9 +204,7 @@ class EnumExtensionRoute extends GoRouteData with $EnumExtensionRoute { const EnumExtensionRoute({ required this.requiredEnumField, this.enumField, - this.enumFieldWithDefaultValue = const PersonDetailsExtension( - PersonDetails.favoriteFood, - ), + this.enumFieldWithDefaultValue = const PersonDetailsExtension(PersonDetails.favoriteFood), }); final PersonDetailsExtension requiredEnumField; @@ -223,13 +212,12 @@ class EnumExtensionRoute extends GoRouteData with $EnumExtensionRoute { final PersonDetailsExtension enumFieldWithDefaultValue; @override - Widget build(BuildContext context, GoRouterState state) => - BasePage( - dataTitle: 'EnumExtensionRoute', - param: requiredEnumField.value, - queryParam: enumField?.value, - queryParamWithDefaultValue: enumFieldWithDefaultValue.value, - ); + Widget build(BuildContext context, GoRouterState state) => BasePage( + dataTitle: 'EnumExtensionRoute', + param: requiredEnumField.value, + queryParam: enumField?.value, + queryParamWithDefaultValue: enumFieldWithDefaultValue.value, + ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('EnumExtensionRoute'), @@ -238,14 +226,11 @@ class EnumExtensionRoute extends GoRouteData with $EnumExtensionRoute { ); } -class EnhancedEnumExtensionRoute extends GoRouteData - with $EnhancedEnumExtensionRoute { +class EnhancedEnumExtensionRoute extends GoRouteData with $EnhancedEnumExtensionRoute { const EnhancedEnumExtensionRoute({ required this.requiredEnumField, this.enumField, - this.enumFieldWithDefaultValue = const SportDetailsExtension( - SportDetails.football, - ), + this.enumFieldWithDefaultValue = const SportDetailsExtension(SportDetails.football), }); final SportDetailsExtension requiredEnumField; @@ -253,13 +238,12 @@ class EnhancedEnumExtensionRoute extends GoRouteData final SportDetailsExtension enumFieldWithDefaultValue; @override - Widget build(BuildContext context, GoRouterState state) => - BasePage( - dataTitle: 'EnhancedEnumExtensionRoute', - param: requiredEnumField.value, - queryParam: enumField?.value, - queryParamWithDefaultValue: enumFieldWithDefaultValue.value, - ); + Widget build(BuildContext context, GoRouterState state) => BasePage( + dataTitle: 'EnhancedEnumExtensionRoute', + param: requiredEnumField.value, + queryParam: enumField?.value, + queryParamWithDefaultValue: enumFieldWithDefaultValue.value, + ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('EnhancedEnumExtensionRoute'), @@ -363,9 +347,7 @@ class BasePage extends StatelessWidget { stringField: StringExtension(r'$!/#bob%%20'), ).drawerTile(context), const EnumExtensionRoute( - requiredEnumField: PersonDetailsExtension( - PersonDetails.favoriteSport, - ), + requiredEnumField: PersonDetailsExtension(PersonDetails.favoriteSport), enumField: PersonDetailsExtension(PersonDetails.favoriteFood), ).drawerTile(context), const EnhancedEnumExtensionRoute( @@ -389,9 +371,7 @@ class BasePage extends StatelessWidget { Text('Query param: $queryParam'), Text('Query param with default value: $queryParamWithDefaultValue'), SelectableText(GoRouterState.of(context).uri.path), - SelectableText( - GoRouterState.of(context).uri.queryParameters.toString(), - ), + SelectableText(GoRouterState.of(context).uri.queryParameters.toString()), ], ), ), @@ -404,8 +384,7 @@ class AllExtensionTypesApp extends StatelessWidget { AllExtensionTypesApp({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); late final GoRouter _router = GoRouter( debugLogDiagnostics: true, diff --git a/packages/go_router_builder/example/lib/all_extension_types.g.dart b/packages/go_router_builder/example/lib/all_extension_types.g.dart index 3fd882af5efd..dc082f2039b9 100644 --- a/packages/go_router_builder/example/lib/all_extension_types.g.dart +++ b/packages/go_router_builder/example/lib/all_extension_types.g.dart @@ -30,14 +30,8 @@ RouteBase get $allTypesBaseRoute => GoRouteData.$route( path: 'double-route/:requiredDoubleField', factory: $DoubleExtensionRoute._fromState, ), - GoRouteData.$route( - path: 'int-route/:requiredIntField', - factory: $IntExtensionRoute._fromState, - ), - GoRouteData.$route( - path: 'num-route/:requiredNumField', - factory: $NumExtensionRoute._fromState, - ), + GoRouteData.$route(path: 'int-route/:requiredIntField', factory: $IntExtensionRoute._fromState), + GoRouteData.$route(path: 'num-route/:requiredNumField', factory: $NumExtensionRoute._fromState), GoRouteData.$route( path: 'double-route/:requiredDoubleField', factory: $DoubleExtensionRoute._fromState, @@ -54,16 +48,12 @@ RouteBase get $allTypesBaseRoute => GoRouteData.$route( path: 'string-route/:requiredStringField', factory: $StringExtensionRoute._fromState, ), - GoRouteData.$route( - path: 'uri-route/:requiredUriField', - factory: $UriExtensionRoute._fromState, - ), + GoRouteData.$route(path: 'uri-route/:requiredUriField', factory: $UriExtensionRoute._fromState), ], ); mixin $AllTypesBaseRoute on GoRouteData { - static AllTypesBaseRoute _fromState(GoRouterState state) => - const AllTypesBaseRoute(); + static AllTypesBaseRoute _fromState(GoRouterState state) => const AllTypesBaseRoute(); @override String get location => GoRouteData.$location('/'); @@ -75,33 +65,26 @@ mixin $AllTypesBaseRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $BigIntExtensionRoute on GoRouteData { - static BigIntExtensionRoute _fromState(GoRouterState state) => - BigIntExtensionRoute( - requiredBigIntField: - BigInt.parse(state.pathParameters['requiredBigIntField']!) - as BigIntExtension, - bigIntField: - BigInt.tryParse(state.uri.queryParameters['big-int-field'] ?? '') - as BigIntExtension?, - ); + static BigIntExtensionRoute _fromState(GoRouterState state) => BigIntExtensionRoute( + requiredBigIntField: + BigInt.parse(state.pathParameters['requiredBigIntField']!) as BigIntExtension, + bigIntField: + BigInt.tryParse(state.uri.queryParameters['big-int-field'] ?? '') as BigIntExtension?, + ); BigIntExtensionRoute get _self => this as BigIntExtensionRoute; @override String get location => GoRouteData.$location( '/big-int-route/${Uri.encodeComponent(_self.requiredBigIntField.toString())}', - queryParams: { - if (_self.bigIntField != null) - 'big-int-field': _self.bigIntField!.toString(), - }, + queryParams: {if (_self.bigIntField != null) 'big-int-field': _self.bigIntField!.toString()}, ); @override @@ -111,26 +94,18 @@ mixin $BigIntExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $BoolExtensionRoute on GoRouteData { - static BoolExtensionRoute _fromState( - GoRouterState state, - ) => BoolExtensionRoute( - requiredBoolField: - bool.parse(state.pathParameters['requiredBoolField']!) as BoolExtension, - boolField: - bool.tryParse(state.uri.queryParameters['bool-field'] ?? '') - as BoolExtension?, + static BoolExtensionRoute _fromState(GoRouterState state) => BoolExtensionRoute( + requiredBoolField: bool.parse(state.pathParameters['requiredBoolField']!) as BoolExtension, + boolField: bool.tryParse(state.uri.queryParameters['bool-field'] ?? '') as BoolExtension?, boolFieldWithDefaultValue: - bool.tryParse( - state.uri.queryParameters['bool-field-with-default-value'] ?? '', - ) + bool.tryParse(state.uri.queryParameters['bool-field-with-default-value'] ?? '') as BoolExtension? ?? const BoolExtension(true), ); @@ -143,8 +118,7 @@ mixin $BoolExtensionRoute on GoRouteData { queryParams: { if (_self.boolField != null) 'bool-field': _self.boolField!.toString(), if (_self.boolFieldWithDefaultValue != const BoolExtension(true)) - 'bool-field-with-default-value': _self.boolFieldWithDefaultValue - .toString(), + 'bool-field-with-default-value': _self.boolFieldWithDefaultValue.toString(), }, ); @@ -155,25 +129,19 @@ mixin $BoolExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $DateTimeExtensionRoute on GoRouteData { - static DateTimeExtensionRoute _fromState(GoRouterState state) => - DateTimeExtensionRoute( - requiredDateTimeField: - DateTime.parse(state.pathParameters['requiredDateTimeField']!) - as DateTimeExtension, - dateTimeField: - DateTime.tryParse( - state.uri.queryParameters['date-time-field'] ?? '', - ) - as DateTimeExtension?, - ); + static DateTimeExtensionRoute _fromState(GoRouterState state) => DateTimeExtensionRoute( + requiredDateTimeField: + DateTime.parse(state.pathParameters['requiredDateTimeField']!) as DateTimeExtension, + dateTimeField: + DateTime.tryParse(state.uri.queryParameters['date-time-field'] ?? '') as DateTimeExtension?, + ); DateTimeExtensionRoute get _self => this as DateTimeExtensionRoute; @@ -181,8 +149,7 @@ mixin $DateTimeExtensionRoute on GoRouteData { String get location => GoRouteData.$location( '/date-time-route/${Uri.encodeComponent(_self.requiredDateTimeField.toString())}', queryParams: { - if (_self.dateTimeField != null) - 'date-time-field': _self.dateTimeField!.toString(), + if (_self.dateTimeField != null) 'date-time-field': _self.dateTimeField!.toString(), }, ); @@ -193,28 +160,20 @@ mixin $DateTimeExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $DoubleExtensionRoute on GoRouteData { - static DoubleExtensionRoute _fromState( - GoRouterState state, - ) => DoubleExtensionRoute( + static DoubleExtensionRoute _fromState(GoRouterState state) => DoubleExtensionRoute( requiredDoubleField: - double.parse(state.pathParameters['requiredDoubleField']!) - as DoubleExtension, + double.parse(state.pathParameters['requiredDoubleField']!) as DoubleExtension, doubleField: - double.tryParse(state.uri.queryParameters['double-field'] ?? '') - as DoubleExtension?, + double.tryParse(state.uri.queryParameters['double-field'] ?? '') as DoubleExtension?, doubleFieldWithDefaultValue: - double.tryParse( - state.uri.queryParameters['double-field-with-default-value'] ?? - '', - ) + double.tryParse(state.uri.queryParameters['double-field-with-default-value'] ?? '') as DoubleExtension? ?? const DoubleExtension(1.0), ); @@ -225,11 +184,9 @@ mixin $DoubleExtensionRoute on GoRouteData { String get location => GoRouteData.$location( '/double-route/${Uri.encodeComponent(_self.requiredDoubleField.toString())}', queryParams: { - if (_self.doubleField != null) - 'double-field': _self.doubleField!.toString(), + if (_self.doubleField != null) 'double-field': _self.doubleField!.toString(), if (_self.doubleFieldWithDefaultValue != const DoubleExtension(1.0)) - 'double-field-with-default-value': _self.doubleFieldWithDefaultValue - .toString(), + 'double-field-with-default-value': _self.doubleFieldWithDefaultValue.toString(), }, ); @@ -240,8 +197,7 @@ mixin $DoubleExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -249,15 +205,10 @@ mixin $DoubleExtensionRoute on GoRouteData { mixin $IntExtensionRoute on GoRouteData { static IntExtensionRoute _fromState(GoRouterState state) => IntExtensionRoute( - requiredIntField: - int.parse(state.pathParameters['requiredIntField']!) as IntExtension, - intField: - int.tryParse(state.uri.queryParameters['int-field'] ?? '') - as IntExtension?, + requiredIntField: int.parse(state.pathParameters['requiredIntField']!) as IntExtension, + intField: int.tryParse(state.uri.queryParameters['int-field'] ?? '') as IntExtension?, intFieldWithDefaultValue: - int.tryParse( - state.uri.queryParameters['int-field-with-default-value'] ?? '', - ) + int.tryParse(state.uri.queryParameters['int-field-with-default-value'] ?? '') as IntExtension? ?? const IntExtension(1), ); @@ -270,8 +221,7 @@ mixin $IntExtensionRoute on GoRouteData { queryParams: { if (_self.intField != null) 'int-field': _self.intField!.toString(), if (_self.intFieldWithDefaultValue != const IntExtension(1)) - 'int-field-with-default-value': _self.intFieldWithDefaultValue - .toString(), + 'int-field-with-default-value': _self.intFieldWithDefaultValue.toString(), }, ); @@ -282,8 +232,7 @@ mixin $IntExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -291,15 +240,10 @@ mixin $IntExtensionRoute on GoRouteData { mixin $NumExtensionRoute on GoRouteData { static NumExtensionRoute _fromState(GoRouterState state) => NumExtensionRoute( - requiredNumField: - num.parse(state.pathParameters['requiredNumField']!) as NumExtension, - numField: - num.tryParse(state.uri.queryParameters['num-field'] ?? '') - as NumExtension?, + requiredNumField: num.parse(state.pathParameters['requiredNumField']!) as NumExtension, + numField: num.tryParse(state.uri.queryParameters['num-field'] ?? '') as NumExtension?, numFieldWithDefaultValue: - num.tryParse( - state.uri.queryParameters['num-field-with-default-value'] ?? '', - ) + num.tryParse(state.uri.queryParameters['num-field-with-default-value'] ?? '') as NumExtension? ?? const NumExtension(1), ); @@ -312,8 +256,7 @@ mixin $NumExtensionRoute on GoRouteData { queryParams: { if (_self.numField != null) 'num-field': _self.numField!.toString(), if (_self.numFieldWithDefaultValue != const NumExtension(1)) - 'num-field-with-default-value': _self.numFieldWithDefaultValue - .toString(), + 'num-field-with-default-value': _self.numFieldWithDefaultValue.toString(), }, ); @@ -324,33 +267,26 @@ mixin $NumExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $EnumExtensionRoute on GoRouteData { - static EnumExtensionRoute _fromState(GoRouterState state) => - EnumExtensionRoute( - requiredEnumField: - _$PersonDetailsEnumMap._$fromName( - state.pathParameters['requiredEnumField']!, - ) - as PersonDetailsExtension, - enumField: - _$PersonDetailsEnumMap._$fromName( - state.uri.queryParameters['enum-field'], - ) - as PersonDetailsExtension?, - enumFieldWithDefaultValue: - _$PersonDetailsEnumMap._$fromName( - state.uri.queryParameters['enum-field-with-default-value'], - ) - as PersonDetailsExtension? ?? - const PersonDetailsExtension(PersonDetails.favoriteFood), - ); + static EnumExtensionRoute _fromState(GoRouterState state) => EnumExtensionRoute( + requiredEnumField: _$PersonDetailsEnumMap._$fromName( + state.pathParameters['requiredEnumField']!, + ) as PersonDetailsExtension, + enumField: _$PersonDetailsEnumMap._$fromName( + state.uri.queryParameters['enum-field'], + ) as PersonDetailsExtension?, + enumFieldWithDefaultValue: + _$PersonDetailsEnumMap._$fromName( + state.uri.queryParameters['enum-field-with-default-value'], + ) as PersonDetailsExtension? ?? + const PersonDetailsExtension(PersonDetails.favoriteFood), + ); EnumExtensionRoute get _self => this as EnumExtensionRoute; @@ -359,13 +295,11 @@ mixin $EnumExtensionRoute on GoRouteData { '/enum-route/${Uri.encodeComponent(_$PersonDetailsEnumMap[_self.requiredEnumField as PersonDetails]!)}', queryParams: { if (_self.enumField != null) - 'enum-field': - _$PersonDetailsEnumMap[_self.enumField! as PersonDetails]!, + 'enum-field': _$PersonDetailsEnumMap[_self.enumField! as PersonDetails]!, if (_self.enumFieldWithDefaultValue != const PersonDetailsExtension(PersonDetails.favoriteFood)) 'enum-field-with-default-value': - _$PersonDetailsEnumMap[_self.enumFieldWithDefaultValue - as PersonDetails]!, + _$PersonDetailsEnumMap[_self.enumFieldWithDefaultValue as PersonDetails]!, }, ); @@ -376,8 +310,7 @@ mixin $EnumExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -390,25 +323,18 @@ const _$PersonDetailsEnumMap = { }; mixin $EnhancedEnumExtensionRoute on GoRouteData { - static EnhancedEnumExtensionRoute _fromState(GoRouterState state) => - EnhancedEnumExtensionRoute( - requiredEnumField: - _$SportDetailsEnumMap._$fromName( - state.pathParameters['requiredEnumField']!, - ) - as SportDetailsExtension, - enumField: - _$SportDetailsEnumMap._$fromName( - state.uri.queryParameters['enum-field'], - ) - as SportDetailsExtension?, - enumFieldWithDefaultValue: - _$SportDetailsEnumMap._$fromName( - state.uri.queryParameters['enum-field-with-default-value'], - ) - as SportDetailsExtension? ?? - const SportDetailsExtension(SportDetails.football), - ); + static EnhancedEnumExtensionRoute _fromState(GoRouterState state) => EnhancedEnumExtensionRoute( + requiredEnumField: _$SportDetailsEnumMap._$fromName( + state.pathParameters['requiredEnumField']!, + ) as SportDetailsExtension, + enumField: _$SportDetailsEnumMap._$fromName( + state.uri.queryParameters['enum-field'], + ) as SportDetailsExtension?, + enumFieldWithDefaultValue: + _$SportDetailsEnumMap._$fromName(state.uri.queryParameters['enum-field-with-default-value']) + as SportDetailsExtension? ?? + const SportDetailsExtension(SportDetails.football), + ); EnhancedEnumExtensionRoute get _self => this as EnhancedEnumExtensionRoute; @@ -418,11 +344,9 @@ mixin $EnhancedEnumExtensionRoute on GoRouteData { queryParams: { if (_self.enumField != null) 'enum-field': _$SportDetailsEnumMap[_self.enumField! as SportDetails]!, - if (_self.enumFieldWithDefaultValue != - const SportDetailsExtension(SportDetails.football)) + if (_self.enumFieldWithDefaultValue != const SportDetailsExtension(SportDetails.football)) 'enum-field-with-default-value': - _$SportDetailsEnumMap[_self.enumFieldWithDefaultValue - as SportDetails]!, + _$SportDetailsEnumMap[_self.enumFieldWithDefaultValue as SportDetails]!, }, ); @@ -433,8 +357,7 @@ mixin $EnhancedEnumExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -448,17 +371,13 @@ const _$SportDetailsEnumMap = { }; mixin $StringExtensionRoute on GoRouteData { - static StringExtensionRoute _fromState(GoRouterState state) => - StringExtensionRoute( - requiredStringField: - state.pathParameters['requiredStringField']! as StringExtension, - stringField: - state.uri.queryParameters['string-field'] as StringExtension?, - stringFieldWithDefaultValue: - state.uri.queryParameters['string-field-with-default-value'] - as StringExtension? ?? - const StringExtension('defaultValue'), - ); + static StringExtensionRoute _fromState(GoRouterState state) => StringExtensionRoute( + requiredStringField: state.pathParameters['requiredStringField']! as StringExtension, + stringField: state.uri.queryParameters['string-field'] as StringExtension?, + stringFieldWithDefaultValue: + state.uri.queryParameters['string-field-with-default-value'] as StringExtension? ?? + const StringExtension('defaultValue'), + ); StringExtensionRoute get _self => this as StringExtensionRoute; @@ -466,12 +385,9 @@ mixin $StringExtensionRoute on GoRouteData { String get location => GoRouteData.$location( '/string-route/${Uri.encodeComponent(_self.requiredStringField as String)}', queryParams: { - if (_self.stringField != null) - 'string-field': _self.stringField! as String, - if (_self.stringFieldWithDefaultValue != - const StringExtension('defaultValue')) - 'string-field-with-default-value': - _self.stringFieldWithDefaultValue as String, + if (_self.stringField != null) 'string-field': _self.stringField! as String, + if (_self.stringFieldWithDefaultValue != const StringExtension('defaultValue')) + 'string-field-with-default-value': _self.stringFieldWithDefaultValue as String, }, ); @@ -482,8 +398,7 @@ mixin $StringExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -491,11 +406,8 @@ mixin $StringExtensionRoute on GoRouteData { mixin $UriExtensionRoute on GoRouteData { static UriExtensionRoute _fromState(GoRouterState state) => UriExtensionRoute( - requiredUriField: - Uri.parse(state.pathParameters['requiredUriField']!) as UriExtension, - uriField: - Uri.tryParse(state.uri.queryParameters['uri-field'] ?? '') - as UriExtension?, + requiredUriField: Uri.parse(state.pathParameters['requiredUriField']!) as UriExtension, + uriField: Uri.tryParse(state.uri.queryParameters['uri-field'] ?? '') as UriExtension?, ); UriExtensionRoute get _self => this as UriExtensionRoute; @@ -503,9 +415,7 @@ mixin $UriExtensionRoute on GoRouteData { @override String get location => GoRouteData.$location( '/uri-route/${Uri.encodeComponent(_self.requiredUriField.toString())}', - queryParams: { - if (_self.uriField != null) 'uri-field': _self.uriField!.toString(), - }, + queryParams: {if (_self.uriField != null) 'uri-field': _self.uriField!.toString()}, ); @override @@ -515,8 +425,7 @@ mixin $UriExtensionRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/all_types.dart b/packages/go_router_builder/example/lib/all_types.dart index d984043e3865..da790e5e5ec7 100644 --- a/packages/go_router_builder/example/lib/all_types.dart +++ b/packages/go_router_builder/example/lib/all_types.dart @@ -22,15 +22,11 @@ part 'all_types.g.dart'; TypedGoRoute(path: 'num-route/:requiredNumField'), TypedGoRoute(path: 'double-route/:requiredDoubleField'), TypedGoRoute(path: 'enum-route/:requiredEnumField'), - TypedGoRoute( - path: 'enhanced-enum-route/:requiredEnumField', - ), + TypedGoRoute(path: 'enhanced-enum-route/:requiredEnumField'), TypedGoRoute(path: 'string-route/:requiredStringField'), TypedGoRoute(path: 'uri-route/:requiredUriField'), TypedGoRoute(path: 'iterable-route'), - TypedGoRoute( - path: 'iterable-route-with-default-values', - ), + TypedGoRoute(path: 'iterable-route-with-default-values'), ], ) @immutable @@ -135,11 +131,7 @@ class DoubleRoute extends GoRouteData with $DoubleRoute { } class IntRoute extends GoRouteData with $IntRoute { - IntRoute({ - required this.requiredIntField, - this.intField, - this.intFieldWithDefaultValue = 1, - }); + IntRoute({required this.requiredIntField, this.intField, this.intFieldWithDefaultValue = 1}); final int requiredIntField; final int? intField; @@ -161,11 +153,7 @@ class IntRoute extends GoRouteData with $IntRoute { } class NumRoute extends GoRouteData with $NumRoute { - NumRoute({ - required this.requiredNumField, - this.numField, - this.numFieldWithDefaultValue = 1, - }); + NumRoute({required this.requiredNumField, this.numField, this.numFieldWithDefaultValue = 1}); final num requiredNumField; final num? numField; @@ -198,13 +186,12 @@ class EnumRoute extends GoRouteData with $EnumRoute { final PersonDetails enumFieldWithDefaultValue; @override - Widget build(BuildContext context, GoRouterState state) => - BasePage( - dataTitle: 'EnumRoute', - param: requiredEnumField, - queryParam: enumField, - queryParamWithDefaultValue: enumFieldWithDefaultValue, - ); + Widget build(BuildContext context, GoRouterState state) => BasePage( + dataTitle: 'EnumRoute', + param: requiredEnumField, + queryParam: enumField, + queryParamWithDefaultValue: enumFieldWithDefaultValue, + ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('EnumRoute'), @@ -225,13 +212,12 @@ class EnhancedEnumRoute extends GoRouteData with $EnhancedEnumRoute { final SportDetails enumFieldWithDefaultValue; @override - Widget build(BuildContext context, GoRouterState state) => - BasePage( - dataTitle: 'EnhancedEnumRoute', - param: requiredEnumField, - queryParam: enumField, - queryParamWithDefaultValue: enumFieldWithDefaultValue, - ); + Widget build(BuildContext context, GoRouterState state) => BasePage( + dataTitle: 'EnhancedEnumRoute', + param: requiredEnumField, + queryParam: enumField, + queryParamWithDefaultValue: enumFieldWithDefaultValue, + ); Widget drawerTile(BuildContext context) => ListTile( title: const Text('EnhancedEnumRoute'), @@ -273,11 +259,8 @@ class UriRoute extends GoRouteData with $UriRoute { final Uri? uriField; @override - Widget build(BuildContext context, GoRouterState state) => BasePage( - dataTitle: 'UriRoute', - param: requiredUriField, - queryParam: uriField, - ); + Widget build(BuildContext context, GoRouterState state) => + BasePage(dataTitle: 'UriRoute', param: requiredUriField, queryParam: uriField); Widget drawerTile(BuildContext context) => ListTile( title: const Text('UriRoute'), @@ -359,17 +342,13 @@ class IterableRoute extends GoRouteData with $IterableRoute { ); } -class IterableRouteWithDefaultValues extends GoRouteData - with $IterableRouteWithDefaultValues { +class IterableRouteWithDefaultValues extends GoRouteData with $IterableRouteWithDefaultValues { const IterableRouteWithDefaultValues({ this.intIterableField = const [0], this.doubleIterableField = const [0, 1, 2], this.stringIterableField = const ['defaultValue'], this.boolIterableField = const [false], - this.enumIterableField = const [ - SportDetails.tennis, - SportDetails.hockey, - ], + this.enumIterableField = const [SportDetails.tennis, SportDetails.hockey], this.intListField = const [0], this.doubleListField = const [1, 2, 3], this.stringListField = const ['defaultValue0', 'defaultValue1'], @@ -453,23 +432,14 @@ class BasePage extends StatelessWidget { requiredBigIntField: BigInt.two, bigIntField: BigInt.zero, ).drawerTile(context), - BoolRoute( - requiredBoolField: true, - boolField: false, - ).drawerTile(context), + BoolRoute(requiredBoolField: true, boolField: false).drawerTile(context), DateTimeRoute( requiredDateTimeField: DateTime(1970), dateTimeField: DateTime(0), ).drawerTile(context), - DoubleRoute( - requiredDoubleField: 3.14, - doubleField: -3.14, - ).drawerTile(context), + DoubleRoute(requiredDoubleField: 3.14, doubleField: -3.14).drawerTile(context), IntRoute(requiredIntField: 42, intField: -42).drawerTile(context), - NumRoute( - requiredNumField: 2.71828, - numField: -2.71828, - ).drawerTile(context), + NumRoute(requiredNumField: 2.71828, numField: -2.71828).drawerTile(context), StringRoute( requiredStringField: r'$!/#bob%%20', stringField: r'$!/#bob%%20', @@ -491,26 +461,17 @@ class BasePage extends StatelessWidget { doubleIterableField: [.3, .4, .5], stringIterableField: ['quo usque tandem'], boolIterableField: [true, false, false], - enumIterableField: [ - SportDetails.football, - SportDetails.hockey, - ], + enumIterableField: [SportDetails.football, SportDetails.hockey], intListField: [1, 2, 3], doubleListField: [.3, .4, .5], stringListField: ['quo usque tandem'], boolListField: [true, false, false], - enumListField: [ - SportDetails.football, - SportDetails.hockey, - ], + enumListField: [SportDetails.football, SportDetails.hockey], intSetField: {1, 2, 3}, doubleSetField: {.3, .4, .5}, stringSetField: {'quo usque tandem'}, boolSetField: {true, false}, - enumSetField: { - SportDetails.football, - SportDetails.hockey, - }, + enumSetField: {SportDetails.football, SportDetails.hockey}, ).drawerTile(context), const IterableRouteWithDefaultValues().drawerTile(context), ], @@ -526,9 +487,7 @@ class BasePage extends StatelessWidget { Text('Query param: $queryParam'), Text('Query param with default value: $queryParamWithDefaultValue'), SelectableText(GoRouterState.of(context).uri.path), - SelectableText( - GoRouterState.of(context).uri.queryParameters.toString(), - ), + SelectableText(GoRouterState.of(context).uri.queryParameters.toString()), ], ), ), @@ -541,8 +500,7 @@ class AllTypesApp extends StatelessWidget { AllTypesApp({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); late final GoRouter _router = GoRouter( debugLogDiagnostics: true, diff --git a/packages/go_router_builder/example/lib/all_types.g.dart b/packages/go_router_builder/example/lib/all_types.g.dart index 81f90bb61d69..5e04883cdf46 100644 --- a/packages/go_router_builder/example/lib/all_types.g.dart +++ b/packages/go_router_builder/example/lib/all_types.g.dart @@ -18,50 +18,23 @@ RouteBase get $allTypesBaseRoute => GoRouteData.$route( path: 'big-int-route/:requiredBigIntField', factory: $BigIntRoute._fromState, ), - GoRouteData.$route( - path: 'bool-route/:requiredBoolField', - factory: $BoolRoute._fromState, - ), + GoRouteData.$route(path: 'bool-route/:requiredBoolField', factory: $BoolRoute._fromState), GoRouteData.$route( path: 'date-time-route/:requiredDateTimeField', factory: $DateTimeRoute._fromState, ), - GoRouteData.$route( - path: 'double-route/:requiredDoubleField', - factory: $DoubleRoute._fromState, - ), - GoRouteData.$route( - path: 'int-route/:requiredIntField', - factory: $IntRoute._fromState, - ), - GoRouteData.$route( - path: 'num-route/:requiredNumField', - factory: $NumRoute._fromState, - ), - GoRouteData.$route( - path: 'double-route/:requiredDoubleField', - factory: $DoubleRoute._fromState, - ), - GoRouteData.$route( - path: 'enum-route/:requiredEnumField', - factory: $EnumRoute._fromState, - ), + GoRouteData.$route(path: 'double-route/:requiredDoubleField', factory: $DoubleRoute._fromState), + GoRouteData.$route(path: 'int-route/:requiredIntField', factory: $IntRoute._fromState), + GoRouteData.$route(path: 'num-route/:requiredNumField', factory: $NumRoute._fromState), + GoRouteData.$route(path: 'double-route/:requiredDoubleField', factory: $DoubleRoute._fromState), + GoRouteData.$route(path: 'enum-route/:requiredEnumField', factory: $EnumRoute._fromState), GoRouteData.$route( path: 'enhanced-enum-route/:requiredEnumField', factory: $EnhancedEnumRoute._fromState, ), - GoRouteData.$route( - path: 'string-route/:requiredStringField', - factory: $StringRoute._fromState, - ), - GoRouteData.$route( - path: 'uri-route/:requiredUriField', - factory: $UriRoute._fromState, - ), - GoRouteData.$route( - path: 'iterable-route', - factory: $IterableRoute._fromState, - ), + GoRouteData.$route(path: 'string-route/:requiredStringField', factory: $StringRoute._fromState), + GoRouteData.$route(path: 'uri-route/:requiredUriField', factory: $UriRoute._fromState), + GoRouteData.$route(path: 'iterable-route', factory: $IterableRoute._fromState), GoRouteData.$route( path: 'iterable-route-with-default-values', factory: $IterableRouteWithDefaultValues._fromState, @@ -70,8 +43,7 @@ RouteBase get $allTypesBaseRoute => GoRouteData.$route( ); mixin $AllTypesBaseRoute on GoRouteData { - static AllTypesBaseRoute _fromState(GoRouterState state) => - const AllTypesBaseRoute(); + static AllTypesBaseRoute _fromState(GoRouterState state) => const AllTypesBaseRoute(); @override String get location => GoRouteData.$location('/'); @@ -83,8 +55,7 @@ mixin $AllTypesBaseRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -92,14 +63,8 @@ mixin $AllTypesBaseRoute on GoRouteData { mixin $BigIntRoute on GoRouteData { static BigIntRoute _fromState(GoRouterState state) => BigIntRoute( - requiredBigIntField: BigInt.parse( - state.pathParameters['requiredBigIntField']!, - ), - bigIntField: _$convertMapValue( - 'big-int-field', - state.uri.queryParameters, - BigInt.tryParse, - ), + requiredBigIntField: BigInt.parse(state.pathParameters['requiredBigIntField']!), + bigIntField: _$convertMapValue('big-int-field', state.uri.queryParameters, BigInt.tryParse), ); BigIntRoute get _self => this as BigIntRoute; @@ -107,10 +72,7 @@ mixin $BigIntRoute on GoRouteData { @override String get location => GoRouteData.$location( '/big-int-route/${Uri.encodeComponent(_self.requiredBigIntField.toString())}', - queryParams: { - if (_self.bigIntField != null) - 'big-int-field': _self.bigIntField!.toString(), - }, + queryParams: {if (_self.bigIntField != null) 'big-int-field': _self.bigIntField!.toString()}, ); @override @@ -120,8 +82,7 @@ mixin $BigIntRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -129,14 +90,8 @@ mixin $BigIntRoute on GoRouteData { mixin $BoolRoute on GoRouteData { static BoolRoute _fromState(GoRouterState state) => BoolRoute( - requiredBoolField: _$boolConverter( - state.pathParameters['requiredBoolField']!, - ), - boolField: _$convertMapValue( - 'bool-field', - state.uri.queryParameters, - _$boolConverter, - ), + requiredBoolField: _$boolConverter(state.pathParameters['requiredBoolField']!), + boolField: _$convertMapValue('bool-field', state.uri.queryParameters, _$boolConverter), boolFieldWithDefaultValue: _$convertMapValue( 'bool-field-with-default-value', @@ -154,8 +109,7 @@ mixin $BoolRoute on GoRouteData { queryParams: { if (_self.boolField != null) 'bool-field': _self.boolField!.toString(), if (_self.boolFieldWithDefaultValue != true) - 'bool-field-with-default-value': _self.boolFieldWithDefaultValue - .toString(), + 'bool-field-with-default-value': _self.boolFieldWithDefaultValue.toString(), }, ); @@ -166,8 +120,7 @@ mixin $BoolRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -175,9 +128,7 @@ mixin $BoolRoute on GoRouteData { mixin $DateTimeRoute on GoRouteData { static DateTimeRoute _fromState(GoRouterState state) => DateTimeRoute( - requiredDateTimeField: DateTime.parse( - state.pathParameters['requiredDateTimeField']!, - ), + requiredDateTimeField: DateTime.parse(state.pathParameters['requiredDateTimeField']!), dateTimeField: _$convertMapValue( 'date-time-field', state.uri.queryParameters, @@ -191,8 +142,7 @@ mixin $DateTimeRoute on GoRouteData { String get location => GoRouteData.$location( '/date-time-route/${Uri.encodeComponent(_self.requiredDateTimeField.toString())}', queryParams: { - if (_self.dateTimeField != null) - 'date-time-field': _self.dateTimeField!.toString(), + if (_self.dateTimeField != null) 'date-time-field': _self.dateTimeField!.toString(), }, ); @@ -203,8 +153,7 @@ mixin $DateTimeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -212,14 +161,8 @@ mixin $DateTimeRoute on GoRouteData { mixin $DoubleRoute on GoRouteData { static DoubleRoute _fromState(GoRouterState state) => DoubleRoute( - requiredDoubleField: double.parse( - state.pathParameters['requiredDoubleField']!, - ), - doubleField: _$convertMapValue( - 'double-field', - state.uri.queryParameters, - double.tryParse, - ), + requiredDoubleField: double.parse(state.pathParameters['requiredDoubleField']!), + doubleField: _$convertMapValue('double-field', state.uri.queryParameters, double.tryParse), doubleFieldWithDefaultValue: _$convertMapValue( 'double-field-with-default-value', @@ -235,11 +178,9 @@ mixin $DoubleRoute on GoRouteData { String get location => GoRouteData.$location( '/double-route/${Uri.encodeComponent(_self.requiredDoubleField.toString())}', queryParams: { - if (_self.doubleField != null) - 'double-field': _self.doubleField!.toString(), + if (_self.doubleField != null) 'double-field': _self.doubleField!.toString(), if (_self.doubleFieldWithDefaultValue != 1.0) - 'double-field-with-default-value': _self.doubleFieldWithDefaultValue - .toString(), + 'double-field-with-default-value': _self.doubleFieldWithDefaultValue.toString(), }, ); @@ -250,8 +191,7 @@ mixin $DoubleRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -260,17 +200,9 @@ mixin $DoubleRoute on GoRouteData { mixin $IntRoute on GoRouteData { static IntRoute _fromState(GoRouterState state) => IntRoute( requiredIntField: int.parse(state.pathParameters['requiredIntField']!), - intField: _$convertMapValue( - 'int-field', - state.uri.queryParameters, - int.tryParse, - ), + intField: _$convertMapValue('int-field', state.uri.queryParameters, int.tryParse), intFieldWithDefaultValue: - _$convertMapValue( - 'int-field-with-default-value', - state.uri.queryParameters, - int.parse, - ) ?? + _$convertMapValue('int-field-with-default-value', state.uri.queryParameters, int.parse) ?? 1, ); @@ -282,8 +214,7 @@ mixin $IntRoute on GoRouteData { queryParams: { if (_self.intField != null) 'int-field': _self.intField!.toString(), if (_self.intFieldWithDefaultValue != 1) - 'int-field-with-default-value': _self.intFieldWithDefaultValue - .toString(), + 'int-field-with-default-value': _self.intFieldWithDefaultValue.toString(), }, ); @@ -294,8 +225,7 @@ mixin $IntRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -304,17 +234,9 @@ mixin $IntRoute on GoRouteData { mixin $NumRoute on GoRouteData { static NumRoute _fromState(GoRouterState state) => NumRoute( requiredNumField: num.parse(state.pathParameters['requiredNumField']!), - numField: _$convertMapValue( - 'num-field', - state.uri.queryParameters, - num.tryParse, - ), + numField: _$convertMapValue('num-field', state.uri.queryParameters, num.tryParse), numFieldWithDefaultValue: - _$convertMapValue( - 'num-field-with-default-value', - state.uri.queryParameters, - num.parse, - ) ?? + _$convertMapValue('num-field-with-default-value', state.uri.queryParameters, num.parse) ?? 1, ); @@ -326,8 +248,7 @@ mixin $NumRoute on GoRouteData { queryParams: { if (_self.numField != null) 'num-field': _self.numField!.toString(), if (_self.numFieldWithDefaultValue != 1) - 'num-field-with-default-value': _self.numFieldWithDefaultValue - .toString(), + 'num-field-with-default-value': _self.numFieldWithDefaultValue.toString(), }, ); @@ -338,8 +259,7 @@ mixin $NumRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -370,11 +290,9 @@ mixin $EnumRoute on GoRouteData { String get location => GoRouteData.$location( '/enum-route/${Uri.encodeComponent(_$PersonDetailsEnumMap[_self.requiredEnumField]!)}', queryParams: { - if (_self.enumField != null) - 'enum-field': _$PersonDetailsEnumMap[_self.enumField!], + if (_self.enumField != null) 'enum-field': _$PersonDetailsEnumMap[_self.enumField!], if (_self.enumFieldWithDefaultValue != PersonDetails.favoriteFood) - 'enum-field-with-default-value': - _$PersonDetailsEnumMap[_self.enumFieldWithDefaultValue], + 'enum-field-with-default-value': _$PersonDetailsEnumMap[_self.enumFieldWithDefaultValue], }, ); @@ -385,8 +303,7 @@ mixin $EnumRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -423,11 +340,9 @@ mixin $EnhancedEnumRoute on GoRouteData { String get location => GoRouteData.$location( '/enhanced-enum-route/${Uri.encodeComponent(_$SportDetailsEnumMap[_self.requiredEnumField]!)}', queryParams: { - if (_self.enumField != null) - 'enum-field': _$SportDetailsEnumMap[_self.enumField!], + if (_self.enumField != null) 'enum-field': _$SportDetailsEnumMap[_self.enumField!], if (_self.enumFieldWithDefaultValue != SportDetails.football) - 'enum-field-with-default-value': - _$SportDetailsEnumMap[_self.enumFieldWithDefaultValue], + 'enum-field-with-default-value': _$SportDetailsEnumMap[_self.enumFieldWithDefaultValue], }, ); @@ -438,8 +353,7 @@ mixin $EnhancedEnumRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -457,8 +371,7 @@ mixin $StringRoute on GoRouteData { requiredStringField: state.pathParameters['requiredStringField']!, stringField: state.uri.queryParameters['string-field'], stringFieldWithDefaultValue: - state.uri.queryParameters['string-field-with-default-value'] ?? - 'defaultValue', + state.uri.queryParameters['string-field-with-default-value'] ?? 'defaultValue', ); StringRoute get _self => this as StringRoute; @@ -480,8 +393,7 @@ mixin $StringRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -490,11 +402,7 @@ mixin $StringRoute on GoRouteData { mixin $UriRoute on GoRouteData { static UriRoute _fromState(GoRouterState state) => UriRoute( requiredUriField: Uri.parse(state.pathParameters['requiredUriField']!), - uriField: _$convertMapValue( - 'uri-field', - state.uri.queryParameters, - Uri.tryParse, - ), + uriField: _$convertMapValue('uri-field', state.uri.queryParameters, Uri.tryParse), ); UriRoute get _self => this as UriRoute; @@ -502,9 +410,7 @@ mixin $UriRoute on GoRouteData { @override String get location => GoRouteData.$location( '/uri-route/${Uri.encodeComponent(_self.requiredUriField.toString())}', - queryParams: { - if (_self.uriField != null) 'uri-field': _self.uriField!.toString(), - }, + queryParams: {if (_self.uriField != null) 'uri-field': _self.uriField!.toString()}, ); @override @@ -514,8 +420,7 @@ mixin $UriRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -529,17 +434,14 @@ mixin $IterableRoute on GoRouteData { doubleIterableField: state.uri.queryParametersAll['double-iterable-field'] ?.map(double.parse) .cast(), - stringIterableField: state.uri.queryParametersAll['string-iterable-field'] - ?.map((e) => e), + stringIterableField: state.uri.queryParametersAll['string-iterable-field']?.map((e) => e), boolIterableField: state.uri.queryParametersAll['bool-iterable-field'] ?.map(_$boolConverter) .cast(), enumIterableField: state.uri.queryParametersAll['enum-iterable-field'] ?.map(_$SportDetailsEnumMap._$fromName) .cast(), - enumOnlyInIterableField: state - .uri - .queryParametersAll['enum-only-in-iterable-field'] + enumOnlyInIterableField: state.uri.queryParametersAll['enum-only-in-iterable-field'] ?.map(_$CookingRecipeEnumMap._$fromName) .cast(), intListField: state.uri.queryParametersAll['int-list-field'] @@ -550,9 +452,7 @@ mixin $IterableRoute on GoRouteData { ?.map(double.parse) .cast() .toList(), - stringListField: state.uri.queryParametersAll['string-list-field'] - ?.map((e) => e) - .toList(), + stringListField: state.uri.queryParametersAll['string-list-field']?.map((e) => e).toList(), boolListField: state.uri.queryParametersAll['bool-list-field'] ?.map(_$boolConverter) .cast() @@ -565,17 +465,12 @@ mixin $IterableRoute on GoRouteData { ?.map(_$CookingRecipeEnumMap._$fromName) .cast() .toList(), - intSetField: state.uri.queryParametersAll['int-set-field'] - ?.map(int.parse) - .cast() - .toSet(), + intSetField: state.uri.queryParametersAll['int-set-field']?.map(int.parse).cast().toSet(), doubleSetField: state.uri.queryParametersAll['double-set-field'] ?.map(double.parse) .cast() .toSet(), - stringSetField: state.uri.queryParametersAll['string-set-field'] - ?.map((e) => e) - .toSet(), + stringSetField: state.uri.queryParametersAll['string-set-field']?.map((e) => e).toSet(), boolSetField: state.uri.queryParametersAll['bool-set-field'] ?.map(_$boolConverter) .cast() @@ -597,21 +492,13 @@ mixin $IterableRoute on GoRouteData { '/iterable-route', queryParams: { if (_self.intIterableField != null) - 'int-iterable-field': _self.intIterableField - ?.map((e) => e.toString()) - .toList(), + 'int-iterable-field': _self.intIterableField?.map((e) => e.toString()).toList(), if (_self.doubleIterableField != null) - 'double-iterable-field': _self.doubleIterableField - ?.map((e) => e.toString()) - .toList(), + 'double-iterable-field': _self.doubleIterableField?.map((e) => e.toString()).toList(), if (_self.stringIterableField != null) - 'string-iterable-field': _self.stringIterableField - ?.map((e) => e) - .toList(), + 'string-iterable-field': _self.stringIterableField?.map((e) => e).toList(), if (_self.boolIterableField != null) - 'bool-iterable-field': _self.boolIterableField - ?.map((e) => e.toString()) - .toList(), + 'bool-iterable-field': _self.boolIterableField?.map((e) => e.toString()).toList(), if (_self.enumIterableField != null) 'enum-iterable-field': _self.enumIterableField ?.map((e) => _$SportDetailsEnumMap[e]) @@ -623,19 +510,13 @@ mixin $IterableRoute on GoRouteData { if (_self.intListField != null) 'int-list-field': _self.intListField?.map((e) => e.toString()).toList(), if (_self.doubleListField != null) - 'double-list-field': _self.doubleListField - ?.map((e) => e.toString()) - .toList(), + 'double-list-field': _self.doubleListField?.map((e) => e.toString()).toList(), if (_self.stringListField != null) 'string-list-field': _self.stringListField?.map((e) => e).toList(), if (_self.boolListField != null) - 'bool-list-field': _self.boolListField - ?.map((e) => e.toString()) - .toList(), + 'bool-list-field': _self.boolListField?.map((e) => e.toString()).toList(), if (_self.enumListField != null) - 'enum-list-field': _self.enumListField - ?.map((e) => _$SportDetailsEnumMap[e]) - .toList(), + 'enum-list-field': _self.enumListField?.map((e) => _$SportDetailsEnumMap[e]).toList(), if (_self.enumOnlyInListField != null) 'enum-only-in-list-field': _self.enumOnlyInListField ?.map((e) => _$CookingRecipeEnumMap[e]) @@ -643,17 +524,13 @@ mixin $IterableRoute on GoRouteData { if (_self.intSetField != null) 'int-set-field': _self.intSetField?.map((e) => e.toString()).toList(), if (_self.doubleSetField != null) - 'double-set-field': _self.doubleSetField - ?.map((e) => e.toString()) - .toList(), + 'double-set-field': _self.doubleSetField?.map((e) => e.toString()).toList(), if (_self.stringSetField != null) 'string-set-field': _self.stringSetField?.map((e) => e).toList(), if (_self.boolSetField != null) 'bool-set-field': _self.boolSetField?.map((e) => e.toString()).toList(), if (_self.enumSetField != null) - 'enum-set-field': _self.enumSetField - ?.map((e) => _$SportDetailsEnumMap[e]) - .toList(), + 'enum-set-field': _self.enumSetField?.map((e) => _$SportDetailsEnumMap[e]).toList(), if (_self.enumOnlyInSetField != null) 'enum-only-in-set-field': _self.enumOnlyInSetField ?.map((e) => _$CookingRecipeEnumMap[e]) @@ -668,8 +545,7 @@ mixin $IterableRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -682,118 +558,87 @@ const _$CookingRecipeEnumMap = { }; mixin $IterableRouteWithDefaultValues on GoRouteData { - static IterableRouteWithDefaultValues _fromState(GoRouterState state) => - IterableRouteWithDefaultValues( - intIterableField: - state.uri.queryParametersAll['int-iterable-field'] - ?.map(int.parse) - .cast() ?? - const [0], - doubleIterableField: - state.uri.queryParametersAll['double-iterable-field'] - ?.map(double.parse) - .cast() ?? - const [0, 1, 2], - stringIterableField: - state.uri.queryParametersAll['string-iterable-field']?.map( - (e) => e, - ) ?? - const ['defaultValue'], - boolIterableField: - state.uri.queryParametersAll['bool-iterable-field'] - ?.map(_$boolConverter) - .cast() ?? - const [false], - enumIterableField: - state.uri.queryParametersAll['enum-iterable-field'] - ?.map(_$SportDetailsEnumMap._$fromName) - .cast() ?? - const [SportDetails.tennis, SportDetails.hockey], - intListField: - state.uri.queryParametersAll['int-list-field'] - ?.map(int.parse) - .cast() - .toList() ?? - const [0], - doubleListField: - state.uri.queryParametersAll['double-list-field'] - ?.map(double.parse) - .cast() - .toList() ?? - const [1, 2, 3], - stringListField: - state.uri.queryParametersAll['string-list-field'] - ?.map((e) => e) - .toList() ?? - const ['defaultValue0', 'defaultValue1'], - boolListField: - state.uri.queryParametersAll['bool-list-field'] - ?.map(_$boolConverter) - .cast() - .toList() ?? - const [true], - enumListField: - state.uri.queryParametersAll['enum-list-field'] - ?.map(_$SportDetailsEnumMap._$fromName) - .cast() - .toList() ?? - const [SportDetails.football], - intSetField: - state.uri.queryParametersAll['int-set-field'] - ?.map(int.parse) - .cast() - .toSet() ?? - const {0, 1}, - doubleSetField: - state.uri.queryParametersAll['double-set-field'] - ?.map(double.parse) - .cast() - .toSet() ?? - const {}, - stringSetField: - state.uri.queryParametersAll['string-set-field'] - ?.map((e) => e) - .toSet() ?? - const {'defaultValue'}, - boolSetField: - state.uri.queryParametersAll['bool-set-field'] - ?.map(_$boolConverter) - .cast() - .toSet() ?? - const {true, false}, - enumSetField: - state.uri.queryParametersAll['enum-set-field'] - ?.map(_$SportDetailsEnumMap._$fromName) - .cast() - .toSet() ?? - const {SportDetails.hockey}, - ); - - IterableRouteWithDefaultValues get _self => - this as IterableRouteWithDefaultValues; + static IterableRouteWithDefaultValues _fromState( + GoRouterState state, + ) => IterableRouteWithDefaultValues( + intIterableField: + state.uri.queryParametersAll['int-iterable-field']?.map(int.parse).cast() ?? + const [0], + doubleIterableField: + state.uri.queryParametersAll['double-iterable-field']?.map(double.parse).cast() ?? + const [0, 1, 2], + stringIterableField: + state.uri.queryParametersAll['string-iterable-field']?.map((e) => e) ?? + const ['defaultValue'], + boolIterableField: + state.uri.queryParametersAll['bool-iterable-field']?.map(_$boolConverter).cast() ?? + const [false], + enumIterableField: + state.uri.queryParametersAll['enum-iterable-field'] + ?.map(_$SportDetailsEnumMap._$fromName) + .cast() ?? + const [SportDetails.tennis, SportDetails.hockey], + intListField: + state.uri.queryParametersAll['int-list-field']?.map(int.parse).cast().toList() ?? + const [0], + doubleListField: + state.uri.queryParametersAll['double-list-field'] + ?.map(double.parse) + .cast() + .toList() ?? + const [1, 2, 3], + stringListField: + state.uri.queryParametersAll['string-list-field']?.map((e) => e).toList() ?? + const ['defaultValue0', 'defaultValue1'], + boolListField: + state.uri.queryParametersAll['bool-list-field'] + ?.map(_$boolConverter) + .cast() + .toList() ?? + const [true], + enumListField: + state.uri.queryParametersAll['enum-list-field'] + ?.map(_$SportDetailsEnumMap._$fromName) + .cast() + .toList() ?? + const [SportDetails.football], + intSetField: + state.uri.queryParametersAll['int-set-field']?.map(int.parse).cast().toSet() ?? + const {0, 1}, + doubleSetField: + state.uri.queryParametersAll['double-set-field'] + ?.map(double.parse) + .cast() + .toSet() ?? + const {}, + stringSetField: + state.uri.queryParametersAll['string-set-field']?.map((e) => e).toSet() ?? + const {'defaultValue'}, + boolSetField: + state.uri.queryParametersAll['bool-set-field']?.map(_$boolConverter).cast().toSet() ?? + const {true, false}, + enumSetField: + state.uri.queryParametersAll['enum-set-field'] + ?.map(_$SportDetailsEnumMap._$fromName) + .cast() + .toSet() ?? + const {SportDetails.hockey}, + ); + + IterableRouteWithDefaultValues get _self => this as IterableRouteWithDefaultValues; @override String get location => GoRouteData.$location( '/iterable-route-with-default-values', queryParams: { if (!_$iterablesEqual(_self.intIterableField, const [0])) - 'int-iterable-field': _self.intIterableField - .map((e) => e.toString()) - .toList(), + 'int-iterable-field': _self.intIterableField.map((e) => e.toString()).toList(), if (!_$iterablesEqual(_self.doubleIterableField, const [0, 1, 2])) - 'double-iterable-field': _self.doubleIterableField - .map((e) => e.toString()) - .toList(), - if (!_$iterablesEqual(_self.stringIterableField, const [ - 'defaultValue', - ])) - 'string-iterable-field': _self.stringIterableField - .map((e) => e) - .toList(), + 'double-iterable-field': _self.doubleIterableField.map((e) => e.toString()).toList(), + if (!_$iterablesEqual(_self.stringIterableField, const ['defaultValue'])) + 'string-iterable-field': _self.stringIterableField.map((e) => e).toList(), if (!_$iterablesEqual(_self.boolIterableField, const [false])) - 'bool-iterable-field': _self.boolIterableField - .map((e) => e.toString()) - .toList(), + 'bool-iterable-field': _self.boolIterableField.map((e) => e.toString()).toList(), if (!_$iterablesEqual(_self.enumIterableField, const [ SportDetails.tennis, SportDetails.hockey, @@ -804,42 +649,26 @@ mixin $IterableRouteWithDefaultValues on GoRouteData { if (!_$iterablesEqual(_self.intListField, const [0])) 'int-list-field': _self.intListField.map((e) => e.toString()).toList(), if (!_$iterablesEqual(_self.doubleListField, const [1, 2, 3])) - 'double-list-field': _self.doubleListField - .map((e) => e.toString()) - .toList(), + 'double-list-field': _self.doubleListField.map((e) => e.toString()).toList(), if (!_$iterablesEqual(_self.stringListField, const [ 'defaultValue0', 'defaultValue1', ])) 'string-list-field': _self.stringListField.map((e) => e).toList(), if (!_$iterablesEqual(_self.boolListField, const [true])) - 'bool-list-field': _self.boolListField - .map((e) => e.toString()) - .toList(), - if (!_$iterablesEqual(_self.enumListField, const [ - SportDetails.football, - ])) - 'enum-list-field': _self.enumListField - .map((e) => _$SportDetailsEnumMap[e]) - .toList(), + 'bool-list-field': _self.boolListField.map((e) => e.toString()).toList(), + if (!_$iterablesEqual(_self.enumListField, const [SportDetails.football])) + 'enum-list-field': _self.enumListField.map((e) => _$SportDetailsEnumMap[e]).toList(), if (!_$iterablesEqual(_self.intSetField, const {0, 1})) 'int-set-field': _self.intSetField.map((e) => e.toString()).toList(), if (!_$iterablesEqual(_self.doubleSetField, const {})) - 'double-set-field': _self.doubleSetField - .map((e) => e.toString()) - .toList(), - if (!_$iterablesEqual(_self.stringSetField, const { - 'defaultValue', - })) + 'double-set-field': _self.doubleSetField.map((e) => e.toString()).toList(), + if (!_$iterablesEqual(_self.stringSetField, const {'defaultValue'})) 'string-set-field': _self.stringSetField.map((e) => e).toList(), if (!_$iterablesEqual(_self.boolSetField, const {true, false})) 'bool-set-field': _self.boolSetField.map((e) => e.toString()).toList(), - if (!_$iterablesEqual(_self.enumSetField, const { - SportDetails.hockey, - })) - 'enum-set-field': _self.enumSetField - .map((e) => _$SportDetailsEnumMap[e]) - .toList(), + if (!_$iterablesEqual(_self.enumSetField, const {SportDetails.hockey})) + 'enum-set-field': _self.enumSetField.map((e) => _$SportDetailsEnumMap[e]).toList(), }, ); @@ -850,18 +679,13 @@ mixin $IterableRouteWithDefaultValues on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -T? _$convertMapValue( - String key, - Map map, - T? Function(String) converter, -) { +T? _$convertMapValue(String key, Map map, T? Function(String) converter) { final value = map[key]; return value == null ? null : converter(value); } diff --git a/packages/go_router_builder/example/lib/case_sensitive_example.dart b/packages/go_router_builder/example/lib/case_sensitive_example.dart index 77636cc8a173..4421932cc3ad 100644 --- a/packages/go_router_builder/example/lib/case_sensitive_example.dart +++ b/packages/go_router_builder/example/lib/case_sensitive_example.dart @@ -15,13 +15,9 @@ class CaseSensitivityApp extends StatelessWidget { CaseSensitivityApp({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); - final GoRouter _router = GoRouter( - initialLocation: '/case-sensitive', - routes: $appRoutes, - ); + final GoRouter _router = GoRouter(initialLocation: '/case-sensitive', routes: $appRoutes); } @TypedGoRoute(path: '/case-sensitive') @@ -29,14 +25,10 @@ class CaseSensitiveRoute extends GoRouteData with $CaseSensitiveRoute { const CaseSensitiveRoute(); @override - Widget build(BuildContext context, GoRouterState state) => - const Screen(title: 'Case Sensitive'); + Widget build(BuildContext context, GoRouterState state) => const Screen(title: 'Case Sensitive'); } -@TypedGoRoute( - path: '/not-case-sensitive', - caseSensitive: false, -) +@TypedGoRoute(path: '/not-case-sensitive', caseSensitive: false) class NotCaseSensitiveRoute extends GoRouteData with $NotCaseSensitiveRoute { const NotCaseSensitiveRoute(); @@ -54,10 +46,7 @@ class Screen extends StatelessWidget { appBar: AppBar(title: Text(title)), body: ListView( children: [ - ListTile( - title: const Text('Case Sensitive'), - onTap: () => context.go('/case-sensitive'), - ), + ListTile(title: const Text('Case Sensitive'), onTap: () => context.go('/case-sensitive')), ListTile( title: const Text('Not Case Sensitive'), onTap: () => context.go('/not-case-sensitive'), diff --git a/packages/go_router_builder/example/lib/case_sensitive_example.g.dart b/packages/go_router_builder/example/lib/case_sensitive_example.g.dart index 0d1307641d31..3bed583542ec 100644 --- a/packages/go_router_builder/example/lib/case_sensitive_example.g.dart +++ b/packages/go_router_builder/example/lib/case_sensitive_example.g.dart @@ -10,14 +10,11 @@ part of 'case_sensitive_example.dart'; List get $appRoutes => [$caseSensitiveRoute, $notCaseSensitiveRoute]; -RouteBase get $caseSensitiveRoute => GoRouteData.$route( - path: '/case-sensitive', - factory: $CaseSensitiveRoute._fromState, -); +RouteBase get $caseSensitiveRoute => + GoRouteData.$route(path: '/case-sensitive', factory: $CaseSensitiveRoute._fromState); mixin $CaseSensitiveRoute on GoRouteData { - static CaseSensitiveRoute _fromState(GoRouterState state) => - const CaseSensitiveRoute(); + static CaseSensitiveRoute _fromState(GoRouterState state) => const CaseSensitiveRoute(); @override String get location => GoRouteData.$location('/case-sensitive'); @@ -29,8 +26,7 @@ mixin $CaseSensitiveRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -43,8 +39,7 @@ RouteBase get $notCaseSensitiveRoute => GoRouteData.$route( ); mixin $NotCaseSensitiveRoute on GoRouteData { - static NotCaseSensitiveRoute _fromState(GoRouterState state) => - const NotCaseSensitiveRoute(); + static NotCaseSensitiveRoute _fromState(GoRouterState state) => const NotCaseSensitiveRoute(); @override String get location => GoRouteData.$location('/not-case-sensitive'); @@ -56,8 +51,7 @@ mixin $NotCaseSensitiveRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/custom_encoder_example.dart b/packages/go_router_builder/example/lib/custom_encoder_example.dart index 00a34125c0f3..228414564fcc 100644 --- a/packages/go_router_builder/example/lib/custom_encoder_example.dart +++ b/packages/go_router_builder/example/lib/custom_encoder_example.dart @@ -17,8 +17,7 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: _appTitle); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: _appTitle); final GoRouter _router = GoRouter(routes: $appRoutes); } @@ -26,9 +25,7 @@ class App extends StatelessWidget { @TypedGoRoute( path: '/', name: 'Home', - routes: >[ - TypedGoRoute(path: 'encoded'), - ], + routes: >[TypedGoRoute(path: 'encoded')], ) class HomeRoute extends GoRouteData with $HomeRoute { const HomeRoute(); @@ -44,8 +41,7 @@ class EncodedRoute extends GoRouteData with $EncodedRoute { final String token; @override - Widget build(BuildContext context, GoRouterState state) => - EncodedScreen(token: token); + Widget build(BuildContext context, GoRouterState state) => EncodedScreen(token: token); } class HomeScreen extends StatelessWidget { @@ -82,9 +78,7 @@ class EncodedScreen extends StatelessWidget { } String fromBase64(String value) { - return const Utf8Decoder().convert( - base64Url.decode(base64Url.normalize(value)), - ); + return const Utf8Decoder().convert(base64Url.decode(base64Url.normalize(value))); } String toBase64(String value) { diff --git a/packages/go_router_builder/example/lib/custom_encoder_example.g.dart b/packages/go_router_builder/example/lib/custom_encoder_example.g.dart index ab002c500782..e3b42775d6f9 100644 --- a/packages/go_router_builder/example/lib/custom_encoder_example.g.dart +++ b/packages/go_router_builder/example/lib/custom_encoder_example.g.dart @@ -14,9 +14,7 @@ RouteBase get $homeRoute => GoRouteData.$route( path: '/', name: 'Home', factory: $HomeRoute._fromState, - routes: [ - GoRouteData.$route(path: 'encoded', factory: $EncodedRoute._fromState), - ], + routes: [GoRouteData.$route(path: 'encoded', factory: $EncodedRoute._fromState)], ); mixin $HomeRoute on GoRouteData { @@ -32,8 +30,7 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -46,10 +43,8 @@ mixin $EncodedRoute on GoRouteData { EncodedRoute get _self => this as EncodedRoute; @override - String get location => GoRouteData.$location( - '/encoded', - queryParams: {'token': toBase64(_self.token)}, - ); + String get location => + GoRouteData.$location('/encoded', queryParams: {'token': toBase64(_self.token)}); @override void go(BuildContext context) => context.go(location); @@ -58,8 +53,7 @@ mixin $EncodedRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/extra_example.dart b/packages/go_router_builder/example/lib/extra_example.dart index 9c38f35b9ae1..4db9062122af 100644 --- a/packages/go_router_builder/example/lib/extra_example.dart +++ b/packages/go_router_builder/example/lib/extra_example.dart @@ -11,10 +11,7 @@ part 'extra_example.g.dart'; void main() => runApp(const App()); -final GoRouter _router = GoRouter( - routes: $appRoutes, - initialLocation: '/splash', -); +final GoRouter _router = GoRouter(routes: $appRoutes, initialLocation: '/splash'); class App extends StatelessWidget { const App({super.key}); @@ -38,8 +35,7 @@ class RequiredExtraRoute extends GoRouteData with $RequiredExtraRoute { final Extra $extra; @override - Widget build(BuildContext context, GoRouterState state) => - RequiredExtraScreen(extra: $extra); + Widget build(BuildContext context, GoRouterState state) => RequiredExtraScreen(extra: $extra); } class RequiredExtraScreen extends StatelessWidget { @@ -63,8 +59,7 @@ class OptionalExtraRoute extends GoRouteData with $OptionalExtraRoute { final Extra? $extra; @override - Widget build(BuildContext context, GoRouterState state) => - OptionalExtraScreen(extra: $extra); + Widget build(BuildContext context, GoRouterState state) => OptionalExtraScreen(extra: $extra); } class OptionalExtraScreen extends StatelessWidget { @@ -101,13 +96,11 @@ class Splash extends StatelessWidget { children: [ const Placeholder(), ElevatedButton( - onPressed: () => - const RequiredExtraRoute($extra: Extra(1)).go(context), + onPressed: () => const RequiredExtraRoute($extra: Extra(1)).go(context), child: const Text('Required Extra'), ), ElevatedButton( - onPressed: () => - const OptionalExtraRoute($extra: Extra(2)).go(context), + onPressed: () => const OptionalExtraRoute($extra: Extra(2)).go(context), child: const Text('Optional Extra'), ), ElevatedButton( diff --git a/packages/go_router_builder/example/lib/extra_example.g.dart b/packages/go_router_builder/example/lib/extra_example.g.dart index ee366a688a38..b4b0e5f19ac3 100644 --- a/packages/go_router_builder/example/lib/extra_example.g.dart +++ b/packages/go_router_builder/example/lib/extra_example.g.dart @@ -8,16 +8,10 @@ part of 'extra_example.dart'; // GoRouterGenerator // ************************************************************************** -List get $appRoutes => [ - $requiredExtraRoute, - $optionalExtraRoute, - $splashRoute, -]; +List get $appRoutes => [$requiredExtraRoute, $optionalExtraRoute, $splashRoute]; -RouteBase get $requiredExtraRoute => GoRouteData.$route( - path: '/requiredExtra', - factory: $RequiredExtraRoute._fromState, -); +RouteBase get $requiredExtraRoute => + GoRouteData.$route(path: '/requiredExtra', factory: $RequiredExtraRoute._fromState); mixin $RequiredExtraRoute on GoRouteData { static RequiredExtraRoute _fromState(GoRouterState state) => @@ -32,22 +26,18 @@ mixin $RequiredExtraRoute on GoRouteData { void go(BuildContext context) => context.go(location, extra: _self.$extra); @override - Future push(BuildContext context) => - context.push(location, extra: _self.$extra); + Future push(BuildContext context) => context.push(location, extra: _self.$extra); @override void pushReplacement(BuildContext context) => context.pushReplacement(location, extra: _self.$extra); @override - void replace(BuildContext context) => - context.replace(location, extra: _self.$extra); + void replace(BuildContext context) => context.replace(location, extra: _self.$extra); } -RouteBase get $optionalExtraRoute => GoRouteData.$route( - path: '/optionalExtra', - factory: $OptionalExtraRoute._fromState, -); +RouteBase get $optionalExtraRoute => + GoRouteData.$route(path: '/optionalExtra', factory: $OptionalExtraRoute._fromState); mixin $OptionalExtraRoute on GoRouteData { static OptionalExtraRoute _fromState(GoRouterState state) => @@ -62,20 +52,17 @@ mixin $OptionalExtraRoute on GoRouteData { void go(BuildContext context) => context.go(location, extra: _self.$extra); @override - Future push(BuildContext context) => - context.push(location, extra: _self.$extra); + Future push(BuildContext context) => context.push(location, extra: _self.$extra); @override void pushReplacement(BuildContext context) => context.pushReplacement(location, extra: _self.$extra); @override - void replace(BuildContext context) => - context.replace(location, extra: _self.$extra); + void replace(BuildContext context) => context.replace(location, extra: _self.$extra); } -RouteBase get $splashRoute => - GoRouteData.$route(path: '/splash', factory: $SplashRoute._fromState); +RouteBase get $splashRoute => GoRouteData.$route(path: '/splash', factory: $SplashRoute._fromState); mixin $SplashRoute on GoRouteData { static SplashRoute _fromState(GoRouterState state) => const SplashRoute(); @@ -90,8 +77,7 @@ mixin $SplashRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/go_relative.dart b/packages/go_router_builder/example/lib/go_relative.dart index 988df38c0c76..5377e42f4227 100644 --- a/packages/go_router_builder/example/lib/go_relative.dart +++ b/packages/go_router_builder/example/lib/go_relative.dart @@ -24,21 +24,15 @@ class MyApp extends StatelessWidget { /// The route configuration. final GoRouter _router = GoRouter(routes: $appRoutes); -const TypedRelativeGoRoute detailRoute = - TypedRelativeGoRoute( - path: 'details/:detailId', - routes: >[ - TypedRelativeGoRoute(path: 'settings/:settingId'), - ], - ); +const TypedRelativeGoRoute detailRoute = TypedRelativeGoRoute( + path: 'details/:detailId', + routes: >[TypedRelativeGoRoute(path: 'settings/:settingId')], +); @TypedGoRoute( path: '/', routes: >[ - TypedGoRoute( - path: '/dashboard', - routes: >[detailRoute], - ), + TypedGoRoute(path: '/dashboard', routes: >[detailRoute]), detailRoute, ], ) @@ -123,10 +117,7 @@ class DashboardScreen extends StatelessWidget { }, child: const Text('Go to the Details screen'), ), - ElevatedButton( - onPressed: () => context.pop(), - child: const Text('Go back'), - ), + ElevatedButton(onPressed: () => context.pop(), child: const Text('Go back')), ], ), ); @@ -147,14 +138,9 @@ class DetailsScreen extends StatelessWidget { body: Center( child: Column( children: [ + ElevatedButton(onPressed: () => context.pop(), child: const Text('Go back')), ElevatedButton( - onPressed: () => context.pop(), - child: const Text('Go back'), - ), - ElevatedButton( - onPressed: () => const SettingsRoute( - settingId: 'SettingsId', - ).goRelative(context), + onPressed: () => const SettingsRoute(settingId: 'SettingsId').goRelative(context), child: const Text('Go to the Settings screen'), ), ], @@ -176,10 +162,7 @@ class SettingsScreen extends StatelessWidget { return Scaffold( appBar: AppBar(title: Text('Settings Screen $id')), body: Center( - child: TextButton( - onPressed: () => context.pop(), - child: const Text('Go back'), - ), + child: TextButton(onPressed: () => context.pop(), child: const Text('Go back')), ), ); } diff --git a/packages/go_router_builder/example/lib/go_relative.g.dart b/packages/go_router_builder/example/lib/go_relative.g.dart index ef565d171a96..9cb841bdd764 100644 --- a/packages/go_router_builder/example/lib/go_relative.g.dart +++ b/packages/go_router_builder/example/lib/go_relative.g.dart @@ -34,10 +34,7 @@ RouteBase get $homeRoute => GoRouteData.$route( path: 'details/:detailId', factory: $DetailsRoute._fromState, routes: [ - RelativeGoRouteData.$route( - path: 'settings/:settingId', - factory: $SettingsRoute._fromState, - ), + RelativeGoRouteData.$route(path: 'settings/:settingId', factory: $SettingsRoute._fromState), ], ), ], @@ -56,8 +53,7 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -76,8 +72,7 @@ mixin $DashboardRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -90,9 +85,8 @@ mixin $DetailsRoute on RelativeGoRouteData { DetailsRoute get _self => this as DetailsRoute; @override - String get subLocation => RelativeGoRouteData.$location( - 'details/${Uri.encodeComponent(_self.detailId)}', - ); + String get subLocation => + RelativeGoRouteData.$location('details/${Uri.encodeComponent(_self.detailId)}'); @override String get relativeLocation => './$subLocation'; @@ -101,16 +95,13 @@ mixin $DetailsRoute on RelativeGoRouteData { void goRelative(BuildContext context) => context.go(relativeLocation); @override - Future pushRelative(BuildContext context) => - context.push(relativeLocation); + Future pushRelative(BuildContext context) => context.push(relativeLocation); @override - void pushReplacementRelative(BuildContext context) => - context.pushReplacement(relativeLocation); + void pushReplacementRelative(BuildContext context) => context.pushReplacement(relativeLocation); @override - void replaceRelative(BuildContext context) => - context.replace(relativeLocation); + void replaceRelative(BuildContext context) => context.replace(relativeLocation); } mixin $SettingsRoute on RelativeGoRouteData { @@ -120,9 +111,8 @@ mixin $SettingsRoute on RelativeGoRouteData { SettingsRoute get _self => this as SettingsRoute; @override - String get subLocation => RelativeGoRouteData.$location( - 'settings/${Uri.encodeComponent(_self.settingId)}', - ); + String get subLocation => + RelativeGoRouteData.$location('settings/${Uri.encodeComponent(_self.settingId)}'); @override String get relativeLocation => './$subLocation'; @@ -131,14 +121,11 @@ mixin $SettingsRoute on RelativeGoRouteData { void goRelative(BuildContext context) => context.go(relativeLocation); @override - Future pushRelative(BuildContext context) => - context.push(relativeLocation); + Future pushRelative(BuildContext context) => context.push(relativeLocation); @override - void pushReplacementRelative(BuildContext context) => - context.pushReplacement(relativeLocation); + void pushReplacementRelative(BuildContext context) => context.pushReplacement(relativeLocation); @override - void replaceRelative(BuildContext context) => - context.replace(relativeLocation); + void replaceRelative(BuildContext context) => context.replace(relativeLocation); } diff --git a/packages/go_router_builder/example/lib/json_example.dart b/packages/go_router_builder/example/lib/json_example.dart index 38bb868da612..dbb5b3d03d0f 100644 --- a/packages/go_router_builder/example/lib/json_example.dart +++ b/packages/go_router_builder/example/lib/json_example.dart @@ -19,8 +19,7 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: _appTitle); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: _appTitle); final GoRouter _router = GoRouter(routes: $appRoutes); } @@ -43,8 +42,7 @@ class JsonRoute extends GoRouteData with $JsonRoute { final JsonExample json; @override - Widget build(BuildContext context, GoRouterState state) => - JsonScreen(json: json); + Widget build(BuildContext context, GoRouterState state) => JsonScreen(json: json); } class HomeScreen extends StatelessWidget { @@ -56,10 +54,7 @@ class HomeScreen extends StatelessWidget { body: ListView( children: [ for (final JsonExample json in jsonData) - ListTile( - title: Text(json.name), - onTap: () => JsonRoute(json).go(context), - ), + ListTile(title: Text(json.name), onTap: () => JsonRoute(json).go(context)), ], ), ); diff --git a/packages/go_router_builder/example/lib/json_example.g.dart b/packages/go_router_builder/example/lib/json_example.g.dart index 99600db150ef..ef9a4169056e 100644 --- a/packages/go_router_builder/example/lib/json_example.g.dart +++ b/packages/go_router_builder/example/lib/json_example.g.dart @@ -30,8 +30,7 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -45,10 +44,8 @@ mixin $JsonRoute on GoRouteData { JsonRoute get _self => this as JsonRoute; @override - String get location => GoRouteData.$location( - '/json', - queryParams: {'json': jsonEncode(_self.json.toJson())}, - ); + String get location => + GoRouteData.$location('/json', queryParams: {'json': jsonEncode(_self.json.toJson())}); @override void go(BuildContext context) => context.go(location); @@ -57,8 +54,7 @@ mixin $JsonRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/json_nested_example.dart b/packages/go_router_builder/example/lib/json_nested_example.dart index f88f8770b2a8..884196415786 100644 --- a/packages/go_router_builder/example/lib/json_nested_example.dart +++ b/packages/go_router_builder/example/lib/json_nested_example.dart @@ -19,8 +19,7 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: _appTitle); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: _appTitle); final GoRouter _router = GoRouter(routes: $appRoutes); } @@ -43,8 +42,7 @@ class JsonRoute extends GoRouteData with $JsonRoute { final JsonExampleNested json; @override - Widget build(BuildContext context, GoRouterState state) => - JsonScreen(json: json.child); + Widget build(BuildContext context, GoRouterState state) => JsonScreen(json: json.child); } class HomeScreen extends StatelessWidget { @@ -58,9 +56,7 @@ class HomeScreen extends StatelessWidget { for (final JsonExample json in jsonData) ListTile( title: Text(json.name), - onTap: () => JsonRoute( - JsonExampleNested(child: json), - ).go(context), + onTap: () => JsonRoute(JsonExampleNested(child: json)).go(context), ), ], ), diff --git a/packages/go_router_builder/example/lib/json_nested_example.g.dart b/packages/go_router_builder/example/lib/json_nested_example.g.dart index 18411ebc9a7c..5a362a546f95 100644 --- a/packages/go_router_builder/example/lib/json_nested_example.g.dart +++ b/packages/go_router_builder/example/lib/json_nested_example.g.dart @@ -30,8 +30,7 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -39,21 +38,16 @@ mixin $HomeRoute on GoRouteData { mixin $JsonRoute on GoRouteData { static JsonRoute _fromState(GoRouterState state) => JsonRoute((String json0) { - return JsonExampleNested.fromJson( - jsonDecode(json0) as Map, - (Object? json1) { - return JsonExample.fromJson(json1 as Map); - }, - ); + return JsonExampleNested.fromJson(jsonDecode(json0) as Map, (Object? json1) { + return JsonExample.fromJson(json1 as Map); + }); }(state.uri.queryParameters['json']!)); JsonRoute get _self => this as JsonRoute; @override - String get location => GoRouteData.$location( - '/json', - queryParams: {'json': jsonEncode(_self.json.toJson())}, - ); + String get location => + GoRouteData.$location('/json', queryParams: {'json': jsonEncode(_self.json.toJson())}); @override void go(BuildContext context) => context.go(location); @@ -62,8 +56,7 @@ mixin $JsonRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/main.dart b/packages/go_router_builder/example/lib/main.dart index ca39237097d6..8b81e402cd67 100644 --- a/packages/go_router_builder/example/lib/main.dart +++ b/packages/go_router_builder/example/lib/main.dart @@ -94,8 +94,7 @@ class LoginRoute extends GoRouteData with $LoginRoute { final String? fromPage; @override - Widget build(BuildContext context, GoRouterState state) => - LoginScreen(from: fromPage); + Widget build(BuildContext context, GoRouterState state) => LoginScreen(from: fromPage); } class FamilyRoute extends GoRouteData with $FamilyRoute { @@ -104,8 +103,7 @@ class FamilyRoute extends GoRouteData with $FamilyRoute { final String fid; @override - Widget build(BuildContext context, GoRouterState state) => - FamilyScreen(family: familyById(fid)); + Widget build(BuildContext context, GoRouterState state) => FamilyScreen(family: familyById(fid)); } class PersonRoute extends GoRouteData with $PersonRoute { @@ -138,12 +136,7 @@ class PersonDetailsRoute extends GoRouteData with $PersonDetailsRoute { return MaterialPage( fullscreenDialog: true, key: state.pageKey, - child: PersonDetailsPage( - family: family, - person: person, - detailsKey: details, - extra: $extra, - ), + child: PersonDetailsPage(family: family, person: person, detailsKey: details, extra: $extra), ); } } @@ -154,8 +147,7 @@ class FamilyCountRoute extends GoRouteData with $FamilyCountRoute { final int count; @override - Widget build(BuildContext context, GoRouterState state) => - FamilyCountScreen(count: count); + Widget build(BuildContext context, GoRouterState state) => FamilyCountScreen(count: count); } class HomeScreen extends StatelessWidget { @@ -183,16 +175,14 @@ class HomeScreen extends StatelessWidget { child: const Text('Push w/ return value'), onTap: () async { unawaited( - FamilyCountRoute( - familyData.length, - ).push(context).then((int? value) { + FamilyCountRoute(familyData.length).push(context).then((int? value) { if (!context.mounted) { return; } if (value != null) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Age was: $value')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Age was: $value'))); } }), ); @@ -211,10 +201,7 @@ class HomeScreen extends StatelessWidget { body: ListView( children: [ for (final Family f in familyData) - ListTile( - title: Text(f.name), - onTap: () => FamilyRoute(f.id).go(context), - ), + ListTile(title: Text(f.name), onTap: () => FamilyRoute(f.id).go(context)), ], ), ); @@ -231,10 +218,7 @@ class FamilyScreen extends StatelessWidget { body: ListView( children: [ for (final Person p in family.people) - ListTile( - title: Text(p.name), - onTap: () => PersonRoute(family.id, p.id).go(context), - ), + ListTile(title: Text(p.name), onTap: () => PersonRoute(family.id, p.id).go(context)), ], ), ); @@ -253,13 +237,8 @@ class PersonScreen extends StatelessWidget { appBar: AppBar(title: Text(person.name)), body: ListView( children: [ - ListTile( - title: Text( - '${person.name} ${family.name} is ${person.age} years old', - ), - ), - for (final MapEntry entry - in person.details.entries) + ListTile(title: Text('${person.name} ${family.name} is ${person.age} years old')), + for (final MapEntry entry in person.details.entries) ListTile( title: Text('${entry.key.name} - ${entry.value}'), trailing: OutlinedButton( @@ -271,8 +250,7 @@ class PersonScreen extends StatelessWidget { ).go(context), child: const Text('With extra...'), ), - onTap: () => - PersonDetailsRoute(family.id, person.id, entry.key).go(context), + onTap: () => PersonDetailsRoute(family.id, person.id, entry.key).go(context), ), ], ), diff --git a/packages/go_router_builder/example/lib/main.g.dart b/packages/go_router_builder/example/lib/main.g.dart index fc044ef4186b..373f9a20e7de 100644 --- a/packages/go_router_builder/example/lib/main.g.dart +++ b/packages/go_router_builder/example/lib/main.g.dart @@ -22,18 +22,12 @@ RouteBase get $homeRoute => GoRouteData.$route( path: 'person/:pid', factory: $PersonRoute._fromState, routes: [ - GoRouteData.$route( - path: 'details/:details', - factory: $PersonDetailsRoute._fromState, - ), + GoRouteData.$route(path: 'details/:details', factory: $PersonDetailsRoute._fromState), ], ), ], ), - GoRouteData.$route( - path: 'family-count/:count', - factory: $FamilyCountRoute._fromState, - ), + GoRouteData.$route(path: 'family-count/:count', factory: $FamilyCountRoute._fromState), ], ); @@ -50,22 +44,19 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $FamilyRoute on GoRouteData { - static FamilyRoute _fromState(GoRouterState state) => - FamilyRoute(state.pathParameters['fid']!); + static FamilyRoute _fromState(GoRouterState state) => FamilyRoute(state.pathParameters['fid']!); FamilyRoute get _self => this as FamilyRoute; @override - String get location => - GoRouteData.$location('/family/${Uri.encodeComponent(_self.fid)}'); + String get location => GoRouteData.$location('/family/${Uri.encodeComponent(_self.fid)}'); @override void go(BuildContext context) => context.go(location); @@ -74,18 +65,15 @@ mixin $FamilyRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $PersonRoute on GoRouteData { - static PersonRoute _fromState(GoRouterState state) => PersonRoute( - state.pathParameters['fid']!, - int.parse(state.pathParameters['pid']!), - ); + static PersonRoute _fromState(GoRouterState state) => + PersonRoute(state.pathParameters['fid']!, int.parse(state.pathParameters['pid']!)); PersonRoute get _self => this as PersonRoute; @@ -101,21 +89,19 @@ mixin $PersonRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $PersonDetailsRoute on GoRouteData { - static PersonDetailsRoute _fromState(GoRouterState state) => - PersonDetailsRoute( - state.pathParameters['fid']!, - int.parse(state.pathParameters['pid']!), - _$PersonDetailsEnumMap._$fromName(state.pathParameters['details']!)!, - $extra: state.extra as int?, - ); + static PersonDetailsRoute _fromState(GoRouterState state) => PersonDetailsRoute( + state.pathParameters['fid']!, + int.parse(state.pathParameters['pid']!), + _$PersonDetailsEnumMap._$fromName(state.pathParameters['details']!)!, + $extra: state.extra as int?, + ); PersonDetailsRoute get _self => this as PersonDetailsRoute; @@ -128,16 +114,14 @@ mixin $PersonDetailsRoute on GoRouteData { void go(BuildContext context) => context.go(location, extra: _self.$extra); @override - Future push(BuildContext context) => - context.push(location, extra: _self.$extra); + Future push(BuildContext context) => context.push(location, extra: _self.$extra); @override void pushReplacement(BuildContext context) => context.pushReplacement(location, extra: _self.$extra); @override - void replace(BuildContext context) => - context.replace(location, extra: _self.$extra); + void replace(BuildContext context) => context.replace(location, extra: _self.$extra); } const _$PersonDetailsEnumMap = { @@ -153,9 +137,8 @@ mixin $FamilyCountRoute on GoRouteData { FamilyCountRoute get _self => this as FamilyCountRoute; @override - String get location => GoRouteData.$location( - '/family-count/${Uri.encodeComponent(_self.count.toString())}', - ); + String get location => + GoRouteData.$location('/family-count/${Uri.encodeComponent(_self.count.toString())}'); @override void go(BuildContext context) => context.go(location); @@ -164,8 +147,7 @@ mixin $FamilyCountRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -176,8 +158,7 @@ extension on Map { entries.where((element) => element.value == value).firstOrNull?.key; } -RouteBase get $loginRoute => - GoRouteData.$route(path: '/login', factory: $LoginRoute._fromState); +RouteBase get $loginRoute => GoRouteData.$route(path: '/login', factory: $LoginRoute._fromState); mixin $LoginRoute on GoRouteData { static LoginRoute _fromState(GoRouterState state) => @@ -198,8 +179,7 @@ mixin $LoginRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/on_exit_example.dart b/packages/go_router_builder/example/lib/on_exit_example.dart index 155f67195354..82905dfb4ae8 100644 --- a/packages/go_router_builder/example/lib/on_exit_example.dart +++ b/packages/go_router_builder/example/lib/on_exit_example.dart @@ -15,17 +15,14 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: _appTitle); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: _appTitle); final GoRouter _router = GoRouter(routes: $appRoutes); } @TypedGoRoute( path: '/', - routes: >[ - TypedGoRoute(path: 'sub-route'), - ], + routes: >[TypedGoRoute(path: 'sub-route')], ) class HomeRoute extends GoRouteData with $HomeRoute { const HomeRoute(); diff --git a/packages/go_router_builder/example/lib/on_exit_example.g.dart b/packages/go_router_builder/example/lib/on_exit_example.g.dart index e108c912ab38..026b17382513 100644 --- a/packages/go_router_builder/example/lib/on_exit_example.g.dart +++ b/packages/go_router_builder/example/lib/on_exit_example.g.dart @@ -13,9 +13,7 @@ List get $appRoutes => [$homeRoute]; RouteBase get $homeRoute => GoRouteData.$route( path: '/', factory: $HomeRoute._fromState, - routes: [ - GoRouteData.$route(path: 'sub-route', factory: $SubRoute._fromState), - ], + routes: [GoRouteData.$route(path: 'sub-route', factory: $SubRoute._fromState)], ); mixin $HomeRoute on GoRouteData { @@ -31,8 +29,7 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -51,8 +48,7 @@ mixin $SubRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/readme_excerpts.dart b/packages/go_router_builder/example/lib/readme_excerpts.dart index 97c74ed3f503..e53dbd736894 100644 --- a/packages/go_router_builder/example/lib/readme_excerpts.dart +++ b/packages/go_router_builder/example/lib/readme_excerpts.dart @@ -10,6 +10,7 @@ import 'shared/data.dart'; import 'package:go_router/go_router.dart'; part 'readme_excerpts.g.dart'; + // #enddocregion import void otherDoc(BuildContext context) { @@ -25,8 +26,7 @@ void otherDoc(BuildContext context) { // #enddocregion GoRoute // #docregion GoWrong - void tap() => - context.go('/familyId/a42'); // This is an error: `a42` is not an `int`. + void tap() => context.go('/familyId/a42'); // This is an error: `a42` is not an `int`. // #enddocregion GoWrong // #docregion GoRouter @@ -55,6 +55,7 @@ void otherDoc(BuildContext context) { void tapWithExtra() { PersonRouteWithExtra(Person(id: 1, name: 'Marvin', age: 42)).go(context); } + // #enddocregion tapWithExtra // #docregion goRelative @@ -84,9 +85,7 @@ void otherDoc(BuildContext context) { // #docregion TypedGoRouteHomeRoute @TypedGoRoute( path: '/', - routes: >[ - TypedGoRoute(path: 'family/:fid'), - ], + routes: >[TypedGoRoute(path: 'family/:fid')], ) // #docregion HomeRoute class HomeRoute extends GoRouteData with $HomeRoute { @@ -95,6 +94,7 @@ class HomeRoute extends GoRouteData with $HomeRoute { @override Widget build(BuildContext context, GoRouterState state) => const HomeScreen(); } + // #enddocregion HomeRoute // #docregion RedirectRoute @@ -105,6 +105,7 @@ class RedirectRoute extends GoRouteData { return const HomeRoute().location; } } + // #enddocregion RedirectRoute // #docregion login @@ -118,6 +119,7 @@ class LoginRoute extends GoRouteData with $LoginRoute { return LoginScreen(from: from); } } + // #enddocregion login // #enddocregion TypedGoRouteHomeRoute @@ -131,9 +133,7 @@ class HomeScreen extends StatelessWidget { body: TextButton( onPressed: () async { // #docregion awaitPush - final bool? result = await const FamilyRoute( - fid: 'John', - ).push(context); + final bool? result = await const FamilyRoute(fid: 'John').push(context); // #enddocregion awaitPush print('result is $result'); }, @@ -183,6 +183,7 @@ class ErrorRoute extends GoRouteData { return ErrorScreen(error: error); } } + // #enddocregion ErrorRoute class ErrorScreen extends StatelessWidget { @@ -220,6 +221,7 @@ class MyRoute extends GoRouteData with $MyRoute { return MyScreen(queryParameter: queryParameter); } } + // #enddocregion MyRoute class MyScreen extends StatelessWidget { @@ -243,6 +245,7 @@ class PersonRouteWithExtra extends GoRouteData with $PersonRouteWithExtra { return PersonScreen($extra); } } + // #enddocregion PersonRouteWithExtra class PersonScreen extends StatelessWidget { @@ -257,8 +260,7 @@ class PersonScreen extends StatelessWidget { // #docregion HotdogRouteWithEverything @TypedGoRoute(path: '/:ketchup') -class HotdogRouteWithEverything extends GoRouteData - with $HotdogRouteWithEverything { +class HotdogRouteWithEverything extends GoRouteData with $HotdogRouteWithEverything { HotdogRouteWithEverything(this.ketchup, this.mustard, this.$extra); final bool ketchup; // A required path parameter. final String? mustard; // An optional query parameter. @@ -269,6 +271,7 @@ class HotdogRouteWithEverything extends GoRouteData return HotdogScreen(ketchup, mustard, $extra); } } + // #enddocregion HotdogRouteWithEverything class Sauce {} @@ -298,6 +301,7 @@ class BooksRoute extends GoRouteData with $BooksRoute { return BooksScreen(kind: kind); } } + // #enddocregion BookKind class BooksScreen extends StatelessWidget { @@ -320,6 +324,7 @@ class MyMaterialRouteWithKey extends GoRouteData with $MyMaterialRouteWithKey { return const MaterialPage(key: _key, child: MyPage()); } } + // #enddocregion MyMaterialRouteWithKey class MyPage extends StatelessWidget { @@ -349,10 +354,7 @@ class MyShellRoutePage extends StatelessWidget { class FancyRoute extends GoRouteData with $FancyRoute { const FancyRoute(); @override - CustomTransitionPage buildPage( - BuildContext context, - GoRouterState state, - ) { + CustomTransitionPage buildPage(BuildContext context, GoRouterState state) { return CustomTransitionPage( key: state.pageKey, child: const MyPage(), @@ -368,6 +370,7 @@ class FancyRoute extends GoRouteData with $FancyRoute { ); } } + // #enddocregion FancyRoute // #docregion MyShellRouteData @@ -375,9 +378,7 @@ final GlobalKey shellNavigatorKey = GlobalKey(); final GlobalKey rootNavigatorKey = GlobalKey(); @TypedShellRoute( - routes: >[ - TypedGoRoute(path: 'my-go-route'), - ], + routes: >[TypedGoRoute(path: 'my-go-route')], ) class MyShellRouteData extends ShellRouteData { const MyShellRouteData(); @@ -408,9 +409,9 @@ class DetailsRoute extends RelativeGoRouteData with $DetailsRoute { const DetailsRoute(); @override - Widget build(BuildContext context, GoRouterState state) => - const DetailsScreen(); + Widget build(BuildContext context, GoRouterState state) => const DetailsScreen(); } + // #enddocregion relativeRoute class DetailsScreen extends StatelessWidget { diff --git a/packages/go_router_builder/example/lib/readme_excerpts.g.dart b/packages/go_router_builder/example/lib/readme_excerpts.g.dart index 9cfd76b05eb4..a15e61fd15b0 100644 --- a/packages/go_router_builder/example/lib/readme_excerpts.g.dart +++ b/packages/go_router_builder/example/lib/readme_excerpts.g.dart @@ -24,9 +24,7 @@ List get $appRoutes => [ RouteBase get $homeRoute => GoRouteData.$route( path: '/', factory: $HomeRoute._fromState, - routes: [ - GoRouteData.$route(path: 'family/:fid', factory: $FamilyRoute._fromState), - ], + routes: [GoRouteData.$route(path: 'family/:fid', factory: $FamilyRoute._fromState)], ); mixin $HomeRoute on GoRouteData { @@ -42,8 +40,7 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -56,8 +53,7 @@ mixin $FamilyRoute on GoRouteData { FamilyRoute get _self => this as FamilyRoute; @override - String get location => - GoRouteData.$location('/family/${Uri.encodeComponent(_self.fid ?? '')}'); + String get location => GoRouteData.$location('/family/${Uri.encodeComponent(_self.fid ?? '')}'); @override void go(BuildContext context) => context.go(location); @@ -66,15 +62,13 @@ mixin $FamilyRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -RouteBase get $loginRoute => - GoRouteData.$route(path: '/login', factory: $LoginRoute._fromState); +RouteBase get $loginRoute => GoRouteData.$route(path: '/login', factory: $LoginRoute._fromState); mixin $LoginRoute on GoRouteData { static LoginRoute _fromState(GoRouterState state) => @@ -83,10 +77,8 @@ mixin $LoginRoute on GoRouteData { LoginRoute get _self => this as LoginRoute; @override - String get location => GoRouteData.$location( - '/login', - queryParams: {if (_self.from != null) 'from': _self.from}, - ); + String get location => + GoRouteData.$location('/login', queryParams: {if (_self.from != null) 'from': _self.from}); @override void go(BuildContext context) => context.go(location); @@ -95,21 +87,17 @@ mixin $LoginRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -RouteBase get $myRoute => - GoRouteData.$route(path: '/my-route', factory: $MyRoute._fromState); +RouteBase get $myRoute => GoRouteData.$route(path: '/my-route', factory: $MyRoute._fromState); mixin $MyRoute on GoRouteData { - static MyRoute _fromState(GoRouterState state) => MyRoute( - queryParameter: - state.uri.queryParameters['query-parameter'] ?? 'defaultValue', - ); + static MyRoute _fromState(GoRouterState state) => + MyRoute(queryParameter: state.uri.queryParameters['query-parameter'] ?? 'defaultValue'); MyRoute get _self => this as MyRoute; @@ -117,8 +105,7 @@ mixin $MyRoute on GoRouteData { String get location => GoRouteData.$location( '/my-route', queryParams: { - if (_self.queryParameter != 'defaultValue') - 'query-parameter': _self.queryParameter, + if (_self.queryParameter != 'defaultValue') 'query-parameter': _self.queryParameter, }, ); @@ -129,17 +116,14 @@ mixin $MyRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -RouteBase get $personRouteWithExtra => GoRouteData.$route( - path: '/person', - factory: $PersonRouteWithExtra._fromState, -); +RouteBase get $personRouteWithExtra => + GoRouteData.$route(path: '/person', factory: $PersonRouteWithExtra._fromState); mixin $PersonRouteWithExtra on GoRouteData { static PersonRouteWithExtra _fromState(GoRouterState state) => @@ -154,30 +138,25 @@ mixin $PersonRouteWithExtra on GoRouteData { void go(BuildContext context) => context.go(location, extra: _self.$extra); @override - Future push(BuildContext context) => - context.push(location, extra: _self.$extra); + Future push(BuildContext context) => context.push(location, extra: _self.$extra); @override void pushReplacement(BuildContext context) => context.pushReplacement(location, extra: _self.$extra); @override - void replace(BuildContext context) => - context.replace(location, extra: _self.$extra); + void replace(BuildContext context) => context.replace(location, extra: _self.$extra); } -RouteBase get $hotdogRouteWithEverything => GoRouteData.$route( - path: '/:ketchup', - factory: $HotdogRouteWithEverything._fromState, -); +RouteBase get $hotdogRouteWithEverything => + GoRouteData.$route(path: '/:ketchup', factory: $HotdogRouteWithEverything._fromState); mixin $HotdogRouteWithEverything on GoRouteData { - static HotdogRouteWithEverything _fromState(GoRouterState state) => - HotdogRouteWithEverything( - _$boolConverter(state.pathParameters['ketchup']!), - state.uri.queryParameters['mustard'], - state.extra as Sauce, - ); + static HotdogRouteWithEverything _fromState(GoRouterState state) => HotdogRouteWithEverything( + _$boolConverter(state.pathParameters['ketchup']!), + state.uri.queryParameters['mustard'], + state.extra as Sauce, + ); HotdogRouteWithEverything get _self => this as HotdogRouteWithEverything; @@ -191,16 +170,14 @@ mixin $HotdogRouteWithEverything on GoRouteData { void go(BuildContext context) => context.go(location, extra: _self.$extra); @override - Future push(BuildContext context) => - context.push(location, extra: _self.$extra); + Future push(BuildContext context) => context.push(location, extra: _self.$extra); @override void pushReplacement(BuildContext context) => context.pushReplacement(location, extra: _self.$extra); @override - void replace(BuildContext context) => - context.replace(location, extra: _self.$extra); + void replace(BuildContext context) => context.replace(location, extra: _self.$extra); } bool _$boolConverter(String value) { @@ -214,17 +191,12 @@ bool _$boolConverter(String value) { } } -RouteBase get $booksRoute => - GoRouteData.$route(path: '/books', factory: $BooksRoute._fromState); +RouteBase get $booksRoute => GoRouteData.$route(path: '/books', factory: $BooksRoute._fromState); mixin $BooksRoute on GoRouteData { static BooksRoute _fromState(GoRouterState state) => BooksRoute( kind: - _$convertMapValue( - 'kind', - state.uri.queryParameters, - _$BookKindEnumMap._$fromName, - ) ?? + _$convertMapValue('kind', state.uri.queryParameters, _$BookKindEnumMap._$fromName) ?? BookKind.popular, ); @@ -233,9 +205,7 @@ mixin $BooksRoute on GoRouteData { @override String get location => GoRouteData.$location( '/books', - queryParams: { - if (_self.kind != BookKind.popular) 'kind': _$BookKindEnumMap[_self.kind], - }, + queryParams: {if (_self.kind != BookKind.popular) 'kind': _$BookKindEnumMap[_self.kind]}, ); @override @@ -245,8 +215,7 @@ mixin $BooksRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -258,11 +227,7 @@ const _$BookKindEnumMap = { BookKind.recent: 'recent', }; -T? _$convertMapValue( - String key, - Map map, - T? Function(String) converter, -) { +T? _$convertMapValue(String key, Map map, T? Function(String) converter) { final value = map[key]; return value == null ? null : converter(value); } @@ -278,8 +243,7 @@ RouteBase get $myMaterialRouteWithKey => GoRouteData.$route( ); mixin $MyMaterialRouteWithKey on GoRouteData { - static MyMaterialRouteWithKey _fromState(GoRouterState state) => - const MyMaterialRouteWithKey(); + static MyMaterialRouteWithKey _fromState(GoRouterState state) => const MyMaterialRouteWithKey(); @override String get location => GoRouteData.$location('/my-material-route-with-key'); @@ -291,15 +255,13 @@ mixin $MyMaterialRouteWithKey on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -RouteBase get $fancyRoute => - GoRouteData.$route(path: '/fancy', factory: $FancyRoute._fromState); +RouteBase get $fancyRoute => GoRouteData.$route(path: '/fancy', factory: $FancyRoute._fromState); mixin $FancyRoute on GoRouteData { static FancyRoute _fromState(GoRouterState state) => const FancyRoute(); @@ -314,8 +276,7 @@ mixin $FancyRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -334,8 +295,7 @@ RouteBase get $myShellRouteData => ShellRouteData.$route( ); extension $MyShellRouteDataExtension on MyShellRouteData { - static MyShellRouteData _fromState(GoRouterState state) => - const MyShellRouteData(); + static MyShellRouteData _fromState(GoRouterState state) => const MyShellRouteData(); } mixin $MyGoRouteData on GoRouteData { @@ -351,17 +311,14 @@ mixin $MyGoRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -RouteBase get $detailsRoute => RelativeGoRouteData.$route( - path: 'details', - factory: $DetailsRoute._fromState, -); +RouteBase get $detailsRoute => + RelativeGoRouteData.$route(path: 'details', factory: $DetailsRoute._fromState); mixin $DetailsRoute on RelativeGoRouteData { static DetailsRoute _fromState(GoRouterState state) => const DetailsRoute(); @@ -376,14 +333,11 @@ mixin $DetailsRoute on RelativeGoRouteData { void goRelative(BuildContext context) => context.go(relativeLocation); @override - Future pushRelative(BuildContext context) => - context.push(relativeLocation); + Future pushRelative(BuildContext context) => context.push(relativeLocation); @override - void pushReplacementRelative(BuildContext context) => - context.pushReplacement(relativeLocation); + void pushReplacementRelative(BuildContext context) => context.pushReplacement(relativeLocation); @override - void replaceRelative(BuildContext context) => - context.replace(relativeLocation); + void replaceRelative(BuildContext context) => context.replace(relativeLocation); } diff --git a/packages/go_router_builder/example/lib/shared/data.dart b/packages/go_router_builder/example/lib/shared/data.dart index 89d02c65989c..71baccebc9ab 100644 --- a/packages/go_router_builder/example/lib/shared/data.dart +++ b/packages/go_router_builder/example/lib/shared/data.dart @@ -136,10 +136,8 @@ final List familyData = [ Family familyById(String fid) => familyData.family(fid); extension on List { - Family family(String fid) => singleWhere( - (Family f) => f.id == fid, - orElse: () => throw Exception('unknown family $fid'), - ); + Family family(String fid) => + singleWhere((Family f) => f.id == fid, orElse: () => throw Exception('unknown family $fid')); } class LoginInfo extends ChangeNotifier { @@ -179,8 +177,7 @@ class Repository { return familyData; } - Future getFamily(String fid) async => - (await getFamilies()).family(fid); + Future getFamily(String fid) async => (await getFamilies()).family(fid); Future getPerson(String fid, int pid) async { final Family family = await getFamily(fid); diff --git a/packages/go_router_builder/example/lib/shell_route_example.dart b/packages/go_router_builder/example/lib/shell_route_example.dart index 9da4046af1d8..575a84f9f959 100644 --- a/packages/go_router_builder/example/lib/shell_route_example.dart +++ b/packages/go_router_builder/example/lib/shell_route_example.dart @@ -15,21 +15,16 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); - final GoRouter _router = GoRouter( - routes: $appRoutes, - initialLocation: '/foo', - ); + final GoRouter _router = GoRouter(routes: $appRoutes, initialLocation: '/foo'); } class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override - Widget build(BuildContext context) => - Scaffold(appBar: AppBar(title: const Text('foo'))); + Widget build(BuildContext context) => Scaffold(appBar: AppBar(title: const Text('foo'))); } @TypedShellRoute( @@ -125,8 +120,7 @@ class LoginRoute extends GoRouteData with $LoginRoute { const LoginRoute(); @override - Widget build(BuildContext context, GoRouterState state) => - const LoginScreen(); + Widget build(BuildContext context, GoRouterState state) => const LoginScreen(); } class LoginScreen extends StatelessWidget { diff --git a/packages/go_router_builder/example/lib/shell_route_example.g.dart b/packages/go_router_builder/example/lib/shell_route_example.g.dart index cac7b3d666ab..bac3119135dd 100644 --- a/packages/go_router_builder/example/lib/shell_route_example.g.dart +++ b/packages/go_router_builder/example/lib/shell_route_example.g.dart @@ -19,8 +19,7 @@ RouteBase get $myShellRouteData => ShellRouteData.$route( ); extension $MyShellRouteDataExtension on MyShellRouteData { - static MyShellRouteData _fromState(GoRouterState state) => - const MyShellRouteData(); + static MyShellRouteData _fromState(GoRouterState state) => const MyShellRouteData(); } mixin $FooRouteData on GoRouteData { @@ -36,8 +35,7 @@ mixin $FooRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -56,15 +54,13 @@ mixin $BarRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -RouteBase get $loginRoute => - GoRouteData.$route(path: '/login', factory: $LoginRoute._fromState); +RouteBase get $loginRoute => GoRouteData.$route(path: '/login', factory: $LoginRoute._fromState); mixin $LoginRoute on GoRouteData { static LoginRoute _fromState(GoRouterState state) => const LoginRoute(); @@ -79,8 +75,7 @@ mixin $LoginRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/shell_route_with_keys_example.dart b/packages/go_router_builder/example/lib/shell_route_with_keys_example.dart index c194784074a5..1ebd8d3c2634 100644 --- a/packages/go_router_builder/example/lib/shell_route_with_keys_example.dart +++ b/packages/go_router_builder/example/lib/shell_route_with_keys_example.dart @@ -18,8 +18,7 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); final GoRouter _router = GoRouter( routes: $appRoutes, @@ -33,9 +32,7 @@ class App extends StatelessWidget { TypedGoRoute(path: '/home'), TypedGoRoute( path: '/users', - routes: >[ - TypedGoRoute(path: ':id'), - ], + routes: >[TypedGoRoute(path: ':id')], ), ], ) @@ -72,14 +69,8 @@ class MyShellRouteScreen extends StatelessWidget { children: [ NavigationRail( destinations: const [ - NavigationRailDestination( - icon: Icon(Icons.home), - label: Text('Home'), - ), - NavigationRailDestination( - icon: Icon(Icons.group), - label: Text('Users'), - ), + NavigationRailDestination(icon: Icon(Icons.home), label: Text('Home')), + NavigationRailDestination(icon: Icon(Icons.group), label: Text('Users')), ], selectedIndex: selectedIndex, onDestinationSelected: (int index) { diff --git a/packages/go_router_builder/example/lib/shell_route_with_keys_example.g.dart b/packages/go_router_builder/example/lib/shell_route_with_keys_example.g.dart index 8c09a9983e29..8a338f58f52c 100644 --- a/packages/go_router_builder/example/lib/shell_route_with_keys_example.g.dart +++ b/packages/go_router_builder/example/lib/shell_route_with_keys_example.g.dart @@ -30,8 +30,7 @@ RouteBase get $myShellRouteData => ShellRouteData.$route( ); extension $MyShellRouteDataExtension on MyShellRouteData { - static MyShellRouteData _fromState(GoRouterState state) => - const MyShellRouteData(); + static MyShellRouteData _fromState(GoRouterState state) => const MyShellRouteData(); } mixin $HomeRouteData on GoRouteData { @@ -47,16 +46,14 @@ mixin $HomeRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $UsersRouteData on GoRouteData { - static UsersRouteData _fromState(GoRouterState state) => - const UsersRouteData(); + static UsersRouteData _fromState(GoRouterState state) => const UsersRouteData(); @override String get location => GoRouteData.$location('/users'); @@ -68,8 +65,7 @@ mixin $UsersRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -82,9 +78,8 @@ mixin $UserRouteData on GoRouteData { UserRouteData get _self => this as UserRouteData; @override - String get location => GoRouteData.$location( - '/users/${Uri.encodeComponent(_self.id.toString())}', - ); + String get location => + GoRouteData.$location('/users/${Uri.encodeComponent(_self.id.toString())}'); @override void go(BuildContext context) => context.go(location); @@ -93,8 +88,7 @@ mixin $UserRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/shell_route_with_observers_example.dart b/packages/go_router_builder/example/lib/shell_route_with_observers_example.dart index 15aeea4e4c57..1e0966026af7 100644 --- a/packages/go_router_builder/example/lib/shell_route_with_observers_example.dart +++ b/packages/go_router_builder/example/lib/shell_route_with_observers_example.dart @@ -15,13 +15,9 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); - final GoRouter _router = GoRouter( - routes: $appRoutes, - initialLocation: '/home', - ); + final GoRouter _router = GoRouter(routes: $appRoutes, initialLocation: '/home'); } @TypedShellRoute( @@ -29,18 +25,14 @@ class App extends StatelessWidget { TypedGoRoute(path: '/home'), TypedGoRoute( path: '/users', - routes: >[ - TypedGoRoute(path: ':id'), - ], + routes: >[TypedGoRoute(path: ':id')], ), ], ) class MyShellRouteData extends ShellRouteData { const MyShellRouteData(); - static final List $observers = [ - MyNavigatorObserver(), - ]; + static final List $observers = [MyNavigatorObserver()]; @override Widget builder(BuildContext context, GoRouterState state, Widget navigator) { @@ -75,14 +67,8 @@ class MyShellRouteScreen extends StatelessWidget { children: [ NavigationRail( destinations: const [ - NavigationRailDestination( - icon: Icon(Icons.home), - label: Text('Home'), - ), - NavigationRailDestination( - icon: Icon(Icons.group), - label: Text('Users'), - ), + NavigationRailDestination(icon: Icon(Icons.home), label: Text('Home')), + NavigationRailDestination(icon: Icon(Icons.group), label: Text('Users')), ], selectedIndex: selectedIndex, onDestinationSelected: (int index) { diff --git a/packages/go_router_builder/example/lib/shell_route_with_observers_example.g.dart b/packages/go_router_builder/example/lib/shell_route_with_observers_example.g.dart index b52f89783f87..85596408e39c 100644 --- a/packages/go_router_builder/example/lib/shell_route_with_observers_example.g.dart +++ b/packages/go_router_builder/example/lib/shell_route_with_observers_example.g.dart @@ -18,16 +18,13 @@ RouteBase get $myShellRouteData => ShellRouteData.$route( GoRouteData.$route( path: '/users', factory: $UsersRouteData._fromState, - routes: [ - GoRouteData.$route(path: ':id', factory: $UserRouteData._fromState), - ], + routes: [GoRouteData.$route(path: ':id', factory: $UserRouteData._fromState)], ), ], ); extension $MyShellRouteDataExtension on MyShellRouteData { - static MyShellRouteData _fromState(GoRouterState state) => - const MyShellRouteData(); + static MyShellRouteData _fromState(GoRouterState state) => const MyShellRouteData(); } mixin $HomeRouteData on GoRouteData { @@ -43,16 +40,14 @@ mixin $HomeRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $UsersRouteData on GoRouteData { - static UsersRouteData _fromState(GoRouterState state) => - const UsersRouteData(); + static UsersRouteData _fromState(GoRouterState state) => const UsersRouteData(); @override String get location => GoRouteData.$location('/users'); @@ -64,8 +59,7 @@ mixin $UsersRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -78,9 +72,8 @@ mixin $UserRouteData on GoRouteData { UserRouteData get _self => this as UserRouteData; @override - String get location => GoRouteData.$location( - '/users/${Uri.encodeComponent(_self.id.toString())}', - ); + String get location => + GoRouteData.$location('/users/${Uri.encodeComponent(_self.id.toString())}'); @override void go(BuildContext context) => context.go(location); @@ -89,8 +82,7 @@ mixin $UserRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/simple_example.dart b/packages/go_router_builder/example/lib/simple_example.dart index 06867f1d47da..0ca0f0a19ec0 100644 --- a/packages/go_router_builder/example/lib/simple_example.dart +++ b/packages/go_router_builder/example/lib/simple_example.dart @@ -17,8 +17,7 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router, title: _appTitle); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router, title: _appTitle); final GoRouter _router = GoRouter(routes: $appRoutes); } @@ -26,9 +25,7 @@ class App extends StatelessWidget { @TypedGoRoute( path: '/', name: 'Home', - routes: >[ - TypedGoRoute(path: 'family/:familyId'), - ], + routes: >[TypedGoRoute(path: 'family/:familyId')], ) class HomeRoute extends GoRouteData with $HomeRoute { const HomeRoute(); @@ -57,10 +54,7 @@ class HomeScreen extends StatelessWidget { body: ListView( children: [ for (final Family family in familyData) - ListTile( - title: Text(family.name), - onTap: () => FamilyRoute(family.id).go(context), - ), + ListTile(title: Text(family.name), onTap: () => FamilyRoute(family.id).go(context)), ], ), ); @@ -74,9 +68,7 @@ class FamilyScreen extends StatelessWidget { Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: Text(family.name)), body: ListView( - children: [ - for (final Person p in family.people) ListTile(title: Text(p.name)), - ], + children: [for (final Person p in family.people) ListTile(title: Text(p.name))], ), ); } diff --git a/packages/go_router_builder/example/lib/simple_example.g.dart b/packages/go_router_builder/example/lib/simple_example.g.dart index 376c28ded398..cbfa1b40ba20 100644 --- a/packages/go_router_builder/example/lib/simple_example.g.dart +++ b/packages/go_router_builder/example/lib/simple_example.g.dart @@ -14,12 +14,7 @@ RouteBase get $homeRoute => GoRouteData.$route( path: '/', name: 'Home', factory: $HomeRoute._fromState, - routes: [ - GoRouteData.$route( - path: 'family/:familyId', - factory: $FamilyRoute._fromState, - ), - ], + routes: [GoRouteData.$route(path: 'family/:familyId', factory: $FamilyRoute._fromState)], ); mixin $HomeRoute on GoRouteData { @@ -35,8 +30,7 @@ mixin $HomeRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -49,8 +43,7 @@ mixin $FamilyRoute on GoRouteData { FamilyRoute get _self => this as FamilyRoute; @override - String get location => - GoRouteData.$location('/family/${Uri.encodeComponent(_self.familyId)}'); + String get location => GoRouteData.$location('/family/${Uri.encodeComponent(_self.familyId)}'); @override void go(BuildContext context) => context.go(location); @@ -59,8 +52,7 @@ mixin $FamilyRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/stateful_shell_route_example.dart b/packages/go_router_builder/example/lib/stateful_shell_route_example.dart index b291ff166add..ae80bf7bc184 100644 --- a/packages/go_router_builder/example/lib/stateful_shell_route_example.dart +++ b/packages/go_router_builder/example/lib/stateful_shell_route_example.dart @@ -10,8 +10,9 @@ import 'package:go_router/go_router.dart'; part 'stateful_shell_route_example.g.dart'; -final GlobalKey _sectionANavigatorKey = - GlobalKey(debugLabel: 'sectionANav'); +final GlobalKey _sectionANavigatorKey = GlobalKey( + debugLabel: 'sectionANav', +); void main() => runApp(App()); @@ -19,34 +20,25 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); - final GoRouter _router = GoRouter( - routes: $appRoutes, - initialLocation: '/detailsA', - ); + final GoRouter _router = GoRouter(routes: $appRoutes, initialLocation: '/detailsA'); } class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override - Widget build(BuildContext context) => - Scaffold(appBar: AppBar(title: const Text('foo'))); + Widget build(BuildContext context) => Scaffold(appBar: AppBar(title: const Text('foo'))); } @TypedStatefulShellRoute( branches: >[ TypedStatefulShellBranch( - routes: >[ - TypedGoRoute(path: '/detailsA'), - ], + routes: >[TypedGoRoute(path: '/detailsA')], ), TypedStatefulShellBranch( - routes: >[ - TypedGoRoute(path: '/detailsB'), - ], + routes: >[TypedGoRoute(path: '/detailsB')], ), ], ) @@ -69,10 +61,7 @@ class MyShellRouteData extends StatefulShellRouteData { StatefulNavigationShell navigationShell, List children, ) { - return ScaffoldWithNavBar( - navigationShell: navigationShell, - children: children, - ); + return ScaffoldWithNavBar(navigationShell: navigationShell, children: children); } } @@ -109,11 +98,8 @@ class DetailsBRouteData extends GoRouteData with $DetailsBRouteData { /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. - const ScaffoldWithNavBar({ - required this.navigationShell, - required this.children, - Key? key, - }) : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); + const ScaffoldWithNavBar({required this.navigationShell, required this.children, Key? key}) + : super(key: key ?? const ValueKey('ScaffoldWithNavBar')); /// The navigation shell and container for the branch Navigators. final StatefulNavigationShell navigationShell; @@ -125,10 +111,7 @@ class ScaffoldWithNavBar extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - body: AnimatedBranchContainer( - currentIndex: navigationShell.currentIndex, - children: children, - ), + body: AnimatedBranchContainer(currentIndex: navigationShell.currentIndex, children: children), bottomNavigationBar: BottomNavigationBar( // Here, the items of BottomNavigationBar are hard coded. In a real // world scenario, the items would most likely be generated from the @@ -165,11 +148,7 @@ class ScaffoldWithNavBar extends StatelessWidget { /// when switching branches. class AnimatedBranchContainer extends StatelessWidget { /// Creates a AnimatedBranchContainer - const AnimatedBranchContainer({ - super.key, - required this.currentIndex, - required this.children, - }); + const AnimatedBranchContainer({super.key, required this.currentIndex, required this.children}); /// The index (in [children]) of the branch Navigator to display. final int currentIndex; @@ -249,16 +228,10 @@ class DetailsScreenState extends State { ), const Padding(padding: EdgeInsets.all(8)), if (widget.param != null) - Text( - 'Parameter: ${widget.param!}', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Parameter: ${widget.param!}', style: Theme.of(context).textTheme.titleMedium), const Padding(padding: EdgeInsets.all(8)), if (widget.extra != null) - Text( - 'Extra: ${widget.extra!}', - style: Theme.of(context).textTheme.titleMedium, - ), + Text('Extra: ${widget.extra!}', style: Theme.of(context).textTheme.titleMedium), ], ), ); diff --git a/packages/go_router_builder/example/lib/stateful_shell_route_example.g.dart b/packages/go_router_builder/example/lib/stateful_shell_route_example.g.dart index ecd05a1b79c4..ee2ad83016dd 100644 --- a/packages/go_router_builder/example/lib/stateful_shell_route_example.g.dart +++ b/packages/go_router_builder/example/lib/stateful_shell_route_example.g.dart @@ -16,34 +16,22 @@ RouteBase get $myShellRouteData => StatefulShellRouteData.$route( factory: $MyShellRouteDataExtension._fromState, branches: [ StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route( - path: '/detailsA', - factory: $DetailsARouteData._fromState, - ), - ], + routes: [GoRouteData.$route(path: '/detailsA', factory: $DetailsARouteData._fromState)], ), StatefulShellBranchData.$branch( navigatorKey: BranchBData.$navigatorKey, restorationScopeId: BranchBData.$restorationScopeId, - routes: [ - GoRouteData.$route( - path: '/detailsB', - factory: $DetailsBRouteData._fromState, - ), - ], + routes: [GoRouteData.$route(path: '/detailsB', factory: $DetailsBRouteData._fromState)], ), ], ); extension $MyShellRouteDataExtension on MyShellRouteData { - static MyShellRouteData _fromState(GoRouterState state) => - const MyShellRouteData(); + static MyShellRouteData _fromState(GoRouterState state) => const MyShellRouteData(); } mixin $DetailsARouteData on GoRouteData { - static DetailsARouteData _fromState(GoRouterState state) => - const DetailsARouteData(); + static DetailsARouteData _fromState(GoRouterState state) => const DetailsARouteData(); @override String get location => GoRouteData.$location('/detailsA'); @@ -55,16 +43,14 @@ mixin $DetailsARouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $DetailsBRouteData on GoRouteData { - static DetailsBRouteData _fromState(GoRouterState state) => - const DetailsBRouteData(); + static DetailsBRouteData _fromState(GoRouterState state) => const DetailsBRouteData(); @override String get location => GoRouteData.$location('/detailsB'); @@ -76,8 +62,7 @@ mixin $DetailsBRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart index 0f51f815cb77..8ba14f797f7a 100644 --- a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart +++ b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.dart @@ -17,29 +17,22 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); - final GoRouter _router = GoRouter( - routes: $appRoutes, - initialLocation: '/home', - ); + final GoRouter _router = GoRouter(routes: $appRoutes, initialLocation: '/home'); } class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override - Widget build(BuildContext context) => - Scaffold(appBar: AppBar(title: const Text('foo'))); + Widget build(BuildContext context) => Scaffold(appBar: AppBar(title: const Text('foo'))); } @TypedStatefulShellRoute( branches: >[ TypedStatefulShellBranch( - routes: >[ - TypedGoRoute(path: '/home'), - ], + routes: >[TypedGoRoute(path: '/home')], ), TypedStatefulShellBranch( routes: >[ @@ -47,9 +40,7 @@ class HomeScreen extends StatelessWidget { ], ), TypedStatefulShellBranch( - routes: >[ - TypedGoRoute(path: '/orders'), - ], + routes: >[TypedGoRoute(path: '/orders')], ), ], ) @@ -115,10 +106,7 @@ class MainPageView extends StatelessWidget { bottomNavigationBar: BottomNavigationBar( items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), - BottomNavigationBarItem( - icon: Icon(Icons.favorite), - label: 'Notifications', - ), + BottomNavigationBarItem(icon: Icon(Icons.favorite), label: 'Notifications'), BottomNavigationBarItem(icon: Icon(Icons.list), label: 'Orders'), ], currentIndex: navigationShell.currentIndex, @@ -128,10 +116,7 @@ class MainPageView extends StatelessWidget { } void _onTap(BuildContext context, int index) { - navigationShell.goBranch( - index, - initialLocation: index == navigationShell.currentIndex, - ); + navigationShell.goBranch(index, initialLocation: index == navigationShell.currentIndex); } } diff --git a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart index 690ffbdf9c67..578bda39038b 100644 --- a/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart +++ b/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart @@ -14,9 +14,7 @@ RouteBase get $mainShellRouteData => StatefulShellRouteData.$route( factory: $MainShellRouteDataExtension._fromState, branches: [ StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route(path: '/home', factory: $HomeRouteData._fromState), - ], + routes: [GoRouteData.$route(path: '/home', factory: $HomeRouteData._fromState)], ), StatefulShellBranchData.$branch( initialLocation: NotificationsShellBranchData.$initialLocation, @@ -28,19 +26,13 @@ RouteBase get $mainShellRouteData => StatefulShellRouteData.$route( ], ), StatefulShellBranchData.$branch( - routes: [ - GoRouteData.$route( - path: '/orders', - factory: $OrdersRouteData._fromState, - ), - ], + routes: [GoRouteData.$route(path: '/orders', factory: $OrdersRouteData._fromState)], ), ], ); extension $MainShellRouteDataExtension on MainShellRouteData { - static MainShellRouteData _fromState(GoRouterState state) => - const MainShellRouteData(); + static MainShellRouteData _fromState(GoRouterState state) => const MainShellRouteData(); } mixin $HomeRouteData on GoRouteData { @@ -56,20 +48,16 @@ mixin $HomeRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } mixin $NotificationsRouteData on GoRouteData { - static NotificationsRouteData _fromState(GoRouterState state) => - NotificationsRouteData( - section: _$NotificationsPageSectionEnumMap._$fromName( - state.pathParameters['section']!, - )!, - ); + static NotificationsRouteData _fromState(GoRouterState state) => NotificationsRouteData( + section: _$NotificationsPageSectionEnumMap._$fromName(state.pathParameters['section']!)!, + ); NotificationsRouteData get _self => this as NotificationsRouteData; @@ -85,8 +73,7 @@ mixin $NotificationsRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); @@ -99,8 +86,7 @@ const _$NotificationsPageSectionEnumMap = { }; mixin $OrdersRouteData on GoRouteData { - static OrdersRouteData _fromState(GoRouterState state) => - const OrdersRouteData(); + static OrdersRouteData _fromState(GoRouterState state) => const OrdersRouteData(); @override String get location => GoRouteData.$location('/orders'); @@ -112,8 +98,7 @@ mixin $OrdersRouteData on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); diff --git a/packages/go_router_builder/example/lib/typed_query_parameter_example.dart b/packages/go_router_builder/example/lib/typed_query_parameter_example.dart index 23b615783542..7556b8aec9e6 100644 --- a/packages/go_router_builder/example/lib/typed_query_parameter_example.dart +++ b/packages/go_router_builder/example/lib/typed_query_parameter_example.dart @@ -23,10 +23,7 @@ class CustomParameter { static CustomParameter decode(String value) { final List parts = value.split(','); - return CustomParameter( - valueString: parts[0], - valueInt: int.parse(parts[1]), - ); + return CustomParameter(valueString: parts[0], valueInt: int.parse(parts[1])); } static bool compare(CustomParameter a, CustomParameter b) { @@ -38,21 +35,16 @@ class App extends StatelessWidget { App({super.key}); @override - Widget build(BuildContext context) => - MaterialApp.router(routerConfig: _router); + Widget build(BuildContext context) => MaterialApp.router(routerConfig: _router); - final GoRouter _router = GoRouter( - initialLocation: '/int-route', - routes: $appRoutes, - ); + final GoRouter _router = GoRouter(initialLocation: '/int-route', routes: $appRoutes); } @TypedGoRoute(path: '/int-route') class IntRoute extends GoRouteData with $IntRoute { IntRoute({ @TypedQueryParameter(name: 'intField') this.intField, - @TypedQueryParameter(name: 'int_field_with_default_value') - this.intFieldWithDefaultValue = 1, + @TypedQueryParameter(name: 'int_field_with_default_value') this.intFieldWithDefaultValue = 1, @TypedQueryParameter(name: 'int field') this.intFieldWithSpace, @TypedQueryParameter( encoder: CustomParameter.encode, @@ -64,10 +56,7 @@ class IntRoute extends GoRouteData with $IntRoute { decoder: CustomParameter.decode, compare: CustomParameter.compare, ) - this.customFieldWithDefaultValue = const CustomParameter( - valueString: 'default', - valueInt: 0, - ), + this.customFieldWithDefaultValue = const CustomParameter(valueString: 'default', valueInt: 0), }); final int? intField; @@ -103,9 +92,7 @@ class Screen extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( - appBar: AppBar( - title: const Text('Go router with custom URI parameter names'), - ), + appBar: AppBar(title: const Text('Go router with custom URI parameter names')), body: Center( child: Column( mainAxisSize: MainAxisSize.min, @@ -157,9 +144,7 @@ class Screen extends StatelessWidget { ), ListTile( title: const Text('customField:'), - subtitle: Text( - customField == null ? '' : CustomParameter.encode(customField!), - ), + subtitle: Text(customField == null ? '' : CustomParameter.encode(customField!)), trailing: const Icon(Icons.add), onTap: () { final newValue = CustomParameter( diff --git a/packages/go_router_builder/example/lib/typed_query_parameter_example.g.dart b/packages/go_router_builder/example/lib/typed_query_parameter_example.g.dart index d4c30ac00c85..8d5a786e5e22 100644 --- a/packages/go_router_builder/example/lib/typed_query_parameter_example.g.dart +++ b/packages/go_router_builder/example/lib/typed_query_parameter_example.g.dart @@ -10,28 +10,15 @@ part of 'typed_query_parameter_example.dart'; List get $appRoutes => [$intRoute]; -RouteBase get $intRoute => - GoRouteData.$route(path: '/int-route', factory: $IntRoute._fromState); +RouteBase get $intRoute => GoRouteData.$route(path: '/int-route', factory: $IntRoute._fromState); mixin $IntRoute on GoRouteData { static IntRoute _fromState(GoRouterState state) => IntRoute( - intField: _$convertMapValue( - 'intField', - state.uri.queryParameters, - int.tryParse, - ), + intField: _$convertMapValue('intField', state.uri.queryParameters, int.tryParse), intFieldWithDefaultValue: - _$convertMapValue( - 'int_field_with_default_value', - state.uri.queryParameters, - int.parse, - ) ?? + _$convertMapValue('int_field_with_default_value', state.uri.queryParameters, int.parse) ?? 1, - intFieldWithSpace: _$convertMapValue( - 'int field', - state.uri.queryParameters, - int.tryParse, - ), + intFieldWithSpace: _$convertMapValue('int field', state.uri.queryParameters, int.tryParse), customField: (state.uri.queryParameters['custom-field'] == null ? null : CustomParameter.decode(state.uri.queryParameters['custom-field']!)), @@ -52,10 +39,8 @@ mixin $IntRoute on GoRouteData { queryParams: { if (_self.intField != null) 'intField': _self.intField!.toString(), if (_self.intFieldWithDefaultValue != 1) - 'int_field_with_default_value': _self.intFieldWithDefaultValue - .toString(), - if (_self.intFieldWithSpace != null) - 'int field': _self.intFieldWithSpace!.toString(), + 'int_field_with_default_value': _self.intFieldWithDefaultValue.toString(), + if (_self.intFieldWithSpace != null) 'int field': _self.intFieldWithSpace!.toString(), if (_self.customField != null) 'custom-field': _self.customField != null ? CustomParameter.encode(_self.customField!) @@ -77,18 +62,13 @@ mixin $IntRoute on GoRouteData { Future push(BuildContext context) => context.push(location); @override - void pushReplacement(BuildContext context) => - context.pushReplacement(location); + void pushReplacement(BuildContext context) => context.pushReplacement(location); @override void replace(BuildContext context) => context.replace(location); } -T? _$convertMapValue( - String key, - Map map, - T? Function(String) converter, -) { +T? _$convertMapValue(String key, Map map, T? Function(String) converter) { final value = map[key]; return value == null ? null : converter(value); } diff --git a/packages/go_router_builder/example/test/all_types_test.dart b/packages/go_router_builder/example/test/all_types_test.dart index 31da7b495040..43a4ec8c7f49 100644 --- a/packages/go_router_builder/example/test/all_types_test.dart +++ b/packages/go_router_builder/example/test/all_types_test.dart @@ -12,9 +12,7 @@ void main() { testWidgets('Test typed route navigation', (WidgetTester tester) async { await tester.pumpWidget(AllTypesApp()); - final ScaffoldState scaffoldState = tester.firstState( - find.byType(Scaffold), - ); + final ScaffoldState scaffoldState = tester.firstState(find.byType(Scaffold)); BigIntRoute( requiredBigIntField: BigInt.from(4), @@ -25,10 +23,7 @@ void main() { expect(find.text('Param: 4'), findsOneWidget); expect(find.text('Query param: 8'), findsOneWidget); - BoolRoute( - requiredBoolField: false, - boolField: true, - ).go(scaffoldState.context); + BoolRoute(requiredBoolField: false, boolField: true).go(scaffoldState.context); await tester.pumpAndSettle(); expect(find.text('BoolRoute'), findsOneWidget); expect(find.text('Param: false'), findsOneWidget); @@ -37,19 +32,13 @@ void main() { final param = DateTime.now(); final query = DateTime(2017, 9, 7, 17, 30); - DateTimeRoute( - requiredDateTimeField: param, - dateTimeField: query, - ).go(scaffoldState.context); + DateTimeRoute(requiredDateTimeField: param, dateTimeField: query).go(scaffoldState.context); await tester.pumpAndSettle(); expect(find.text('DateTimeRoute'), findsOneWidget); expect(find.text('Param: $param'), findsOneWidget); expect(find.text('Query param: $query'), findsOneWidget); - DoubleRoute( - requiredDoubleField: 3.14, - doubleField: -3.14, - ).go(scaffoldState.context); + DoubleRoute(requiredDoubleField: 3.14, doubleField: -3.14).go(scaffoldState.context); await tester.pumpAndSettle(); expect(find.text('DoubleRoute'), findsOneWidget); expect(find.text('Param: 3.14'), findsOneWidget); @@ -64,10 +53,7 @@ void main() { expect(find.text('Query param: -65'), findsOneWidget); expect(find.text('Query param with default value: 1'), findsOneWidget); - NumRoute( - requiredNumField: 987.32, - numField: -987.32, - ).go(scaffoldState.context); + NumRoute(requiredNumField: 987.32, numField: -987.32).go(scaffoldState.context); await tester.pumpAndSettle(); expect(find.text('NumRoute'), findsOneWidget); expect(find.text('Param: 987.32'), findsOneWidget); @@ -80,18 +66,9 @@ void main() { ).go(scaffoldState.context); await tester.pumpAndSettle(); expect(find.text('StringRoute'), findsOneWidget); - expect( - find.text('Param: Tytire tu patulae recubans sub tegmine fagi.'), - findsOneWidget, - ); - expect( - find.text('Query param: Tytire tu patulae recubans sub tegmine fagi.'), - findsOneWidget, - ); - expect( - find.text('Query param with default value: defaultValue'), - findsOneWidget, - ); + expect(find.text('Param: Tytire tu patulae recubans sub tegmine fagi.'), findsOneWidget); + expect(find.text('Query param: Tytire tu patulae recubans sub tegmine fagi.'), findsOneWidget); + expect(find.text('Query param with default value: defaultValue'), findsOneWidget); EnumRoute( requiredEnumField: PersonDetails.favoriteFood, @@ -100,14 +77,8 @@ void main() { await tester.pumpAndSettle(); expect(find.text('EnumRoute'), findsOneWidget); expect(find.text('Param: PersonDetails.favoriteFood'), findsOneWidget); - expect( - find.text('Query param: PersonDetails.favoriteSport'), - findsOneWidget, - ); - expect( - find.text('Query param with default value: PersonDetails.favoriteFood'), - findsOneWidget, - ); + expect(find.text('Query param: PersonDetails.favoriteSport'), findsOneWidget); + expect(find.text('Query param with default value: PersonDetails.favoriteFood'), findsOneWidget); EnhancedEnumRoute( requiredEnumField: SportDetails.football, @@ -117,10 +88,7 @@ void main() { expect(find.text('EnhancedEnumRoute'), findsOneWidget); expect(find.text('Param: SportDetails.football'), findsOneWidget); expect(find.text('Query param: SportDetails.hockey'), findsOneWidget); - expect( - find.text('Query param with default value: SportDetails.football'), - findsOneWidget, - ); + expect(find.text('Query param with default value: SportDetails.football'), findsOneWidget); UriRoute( requiredUriField: Uri.parse('https://dart.dev'), @@ -134,10 +102,7 @@ void main() { IterableRoute( enumIterableField: [SportDetails.football], intListField: [1, 2, 3], - enumOnlyInSetField: { - CookingRecipe.burger, - CookingRecipe.pizza, - }, + enumOnlyInSetField: {CookingRecipe.burger, CookingRecipe.pizza}, ).go(scaffoldState.context); await tester.pumpAndSettle(); expect(find.text('IterableRoute'), findsOneWidget); @@ -150,183 +115,128 @@ void main() { ); }); - testWidgets( - 'It should navigate to the iterable route with its default values', - (WidgetTester tester) async { - await tester.pumpWidget(AllTypesApp()); + testWidgets('It should navigate to the iterable route with its default values', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(AllTypesApp()); - final ScaffoldState scaffoldState = tester.firstState( - find.byType(Scaffold), - ); + final ScaffoldState scaffoldState = tester.firstState(find.byType(Scaffold)); - const IterableRouteWithDefaultValues().go(scaffoldState.context); - await tester.pumpAndSettle(); - expect(find.text('IterableRouteWithDefaultValues'), findsOneWidget); - final IterablePage page = tester.widget( - find.byType(IterablePage), - ); - expect( - page, - isA() - .having( - (IterablePage page) => page.intIterableField, - 'intIterableField', - const [0], - ) - .having( - (IterablePage page) => page.intListField, - 'intListField', - const [0], - ) - .having( - (IterablePage page) => page.intSetField, - 'intSetField', - const {0, 1}, - ) - .having( - (IterablePage page) => page.doubleIterableField, - 'doubleIterableField', - const [0, 1, 2], - ) - .having( - (IterablePage page) => page.doubleListField, - 'doubleListField', - const [1, 2, 3], - ) - .having( - (IterablePage page) => page.doubleSetField, - 'doubleSetField', - const {}, - ) - .having( - (IterablePage page) => page.stringIterableField, - 'stringIterableField', - const ['defaultValue'], - ) - .having( - (IterablePage page) => page.stringListField, - 'stringListField', - const ['defaultValue0', 'defaultValue1'], - ) - .having( - (IterablePage page) => page.stringSetField, - 'stringSetField', - const {'defaultValue'}, - ) - .having( - (IterablePage page) => page.boolIterableField, - 'boolIterableField', - const [false], - ) - .having( - (IterablePage page) => page.boolListField, - 'boolListField', - const [true], - ) - .having( - (IterablePage page) => page.boolSetField, - 'boolSetField', - const {true, false}, - ) - .having( - (IterablePage page) => page.enumIterableField, - 'enumIterableField', - const [SportDetails.tennis, SportDetails.hockey], - ) - .having( - (IterablePage page) => page.enumListField, - 'enumListField', - const [SportDetails.football], - ) - .having( - (IterablePage page) => page.enumSetField, - 'enumSetField', - const {SportDetails.hockey}, - ), - ); - expect(find.text('/iterable-route-with-default-values'), findsOneWidget); - }, - ); + const IterableRouteWithDefaultValues().go(scaffoldState.context); + await tester.pumpAndSettle(); + expect(find.text('IterableRouteWithDefaultValues'), findsOneWidget); + final IterablePage page = tester.widget(find.byType(IterablePage)); + expect( + page, + isA() + .having((IterablePage page) => page.intIterableField, 'intIterableField', const [0]) + .having((IterablePage page) => page.intListField, 'intListField', const [0]) + .having((IterablePage page) => page.intSetField, 'intSetField', const {0, 1}) + .having( + (IterablePage page) => page.doubleIterableField, + 'doubleIterableField', + const [0, 1, 2], + ) + .having((IterablePage page) => page.doubleListField, 'doubleListField', const [ + 1, + 2, + 3, + ]) + .having((IterablePage page) => page.doubleSetField, 'doubleSetField', const {}) + .having( + (IterablePage page) => page.stringIterableField, + 'stringIterableField', + const ['defaultValue'], + ) + .having((IterablePage page) => page.stringListField, 'stringListField', const [ + 'defaultValue0', + 'defaultValue1', + ]) + .having((IterablePage page) => page.stringSetField, 'stringSetField', const { + 'defaultValue', + }) + .having((IterablePage page) => page.boolIterableField, 'boolIterableField', const [ + false, + ]) + .having((IterablePage page) => page.boolListField, 'boolListField', const [true]) + .having((IterablePage page) => page.boolSetField, 'boolSetField', const { + true, + false, + }) + .having( + (IterablePage page) => page.enumIterableField, + 'enumIterableField', + const [SportDetails.tennis, SportDetails.hockey], + ) + .having((IterablePage page) => page.enumListField, 'enumListField', const [ + SportDetails.football, + ]) + .having((IterablePage page) => page.enumSetField, 'enumSetField', const { + SportDetails.hockey, + }), + ); + expect(find.text('/iterable-route-with-default-values'), findsOneWidget); + }); - testWidgets( - 'Test navigation with invalid query and path parameters using Uri.parse', - (WidgetTester tester) async { - await tester.pumpWidget(AllTypesApp()); + testWidgets('Test navigation with invalid query and path parameters using Uri.parse', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(AllTypesApp()); - final ScaffoldState scaffoldState = tester.firstState( - find.byType(Scaffold), - ); + final ScaffoldState scaffoldState = tester.firstState(find.byType(Scaffold)); - // Test invalid BigInt parameter - scaffoldState.context.go( - Uri.parse('/big-int-route/4?bigIntField=invalid').toString(), - ); - await tester.pumpAndSettle(); - expect(find.text('BigIntRoute'), findsOneWidget); - expect(find.text('Param: 4'), findsOneWidget); - expect(find.text('Query param: null'), findsOneWidget); + // Test invalid BigInt parameter + scaffoldState.context.go(Uri.parse('/big-int-route/4?bigIntField=invalid').toString()); + await tester.pumpAndSettle(); + expect(find.text('BigIntRoute'), findsOneWidget); + expect(find.text('Param: 4'), findsOneWidget); + expect(find.text('Query param: null'), findsOneWidget); - // Test invalid DateTime parameter - scaffoldState.context.go( - Uri.parse( - '/date-time-route/2021-01-01T00:00:00.000?dateTimeField=invalid-date', - ).toString(), - ); - await tester.pumpAndSettle(); - expect(find.text('DateTimeRoute'), findsOneWidget); - expect(find.text('Param: 2021-01-01 00:00:00.000'), findsOneWidget); - expect(find.text('Query param: null'), findsOneWidget); + // Test invalid DateTime parameter + scaffoldState.context.go( + Uri.parse('/date-time-route/2021-01-01T00:00:00.000?dateTimeField=invalid-date').toString(), + ); + await tester.pumpAndSettle(); + expect(find.text('DateTimeRoute'), findsOneWidget); + expect(find.text('Param: 2021-01-01 00:00:00.000'), findsOneWidget); + expect(find.text('Query param: null'), findsOneWidget); - // Test invalid Double parameter - scaffoldState.context.go( - Uri.parse('/double-route/3.14?doubleField=invalid').toString(), - ); - await tester.pumpAndSettle(); - expect(find.text('DoubleRoute'), findsOneWidget); - expect(find.text('Param: 3.14'), findsOneWidget); - expect(find.text('Query param: null'), findsOneWidget); - expect(find.text('Query param with default value: 1.0'), findsOneWidget); + // Test invalid Double parameter + scaffoldState.context.go(Uri.parse('/double-route/3.14?doubleField=invalid').toString()); + await tester.pumpAndSettle(); + expect(find.text('DoubleRoute'), findsOneWidget); + expect(find.text('Param: 3.14'), findsOneWidget); + expect(find.text('Query param: null'), findsOneWidget); + expect(find.text('Query param with default value: 1.0'), findsOneWidget); - // Test invalid Int parameter - scaffoldState.context.go( - Uri.parse('/int-route/65?intField=invalid').toString(), - ); - await tester.pumpAndSettle(); - expect(find.text('IntRoute'), findsOneWidget); - expect(find.text('Param: 65'), findsOneWidget); - expect(find.text('Query param: null'), findsOneWidget); - expect(find.text('Query param with default value: 1'), findsOneWidget); + // Test invalid Int parameter + scaffoldState.context.go(Uri.parse('/int-route/65?intField=invalid').toString()); + await tester.pumpAndSettle(); + expect(find.text('IntRoute'), findsOneWidget); + expect(find.text('Param: 65'), findsOneWidget); + expect(find.text('Query param: null'), findsOneWidget); + expect(find.text('Query param with default value: 1'), findsOneWidget); - // Test invalid Uri parameter - scaffoldState.context.go( - Uri.parse( - '/uri-route/https%3A%2F%2Fdart.dev?uriField=invalid-uri', - ).toString(), - ); - await tester.pumpAndSettle(); - expect(find.text('UriRoute'), findsOneWidget); - expect(find.text('Param: https://dart.dev'), findsOneWidget); - expect(find.text('Query param: null'), findsOneWidget); + // Test invalid Uri parameter + scaffoldState.context.go( + Uri.parse('/uri-route/https%3A%2F%2Fdart.dev?uriField=invalid-uri').toString(), + ); + await tester.pumpAndSettle(); + expect(find.text('UriRoute'), findsOneWidget); + expect(find.text('Param: https://dart.dev'), findsOneWidget); + expect(find.text('Query param: null'), findsOneWidget); - // Test invalid Enum parameter - scaffoldState.context.go( - Uri.parse('/enum-route/favorite-food?enum-field=invalid').toString(), - ); - await tester.pumpAndSettle(); - expect(find.text('EnumRoute'), findsOneWidget); - expect(find.text('Query param: null'), findsOneWidget); - expect( - find.text('Query param with default value: PersonDetails.favoriteFood'), - findsOneWidget, - ); + // Test invalid Enum parameter + scaffoldState.context.go(Uri.parse('/enum-route/favorite-food?enum-field=invalid').toString()); + await tester.pumpAndSettle(); + expect(find.text('EnumRoute'), findsOneWidget); + expect(find.text('Query param: null'), findsOneWidget); + expect(find.text('Query param with default value: PersonDetails.favoriteFood'), findsOneWidget); - // Test invalid Iterable parameter - scaffoldState.context.go( - Uri.parse('/iterable-route?intListField=invalid').toString(), - ); - await tester.pumpAndSettle(); - expect(find.text('IterableRoute'), findsOneWidget); - expect(find.text('/iterable-route'), findsOneWidget); - }, - ); + // Test invalid Iterable parameter + scaffoldState.context.go(Uri.parse('/iterable-route?intListField=invalid').toString()); + await tester.pumpAndSettle(); + expect(find.text('IterableRoute'), findsOneWidget); + expect(find.text('/iterable-route'), findsOneWidget); + }); } diff --git a/packages/go_router_builder/example/test/case_sensitivity_example_test.dart b/packages/go_router_builder/example/test/case_sensitivity_example_test.dart index d9d15cc1a081..5b8cbcb232a6 100644 --- a/packages/go_router_builder/example/test/case_sensitivity_example_test.dart +++ b/packages/go_router_builder/example/test/case_sensitivity_example_test.dart @@ -20,8 +20,7 @@ void main() { testWidgets( 'It should navigate to the correct screen when the route is not case sensitive and the path matches exactly', (WidgetTester tester) async { - tester.platformDispatcher.defaultRouteNameTestValue = - '/not-case-sensitive'; + tester.platformDispatcher.defaultRouteNameTestValue = '/not-case-sensitive'; await tester.pumpWidget(CaseSensitivityApp()); expect(find.widgetWithText(AppBar, 'Not Case Sensitive'), findsOne); @@ -42,8 +41,7 @@ void main() { testWidgets( 'It should navigate to the correct screen when the route is not case sensitive and the path case does not match', (WidgetTester tester) async { - tester.platformDispatcher.defaultRouteNameTestValue = - '/NOT-case-sensitive'; + tester.platformDispatcher.defaultRouteNameTestValue = '/NOT-case-sensitive'; await tester.pumpWidget(CaseSensitivityApp()); expect(find.widgetWithText(AppBar, 'Not Case Sensitive'), findsOne); diff --git a/packages/go_router_builder/example/test/location_test.dart b/packages/go_router_builder/example/test/location_test.dart index 29a691cfb5c6..cf1dad06d594 100644 --- a/packages/go_router_builder/example/test/location_test.dart +++ b/packages/go_router_builder/example/test/location_test.dart @@ -7,10 +7,7 @@ import 'package:go_router_builder_example/all_types.dart'; void main() { test('IterableRouteWithDefaultValues', () { - expect( - const IterableRouteWithDefaultValues().location, - '/iterable-route-with-default-values', - ); + expect(const IterableRouteWithDefaultValues().location, '/iterable-route-with-default-values'); // Needs to not be a const to test // https://github.com/flutter/flutter/issues/127825. @@ -21,9 +18,7 @@ void main() { ); expect( - IterableRouteWithDefaultValues( - doubleSetField: {0.0, 1.0}, - ).location, + IterableRouteWithDefaultValues(doubleSetField: {0.0, 1.0}).location, '/iterable-route-with-default-values?double-set-field=0.0&double-set-field=1.0', ); @@ -36,9 +31,7 @@ void main() { ); expect( - const IterableRouteWithDefaultValues( - intSetField: {0, 1, 2}, - ).location, + const IterableRouteWithDefaultValues(intSetField: {0, 1, 2}).location, '/iterable-route-with-default-values?int-set-field=0&int-set-field=1&int-set-field=2', ); }); diff --git a/packages/go_router_builder/example/test/on_exit_example_test.dart b/packages/go_router_builder/example/test/on_exit_example_test.dart index 2626a27dbba9..35a7b9746c49 100644 --- a/packages/go_router_builder/example/test/on_exit_example_test.dart +++ b/packages/go_router_builder/example/test/on_exit_example_test.dart @@ -7,9 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_builder_example/on_exit_example.dart'; void main() { - testWidgets('It should trigger the on exit when leaving the route', ( - WidgetTester tester, - ) async { + testWidgets('It should trigger the on exit when leaving the route', (WidgetTester tester) async { await tester.pumpWidget(App()); expect(find.byType(HomeScreen), findsOne); @@ -21,10 +19,7 @@ void main() { await tester.tap(find.widgetWithText(ElevatedButton, 'Go back')); await tester.pumpAndSettle(); - expect( - find.widgetWithText(AlertDialog, 'Are you sure to leave this page?'), - findsOne, - ); + expect(find.widgetWithText(AlertDialog, 'Are you sure to leave this page?'), findsOne); await tester.tap(find.text('Cancel')); await tester.pumpAndSettle(); @@ -34,10 +29,7 @@ void main() { await tester.tap(find.widgetWithText(ElevatedButton, 'Go back')); await tester.pumpAndSettle(); - expect( - find.widgetWithText(AlertDialog, 'Are you sure to leave this page?'), - findsOne, - ); + expect(find.widgetWithText(AlertDialog, 'Are you sure to leave this page?'), findsOne); await tester.tap(find.text('Confirm')); await tester.pumpAndSettle(); diff --git a/packages/go_router_builder/example/test/simple_example_test.dart b/packages/go_router_builder/example/test/simple_example_test.dart index 2286edbddfc4..8362d0caa0a1 100644 --- a/packages/go_router_builder/example/test/simple_example_test.dart +++ b/packages/go_router_builder/example/test/simple_example_test.dart @@ -8,9 +8,7 @@ import 'package:go_router_builder_example/shared/data.dart'; import 'package:go_router_builder_example/simple_example.dart'; void main() { - testWidgets('App starts on HomeScreen and displays families', ( - WidgetTester tester, - ) async { + testWidgets('App starts on HomeScreen and displays families', (WidgetTester tester) async { await tester.pumpWidget(App()); expect(find.byType(HomeScreen), findsOneWidget); expect(find.byType(ListTile), findsNWidgets(familyData.length)); diff --git a/packages/go_router_builder/example/test/stateful_shell_route_initial_location_test.dart b/packages/go_router_builder/example/test/stateful_shell_route_initial_location_test.dart index 31536cff7296..8ee933a6b214 100644 --- a/packages/go_router_builder/example/test/stateful_shell_route_initial_location_test.dart +++ b/packages/go_router_builder/example/test/stateful_shell_route_initial_location_test.dart @@ -6,15 +6,14 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_builder_example/stateful_shell_route_initial_location_example.dart'; void main() { - testWidgets( - 'Navigate to Notifications section with old tab selected by default', - (WidgetTester tester) async { - await tester.pumpWidget(App()); - expect(find.text('Home'), findsOneWidget); + testWidgets('Navigate to Notifications section with old tab selected by default', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(App()); + expect(find.text('Home'), findsOneWidget); - await tester.tap(find.text('Notifications')); - await tester.pumpAndSettle(); - expect(find.text('Old notifications'), findsOneWidget); - }, - ); + await tester.tap(find.text('Notifications')); + await tester.pumpAndSettle(); + expect(find.text('Old notifications'), findsOneWidget); + }); } diff --git a/packages/go_router_builder/example/test/stateful_shell_route_test.dart b/packages/go_router_builder/example/test/stateful_shell_route_test.dart index ae2215730078..18506fb5e8f9 100644 --- a/packages/go_router_builder/example/test/stateful_shell_route_test.dart +++ b/packages/go_router_builder/example/test/stateful_shell_route_test.dart @@ -6,9 +6,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:go_router_builder_example/stateful_shell_route_example.dart'; void main() { - testWidgets('Navigate between section A and section B', ( - WidgetTester tester, - ) async { + testWidgets('Navigate between section A and section B', (WidgetTester tester) async { await tester.pumpWidget(App()); expect(find.text('Details for A - Counter: 0'), findsOneWidget); diff --git a/packages/go_router_builder/example/test/typed_query_parameter_test.dart b/packages/go_router_builder/example/test/typed_query_parameter_test.dart index 564762b76200..bb8e79f12308 100644 --- a/packages/go_router_builder/example/test/typed_query_parameter_test.dart +++ b/packages/go_router_builder/example/test/typed_query_parameter_test.dart @@ -33,11 +33,7 @@ void main() { await tester.tap(find.text('intFieldWithSpace:')); await tester.pumpAndSettle(); - expect( - find.text('1'), - findsExactly(2), - reason: 'intField and intFieldWithSpace are both 1', - ); + expect(find.text('1'), findsExactly(2), reason: 'intField and intFieldWithSpace are both 1'); expect(find.text('2'), findsOne); }); diff --git a/packages/go_router_builder/lib/src/go_router_generator.dart b/packages/go_router_builder/lib/src/go_router_generator.dart index 80fb3ab93bb7..9f0f8414b2c3 100644 --- a/packages/go_router_builder/lib/src/go_router_generator.dart +++ b/packages/go_router_builder/lib/src/go_router_generator.dart @@ -28,9 +28,7 @@ class GoRouterGenerator extends Generator { const GoRouterGenerator(); TypeChecker get _typeChecker => TypeChecker.any( - _annotations.keys.map( - (String annotation) => TypeChecker.fromUrl('$_routeDataUrl#$annotation'), - ), + _annotations.keys.map((String annotation) => TypeChecker.fromUrl('$_routeDataUrl#$annotation')), ); @override @@ -58,14 +56,8 @@ ${getters.map((String e) => "$e,").join('\n')} /// /// This public method is for testing purposes and should not be called /// directly. - void generateForAnnotation( - LibraryReader library, - Set values, - Set getters, - ) { - for (final AnnotatedElement annotatedElement in library.annotatedWith( - _typeChecker, - )) { + void generateForAnnotation(LibraryReader library, Set values, Set getters) { + for (final AnnotatedElement annotatedElement in library.annotatedWith(_typeChecker)) { final InfoIterable generatedValue = _generateForAnnotatedElement( annotatedElement.element, annotatedElement.annotation, @@ -75,17 +67,11 @@ ${getters.map((String e) => "$e,").join('\n')} } } - InfoIterable _generateForAnnotatedElement( - Element element, - ConstantReader annotation, - ) { + InfoIterable _generateForAnnotatedElement(Element element, ConstantReader annotation) { final String typedAnnotation = withoutNullability( annotation.objectValue.type!.getDisplayString(), ); - final String type = typedAnnotation.substring( - 0, - typedAnnotation.indexOf('<'), - ); + final String type = typedAnnotation.substring(0, typedAnnotation.indexOf('<')); final String routeData = _annotations[type]!; if (element is! ClassElement) { throw InvalidGenerationSourceError( @@ -95,9 +81,7 @@ ${getters.map((String e) => "$e,").join('\n')} } final dataChecker = TypeChecker.fromUrl('$_routeDataUrl#$routeData'); - if (!element.allSupertypes.any( - (InterfaceType element) => dataChecker.isExactlyType(element), - )) { + if (!element.allSupertypes.any((InterfaceType element) => dataChecker.isExactlyType(element))) { throw InvalidGenerationSourceError( 'The @$type annotation can only be applied to classes that ' 'extend or implement `$routeData`.', @@ -105,9 +89,6 @@ ${getters.map((String e) => "$e,").join('\n')} ); } - return RouteBaseConfig.fromAnnotation( - annotation, - element, - ).generateMembers(); + return RouteBaseConfig.fromAnnotation(annotation, element).generateMembers(); } } diff --git a/packages/go_router_builder/lib/src/path_utils.dart b/packages/go_router_builder/lib/src/path_utils.dart index 607f9faf2a2b..e495ce78e8ee 100644 --- a/packages/go_router_builder/lib/src/path_utils.dart +++ b/packages/go_router_builder/lib/src/path_utils.dart @@ -15,8 +15,7 @@ final RegExp _parameterRegExp = RegExp(r':(\w+)(\((?:\\.|[^\\()])+\))?'); /// final pathParameters = pathParametersFromPattern(pattern); // {'id', 'bookId'} /// ``` Set pathParametersFromPattern(String pattern) => { - for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) - match[1]!, + for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) match[1]!, }; /// Reconstructs the full path from a [pattern] and path parameters. diff --git a/packages/go_router_builder/lib/src/route_config.dart b/packages/go_router_builder/lib/src/route_config.dart index 4ee1e96c507d..7de0c2dcb2a7 100644 --- a/packages/go_router_builder/lib/src/route_config.dart +++ b/packages/go_router_builder/lib/src/route_config.dart @@ -83,8 +83,7 @@ class ShellRouteConfig extends RouteBaseConfig { '${restorationScopeId == null ? '' : 'restorationScopeId: $restorationScopeId,'}'; @override - String get factorConstructorParameters => - 'factory: $_extensionName._fromState,'; + String get factorConstructorParameters => 'factory: $_extensionName._fromState,'; @override String get routeDataClassName => 'ShellRouteData'; @@ -128,8 +127,7 @@ extension $_extensionName on $_className { '${navigatorContainerBuilder == null ? '' : 'navigatorContainerBuilder: $navigatorContainerBuilder,'}'; @override - String get factorConstructorParameters => - 'factory: $_extensionName._fromState,'; + String get factorConstructorParameters => 'factory: $_extensionName._fromState,'; @override String get routeDataClassName => 'StatefulShellRouteData'; @@ -190,9 +188,7 @@ class StatefulShellBranchConfig extends RouteBaseConfig { mixin _GoRouteMixin on RouteBaseConfig { String get _basePathForLocation; - late final Set _pathParams = pathParametersFromPattern( - _basePathForLocation, - ); + late final Set _pathParams = pathParametersFromPattern(_basePathForLocation); // construct path bits using parent bits // if there are any queryParam objects, add in the `queryParam` bits @@ -226,17 +222,13 @@ mixin _GoRouteMixin on RouteBaseConfig { /// The definition of the mixin to be generated. String get _mixinDefinition; - FormalParameterElement? get _extraParam => - _ctor.formalParameters.singleWhereOrNull( - (FormalParameterElement element) => element.isExtraField, - ); + FormalParameterElement? get _extraParam => _ctor.formalParameters.singleWhereOrNull( + (FormalParameterElement element) => element.isExtraField, + ); String get _fromStateConstructor { final buffer = StringBuffer('=>'); - if (_ctor.isConst && - _ctorParams.isEmpty && - _ctorQueryParams.isEmpty && - _extraParam == null) { + if (_ctor.isConst && _ctorParams.isEmpty && _ctorQueryParams.isEmpty && _extraParam == null) { buffer.writeln('const '); } @@ -254,9 +246,7 @@ mixin _GoRouteMixin on RouteBaseConfig { } String get _castedSelf { - if (_pathParams.isEmpty && - _ctorQueryParams.isEmpty && - _extraParam == null) { + if (_pathParams.isEmpty && _ctorQueryParams.isEmpty && _extraParam == null) { return ''; } @@ -273,14 +263,8 @@ mixin _GoRouteMixin on RouteBaseConfig { ); } } - final List? metadata = _fieldMetadata( - element.displayName, - ); - final String fromStateExpression = decodeParameter( - element, - _pathParams, - metadata, - ); + final List? metadata = _fieldMetadata(element.displayName); + final String fromStateExpression = decodeParameter(element, _pathParams, metadata); if (element.isPositional) { return '$fromStateExpression,'; @@ -343,17 +327,16 @@ mixin _GoRouteMixin on RouteBaseConfig { return buffer.toString(); } - late final List _ctorParams = _ctor.formalParameters - .where((FormalParameterElement element) { - if (_pathParams.contains(element.displayName)) { - return true; - } - return false; - }) - .toList(); + late final List _ctorParams = _ctor.formalParameters.where(( + FormalParameterElement element, + ) { + if (_pathParams.contains(element.displayName)) { + return true; + } + return false; + }).toList(); - late final List _ctorQueryParams = _ctor - .formalParameters + late final List _ctorQueryParams = _ctor.formalParameters .where( (FormalParameterElement element) => !_pathParams.contains(element.displayName) && !element.isExtraField, @@ -364,34 +347,24 @@ mixin _GoRouteMixin on RouteBaseConfig { final ConstructorElement? ctor = routeDataClass.unnamedConstructor; if (ctor == null) { - throw InvalidGenerationSourceError( - 'Missing default constructor', - element: routeDataClass, - ); + throw InvalidGenerationSourceError('Missing default constructor', element: routeDataClass); } return ctor; } @override - Iterable classDeclarations() => [ - _mixinDefinition, - ..._enumDeclarations(), - ]; + Iterable classDeclarations() => [_mixinDefinition, ..._enumDeclarations()]; /// Returns code representing the constant maps that contain the `enum` to /// [String] mapping for each referenced enum. Iterable _enumDeclarations() { final enumParamTypes = {}; - for (final ctorParam in [ - ..._ctorParams, - ..._ctorQueryParams, - ]) { + for (final ctorParam in [..._ctorParams, ..._ctorQueryParams]) { DartType potentialEnumType = ctorParam.type; if (potentialEnumType is ParameterizedType && (ctorParam.type as ParameterizedType).typeArguments.isNotEmpty) { - potentialEnumType = - (ctorParam.type as ParameterizedType).typeArguments.first; + potentialEnumType = (ctorParam.type as ParameterizedType).typeArguments.first; } if (potentialEnumType.isEnum) { @@ -443,8 +416,7 @@ class GoRouteConfig extends RouteBaseConfig with _GoRouteMixin { RouteBaseConfig? config = this; while (config != null) { if (config - case GoRouteConfig(:final String path) || - RelativeGoRouteConfig(:final String path)) { + case GoRouteConfig(:final String path) || RelativeGoRouteConfig(:final String path)) { pathSegments.add(path); } config = config.parent; @@ -459,10 +431,9 @@ class GoRouteConfig extends RouteBaseConfig with _GoRouteMixin { @override String get _mixinDefinition { final bool hasMixin = - getNodeDeclaration(routeDataClass) - ?.withClause - ?.mixinTypes - .any((NamedType e) => e.name.toString() == _mixinName) ?? + getNodeDeclaration( + routeDataClass, + )?.withClause?.mixinTypes.any((NamedType e) => e.name.toString() == _mixinName) ?? false; if (!hasMixin) { @@ -534,10 +505,9 @@ class RelativeGoRouteConfig extends RouteBaseConfig with _GoRouteMixin { @override String get _mixinDefinition { final bool hasMixin = - getNodeDeclaration(routeDataClass) - ?.withClause - ?.mixinTypes - .any((NamedType e) => e.name.toString() == _mixinName) ?? + getNodeDeclaration( + routeDataClass, + )?.withClause?.mixinTypes.any((NamedType e) => e.name.toString() == _mixinName) ?? false; if (!hasMixin) { @@ -591,10 +561,7 @@ abstract class RouteBaseConfig { RouteBaseConfig._({required this.routeDataClass, required this.parent}); /// Creates a new [RouteBaseConfig] represented the annotation data in [reader]. - factory RouteBaseConfig.fromAnnotation( - ConstantReader reader, - InterfaceElement element, - ) { + factory RouteBaseConfig.fromAnnotation(ConstantReader reader, InterfaceElement element) { final definition = RouteBaseConfig._fromAnnotation(reader, element, null); if (element != definition.routeDataClass) { @@ -625,8 +592,7 @@ abstract class RouteBaseConfig { ); } - final bool isRelative = - isAncestorRelative || typeName == 'TypedRelativeGoRoute'; + final bool isRelative = isAncestorRelative || typeName == 'TypedRelativeGoRoute'; final DartType typeParamType = type.typeArguments.single; if (typeParamType is! InterfaceType) { @@ -646,18 +612,12 @@ abstract class RouteBaseConfig { value = ShellRouteConfig._( routeDataClass: classElement, parent: parent, - navigatorKey: _generateParameterGetterCode( - classElement, - parameterName: r'$navigatorKey', - ), + navigatorKey: _generateParameterGetterCode(classElement, parameterName: r'$navigatorKey'), parentNavigatorKey: _generateParameterGetterCode( classElement, parameterName: r'$parentNavigatorKey', ), - observers: _generateParameterGetterCode( - classElement, - parameterName: r'$observers', - ), + observers: _generateParameterGetterCode(classElement, parameterName: r'$observers'), restorationScopeId: _generateParameterGetterCode( classElement, parameterName: r'$restorationScopeId', @@ -684,10 +644,7 @@ abstract class RouteBaseConfig { value = StatefulShellBranchConfig._( routeDataClass: classElement, parent: parent, - navigatorKey: _generateParameterGetterCode( - classElement, - parameterName: r'$navigatorKey', - ), + navigatorKey: _generateParameterGetterCode(classElement, parameterName: r'$navigatorKey'), restorationScopeId: _generateParameterGetterCode( classElement, parameterName: r'$restorationScopeId', @@ -696,14 +653,8 @@ abstract class RouteBaseConfig { classElement, parameterName: r'$initialLocation', ), - observers: _generateParameterGetterCode( - classElement, - parameterName: r'$observers', - ), - preload: _generateParameterGetterCode( - classElement, - parameterName: r'$preload', - ), + observers: _generateParameterGetterCode(classElement, parameterName: r'$observers'), + preload: _generateParameterGetterCode(classElement, parameterName: r'$preload'), ); case 'TypedGoRoute': final ConstantReader pathValue = reader.read('path'); @@ -782,8 +733,7 @@ abstract class RouteBaseConfig { final RouteBaseConfig? parent; static String _generateChildrenGetterName(String name) { - return (name == 'TypedStatefulShellRoute' || - name == 'StatefulShellRouteData') + return (name == 'TypedStatefulShellRoute' || name == 'StatefulShellRouteData') ? 'branches' : 'routes'; } @@ -797,9 +747,7 @@ abstract class RouteBaseConfig { if (!element.isStatic || element.displayName != parameterName) { return false; } - if (parameterName.toLowerCase().contains( - RegExp('navigatorKey | observers'), - )) { + if (parameterName.toLowerCase().contains(RegExp('navigatorKey | observers'))) { final DartType type = element.type; if (type is! ParameterizedType) { return false; @@ -809,8 +757,7 @@ abstract class RouteBaseConfig { return false; } final DartType typeArgument = typeArguments.single; - if (withoutNullability(typeArgument.getDisplayString()) != - 'NavigatorState') { + if (withoutNullability(typeArgument.getDisplayString()) != 'NavigatorState') { return false; } } @@ -836,10 +783,8 @@ abstract class RouteBaseConfig { } /// Generates all of the members that correspond to `this`. - InfoIterable generateMembers() => InfoIterable._( - members: _generateMembers().toList(), - routeGetterName: _routeGetterName, - ); + InfoIterable generateMembers() => + InfoIterable._(members: _generateMembers().toList(), routeGetterName: _routeGetterName); Iterable _generateMembers() sync* { final items = [_rootDefinition()]; @@ -853,9 +798,7 @@ abstract class RouteBaseConfig { yield* items .expand( (String e) => helperNames.entries - .where( - (MapEntry element) => e.contains(element.key), - ) + .where((MapEntry element) => e.contains(element.key)) .map((MapEntry e) => e.value), ) .toSet(); @@ -897,8 +840,7 @@ $routeDataClassName.$dataConvertionFunctionName( '''; } - PropertyAccessorElement? _field(String name) => - routeDataClass.getGetter(name); + PropertyAccessorElement? _field(String name) => routeDataClass.getGetter(name); List? _fieldMetadata(String name) => routeDataClass.fields .firstWhereOrNull((FieldElement element) => element.displayName == name) diff --git a/packages/go_router_builder/lib/src/type_helpers.dart b/packages/go_router_builder/lib/src/type_helpers.dart index 39d8f0b00039..2fd45cd97e80 100644 --- a/packages/go_router_builder/lib/src/type_helpers.dart +++ b/packages/go_router_builder/lib/src/type_helpers.dart @@ -55,15 +55,11 @@ const List<_TypeHelper> _helpers = <_TypeHelper>[ ]; /// Checks if has a function that converts string to string, such as encode and decode. -bool _isStringToStringFunction( - ExecutableElement? executableElement, - String name, -) { +bool _isStringToStringFunction(ExecutableElement? executableElement, String name) { if (executableElement == null) { return false; } - final List parameters = - executableElement.formalParameters; + final List parameters = executableElement.formalParameters; return parameters.length == 1 && parameters.first.type.isDartCoreString && executableElement.returnType.isDartCoreString; @@ -98,14 +94,12 @@ String decodeParameter( if (annotatedDecoder != null) { // If there is a custom decoder, use it directly. - final stateValueAccess = - 'state.${_stateValueAccess(element, pathParameters)}'; + final stateValueAccess = 'state.${_stateValueAccess(element, pathParameters)}'; String decoded; if (!element.type.isNullableType && !element.hasDefaultValue) { decoded = '$annotatedDecoder($stateValueAccess)'; } else { - decoded = - '($stateValueAccess == null ? null : $annotatedDecoder($stateValueAccess!))'; + decoded = '($stateValueAccess == null ? null : $annotatedDecoder($stateValueAccess!))'; } if (element.isOptional && element.hasDefaultValue) { @@ -165,10 +159,7 @@ String decodeParameter( /// Returns the encoded [String] value for [element], if its type is supported. /// /// Otherwise, throws an [InvalidGenerationSourceError]. -String encodeField( - PropertyAccessorElement element, - List? metadata, -) { +String encodeField(PropertyAccessorElement element, List? metadata) { final String? annotatedEncoder = element.encoder; if (annotatedEncoder != null) { final fieldAccess = '$selfFieldName.${element.displayName}'; @@ -226,10 +217,10 @@ T? getNodeDeclaration(InterfaceElement element) { return null; } - final parsedLibrary = - session.getParsedLibraryByElement(element.library) as ParsedLibraryResult; - final FragmentDeclarationResult? declaration = parsedLibrary - .getFragmentDeclaration(element.firstFragment); + final parsedLibrary = session.getParsedLibraryByElement(element.library) as ParsedLibraryResult; + final FragmentDeclarationResult? declaration = parsedLibrary.getFragmentDeclaration( + element.firstFragment, + ); final AstNode? node = declaration?.node; return node is T ? node : null; @@ -246,10 +237,7 @@ String compareField(FormalParameterElement param) { for (final _TypeHelper helper in _helpers) { if (helper._matchesType(param.type)) { - return helper._compare( - '$selfFieldName.${param.displayName}', - param.defaultValueCode!, - ); + return helper._compare('$selfFieldName.${param.displayName}', param.defaultValueCode!); } } @@ -261,25 +249,19 @@ String compareField(FormalParameterElement param) { } /// Gets the name of the `const` map generated to help encode [Enum] types. -String enumMapName(InterfaceType type) => - '_\$${type.element.displayName}EnumMap'; +String enumMapName(InterfaceType type) => '_\$${type.element.displayName}EnumMap'; /// Gets the name of the `const` map generated to help encode [Json] types. String jsonMapName(InterfaceType type) => type.element.displayName; -String _stateValueAccess( - FormalParameterElement element, - Set pathParameters, -) { +String _stateValueAccess(FormalParameterElement element, Set pathParameters) { if (element.isExtraField) { // ignore: avoid_redundant_argument_values return 'extra as ${element.type.getDisplayString()}'; } late String access; - final suffix = !element.type.isNullableType && !element.hasDefaultValue - ? '!' - : ''; + final suffix = !element.type.isNullableType && !element.hasDefaultValue ? '!' : ''; if (pathParameters.contains(element.displayName)) { access = 'pathParameters[${escapeDartString(element.displayName)}]$suffix'; } else { @@ -334,16 +316,11 @@ class _TypeHelperBigInt extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - '$fieldName${type.ensureNotNull}.toString()', - customEncoder, - ); + _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder); @override - bool _matchesType(DartType type) => const TypeChecker.typeNamed( - BigInt, - inSdk: true, - ).isAssignableFromType(type); + bool _matchesType(DartType type) => + const TypeChecker.typeNamed(BigInt, inSdk: true).isAssignableFromType(type); } class _TypeHelperBool extends _TypeHelperWithHelper { @@ -354,10 +331,7 @@ class _TypeHelperBool extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - '$fieldName${type.ensureNotNull}.toString()', - customEncoder, - ); + _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder); @override bool _matchesType(DartType type) => type.isDartCoreBool; @@ -376,16 +350,11 @@ class _TypeHelperDateTime extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - '$fieldName${type.ensureNotNull}.toString()', - customEncoder, - ); + _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder); @override - bool _matchesType(DartType type) => const TypeChecker.typeNamed( - DateTime, - inSdk: true, - ).isAssignableFromType(type); + bool _matchesType(DartType type) => + const TypeChecker.typeNamed(DateTime, inSdk: true).isAssignableFromType(type); } class _TypeHelperDouble extends _TypeHelperWithHelper { @@ -401,10 +370,7 @@ class _TypeHelperDouble extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - '$fieldName${type.ensureNotNull}.toString()', - customEncoder, - ); + _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder); @override bool _matchesType(DartType type) => type.isDartCoreDouble; @@ -418,11 +384,7 @@ class _TypeHelperEnum extends _TypeHelperWithHelper { '${enumMapName(paramType as InterfaceType)}.$enumExtensionHelperName'; @override - String _encode( - String fieldName, - DartType type, - String? customEncoder, - ) => _fieldWithEncoder( + String _encode(String fieldName, DartType type, String? customEncoder) => _fieldWithEncoder( '${enumMapName(type as InterfaceType)}[$fieldName${type.ensureNotNull}]', customEncoder, ); @@ -456,8 +418,7 @@ class _TypeHelperExtensionType extends _TypeHelper { throw NullableDefaultValueError(parameterElement); } - final stateValue = - 'state.${_stateValueAccess(parameterElement, pathParameters)}'; + final stateValue = 'state.${_stateValueAccess(parameterElement, pathParameters)}'; final String castType; if (paramType.isNullableType || parameterElement.hasDefaultValue) { castType = '$paramType${paramType.isNullableType ? '' : '?'}'; @@ -475,9 +436,7 @@ class _TypeHelperExtensionType extends _TypeHelper { '.$enumExtensionHelperName($stateValue) as $castType'; } - final String representationTypeName = withoutNullability( - representationType.getDisplayString(), - ); + final String representationTypeName = withoutNullability(representationType.getDisplayString()); if (paramType.isNullableType || parameterElement.hasDefaultValue) { return "$representationTypeName.tryParse($stateValue ?? '') as $castType"; } else { @@ -514,18 +473,12 @@ class _TypeHelperExtensionType extends _TypeHelper { representationType.isDartCoreNum || representationType.isDartCoreBool || representationType.isEnum || - const TypeChecker.typeNamed( - BigInt, - inSdk: true, - ).isAssignableFromType(representationType) || + const TypeChecker.typeNamed(BigInt, inSdk: true).isAssignableFromType(representationType) || const TypeChecker.typeNamed( DateTime, inSdk: true, ).isAssignableFromType(representationType) || - const TypeChecker.typeNamed( - Uri, - inSdk: true, - ).isAssignableFromType(representationType); + const TypeChecker.typeNamed(Uri, inSdk: true).isAssignableFromType(representationType); } } @@ -542,10 +495,7 @@ class _TypeHelperInt extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - '$fieldName${type.ensureNotNull}.toString()', - customEncoder, - ); + _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder); @override bool _matchesType(DartType type) => type.isDartCoreInt; @@ -564,10 +514,7 @@ class _TypeHelperNum extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - '$fieldName${type.ensureNotNull}.toString()', - customEncoder, - ); + _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder); @override bool _matchesType(DartType type) => type.isDartCoreNum; @@ -604,10 +551,7 @@ class _TypeHelperUri extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - '$fieldName${type.ensureNotNull}.toString()', - customEncoder, - ); + _fieldWithEncoder('$fieldName${type.ensureNotNull}.toString()', customEncoder); @override bool _matchesType(DartType type) => @@ -635,15 +579,13 @@ class _TypeHelperIterable extends _TypeHelperWithHelper { var convertToNotNull = ''; for (final _TypeHelper helper in _helpers) { - if (helper._matchesType(iterableType) && - helper is _TypeHelperWithHelper) { + if (helper._matchesType(iterableType) && helper is _TypeHelperWithHelper) { if (!iterableType.isNullableType) { convertToNotNull = '.cast<$iterableType>()'; } entriesTypeDecoder = helper.helperName(iterableType); if (customDecoder != null) { - entriesTypeDecoder = - '(e) => $entriesTypeDecoder($customDecoder(e))'; + entriesTypeDecoder = '(e) => $entriesTypeDecoder($customDecoder(e))'; } } } @@ -656,8 +598,7 @@ class _TypeHelperIterable extends _TypeHelperWithHelper { inSdk: true, ).isAssignableFromType(parameterElement.type)) { iterableCaster += '.toList()'; - if (!parameterElement.type.isNullableType && - !parameterElement.hasDefaultValue) { + if (!parameterElement.type.isNullableType && !parameterElement.hasDefaultValue) { fallBack = '?? const []'; } } else if (const TypeChecker.typeNamed( @@ -665,8 +606,7 @@ class _TypeHelperIterable extends _TypeHelperWithHelper { inSdk: true, ).isAssignableFromType(parameterElement.type)) { iterableCaster += '.toSet()'; - if (!parameterElement.type.isNullableType && - !parameterElement.hasDefaultValue) { + if (!parameterElement.type.isNullableType && !parameterElement.hasDefaultValue) { fallBack = '?? const {}'; } } @@ -703,14 +643,11 @@ $fieldName$nullAwareAccess.map((e) => e.toString()).toList()'''; } @override - bool _matchesType(DartType type) => const TypeChecker.typeNamed( - Iterable, - inSdk: true, - ).isAssignableFromType(type); + bool _matchesType(DartType type) => + const TypeChecker.typeNamed(Iterable, inSdk: true).isAssignableFromType(type); @override - String _compare(String value1, String value2) => - '!$iterablesEqualHelperName($value1, $value2)'; + String _compare(String value1, String value2) => '!$iterablesEqualHelperName($value1, $value2)'; } class _TypeHelperJson extends _TypeHelperWithHelper { @@ -723,10 +660,7 @@ class _TypeHelperJson extends _TypeHelperWithHelper { @override String _encode(String fieldName, DartType type, String? customEncoder) => - _fieldWithEncoder( - 'jsonEncode($fieldName${type.ensureNotNull}.toJson())', - customEncoder, - ); + _fieldWithEncoder('jsonEncode($fieldName${type.ensureNotNull}.toJson())', customEncoder); @override bool _matchesType(DartType type) { @@ -734,10 +668,7 @@ class _TypeHelperJson extends _TypeHelperWithHelper { return false; } - final MethodElement? toJsonMethod = type.lookUpMethod( - 'toJson', - type.element.library, - ); + final MethodElement? toJsonMethod = type.lookUpMethod('toJson', type.element.library); if (toJsonMethod == null || !toJsonMethod.isPublic || toJsonMethod.formalParameters.isNotEmpty) { @@ -750,16 +681,12 @@ class _TypeHelperJson extends _TypeHelperWithHelper { return _matchesType(type.typeArguments.first); } - final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor( - 'fromJson', - ); + final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor('fromJson'); if (fromJsonMethod == null || !fromJsonMethod.isPublic || fromJsonMethod.formalParameters.length != 1 || - withoutNullability( - fromJsonMethod.formalParameters.first.type.getDisplayString(), - ) != + withoutNullability(fromJsonMethod.formalParameters.first.type.getDisplayString()) != 'Map') { throw InvalidGenerationSourceError( 'The parameter type ' @@ -793,9 +720,7 @@ class _TypeHelperJson extends _TypeHelperWithHelper { bool _isNestedTemplate(InterfaceType type) { // check if has fromJson constructor - final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor( - 'fromJson', - ); + final ConstructorElement? fromJsonMethod = type.element.getNamedConstructor('fromJson'); if (fromJsonMethod == null || !fromJsonMethod.isPublic) { return false; } @@ -805,15 +730,13 @@ class _TypeHelperJson extends _TypeHelperWithHelper { } // check if fromJson method receive two parameters - final List parameters = - fromJsonMethod.formalParameters; + final List parameters = fromJsonMethod.formalParameters; if (parameters.length != 2) { return false; } final FormalParameterElement firstParam = parameters[0]; - if (withoutNullability(firstParam.type.getDisplayString()) != - 'Map') { + if (withoutNullability(firstParam.type.getDisplayString()) != 'Map') { throw InvalidGenerationSourceError( 'The parameter type ' '`${withoutNullability(type.getDisplayString())}` not have a supported fromJson definition.', @@ -865,10 +788,7 @@ abstract class _TypeHelperWithHelper extends _TypeHelper { '${helperName(paramType)})'; } final nullableSuffix = - paramType.isNullableType || - (paramType.isEnum && !paramType.isNullableType) - ? '!' - : ''; + paramType.isNullableType || (paramType.isEnum && !paramType.isNullableType) ? '!' : ''; final String decode = _fieldWithEncoder( 'state.${_stateValueAccess(parameterElement, pathParameters)} ${!parameterElement.isRequired ? " ?? '' " : ''}', @@ -898,9 +818,7 @@ extension FormalParameterElementExtension on FormalParameterElement { final typedQueryParameterReader = ConstantReader( _typedQueryParameterChecker.firstAnnotationOf(this), ); - final String name = - typedQueryParameterReader.peek('name')?.stringValue ?? - displayName.kebab; + final String name = typedQueryParameterReader.peek('name')?.stringValue ?? displayName.kebab; return escapeDartString(name); } @@ -911,11 +829,7 @@ extension FormalParameterElementExtension on FormalParameterElement { _typedQueryParameterChecker.firstAnnotationOf(this), ); - return typedQueryParameterReader - .peek('decoder') - ?.objectValue - .toFunctionValue() - ?.qualifiedName; + return typedQueryParameterReader.peek('decoder')?.objectValue.toFunctionValue()?.qualifiedName; } /// Returns the name of the encoder function for this parameter, if it has a @@ -925,11 +839,7 @@ extension FormalParameterElementExtension on FormalParameterElement { _typedQueryParameterChecker.firstAnnotationOf(this), ); - return typedQueryParameterReader - .peek('encoder') - ?.objectValue - .toFunctionValue() - ?.qualifiedName; + return typedQueryParameterReader.peek('encoder')?.objectValue.toFunctionValue()?.qualifiedName; } /// Returns the name of the compare function for this parameter, if it has a @@ -939,11 +849,7 @@ extension FormalParameterElementExtension on FormalParameterElement { _typedQueryParameterChecker.firstAnnotationOf(this), ); - return typedQueryParameterReader - .peek('compare') - ?.objectValue - .toFunctionValue() - ?.qualifiedName; + return typedQueryParameterReader.peek('compare')?.objectValue.toFunctionValue()?.qualifiedName; } } @@ -952,9 +858,7 @@ extension PropertyAccessorElementExtension on PropertyAccessorElement { /// Returns the name of the encoder function for this property, if it has a /// `TypedQueryParameter` annotation with an encoder specified. String? get encoder { - return (enclosingElement as InterfaceElement) - .unnamedConstructor - ?.formalParameters + return (enclosingElement as InterfaceElement).unnamedConstructor?.formalParameters .firstWhereOrNull((parameter) => parameter.displayName == displayName) ?.encoder; } diff --git a/packages/go_router_builder/test/path_utils_test.dart b/packages/go_router_builder/test/path_utils_test.dart index 68578196188e..ccdd256c53f3 100644 --- a/packages/go_router_builder/test/path_utils_test.dart +++ b/packages/go_router_builder/test/path_utils_test.dart @@ -12,10 +12,7 @@ void main() { expect(pathParametersFromPattern('/user'), const {}); expect(pathParametersFromPattern('/user/:id'), const {'id'}); expect(pathParametersFromPattern('/user/:id/book'), const {'id'}); - expect( - pathParametersFromPattern('/user/:id/book/:bookId'), - const {'id', 'bookId'}, - ); + expect(pathParametersFromPattern('/user/:id/book/:bookId'), const {'id', 'bookId'}); }); }); @@ -23,14 +20,9 @@ void main() { test('It should replace the path parameters with their values', () { expect(patternToPath('/', const {}), '/'); expect(patternToPath('/user', const {}), '/user'); + expect(patternToPath('/user/:id', const {'id': 'user-id'}), '/user/user-id'); expect( - patternToPath('/user/:id', const {'id': 'user-id'}), - '/user/user-id', - ); - expect( - patternToPath('/user/:id/book', const { - 'id': 'user-id', - }), + patternToPath('/user/:id/book', const {'id': 'user-id'}), '/user/user-id/book', ); expect( diff --git a/packages/go_router_builder/test_inputs/case_sensitivity.dart b/packages/go_router_builder/test_inputs/case_sensitivity.dart index 29dc2df7fb3e..5a45e6222421 100644 --- a/packages/go_router_builder/test_inputs/case_sensitivity.dart +++ b/packages/go_router_builder/test_inputs/case_sensitivity.dart @@ -5,13 +5,11 @@ import 'package:go_router/go_router.dart'; mixin $CaseSensitiveRoute {} + mixin $NotCaseSensitiveRoute {} @TypedGoRoute(path: '/case-sensitive-route') class CaseSensitiveRoute extends GoRouteData with $CaseSensitiveRoute {} -@TypedGoRoute( - path: '/not-case-sensitive-route', - caseSensitive: false, -) +@TypedGoRoute(path: '/not-case-sensitive-route', caseSensitive: false) class NotCaseSensitiveRoute extends GoRouteData with $NotCaseSensitiveRoute {} diff --git a/packages/go_router_builder/test_inputs/custom_encoder.dart b/packages/go_router_builder/test_inputs/custom_encoder.dart index 6bf82b380a3f..279d42584b1e 100644 --- a/packages/go_router_builder/test_inputs/custom_encoder.dart +++ b/packages/go_router_builder/test_inputs/custom_encoder.dart @@ -7,9 +7,7 @@ import 'dart:convert'; import 'package:go_router/go_router.dart'; String fromBase64(String value) { - return const Utf8Decoder().convert( - base64Url.decode(base64Url.normalize(value)), - ); + return const Utf8Decoder().convert(base64Url.decode(base64Url.normalize(value))); } String toBase64(String value) { @@ -29,8 +27,7 @@ class CustomParameterRoute extends GoRouteData with $CustomParameterRoute { mixin $CustomParameterComplexRoute {} @TypedGoRoute(path: '/:id/') -class CustomParameterComplexRoute extends GoRouteData - with $CustomParameterComplexRoute { +class CustomParameterComplexRoute extends GoRouteData with $CustomParameterComplexRoute { CustomParameterComplexRoute({ required this.id, this.dir = '', diff --git a/packages/go_router_builder/test_inputs/extension_type_parameter.dart b/packages/go_router_builder/test_inputs/extension_type_parameter.dart index 3163b36dfd9c..f5aabd829605 100644 --- a/packages/go_router_builder/test_inputs/extension_type_parameter.dart +++ b/packages/go_router_builder/test_inputs/extension_type_parameter.dart @@ -5,16 +5,27 @@ import 'package:go_router/go_router.dart'; mixin $ExtensionTypeParam {} + mixin $ExtensionTypeStringParam {} + mixin $ExtensionTypeStringDefaultParam {} + mixin $ExtensionTypeIntParam {} + mixin $ExtensionTypeIntDefaultParam {} + mixin $ExtensionTypeDoubleParam {} + mixin $ExtensionTypeNumParam {} + mixin $ExtensionTypeBoolParam {} + mixin $ExtensionTypeEnumType {} + mixin $ExtensionTypeBigIntParam {} + mixin $ExtensionTypeDateTimeParam {} + mixin $ExtensionTypeUriType {} @TypedGoRoute( @@ -37,8 +48,7 @@ class ExtensionTypeParam extends GoRouteData with $ExtensionTypeParam { ExtensionTypeParam(); } -class ExtensionTypeStringParam extends GoRouteData - with $ExtensionTypeStringParam { +class ExtensionTypeStringParam extends GoRouteData with $ExtensionTypeStringParam { ExtensionTypeStringParam({ required this.s, required this.requiredValue, @@ -51,11 +61,8 @@ class ExtensionTypeStringParam extends GoRouteData final StringExtensionType optionalDefaultValue; } -class ExtensionTypeStringDefaultParam extends GoRouteData - with $ExtensionTypeStringDefaultParam { - ExtensionTypeStringDefaultParam({ - this.s = const StringExtensionType('default'), - }); +class ExtensionTypeStringDefaultParam extends GoRouteData with $ExtensionTypeStringDefaultParam { + ExtensionTypeStringDefaultParam({this.s = const StringExtensionType('default')}); final StringExtensionType s; } @@ -72,14 +79,12 @@ class ExtensionTypeIntParam extends GoRouteData with $ExtensionTypeIntParam { final IntExtensionType optionalDefaultValue; } -class ExtensionTypeIntDefaultParam extends GoRouteData - with $ExtensionTypeIntDefaultParam { +class ExtensionTypeIntDefaultParam extends GoRouteData with $ExtensionTypeIntDefaultParam { ExtensionTypeIntDefaultParam({this.x = const IntExtensionType(42)}); final IntExtensionType x; } -class ExtensionTypeDoubleParam extends GoRouteData - with $ExtensionTypeDoubleParam { +class ExtensionTypeDoubleParam extends GoRouteData with $ExtensionTypeDoubleParam { ExtensionTypeDoubleParam({ required this.d, required this.requiredValue, @@ -133,8 +138,7 @@ class ExtensionTypeEnumType extends GoRouteData with $ExtensionTypeEnumType { final EnumExtensionType optionalDefaultValue; } -class ExtensionTypeBigIntParam extends GoRouteData - with $ExtensionTypeBigIntParam { +class ExtensionTypeBigIntParam extends GoRouteData with $ExtensionTypeBigIntParam { ExtensionTypeBigIntParam({ required this.bi, required this.requiredValue, @@ -147,8 +151,7 @@ class ExtensionTypeBigIntParam extends GoRouteData final BigIntExtensionType? optionalNullableValue; } -class ExtensionTypeDateTimeParam extends GoRouteData - with $ExtensionTypeDateTimeParam { +class ExtensionTypeDateTimeParam extends GoRouteData with $ExtensionTypeDateTimeParam { ExtensionTypeDateTimeParam({ required this.dt, required this.optionalValue, @@ -171,11 +174,19 @@ class ExtensionTypeUriType extends GoRouteData with $ExtensionTypeUriType { } extension type const StringExtensionType(String value) {} + extension type const IntExtensionType(int value) {} + extension type const DoubleExtensionType(double value) {} + extension type const NumExtensionType(num value) {} + extension type const BoolExtensionType(bool value) {} + extension type const EnumExtensionType(MyEnum value) {} + extension type const BigIntExtensionType(BigInt value) {} + extension type const DateTimeExtensionType(DateTime value) {} + extension type const UriExtensionType(Uri value) {} diff --git a/packages/go_router_builder/test_inputs/go_relative.dart b/packages/go_router_builder/test_inputs/go_relative.dart index 53d7fe7310a7..d011e8bf30f1 100644 --- a/packages/go_router_builder/test_inputs/go_relative.dart +++ b/packages/go_router_builder/test_inputs/go_relative.dart @@ -5,30 +5,26 @@ import 'package:go_router/go_router.dart'; mixin $Route1 {} + mixin $Route2 {} + mixin $RelativeRoute {} + mixin $InnerRelativeRoute {} -const TypedRelativeGoRoute relativeRoute = - TypedRelativeGoRoute( - path: 'relative-route', - routes: >[ - TypedRelativeGoRoute(path: 'inner-relative-route'), - ], - ); - -@TypedGoRoute( - path: 'route-1', - routes: >[relativeRoute], -) +const TypedRelativeGoRoute relativeRoute = TypedRelativeGoRoute( + path: 'relative-route', + routes: >[ + TypedRelativeGoRoute(path: 'inner-relative-route'), + ], +); + +@TypedGoRoute(path: 'route-1', routes: >[relativeRoute]) class Route1 extends GoRouteData with $Route1 { const Route1(); } -@TypedGoRoute( - path: 'route-2', - routes: >[relativeRoute], -) +@TypedGoRoute(path: 'route-2', routes: >[relativeRoute]) class Route2 extends GoRouteData with $Route2 { const Route2(); } diff --git a/packages/go_router_builder/test_inputs/iterable_with_default_value.dart b/packages/go_router_builder/test_inputs/iterable_with_default_value.dart index 23eaa3ff8f6b..a927a364bd17 100644 --- a/packages/go_router_builder/test_inputs/iterable_with_default_value.dart +++ b/packages/go_router_builder/test_inputs/iterable_with_default_value.dart @@ -7,8 +7,7 @@ import 'package:go_router/go_router.dart'; mixin $IterableDefaultValueRoute {} @TypedGoRoute(path: '/iterable-default-value-route') -class IterableDefaultValueRoute extends GoRouteData - with $IterableDefaultValueRoute { +class IterableDefaultValueRoute extends GoRouteData with $IterableDefaultValueRoute { IterableDefaultValueRoute({this.param = const [0]}); final Iterable param; } diff --git a/packages/go_router_builder/test_inputs/list.dart b/packages/go_router_builder/test_inputs/list.dart index 1699fa74ba3b..7e9478f0e294 100644 --- a/packages/go_router_builder/test_inputs/list.dart +++ b/packages/go_router_builder/test_inputs/list.dart @@ -8,11 +8,7 @@ mixin $ListRoute {} @TypedGoRoute(path: '/list-route') class ListRoute extends GoRouteData with $ListRoute { - ListRoute({ - required this.ids, - this.nullableIds, - this.idsWithDefaultValue = const [0], - }); + ListRoute({required this.ids, this.nullableIds, this.idsWithDefaultValue = const [0]}); final List ids; final List? nullableIds; final List idsWithDefaultValue; diff --git a/packages/go_router_builder/test_inputs/nullable_default_value.dart b/packages/go_router_builder/test_inputs/nullable_default_value.dart index d6986fae7fae..6f0302cd08aa 100644 --- a/packages/go_router_builder/test_inputs/nullable_default_value.dart +++ b/packages/go_router_builder/test_inputs/nullable_default_value.dart @@ -7,8 +7,7 @@ import 'package:go_router/go_router.dart'; mixin $NullableDefaultValueRoute {} @TypedGoRoute(path: '/nullable-default-value-route') -class NullableDefaultValueRoute extends GoRouteData - with $NullableDefaultValueRoute { +class NullableDefaultValueRoute extends GoRouteData with $NullableDefaultValueRoute { NullableDefaultValueRoute({this.param = 0}); final int? param; } diff --git a/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart b/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart index 28d7f1474214..609b77d457b5 100644 --- a/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart +++ b/packages/go_router_builder/test_inputs/relative_route_with_direct_absolute_sub_route.dart @@ -5,24 +5,20 @@ import 'package:go_router/go_router.dart'; mixin $HomeRoute {} + mixin $RelativeRoute {} + mixin $NonRelativeRoute {} -@TypedGoRoute( - path: '/', - routes: >[relativeRoute], -) +@TypedGoRoute(path: '/', routes: >[relativeRoute]) class HomeRoute extends GoRouteData with $HomeRoute { const HomeRoute(); } -const TypedRelativeGoRoute relativeRoute = - TypedRelativeGoRoute( - path: 'relative-route', - routes: >[ - TypedGoRoute(path: 'non-relative-route'), - ], - ); +const TypedRelativeGoRoute relativeRoute = TypedRelativeGoRoute( + path: 'relative-route', + routes: >[TypedGoRoute(path: 'non-relative-route')], +); class RelativeRoute extends RelativeGoRouteData with $RelativeRoute { const RelativeRoute(); diff --git a/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart b/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart index 4261e9cd2388..a3ed13129011 100644 --- a/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart +++ b/packages/go_router_builder/test_inputs/relative_route_with_indirect_absolute_sub_route.dart @@ -5,23 +5,22 @@ import 'package:go_router/go_router.dart'; mixin $HomeRoute {} + mixin $ShellRoute {} + mixin $RelativeRoute {} + mixin $AbsoluteRoute {} -@TypedGoRoute( - path: '/', - routes: >[relativeRoute], -) +@TypedGoRoute(path: '/', routes: >[relativeRoute]) class HomeRoute extends GoRouteData with $HomeRoute { const HomeRoute(); } -const TypedRelativeGoRoute relativeRoute = - TypedRelativeGoRoute( - path: 'relative-route', - routes: >[shellRoute], - ); +const TypedRelativeGoRoute relativeRoute = TypedRelativeGoRoute( + path: 'relative-route', + routes: >[shellRoute], +); const TypedShellRoute shellRoute = TypedShellRoute( routes: >[absoluteRoute], diff --git a/packages/go_router_builder/test_inputs/required_extra_value.dart b/packages/go_router_builder/test_inputs/required_extra_value.dart index 0d6143f2c9d6..a1ce6473139c 100644 --- a/packages/go_router_builder/test_inputs/required_extra_value.dart +++ b/packages/go_router_builder/test_inputs/required_extra_value.dart @@ -7,8 +7,7 @@ import 'package:go_router/go_router.dart'; mixin $RequiredExtraValueRoute {} @TypedGoRoute(path: '/default-value-route') -class RequiredExtraValueRoute extends GoRouteData - with $RequiredExtraValueRoute { +class RequiredExtraValueRoute extends GoRouteData with $RequiredExtraValueRoute { RequiredExtraValueRoute({required this.$extra}); final int $extra; } diff --git a/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart b/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart index 598123879c74..0dd2a09a0003 100644 --- a/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart +++ b/packages/go_router_builder/test_inputs/required_nullable_type_arguments_extra_value.dart @@ -6,9 +6,7 @@ import 'package:go_router/go_router.dart'; mixin $RequiredNullableTypeArgumentsExtraValueRoute {} -@TypedGoRoute( - path: '/default-value-route', -) +@TypedGoRoute(path: '/default-value-route') class RequiredNullableTypeArgumentsExtraValueRoute extends GoRouteData with $RequiredNullableTypeArgumentsExtraValueRoute { RequiredNullableTypeArgumentsExtraValueRoute({required this.$extra}); diff --git a/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart b/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart index ad31cab52a33..70cc38c2f921 100644 --- a/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart +++ b/packages/go_router_builder/test_inputs/required_parameters_in_path_cannnot_be_null.dart @@ -7,8 +7,7 @@ import 'package:go_router/go_router.dart'; mixin $NullableRequiredParamInPath {} @TypedGoRoute(path: 'bob/:id') -class NullableRequiredParamInPath extends GoRouteData - with $NullableRequiredParamInPath { +class NullableRequiredParamInPath extends GoRouteData with $NullableRequiredParamInPath { NullableRequiredParamInPath({required this.id}); final int? id; } diff --git a/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart b/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart index 03f440c40a6d..9a899287958a 100644 --- a/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart +++ b/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart @@ -7,8 +7,7 @@ import 'package:go_router/go_router.dart'; mixin $NullableRequiredParamNotInPath {} @TypedGoRoute(path: 'bob') -class NullableRequiredParamNotInPath extends GoRouteData - with $NullableRequiredParamNotInPath { +class NullableRequiredParamNotInPath extends GoRouteData with $NullableRequiredParamNotInPath { NullableRequiredParamNotInPath({required this.id}); final int? id; } diff --git a/packages/go_router_builder/test_inputs/set.dart b/packages/go_router_builder/test_inputs/set.dart index fe2623a94ba9..9df22b3d125b 100644 --- a/packages/go_router_builder/test_inputs/set.dart +++ b/packages/go_router_builder/test_inputs/set.dart @@ -8,11 +8,7 @@ mixin $SetRoute {} @TypedGoRoute(path: '/set-route') class SetRoute extends GoRouteData with $SetRoute { - SetRoute({ - required this.ids, - this.nullableIds, - this.idsWithDefaultValue = const {0}, - }); + SetRoute({required this.ids, this.nullableIds, this.idsWithDefaultValue = const {0}}); final Set ids; final Set? nullableIds; final Set idsWithDefaultValue; diff --git a/packages/go_router_builder/test_inputs/typed_query_parameter.dart b/packages/go_router_builder/test_inputs/typed_query_parameter.dart index 5aa56ad22803..5426a61f218a 100644 --- a/packages/go_router_builder/test_inputs/typed_query_parameter.dart +++ b/packages/go_router_builder/test_inputs/typed_query_parameter.dart @@ -26,8 +26,7 @@ class CustomParameter { } @TypedGoRoute(path: '/typed-go-route-parameter') -class OverriddenParameterNameRoute extends GoRouteData - with $OverriddenParameterNameRoute { +class OverriddenParameterNameRoute extends GoRouteData with $OverriddenParameterNameRoute { OverriddenParameterNameRoute({ @TypedQueryParameter(name: 'parameterNameOverride') this.withAnnotation, @TypedQueryParameter(name: 'name with space') this.withSpace, @@ -41,10 +40,7 @@ class OverriddenParameterNameRoute extends GoRouteData decoder: CustomParameter.decode, compare: CustomParameter.compare, ) - this.customFieldWithDefaultValue = const CustomParameter( - valueString: 'default', - valueInt: 0, - ), + this.customFieldWithDefaultValue = const CustomParameter(valueString: 'default', valueInt: 0), }); final int? withAnnotation; final String? withSpace; diff --git a/packages/go_router_builder/tool/run_tests.dart b/packages/go_router_builder/tool/run_tests.dart index d1b8b84acc69..bfd42c78520c 100644 --- a/packages/go_router_builder/tool/run_tests.dart +++ b/packages/go_router_builder/tool/run_tests.dart @@ -19,9 +19,7 @@ import 'package:test/test.dart'; const GoRouterGenerator generator = GoRouterGenerator(); Future main() async { - final formatter = dart_style.DartFormatter( - languageVersion: await _packageVersion(), - ); + final formatter = dart_style.DartFormatter(languageVersion: await _packageVersion()); final dir = Directory('test_inputs'); final List testFiles = dir .listSync() @@ -68,9 +66,7 @@ Future main() async { } Future _packageVersion() async { - final PackageConfig packageConfig = await loadPackageConfigUri( - Isolate.packageConfigSync!, - ); + final PackageConfig packageConfig = await loadPackageConfigUri(Isolate.packageConfigSync!); final Uri pkgUri = Platform.script.resolve('../pubspec.yaml'); final Package? package = packageConfig.packageOf(pkgUri); if (package == null) { diff --git a/packages/google_adsense/example/integration_test/core_test.dart b/packages/google_adsense/example/integration_test/core_test.dart index aee9f023517f..749bdb90e794 100644 --- a/packages/google_adsense/example/integration_test/core_test.dart +++ b/packages/google_adsense/example/integration_test/core_test.dart @@ -44,9 +44,7 @@ void main() async { expect(injected.async, true); }); - testWidgets('sets AdSenseCodeParameters in script tag.', ( - WidgetTester _, - ) async { + testWidgets('sets AdSenseCodeParameters in script tag.', (WidgetTester _) async { final web.HTMLElement target = web.HTMLDivElement(); await adSense.initialize( @@ -67,27 +65,16 @@ void main() async { final injected = target.lastElementChild! as web.HTMLScriptElement; expect(injected.dataset['adHost'], 'test-adHost'); - expect( - injected.dataset['admobInterstitialSlot'], - 'test-admobInterstitialSlot', - ); + expect(injected.dataset['admobInterstitialSlot'], 'test-admobInterstitialSlot'); expect(injected.dataset['admobRewardedSlot'], 'test-admobRewardedSlot'); expect(injected.dataset['adChannel'], 'test-adChannel'); expect(injected.dataset['adbreakTest'], 'test-adbreakTest'); - expect( - injected.dataset['tagForChildDirectedTreatment'], - 'test-tagForChildDirectedTreatment', - ); - expect( - injected.dataset['tagForUnderAgeOfConsent'], - 'test-tagForUnderAgeOfConsent', - ); + expect(injected.dataset['tagForChildDirectedTreatment'], 'test-tagForChildDirectedTreatment'); + expect(injected.dataset['tagForUnderAgeOfConsent'], 'test-tagForUnderAgeOfConsent'); expect(injected.dataset['adFrequencyHint'], 'test-adFrequencyHint'); }); - testWidgets('Skips initialization if script is already present.', ( - WidgetTester _, - ) async { + testWidgets('Skips initialization if script is already present.', (WidgetTester _) async { final script = web.HTMLScriptElement() ..id = 'previously-injected' ..src = testScriptUrl; diff --git a/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart b/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart index 935d01877e92..8179768d0bdf 100644 --- a/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart +++ b/packages/google_adsense/example/integration_test/experimental_ad_unit_widget_test.dart @@ -44,9 +44,7 @@ void main() async { }); group('adSense.adUnit', () { - testWidgets('Responsive (with adFormat) ad units reflow flutter', ( - WidgetTester tester, - ) async { + testWidgets('Responsive (with adFormat) ad units reflow flutter', (WidgetTester tester) async { // The size of the ad that we're going to "inject" const double expectedHeight = 137; @@ -76,44 +74,38 @@ void main() async { expect(size.height, expectedHeight); }); - testWidgets( - 'Fixed size (without adFormat) ad units respect flutter constraints', - (WidgetTester tester) async { - const double maxHeight = 100; - const constraints = BoxConstraints(maxHeight: maxHeight); + testWidgets('Fixed size (without adFormat) ad units respect flutter constraints', ( + WidgetTester tester, + ) async { + const double maxHeight = 100; + const constraints = BoxConstraints(maxHeight: maxHeight); - // When - mockAdsByGoogle(mockAd(size: const Size(320, 157))); + // When + mockAdsByGoogle(mockAd(size: const Size(320, 157))); - await adSense.initialize(testClient); + await adSense.initialize(testClient); - final tracker = CallbackTracker(); - final Widget adUnitWidget = AdUnitWidget( - configuration: AdUnitConfiguration.displayAdUnit(adSlot: testSlot), - adClient: adSense.adClient, - onInjected: tracker.createCallback(), - ); + final tracker = CallbackTracker(); + final Widget adUnitWidget = AdUnitWidget( + configuration: AdUnitConfiguration.displayAdUnit(adSlot: testSlot), + adClient: adSense.adClient, + onInjected: tracker.createCallback(), + ); - final Widget constrainedAd = Container( - constraints: constraints, - child: adUnitWidget, - ); + final Widget constrainedAd = Container(constraints: constraints, child: adUnitWidget); - await pumpAdWidget(constrainedAd, tester, tracker); + await pumpAdWidget(constrainedAd, tester, tracker); - // Then - // Widget level - final Finder adUnit = find.byWidget(adUnitWidget); - expect(adUnit, findsOneWidget); + // Then + // Widget level + final Finder adUnit = find.byWidget(adUnitWidget); + expect(adUnit, findsOneWidget); - final Size size = tester.getSize(adUnit); - expect(size.height, maxHeight); - }, - ); + final Size size = tester.getSize(adUnit); + expect(size.height, maxHeight); + }); - testWidgets('Unfilled ad units collapse widget height', ( - WidgetTester tester, - ) async { + testWidgets('Unfilled ad units collapse widget height', (WidgetTester tester) async { // When mockAdsByGoogle(mockAd(adStatus: AdStatus.UNFILLED)); @@ -176,9 +168,7 @@ void main() async { Container( constraints: const BoxConstraints(maxHeight: 100), child: AdUnitWidget( - configuration: AdUnitConfiguration.displayAdUnit( - adSlot: testSlot, - ), + configuration: AdUnitConfiguration.displayAdUnit(adSlot: testSlot), adClient: adSense.adClient, onInjected: tracker.createCallback(), ), @@ -205,11 +195,7 @@ void main() async { 200, reason: 'Responsive ad widget should resize to match its `ins`', ); - expect( - tester.getSize(adUnits.at(1)).height, - 0, - reason: 'Unfulfilled ad should be 0x0', - ); + expect(tester.getSize(adUnits.at(1)).height, 0, reason: 'Unfulfilled ad should be 0x0'); expect( tester.getSize(adUnits.at(2)).height, 100, @@ -220,11 +206,7 @@ void main() async { } // Pumps an AdUnit Widget into a given tester, with some parameters -Future pumpAdWidget( - Widget adUnit, - WidgetTester tester, - CallbackTracker tracker, -) async { +Future pumpAdWidget(Widget adUnit, WidgetTester tester, CallbackTracker tracker) async { await tester.pumpWidget( MaterialApp( home: Scaffold(body: Center(child: adUnit)), diff --git a/packages/google_adsense/example/integration_test/h5_test.dart b/packages/google_adsense/example/integration_test/h5_test.dart index c98a1215fb6a..26af3ce3b745 100644 --- a/packages/google_adsense/example/integration_test/h5_test.dart +++ b/packages/google_adsense/example/integration_test/h5_test.dart @@ -41,9 +41,7 @@ void main() { expect(lastAdBreakPlacement!.type?.toDart, 'reward'); }); - testWidgets('can call the adBreakDone callback', ( - WidgetTester tester, - ) async { + testWidgets('can call the adBreakDone callback', (WidgetTester tester) async { AdBreakDonePlacementInfo? lastPlacementInfo; void adBreakDoneCallback(AdBreakDonePlacementInfo placementInfo) { @@ -52,9 +50,7 @@ void main() { mockAdsByGoogle( mockAdBreak( - adBreakDonePlacementInfo: AdBreakDonePlacementInfo( - breakName: 'ok-for-tests'.toJS, - ), + adBreakDonePlacementInfo: AdBreakDonePlacementInfo(breakName: 'ok-for-tests'.toJS), ), ); await adSense.initialize('_'); @@ -79,10 +75,7 @@ void main() { mockAdsByGoogle(mockAdBreak()); await adSense.initialize('_'); - final adBreakPlacement = AdBreakPlacement( - type: BreakType.reward, - name: 'my-test-break', - ); + final adBreakPlacement = AdBreakPlacement(type: BreakType.reward, name: 'my-test-break'); h5GamesAds.adBreak(adBreakPlacement); diff --git a/packages/google_adsense/example/integration_test/js_interop_mocks/h5_test_js_interop.dart b/packages/google_adsense/example/integration_test/js_interop_mocks/h5_test_js_interop.dart index 5001ef91de78..8967f3e8fdc1 100644 --- a/packages/google_adsense/example/integration_test/js_interop_mocks/h5_test_js_interop.dart +++ b/packages/google_adsense/example/integration_test/js_interop_mocks/h5_test_js_interop.dart @@ -23,10 +23,7 @@ PushFn mockAdBreak({AdBreakDonePlacementInfo? adBreakDonePlacementInfo}) { // Call `adBreakDone` if set, with `adBreakDonePlacementInfo`. if (adBreakPlacement?.adBreakDone != null) { assert(adBreakDonePlacementInfo != null); - adBreakPlacement!.adBreakDone!.callAsFunction( - null, - adBreakDonePlacementInfo, - ); + adBreakPlacement!.adBreakDone!.callAsFunction(null, adBreakDonePlacementInfo); } }; } diff --git a/packages/google_adsense/example/integration_test/script_tag_test.dart b/packages/google_adsense/example/integration_test/script_tag_test.dart index 7daa95e4c3a6..f8ba31facb2d 100644 --- a/packages/google_adsense/example/integration_test/script_tag_test.dart +++ b/packages/google_adsense/example/integration_test/script_tag_test.dart @@ -25,8 +25,7 @@ void main() async { await adSense.initialize(testClient); // Then - final injected = - web.document.head?.lastElementChild as web.HTMLScriptElement?; + final injected = web.document.head?.lastElementChild as web.HTMLScriptElement?; expect(injected, isNotNull); expect(injected!.src, expectedScriptUrl); diff --git a/packages/google_adsense/example/lib/ad_unit_widget.dart b/packages/google_adsense/example/lib/ad_unit_widget.dart index db201cb788f3..39f524367640 100644 --- a/packages/google_adsense/example/lib/ad_unit_widget.dart +++ b/packages/google_adsense/example/lib/ad_unit_widget.dart @@ -77,10 +77,7 @@ class _MyHomePageState extends State { ), // #docregion constraints Container( - constraints: const BoxConstraints( - maxHeight: 100, - maxWidth: 1200, - ), + constraints: const BoxConstraints(maxHeight: 100, maxWidth: 1200), padding: const EdgeInsets.only(bottom: 10), child: AdUnitWidget( configuration: AdUnitConfiguration.displayAdUnit( diff --git a/packages/google_adsense/example/lib/h5.dart b/packages/google_adsense/example/lib/h5.dart index fe2cab820eda..9ff6e12c2a16 100644 --- a/packages/google_adsense/example/lib/h5.dart +++ b/packages/google_adsense/example/lib/h5.dart @@ -9,16 +9,14 @@ import 'package:flutter/material.dart'; import 'package:google_adsense/google_adsense.dart'; // #docregion import-h5 import 'package:google_adsense/h5.dart'; + // #enddocregion import-h5 void main() async { // #docregion initialize-with-code-parameters await adSense.initialize( '0123456789012345', - adSenseCodeParameters: AdSenseCodeParameters( - adbreakTest: 'on', - adFrequencyHint: '30s', - ), + adSenseCodeParameters: AdSenseCodeParameters(adbreakTest: 'on', adFrequencyHint: '30s'), ); // #enddocregion initialize-with-code-parameters runApp(const MyApp()); @@ -169,23 +167,16 @@ class _MyHomePageState extends State { ), Text( 'Interstitial Ad Status:', - style: Theme.of( - context, - ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), + style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), ), Text('Last Status: ${_lastInterstitialInfo?.breakStatus}'), const Divider(), PaddedCard( children: [ const Text('🪙 Available coins:'), - Text( - '$_coins', - style: Theme.of(context).textTheme.displayLarge, - ), + Text('$_coins', style: Theme.of(context).textTheme.displayLarge), TextButton.icon( - onPressed: _h5Ready && !adBreakAvailable - ? _requestRewardedAd - : null, + onPressed: _h5Ready && !adBreakAvailable ? _requestRewardedAd : null, label: const Text('Prepare Reward'), icon: const Icon(Icons.download_rounded), ), @@ -198,9 +189,7 @@ class _MyHomePageState extends State { ), Text( 'Rewarded Ad Status:', - style: Theme.of( - context, - ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), + style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold), ), Text('Requested? $_adBreakRequested'), Text('Available? $adBreakAvailable'), diff --git a/packages/google_adsense/example/lib/main.dart b/packages/google_adsense/example/lib/main.dart index 413190058f48..974c6ea54035 100644 --- a/packages/google_adsense/example/lib/main.dart +++ b/packages/google_adsense/example/lib/main.dart @@ -17,6 +17,7 @@ void main() async { runApp(const MyApp()); } + // #enddocregion init /// The main app. diff --git a/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart b/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart index baf3a7aa7882..360b8dd1b633 100644 --- a/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart +++ b/packages/google_adsense/lib/src/adsense/ad_unit_configuration.dart @@ -77,12 +77,9 @@ class AdUnitConfiguration { if (isFullWidthResponsive != null) AdUnitParams.FULL_WIDTH_RESPONSIVE: isFullWidthResponsive.toString(), if (matchedContentUiType != null) - AdUnitParams.MATCHED_CONTENT_UI_TYPE: matchedContentUiType - .toString(), - if (columnsNum != null) - AdUnitParams.MATCHED_CONTENT_COLUMNS_NUM: columnsNum.toString(), - if (rowsNum != null) - AdUnitParams.MATCHED_CONTENT_ROWS_NUM: rowsNum.toString(), + AdUnitParams.MATCHED_CONTENT_UI_TYPE: matchedContentUiType.toString(), + if (columnsNum != null) AdUnitParams.MATCHED_CONTENT_COLUMNS_NUM: columnsNum.toString(), + if (rowsNum != null) AdUnitParams.MATCHED_CONTENT_ROWS_NUM: rowsNum.toString(), if (isAdTest != null && isAdTest) AdUnitParams.AD_TEST: 'on', }; diff --git a/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart b/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart index dbb8cb949452..7d92a0ee2c60 100644 --- a/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart +++ b/packages/google_adsense/lib/src/adsense/ad_unit_widget.dart @@ -52,8 +52,7 @@ class AdUnitWidget extends StatefulWidget { State createState() => _AdUnitWidgetWebState(); } -class _AdUnitWidgetWebState extends State - with AutomaticKeepAliveClientMixin { +class _AdUnitWidgetWebState extends State with AutomaticKeepAliveClientMixin { static int _adUnitCounter = 0; static final JSString _adStatusKey = 'adStatus'.toJS; @@ -86,18 +85,13 @@ class _AdUnitWidgetWebState extends State } return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { - if (!widget._adUnitConfiguration.params.containsKey( - AdUnitParams.AD_FORMAT, - )) { + if (!widget._adUnitConfiguration.params.containsKey(AdUnitParams.AD_FORMAT)) { _adSize = Size(_adSize.width, constraints.maxHeight); } return SizedBox( height: _adSize.height, width: _adSize.width, - child: HtmlElementView.fromTagName( - tagName: 'div', - onElementCreated: _onElementCreated, - ), + child: HtmlElementView.fromTagName(tagName: 'div', onElementCreated: _onElementCreated), ); }, ); @@ -131,8 +125,7 @@ class _AdUnitWidgetWebState extends State web.MutationObserver( (JSArray entries, web.MutationObserver observer) { for (final JSObject entry in entries.toDart) { - final target = - (entry as web.MutationRecord).target as web.HTMLElement; + final target = (entry as web.MutationRecord).target as web.HTMLElement; if (_isLoaded(target)) { if (_isFilled(target)) { debugLog( @@ -162,9 +155,7 @@ class _AdUnitWidgetWebState extends State } static void _onElementAttached(web.HTMLElement element) { - debugLog( - '$element attached with w=${element.offsetWidth} and h=${element.offsetHeight}', - ); + debugLog('$element attached with w=${element.offsetWidth} and h=${element.offsetHeight}'); debugLog( '${element.firstChild} size is ${(element.firstChild! as web.HTMLElement).offsetWidth}x${(element.firstChild! as web.HTMLElement).offsetHeight} ', ); @@ -172,17 +163,13 @@ class _AdUnitWidgetWebState extends State } bool _isLoaded(web.HTMLElement target) { - final bool isLoaded = target.dataset - .getProperty(_adStatusKey) - .isDefinedAndNotNull; + final bool isLoaded = target.dataset.getProperty(_adStatusKey).isDefinedAndNotNull; debugLog('Ad isLoaded: $isLoaded'); return isLoaded; } bool _isFilled(web.HTMLElement target) { - final String? adStatus = target.dataset - .getProperty(_adStatusKey) - ?.toDart; + final String? adStatus = target.dataset.getProperty(_adStatusKey)?.toDart; debugLog('Ad isFilled? $adStatus'); if (adStatus == AdStatus.FILLED) { return true; diff --git a/packages/google_adsense/lib/src/core/adsense_code_parameters.dart b/packages/google_adsense/lib/src/core/adsense_code_parameters.dart index 15660f19927e..bdf19db890b6 100644 --- a/packages/google_adsense/lib/src/core/adsense_code_parameters.dart +++ b/packages/google_adsense/lib/src/core/adsense_code_parameters.dart @@ -46,15 +46,13 @@ class AdSenseCodeParameters { String? adFrequencyHint, }) : _adSenseCodeParameters = { if (adHost != null) 'adHost': adHost, - if (admobInterstitialSlot != null) - 'admobInterstitialSlot': admobInterstitialSlot, + if (admobInterstitialSlot != null) 'admobInterstitialSlot': admobInterstitialSlot, if (admobRewardedSlot != null) 'admobRewardedSlot': admobRewardedSlot, if (adChannel != null) 'adChannel': adChannel, if (adbreakTest != null) 'adbreakTest': adbreakTest, if (tagForChildDirectedTreatment != null) 'tagForChildDirectedTreatment': tagForChildDirectedTreatment, - if (tagForUnderAgeOfConsent != null) - 'tagForUnderAgeOfConsent': tagForUnderAgeOfConsent, + if (tagForUnderAgeOfConsent != null) 'tagForUnderAgeOfConsent': tagForUnderAgeOfConsent, if (adFrequencyHint != null) 'adFrequencyHint': adFrequencyHint, }; diff --git a/packages/google_adsense/lib/src/core/js_interop/js_loader.dart b/packages/google_adsense/lib/src/core/js_interop/js_loader.dart index f570abc8ffc6..518d880abd8e 100644 --- a/packages/google_adsense/lib/src/core/js_interop/js_loader.dart +++ b/packages/google_adsense/lib/src/core/js_interop/js_loader.dart @@ -11,8 +11,7 @@ import 'adsbygoogle.dart' show adsbygooglePresent; import 'package_web_tweaks.dart'; // The URL of the ads by google client. -const String _URL = - 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'; +const String _URL = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'; /// Loads the JS SDK for [adClient]. /// @@ -42,9 +41,7 @@ Future loadJsSdk( try { final web.TrustedTypePolicy policy = web.window.trustedTypes.createPolicy( trustedTypePolicyName, - web.TrustedTypePolicyOptions( - createScriptURL: ((JSString url) => url).toJS, - ), + web.TrustedTypePolicyOptions(createScriptURL: ((JSString url) => url).toJS), ); script.trustedSrc = policy.createScriptURLNoArgs(scriptUrl); } catch (e) { @@ -61,10 +58,7 @@ Future loadJsSdk( } // Applies a map of [attributes] to the `dataset` of [element]. -void _applyDataAttributes( - web.HTMLElement element, - Map? attributes, -) { +void _applyDataAttributes(web.HTMLElement element, Map? attributes) { attributes?.forEach((String key, String value) { element.dataset.setProperty(key.toJS, value.toJS); }); diff --git a/packages/google_adsense/lib/src/h5/h5.dart b/packages/google_adsense/lib/src/h5/h5.dart index 2f0a5172e864..82a9b30cb882 100644 --- a/packages/google_adsense/lib/src/h5/h5.dart +++ b/packages/google_adsense/lib/src/h5/h5.dart @@ -7,8 +7,7 @@ import 'dart:async'; import '../core/js_interop/adsbygoogle.dart'; import 'h5_js_interop.dart'; -export 'enums.dart' - show BreakFormat, BreakStatus, BreakType, PreloadAdBreaks, SoundEnabled; +export 'enums.dart' show BreakFormat, BreakStatus, BreakType, PreloadAdBreaks, SoundEnabled; export 'h5_js_interop.dart' show AdBreakDonePlacementInfo, diff --git a/packages/google_adsense/lib/src/h5/h5_js_interop.dart b/packages/google_adsense/lib/src/h5/h5_js_interop.dart index e08ca6369d05..fdc70a9fda03 100644 --- a/packages/google_adsense/lib/src/h5/h5_js_interop.dart +++ b/packages/google_adsense/lib/src/h5/h5_js_interop.dart @@ -176,9 +176,7 @@ extension type AdBreakPlacement._(JSObject _) implements JSObject { /// {@macro pkg_google_adsense_parameter_h5_adBreakDone} /// /// See: https://developers.google.com/ad-placement/apis#prerolls - factory AdBreakPlacement.preroll({ - required H5AdBreakDoneCallback? adBreakDone, - }) { + factory AdBreakPlacement.preroll({required H5AdBreakDoneCallback? adBreakDone}) { return AdBreakPlacement(type: BreakType.preroll, adBreakDone: adBreakDone); } @@ -297,14 +295,12 @@ extension type AdBreakDonePlacementInfo._(JSObject _) implements JSObject { external JSString? _breakName; /// The format of the break. See [BreakFormat]. - BreakFormat? get breakFormat => - BreakFormat.values.maybe(_breakFormat?.toDart); + BreakFormat? get breakFormat => BreakFormat.values.maybe(_breakFormat?.toDart); @JS('breakFormat') external JSString? _breakFormat; /// The status of this placement. See [BreakStatus]. - BreakStatus? get breakStatus => - BreakStatus.values.maybe(_breakStatus?.toDart); + BreakStatus? get breakStatus => BreakStatus.values.maybe(_breakStatus?.toDart); @JS('breakStatus') external JSString? _breakStatus; } @@ -321,8 +317,7 @@ typedef H5BeforeAdCallback = void Function(); typedef H5AfterAdCallback = void Function(); /// The type of the `adBreakDone` callback. -typedef H5AdBreakDoneCallback = - void Function(AdBreakDonePlacementInfo placementInfo); +typedef H5AdBreakDoneCallback = void Function(AdBreakDonePlacementInfo placementInfo); /// The type of the `beforeReward` callback. typedef H5BeforeRewardCallback = void Function(H5ShowAdFn showAdFn); diff --git a/packages/google_fonts/example/lib/example_font_selection.dart b/packages/google_fonts/example/lib/example_font_selection.dart index 5c31dc11439e..af160a7f4562 100644 --- a/packages/google_fonts/example/lib/example_font_selection.dart +++ b/packages/google_fonts/example/lib/example_font_selection.dart @@ -27,9 +27,7 @@ class ExampleFontSelectionState extends State { @override void initState() { _selectedFont = fonts.first; - _googleFontsPending = GoogleFonts.pendingFonts([ - GoogleFonts.getFont(_selectedFont), - ]); + _googleFontsPending = GoogleFonts.pendingFonts([GoogleFonts.getFont(_selectedFont)]); super.initState(); } @@ -63,18 +61,13 @@ class ExampleFontSelectionState extends State { onSelected: (String? newValue) { setState(() { _selectedFont = newValue!; - _googleFontsPending = GoogleFonts.pendingFonts( - [GoogleFonts.getFont(_selectedFont)], - ); + _googleFontsPending = GoogleFonts.pendingFonts([ + GoogleFonts.getFont(_selectedFont), + ]); }); }, - dropdownMenuEntries: GoogleFonts.asMap().keys.map(( - String font, - ) { - return DropdownMenuEntry( - label: font, - value: font, - ); + dropdownMenuEntries: GoogleFonts.asMap().keys.map((String font) { + return DropdownMenuEntry(label: font, value: font); }).toList(), ), ], @@ -83,24 +76,16 @@ class ExampleFontSelectionState extends State { Expanded( child: FutureBuilder>( future: _googleFontsPending, - builder: - ( - BuildContext context, - AsyncSnapshot> snapshot, - ) { - if (snapshot.connectionState != - ConnectionState.done) { - return const SizedBox(); - } + builder: (BuildContext context, AsyncSnapshot> snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const SizedBox(); + } - return Text( - _textEditingController.text, - style: GoogleFonts.getFont( - _selectedFont, - fontSize: 50.0, - ), - ); - }, + return Text( + _textEditingController.text, + style: GoogleFonts.getFont(_selectedFont, fontSize: 50.0), + ); + }, ), ), ], diff --git a/packages/google_fonts/example/lib/example_simple.dart b/packages/google_fonts/example/lib/example_simple.dart index f968de085159..a5d38dafc541 100644 --- a/packages/google_fonts/example/lib/example_simple.dart +++ b/packages/google_fonts/example/lib/example_simple.dart @@ -55,10 +55,7 @@ class ExampleSimpleState extends State { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - 'You have pushed the button this many times:', - style: pushButtonTextStyle, - ), + Text('You have pushed the button this many times:', style: pushButtonTextStyle), Text('$_counter', style: counterTextStyle), ], ); diff --git a/packages/google_fonts/example/lib/main.dart b/packages/google_fonts/example/lib/main.dart index 31b2ab85a05e..646f9dfd6a60 100644 --- a/packages/google_fonts/example/lib/main.dart +++ b/packages/google_fonts/example/lib/main.dart @@ -32,9 +32,7 @@ class MyApp extends StatelessWidget { ], ), ), - body: const TabBarView( - children: [ExampleSimple(), ExampleFontSelection()], - ), + body: const TabBarView(children: [ExampleSimple(), ExampleFontSelection()]), ), ), ); diff --git a/packages/google_fonts/example/lib/readme_excerpts.dart b/packages/google_fonts/example/lib/readme_excerpts.dart index 9d7189826719..49b0b6887175 100644 --- a/packages/google_fonts/example/lib/readme_excerpts.dart +++ b/packages/google_fonts/example/lib/readme_excerpts.dart @@ -20,17 +20,13 @@ List textStyleExamples(BuildContext context) { // #docregion ExistingStyle Text( 'This is Google Fonts', - style: GoogleFonts.lato( - textStyle: const TextStyle(color: Colors.blue, letterSpacing: .5), - ), + style: GoogleFonts.lato(textStyle: const TextStyle(color: Colors.blue, letterSpacing: .5)), ), // #enddocregion ExistingStyle // #docregion ExistingThemeStyle Text( 'This is Google Fonts', - style: GoogleFonts.lato( - textStyle: Theme.of(context).textTheme.headlineMedium, - ), + style: GoogleFonts.lato(textStyle: Theme.of(context).textTheme.headlineMedium), ), // #enddocregion ExistingThemeStyle // #docregion ExistingStyleWithOverrides @@ -88,10 +84,9 @@ class MyApp extends StatelessWidget { ThemeData _buildTheme(Brightness brightness) { final baseTheme = ThemeData(brightness: brightness); - return baseTheme.copyWith( - textTheme: GoogleFonts.latoTextTheme(baseTheme.textTheme), - ); + return baseTheme.copyWith(textTheme: GoogleFonts.latoTextTheme(baseTheme.textTheme)); } + // #enddocregion AppThemeSimple /// Multi-font app theme example. @@ -108,9 +103,9 @@ class MyMultiFontApp extends StatelessWidget { title: 'Example', // #docregion AppThemeComplex theme: ThemeData( - textTheme: GoogleFonts.latoTextTheme(textTheme).copyWith( - bodyMedium: GoogleFonts.oswald(textStyle: textTheme.bodyMedium), - ), + textTheme: GoogleFonts.latoTextTheme( + textTheme, + ).copyWith(bodyMedium: GoogleFonts.oswald(textStyle: textTheme.bodyMedium)), ), // #enddocregion AppThemeComplex home: const Text('placeholder'), diff --git a/packages/google_fonts/example/test/widget_test.dart b/packages/google_fonts/example/test/widget_test.dart index 3f0a48861421..35fb91e64a0e 100644 --- a/packages/google_fonts/example/test/widget_test.dart +++ b/packages/google_fonts/example/test/widget_test.dart @@ -9,9 +9,7 @@ import 'package:google_fonts/google_fonts.dart'; // Consider `flutter test --no-test-assets` if assets are not required. void main() { testWidgets('Can specify text style', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp(home: Text('Hello', style: GoogleFonts.aBeeZee())), - ); + await tester.pumpWidget(MaterialApp(home: Text('Hello', style: GoogleFonts.aBeeZee()))); }); testWidgets('Can specify text theme', (WidgetTester tester) async { @@ -19,9 +17,7 @@ void main() { await tester.pumpWidget( MaterialApp( - theme: baseTheme.copyWith( - textTheme: GoogleFonts.aBeeZeeTextTheme(baseTheme.textTheme), - ), + theme: baseTheme.copyWith(textTheme: GoogleFonts.aBeeZeeTextTheme(baseTheme.textTheme)), ), ); }); diff --git a/packages/google_fonts/generator/fonts.pb.dart b/packages/google_fonts/generator/fonts.pb.dart index 2508ac6d4351..cae17dfa00b7 100644 --- a/packages/google_fonts/generator/fonts.pb.dart +++ b/packages/google_fonts/generator/fonts.pb.dart @@ -43,14 +43,11 @@ class FileSpec extends $pb.GeneratedMessage { [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); - static final $pb.BuilderInfo _i = $pb.BuilderInfo( - _omitMessageNames ? '' : 'FileSpec', - package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), - createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'FileSpec', + package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'filename') ..aInt64(2, _omitFieldNames ? '' : 'fileSize') - ..a<$core.List<$core.int>>( - 3, _omitFieldNames ? '' : 'hash', $pb.PbFieldType.OY) + ..a<$core.List<$core.int>>(3, _omitFieldNames ? '' : 'hash', $pb.PbFieldType.OY) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') @@ -120,10 +117,8 @@ class IntRange extends $pb.GeneratedMessage { [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); - static final $pb.BuilderInfo _i = $pb.BuilderInfo( - _omitMessageNames ? '' : 'IntRange', - package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), - createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'IntRange', + package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create) ..aI(1, _omitFieldNames ? '' : 'start') ..aI(2, _omitFieldNames ? '' : 'end') ..hasRequiredFields = false; @@ -188,10 +183,8 @@ class FloatRange extends $pb.GeneratedMessage { [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); - static final $pb.BuilderInfo _i = $pb.BuilderInfo( - _omitMessageNames ? '' : 'FloatRange', - package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), - createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'FloatRange', + package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create) ..aD(1, _omitFieldNames ? '' : 'start', fieldType: $pb.PbFieldType.OF) ..aD(2, _omitFieldNames ? '' : 'end', fieldType: $pb.PbFieldType.OF) ..hasRequiredFields = false; @@ -210,8 +203,8 @@ class FloatRange extends $pb.GeneratedMessage { @$core.override FloatRange createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') - static FloatRange getDefault() => _defaultInstance ??= - $pb.GeneratedMessage.$_defaultFor(create); + static FloatRange getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static FloatRange? _defaultInstance; @$pb.TagNumber(1) @@ -265,18 +258,12 @@ class Font extends $pb.GeneratedMessage { [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); - static final $pb.BuilderInfo _i = $pb.BuilderInfo( - _omitMessageNames ? '' : 'Font', - package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), - createEmptyInstance: create) - ..aOM(1, _omitFieldNames ? '' : 'file', - subBuilder: FileSpec.create) - ..aOM(2, _omitFieldNames ? '' : 'weight', - subBuilder: IntRange.create) - ..aOM(3, _omitFieldNames ? '' : 'width', - subBuilder: FloatRange.create) - ..aOM(4, _omitFieldNames ? '' : 'italic', - subBuilder: FloatRange.create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Font', + package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create) + ..aOM(1, _omitFieldNames ? '' : 'file', subBuilder: FileSpec.create) + ..aOM(2, _omitFieldNames ? '' : 'weight', subBuilder: IntRange.create) + ..aOM(3, _omitFieldNames ? '' : 'width', subBuilder: FloatRange.create) + ..aOM(4, _omitFieldNames ? '' : 'italic', subBuilder: FloatRange.create) ..aI(7, _omitFieldNames ? '' : 'ttcIndex') ..aOS(8, _omitFieldNames ? '' : 'postScriptName') ..aOB(9, _omitFieldNames ? '' : 'isVf') @@ -296,8 +283,7 @@ class Font extends $pb.GeneratedMessage { @$core.override Font createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') - static Font getDefault() => - _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); + static Font getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Font? _defaultInstance; @$pb.TagNumber(1) @@ -407,10 +393,8 @@ class FontFamily extends $pb.GeneratedMessage { [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); - static final $pb.BuilderInfo _i = $pb.BuilderInfo( - _omitMessageNames ? '' : 'FontFamily', - package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), - createEmptyInstance: create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'FontFamily', + package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'name') ..aI(2, _omitFieldNames ? '' : 'version') ..pPM(4, _omitFieldNames ? '' : 'fonts', subBuilder: Font.create) @@ -430,8 +414,8 @@ class FontFamily extends $pb.GeneratedMessage { @$core.override FontFamily createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') - static FontFamily getDefault() => _defaultInstance ??= - $pb.GeneratedMessage.$_defaultFor(create); + static FontFamily getDefault() => + _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static FontFamily? _defaultInstance; @$pb.TagNumber(1) @@ -482,12 +466,9 @@ class Directory extends $pb.GeneratedMessage { [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); - static final $pb.BuilderInfo _i = $pb.BuilderInfo( - _omitMessageNames ? '' : 'Directory', - package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), - createEmptyInstance: create) - ..pPM(1, _omitFieldNames ? '' : 'family', - subBuilder: FontFamily.create) + static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Directory', + package: const $pb.PackageName(_omitMessageNames ? '' : 'fonts'), createEmptyInstance: create) + ..pPM(1, _omitFieldNames ? '' : 'family', subBuilder: FontFamily.create) ..aI(5, _omitFieldNames ? '' : 'version') ..aOS(6, _omitFieldNames ? '' : 'description') ..hasRequiredFields = false; @@ -534,7 +515,5 @@ class Directory extends $pb.GeneratedMessage { void clearDescription() => $_clearField(6); } -const $core.bool _omitFieldNames = - $core.bool.fromEnvironment('protobuf.omit_field_names'); -const $core.bool _omitMessageNames = - $core.bool.fromEnvironment('protobuf.omit_message_names'); +const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); +const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); diff --git a/packages/google_fonts/generator/generator.dart b/packages/google_fonts/generator/generator.dart index ce943bce01f8..1508b79fa996 100644 --- a/packages/google_fonts/generator/generator.dart +++ b/packages/google_fonts/generator/generator.dart @@ -13,8 +13,7 @@ import 'package:mustache_template/mustache.dart'; import 'fonts.pb.dart'; const String _generatedAllPartsFilePath = 'lib/src/google_fonts_all_parts.dart'; -String _generatedPartFilePath(String part) => - 'lib/src/google_fonts_parts/part_$part.dart'; +String _generatedPartFilePath(String part) => 'lib/src/google_fonts_parts/part_$part.dart'; const String _familiesSupportedPath = 'generator/families_supported'; const String _familiesDiffPath = 'generator/families_diff'; @@ -35,9 +34,7 @@ Future main() async { print(_success); print('\nGenerating $_familiesSupportedPath & $_familiesDiffPath ...'); - File( - _familiesSupportedPath, - ).writeAsStringSync(familiesDelta.printableSupported()); + File(_familiesSupportedPath).writeAsStringSync(familiesDelta.printableSupported()); File(_familiesDiffPath).writeAsStringSync(familiesDelta.markdownDiff()); print(_success); @@ -66,9 +63,7 @@ Future _getProtoUrl({int initialVersion = 7}) async { Uri url(int directoryVersion) { final String paddedVersion = directoryVersion.toString().padLeft(3, '0'); - return Uri.parse( - 'https://fonts.gstatic.com/s/f/directory$paddedVersion.pb', - ); + return Uri.parse('https://fonts.gstatic.com/s/f/directory$paddedVersion.pb'); } var didReachLatestUrl = false; @@ -98,8 +93,7 @@ Future _verifyUrls(Directory fontDirectory) async { var i = 1; for (final FontFamily family in fontDirectory.family) { for (final Font font in family.fonts) { - final urlString = - 'https://fonts.gstatic.com/s/a/${_hashToString(font.file.hash)}.ttf'; + final urlString = 'https://fonts.gstatic.com/s/a/${_hashToString(font.file.hash)}.ttf'; final Uri url = Uri.parse(urlString); await _tryUrl(client, url, font); print('Verified URL ($i/$totalFonts): $urlString'); @@ -114,8 +108,7 @@ Future _tryUrl(http.Client client, Uri url, Font font) async { final http.Response fileContents = await client.get(url); final int actualFileLength = fileContents.bodyBytes.length; final actualFileHash = sha256.convert(fileContents.bodyBytes).toString(); - if (font.file.fileSize != actualFileLength || - _hashToString(font.file.hash) != actualFileHash) { + if (font.file.fileSize != actualFileLength || _hashToString(font.file.hash) != actualFileHash) { throw Exception('Font from $url did not match length of or checksum.'); } } catch (e) { @@ -147,14 +140,10 @@ class _FamiliesDelta { void _init(Directory fontDirectory) { // Currently supported families. - final familiesSupported = Set.from( - File(_familiesSupportedPath).readAsLinesSync(), - ); + final familiesSupported = Set.from(File(_familiesSupportedPath).readAsLinesSync()); // Newly supported families. - all = Set.from( - fontDirectory.family.map((FontFamily item) => item.name), - ); + all = Set.from(fontDirectory.family.map((FontFamily item) => item.name)); added = all.difference(familiesSupported); removed = familiesSupported.difference(all); @@ -166,12 +155,8 @@ class _FamiliesDelta { // Diff of font families, suitable for markdown // (e.g. CHANGELOG, PR description). String markdownDiff() { - final Iterable addedPrintable = added.map( - (String family) => ' - `$family`', - ); - final Iterable removedPrintable = removed.map( - (String family) => ' - `$family`', - ); + final Iterable addedPrintable = added.map((String family) => ' - `$family`'); + final Iterable removedPrintable = removed.map((String family) => ' - `$family`'); var diff = ''; if (addedPrintable.isNotEmpty) { @@ -265,16 +250,13 @@ void _generateDartCode(Directory fontDirectory) { for (final Font variant in filteredVariants) { 'variantWeight': variant.weight.start, - 'variantStyle': variant.italic.start.round() == 1 - ? 'italic' - : 'normal', + 'variantStyle': variant.italic.start.round() == 1 ? 'italic' : 'normal', 'hash': _hashToString(variant.file.hash), 'length': variant.file.fileSize, }, ], 'themeParams': >[ - for (final String themeParam in themeParams) - {'value': themeParam}, + for (final String themeParam in themeParams) {'value': themeParam}, ], }); } @@ -288,9 +270,7 @@ void _generateDartCode(Directory fontDirectory) { final String firstLetter = methodName[0]; if (!methodsByLetter.containsKey(firstLetter)) { allParts.add({ - 'partFilePath': _generatedPartFilePath( - firstLetter, - ).replaceFirst('lib/src/', ''), + 'partFilePath': _generatedPartFilePath(firstLetter).replaceFirst('lib/src/', ''), }); methodsByLetter[firstLetter] = >[map]; } else { @@ -303,10 +283,7 @@ void _generateDartCode(Directory fontDirectory) { File('generator/google_fonts_part.tmpl').readAsStringSync(), htmlEscapeValues: false, ); - methodsByLetter.forEach(( - String letter, - List> methods, - ) async { + methodsByLetter.forEach((String letter, List> methods) async { final String renderedTemplate = partTemplate.renderString({ 'part': letter.toUpperCase(), 'method': methods, @@ -319,12 +296,10 @@ void _generateDartCode(Directory fontDirectory) { File('generator/google_fonts.tmpl').readAsStringSync(), htmlEscapeValues: false, ); - final String renderedTemplate = template.renderString( - >>{ - 'allParts': allParts, - 'method': methods, - }, - ); + final String renderedTemplate = template.renderString(>>{ + 'allParts': allParts, + 'method': methods, + }); _writeDartFile(_generatedAllPartsFilePath, renderedTemplate); } diff --git a/packages/google_fonts/lib/src/file_io.dart b/packages/google_fonts/lib/src/file_io.dart index 83d7fa6dd446..3d1689d34a6d 100644 --- a/packages/google_fonts/lib/src/file_io.dart +++ b/packages/google_fonts/lib/src/file_io.dart @@ -30,9 +30,6 @@ Future saveFontToDeviceFileSystem({ /// Stubbed out version of loadFontFromDeviceFileSystem from /// `file_io_desktop_and_mobile.dart`. -Future loadFontFromDeviceFileSystem({ - required String name, - required String fileHash, -}) { +Future loadFontFromDeviceFileSystem({required String name, required String fileHash}) { return Future.value(); } diff --git a/packages/google_fonts/lib/src/google_fonts_all_parts.dart b/packages/google_fonts/lib/src/google_fonts_all_parts.dart index 1cace54082a5..69ae98af540a 100644 --- a/packages/google_fonts/lib/src/google_fonts_all_parts.dart +++ b/packages/google_fonts/lib/src/google_fonts_all_parts.dart @@ -122,8 +122,7 @@ class GoogleFonts { /// ); /// } /// ``` - static Future> pendingFonts([List? _]) => - Future.wait(pendingFontFutures); + static Future> pendingFonts([List? _]) => Future.wait(pendingFontFutures); /// Get a map of all available fonts. /// @@ -2053,8 +2052,7 @@ class GoogleFonts { /// /// Returns a map where the key is the name of the font family and the value /// is the corresponding [GoogleFonts] `TextTheme` method. - static Map - _asMapOfTextThemes() => const { + static Map _asMapOfTextThemes() => const { 'ABeeZee': PartA.aBeeZeeTextTheme, 'ADLaM Display': PartA.aDLaMDisplayTextTheme, 'AR One Sans': PartA.arOneSansTextTheme, @@ -3079,8 +3077,7 @@ class GoogleFonts { 'Noto Sans': PartN.notoSansTextTheme, 'Noto Sans Adlam': PartN.notoSansAdlamTextTheme, 'Noto Sans Adlam Unjoined': PartN.notoSansAdlamUnjoinedTextTheme, - 'Noto Sans Anatolian Hieroglyphs': - PartN.notoSansAnatolianHieroglyphsTextTheme, + 'Noto Sans Anatolian Hieroglyphs': PartN.notoSansAnatolianHieroglyphsTextTheme, 'Noto Sans Arabic': PartN.notoSansArabicTextTheme, 'Noto Sans Armenian': PartN.notoSansArmenianTextTheme, 'Noto Sans Avestan': PartN.notoSansAvestanTextTheme, @@ -3108,8 +3105,7 @@ class GoogleFonts { 'Noto Sans Devanagari': PartN.notoSansDevanagariTextTheme, 'Noto Sans Display': PartN.notoSansDisplayTextTheme, 'Noto Sans Duployan': PartN.notoSansDuployanTextTheme, - 'Noto Sans Egyptian Hieroglyphs': - PartN.notoSansEgyptianHieroglyphsTextTheme, + 'Noto Sans Egyptian Hieroglyphs': PartN.notoSansEgyptianHieroglyphsTextTheme, 'Noto Sans Elbasan': PartN.notoSansElbasanTextTheme, 'Noto Sans Elymaic': PartN.notoSansElymaicTextTheme, 'Noto Sans Ethiopic': PartN.notoSansEthiopicTextTheme, @@ -3127,10 +3123,8 @@ class GoogleFonts { 'Noto Sans Hebrew': PartN.notoSansHebrewTextTheme, 'Noto Sans Imperial Aramaic': PartN.notoSansImperialAramaicTextTheme, 'Noto Sans Indic Siyaq Numbers': PartN.notoSansIndicSiyaqNumbersTextTheme, - 'Noto Sans Inscriptional Pahlavi': - PartN.notoSansInscriptionalPahlaviTextTheme, - 'Noto Sans Inscriptional Parthian': - PartN.notoSansInscriptionalParthianTextTheme, + 'Noto Sans Inscriptional Pahlavi': PartN.notoSansInscriptionalPahlaviTextTheme, + 'Noto Sans Inscriptional Parthian': PartN.notoSansInscriptionalParthianTextTheme, 'Noto Sans JP': PartN.notoSansJpTextTheme, 'Noto Sans Javanese': PartN.notoSansJavaneseTextTheme, 'Noto Sans KR': PartN.notoSansKrTextTheme, @@ -3285,8 +3279,7 @@ class GoogleFonts { 'Noto Serif Vithkuqi': PartN.notoSerifVithkuqiTextTheme, 'Noto Serif Yezidi': PartN.notoSerifYezidiTextTheme, 'Noto Traditional Nushu': PartN.notoTraditionalNushuTextTheme, - 'Noto Znamenny Musical Notation': - PartN.notoZnamennyMusicalNotationTextTheme, + 'Noto Znamenny Musical Notation': PartN.notoZnamennyMusicalNotationTextTheme, 'Nova Cut': PartN.novaCutTextTheme, 'Nova Flat': PartN.novaFlatTextTheme, 'Nova Mono': PartN.novaMonoTextTheme, @@ -4358,22 +4351,19 @@ class GoogleFonts { static const alumniSansCollegiateOne = PartA.alumniSansCollegiateOne; /// See [PartA.alumniSansCollegiateOneTextTheme]. - static const alumniSansCollegiateOneTextTheme = - PartA.alumniSansCollegiateOneTextTheme; + static const alumniSansCollegiateOneTextTheme = PartA.alumniSansCollegiateOneTextTheme; /// See [PartA.alumniSansInlineOne]. static const alumniSansInlineOne = PartA.alumniSansInlineOne; /// See [PartA.alumniSansInlineOneTextTheme]. - static const alumniSansInlineOneTextTheme = - PartA.alumniSansInlineOneTextTheme; + static const alumniSansInlineOneTextTheme = PartA.alumniSansInlineOneTextTheme; /// See [PartA.alumniSansPinstripe]. static const alumniSansPinstripe = PartA.alumniSansPinstripe; /// See [PartA.alumniSansPinstripeTextTheme]. - static const alumniSansPinstripeTextTheme = - PartA.alumniSansPinstripeTextTheme; + static const alumniSansPinstripeTextTheme = PartA.alumniSansPinstripeTextTheme; /// See [PartA.alumniSansSc]. static const alumniSansSc = PartA.alumniSansSc; @@ -4541,8 +4531,7 @@ class GoogleFonts { static const annieUseYourTelescope = PartA.annieUseYourTelescope; /// See [PartA.annieUseYourTelescopeTextTheme]. - static const annieUseYourTelescopeTextTheme = - PartA.annieUseYourTelescopeTextTheme; + static const annieUseYourTelescopeTextTheme = PartA.annieUseYourTelescopeTextTheme; /// See [PartA.anonymousPro]. static const anonymousPro = PartA.anonymousPro; @@ -4782,22 +4771,19 @@ class GoogleFonts { static const atkinsonHyperlegible = PartA.atkinsonHyperlegible; /// See [PartA.atkinsonHyperlegibleTextTheme]. - static const atkinsonHyperlegibleTextTheme = - PartA.atkinsonHyperlegibleTextTheme; + static const atkinsonHyperlegibleTextTheme = PartA.atkinsonHyperlegibleTextTheme; /// See [PartA.atkinsonHyperlegibleMono]. static const atkinsonHyperlegibleMono = PartA.atkinsonHyperlegibleMono; /// See [PartA.atkinsonHyperlegibleMonoTextTheme]. - static const atkinsonHyperlegibleMonoTextTheme = - PartA.atkinsonHyperlegibleMonoTextTheme; + static const atkinsonHyperlegibleMonoTextTheme = PartA.atkinsonHyperlegibleMonoTextTheme; /// See [PartA.atkinsonHyperlegibleNext]. static const atkinsonHyperlegibleNext = PartA.atkinsonHyperlegibleNext; /// See [PartA.atkinsonHyperlegibleNextTextTheme]. - static const atkinsonHyperlegibleNextTextTheme = - PartA.atkinsonHyperlegibleNextTextTheme; + static const atkinsonHyperlegibleNextTextTheme = PartA.atkinsonHyperlegibleNextTextTheme; /// See [PartA.atma]. static const atma = PartA.atma; @@ -5079,8 +5065,7 @@ class GoogleFonts { static const barlowSemiCondensed = PartB.barlowSemiCondensed; /// See [PartB.barlowSemiCondensedTextTheme]. - static const barlowSemiCondensedTextTheme = - PartB.barlowSemiCondensedTextTheme; + static const barlowSemiCondensedTextTheme = PartB.barlowSemiCondensedTextTheme; /// See [PartB.barriecito]. static const barriecito = PartB.barriecito; @@ -5254,8 +5239,7 @@ class GoogleFonts { static const bigShouldersStencil = PartB.bigShouldersStencil; /// See [PartB.bigShouldersStencilTextTheme]. - static const bigShouldersStencilTextTheme = - PartB.bigShouldersStencilTextTheme; + static const bigShouldersStencilTextTheme = PartB.bigShouldersStencilTextTheme; /// See [PartB.bigelowRules]. static const bigelowRules = PartB.bigelowRules; @@ -5321,8 +5305,7 @@ class GoogleFonts { static const bitcountGridDoubleInk = PartB.bitcountGridDoubleInk; /// See [PartB.bitcountGridDoubleInkTextTheme]. - static const bitcountGridDoubleInkTextTheme = - PartB.bitcountGridDoubleInkTextTheme; + static const bitcountGridDoubleInkTextTheme = PartB.bitcountGridDoubleInkTextTheme; /// See [PartB.bitcountGridSingle]. static const bitcountGridSingle = PartB.bitcountGridSingle; @@ -5334,8 +5317,7 @@ class GoogleFonts { static const bitcountGridSingleInk = PartB.bitcountGridSingleInk; /// See [PartB.bitcountGridSingleInkTextTheme]. - static const bitcountGridSingleInkTextTheme = - PartB.bitcountGridSingleInkTextTheme; + static const bitcountGridSingleInkTextTheme = PartB.bitcountGridSingleInkTextTheme; /// See [PartB.bitcountInk]. static const bitcountInk = PartB.bitcountInk; @@ -5353,8 +5335,7 @@ class GoogleFonts { static const bitcountPropDoubleInk = PartB.bitcountPropDoubleInk; /// See [PartB.bitcountPropDoubleInkTextTheme]. - static const bitcountPropDoubleInkTextTheme = - PartB.bitcountPropDoubleInkTextTheme; + static const bitcountPropDoubleInkTextTheme = PartB.bitcountPropDoubleInkTextTheme; /// See [PartB.bitcountPropSingle]. static const bitcountPropSingle = PartB.bitcountPropSingle; @@ -5366,8 +5347,7 @@ class GoogleFonts { static const bitcountPropSingleInk = PartB.bitcountPropSingleInk; /// See [PartB.bitcountPropSingleInkTextTheme]. - static const bitcountPropSingleInkTextTheme = - PartB.bitcountPropSingleInkTextTheme; + static const bitcountPropSingleInkTextTheme = PartB.bitcountPropSingleInkTextTheme; /// See [PartB.bitcountSingle]. static const bitcountSingle = PartB.bitcountSingle; @@ -5391,8 +5371,7 @@ class GoogleFonts { static const blackAndWhitePicture = PartB.blackAndWhitePicture; /// See [PartB.blackAndWhitePictureTextTheme]. - static const blackAndWhitePictureTextTheme = - PartB.blackAndWhitePictureTextTheme; + static const blackAndWhitePictureTextTheme = PartB.blackAndWhitePictureTextTheme; /// See [PartB.blackHanSans]. static const blackHanSans = PartB.blackHanSans; @@ -5644,8 +5623,7 @@ class GoogleFonts { static const cactusClassicalSerif = PartC.cactusClassicalSerif; /// See [PartC.cactusClassicalSerifTextTheme]. - static const cactusClassicalSerifTextTheme = - PartC.cactusClassicalSerifTextTheme; + static const cactusClassicalSerifTextTheme = PartC.cactusClassicalSerifTextTheme; /// See [PartC.caesarDressing]. static const caesarDressing = PartC.caesarDressing; @@ -5993,8 +5971,7 @@ class GoogleFonts { static const chocolateClassicalSans = PartC.chocolateClassicalSans; /// See [PartC.chocolateClassicalSansTextTheme]. - static const chocolateClassicalSansTextTheme = - PartC.chocolateClassicalSansTextTheme; + static const chocolateClassicalSansTextTheme = PartC.chocolateClassicalSansTextTheme; /// See [PartC.chokokutai]. static const chokokutai = PartC.chokokutai; @@ -6636,8 +6613,7 @@ class GoogleFonts { static const eduNswActFoundation = PartE.eduNswActFoundation; /// See [PartE.eduNswActFoundationTextTheme]. - static const eduNswActFoundationTextTheme = - PartE.eduNswActFoundationTextTheme; + static const eduNswActFoundationTextTheme = PartE.eduNswActFoundationTextTheme; /// See [PartE.eduNswActHandPre]. static const eduNswActHandPre = PartE.eduNswActHandPre; @@ -6997,8 +6973,7 @@ class GoogleFonts { static const firaSansExtraCondensed = PartF.firaSansExtraCondensed; /// See [PartF.firaSansExtraCondensedTextTheme]. - static const firaSansExtraCondensedTextTheme = - PartF.firaSansExtraCondensedTextTheme; + static const firaSansExtraCondensedTextTheme = PartF.firaSansExtraCondensedTextTheme; /// See [PartF.fjallaOne]. static const fjallaOne = PartF.fjallaOne; @@ -7490,8 +7465,7 @@ class GoogleFonts { static const goudyBookletter1911 = PartG.goudyBookletter1911; /// See [PartG.goudyBookletter1911TextTheme]. - static const goudyBookletter1911TextTheme = - PartG.goudyBookletter1911TextTheme; + static const goudyBookletter1911TextTheme = PartG.goudyBookletter1911TextTheme; /// See [PartG.gowunBatang]. static const gowunBatang = PartG.gowunBatang; @@ -7863,8 +7837,7 @@ class GoogleFonts { static const ibmPlexSansDevanagari = PartI.ibmPlexSansDevanagari; /// See [PartI.ibmPlexSansDevanagariTextTheme]. - static const ibmPlexSansDevanagariTextTheme = - PartI.ibmPlexSansDevanagariTextTheme; + static const ibmPlexSansDevanagariTextTheme = PartI.ibmPlexSansDevanagariTextTheme; /// See [PartI.ibmPlexSansHebrew]. static const ibmPlexSansHebrew = PartI.ibmPlexSansHebrew; @@ -7894,8 +7867,7 @@ class GoogleFonts { static const ibmPlexSansThaiLooped = PartI.ibmPlexSansThaiLooped; /// See [PartI.ibmPlexSansThaiLoopedTextTheme]. - static const ibmPlexSansThaiLoopedTextTheme = - PartI.ibmPlexSansThaiLoopedTextTheme; + static const ibmPlexSansThaiLoopedTextTheme = PartI.ibmPlexSansThaiLoopedTextTheme; /// See [PartI.ibmPlexSerif]. static const ibmPlexSerif = PartI.ibmPlexSerif; @@ -7949,8 +7921,7 @@ class GoogleFonts { static const imFellFrenchCanonSc = PartI.imFellFrenchCanonSc; /// See [PartI.imFellFrenchCanonScTextTheme]. - static const imFellFrenchCanonScTextTheme = - PartI.imFellFrenchCanonScTextTheme; + static const imFellFrenchCanonScTextTheme = PartI.imFellFrenchCanonScTextTheme; /// See [PartI.imFellGreatPrimer]. static const imFellGreatPrimer = PartI.imFellGreatPrimer; @@ -7962,8 +7933,7 @@ class GoogleFonts { static const imFellGreatPrimerSc = PartI.imFellGreatPrimerSc; /// See [PartI.imFellGreatPrimerScTextTheme]. - static const imFellGreatPrimerScTextTheme = - PartI.imFellGreatPrimerScTextTheme; + static const imFellGreatPrimerScTextTheme = PartI.imFellGreatPrimerScTextTheme; /// See [PartI.iansui]. static const iansui = PartI.iansui; @@ -8167,8 +8137,7 @@ class GoogleFonts { static const jacquardaBastarda9Charted = PartJ.jacquardaBastarda9Charted; /// See [PartJ.jacquardaBastarda9ChartedTextTheme]. - static const jacquardaBastarda9ChartedTextTheme = - PartJ.jacquardaBastarda9ChartedTextTheme; + static const jacquardaBastarda9ChartedTextTheme = PartJ.jacquardaBastarda9ChartedTextTheme; /// See [PartJ.jacquesFrancois]. static const jacquesFrancois = PartJ.jacquesFrancois; @@ -8180,8 +8149,7 @@ class GoogleFonts { static const jacquesFrancoisShadow = PartJ.jacquesFrancoisShadow; /// See [PartJ.jacquesFrancoisShadowTextTheme]. - static const jacquesFrancoisShadowTextTheme = - PartJ.jacquesFrancoisShadowTextTheme; + static const jacquesFrancoisShadowTextTheme = PartJ.jacquesFrancoisShadowTextTheme; /// See [PartJ.jaini]. static const jaini = PartJ.jaini; @@ -8367,8 +8335,7 @@ class GoogleFonts { static const justMeAgainDownHere = PartJ.justMeAgainDownHere; /// See [PartJ.justMeAgainDownHereTextTheme]. - static const justMeAgainDownHereTextTheme = - PartJ.justMeAgainDownHereTextTheme; + static const justMeAgainDownHereTextTheme = PartJ.justMeAgainDownHereTextTheme; /// See [PartK.k2d]. static const k2d = PartK.k2d; @@ -8944,8 +8911,7 @@ class GoogleFonts { static const libertinusSerifDisplay = PartL.libertinusSerifDisplay; /// See [PartL.libertinusSerifDisplayTextTheme]. - static const libertinusSerifDisplayTextTheme = - PartL.libertinusSerifDisplayTextTheme; + static const libertinusSerifDisplayTextTheme = PartL.libertinusSerifDisplayTextTheme; /// See [PartL.libreBarcode128]. static const libreBarcode128 = PartL.libreBarcode128; @@ -8957,8 +8923,7 @@ class GoogleFonts { static const libreBarcode128Text = PartL.libreBarcode128Text; /// See [PartL.libreBarcode128TextTextTheme]. - static const libreBarcode128TextTextTheme = - PartL.libreBarcode128TextTextTheme; + static const libreBarcode128TextTextTheme = PartL.libreBarcode128TextTextTheme; /// See [PartL.libreBarcode39]. static const libreBarcode39 = PartL.libreBarcode39; @@ -8970,15 +8935,13 @@ class GoogleFonts { static const libreBarcode39Extended = PartL.libreBarcode39Extended; /// See [PartL.libreBarcode39ExtendedTextTheme]. - static const libreBarcode39ExtendedTextTheme = - PartL.libreBarcode39ExtendedTextTheme; + static const libreBarcode39ExtendedTextTheme = PartL.libreBarcode39ExtendedTextTheme; /// See [PartL.libreBarcode39ExtendedText]. static const libreBarcode39ExtendedText = PartL.libreBarcode39ExtendedText; /// See [PartL.libreBarcode39ExtendedTextTextTheme]. - static const libreBarcode39ExtendedTextTextTheme = - PartL.libreBarcode39ExtendedTextTextTheme; + static const libreBarcode39ExtendedTextTextTheme = PartL.libreBarcode39ExtendedTextTextTheme; /// See [PartL.libreBarcode39Text]. static const libreBarcode39Text = PartL.libreBarcode39Text; @@ -8990,8 +8953,7 @@ class GoogleFonts { static const libreBarcodeEan13Text = PartL.libreBarcodeEan13Text; /// See [PartL.libreBarcodeEan13TextTextTheme]. - static const libreBarcodeEan13TextTextTheme = - PartL.libreBarcodeEan13TextTextTheme; + static const libreBarcodeEan13TextTextTheme = PartL.libreBarcodeEan13TextTextTheme; /// See [PartL.libreBaskerville]. static const libreBaskerville = PartL.libreBaskerville; @@ -9369,8 +9331,7 @@ class GoogleFonts { static const manufacturingConsent = PartM.manufacturingConsent; /// See [PartM.manufacturingConsentTextTheme]. - static const manufacturingConsentTextTheme = - PartM.manufacturingConsentTextTheme; + static const manufacturingConsentTextTheme = PartM.manufacturingConsentTextTheme; /// See [PartM.marcellus]. static const marcellus = PartM.marcellus; @@ -9808,15 +9769,13 @@ class GoogleFonts { static const montserratAlternates = PartM.montserratAlternates; /// See [PartM.montserratAlternatesTextTheme]. - static const montserratAlternatesTextTheme = - PartM.montserratAlternatesTextTheme; + static const montserratAlternatesTextTheme = PartM.montserratAlternatesTextTheme; /// See [PartM.montserratUnderline]. static const montserratUnderline = PartM.montserratUnderline; /// See [PartM.montserratUnderlineTextTheme]. - static const montserratUnderlineTextTheme = - PartM.montserratUnderlineTextTheme; + static const montserratUnderlineTextTheme = PartM.montserratUnderlineTextTheme; /// See [PartM.mooLahLah]. static const mooLahLah = PartM.mooLahLah; @@ -9852,8 +9811,7 @@ class GoogleFonts { static const mountainsOfChristmas = PartM.mountainsOfChristmas; /// See [PartM.mountainsOfChristmasTextTheme]. - static const mountainsOfChristmasTextTheme = - PartM.mountainsOfChristmasTextTheme; + static const mountainsOfChristmasTextTheme = PartM.mountainsOfChristmasTextTheme; /// See [PartM.mouseMemoirs]. static const mouseMemoirs = PartM.mouseMemoirs; @@ -10207,16 +10165,13 @@ class GoogleFonts { static const notoSansAdlamUnjoined = PartN.notoSansAdlamUnjoined; /// See [PartN.notoSansAdlamUnjoinedTextTheme]. - static const notoSansAdlamUnjoinedTextTheme = - PartN.notoSansAdlamUnjoinedTextTheme; + static const notoSansAdlamUnjoinedTextTheme = PartN.notoSansAdlamUnjoinedTextTheme; /// See [PartN.notoSansAnatolianHieroglyphs]. - static const notoSansAnatolianHieroglyphs = - PartN.notoSansAnatolianHieroglyphs; + static const notoSansAnatolianHieroglyphs = PartN.notoSansAnatolianHieroglyphs; /// See [PartN.notoSansAnatolianHieroglyphsTextTheme]. - static const notoSansAnatolianHieroglyphsTextTheme = - PartN.notoSansAnatolianHieroglyphsTextTheme; + static const notoSansAnatolianHieroglyphsTextTheme = PartN.notoSansAnatolianHieroglyphsTextTheme; /// See [PartN.notoSansArabic]. static const notoSansArabic = PartN.notoSansArabic; @@ -10294,8 +10249,7 @@ class GoogleFonts { static const notoSansCanadianAboriginal = PartN.notoSansCanadianAboriginal; /// See [PartN.notoSansCanadianAboriginalTextTheme]. - static const notoSansCanadianAboriginalTextTheme = - PartN.notoSansCanadianAboriginalTextTheme; + static const notoSansCanadianAboriginalTextTheme = PartN.notoSansCanadianAboriginalTextTheme; /// See [PartN.notoSansCarian]. static const notoSansCarian = PartN.notoSansCarian; @@ -10307,8 +10261,7 @@ class GoogleFonts { static const notoSansCaucasianAlbanian = PartN.notoSansCaucasianAlbanian; /// See [PartN.notoSansCaucasianAlbanianTextTheme]. - static const notoSansCaucasianAlbanianTextTheme = - PartN.notoSansCaucasianAlbanianTextTheme; + static const notoSansCaucasianAlbanianTextTheme = PartN.notoSansCaucasianAlbanianTextTheme; /// See [PartN.notoSansChakma]. static const notoSansChakma = PartN.notoSansChakma; @@ -10356,8 +10309,7 @@ class GoogleFonts { static const notoSansCyproMinoan = PartN.notoSansCyproMinoan; /// See [PartN.notoSansCyproMinoanTextTheme]. - static const notoSansCyproMinoanTextTheme = - PartN.notoSansCyproMinoanTextTheme; + static const notoSansCyproMinoanTextTheme = PartN.notoSansCyproMinoanTextTheme; /// See [PartN.notoSansDeseret]. static const notoSansDeseret = PartN.notoSansDeseret; @@ -10387,8 +10339,7 @@ class GoogleFonts { static const notoSansEgyptianHieroglyphs = PartN.notoSansEgyptianHieroglyphs; /// See [PartN.notoSansEgyptianHieroglyphsTextTheme]. - static const notoSansEgyptianHieroglyphsTextTheme = - PartN.notoSansEgyptianHieroglyphsTextTheme; + static const notoSansEgyptianHieroglyphsTextTheme = PartN.notoSansEgyptianHieroglyphsTextTheme; /// See [PartN.notoSansElbasan]. static const notoSansElbasan = PartN.notoSansElbasan; @@ -10442,8 +10393,7 @@ class GoogleFonts { static const notoSansGunjalaGondi = PartN.notoSansGunjalaGondi; /// See [PartN.notoSansGunjalaGondiTextTheme]. - static const notoSansGunjalaGondiTextTheme = - PartN.notoSansGunjalaGondiTextTheme; + static const notoSansGunjalaGondiTextTheme = PartN.notoSansGunjalaGondiTextTheme; /// See [PartN.notoSansGurmukhi]. static const notoSansGurmukhi = PartN.notoSansGurmukhi; @@ -10461,8 +10411,7 @@ class GoogleFonts { static const notoSansHanifiRohingya = PartN.notoSansHanifiRohingya; /// See [PartN.notoSansHanifiRohingyaTextTheme]. - static const notoSansHanifiRohingyaTextTheme = - PartN.notoSansHanifiRohingyaTextTheme; + static const notoSansHanifiRohingyaTextTheme = PartN.notoSansHanifiRohingyaTextTheme; /// See [PartN.notoSansHanunoo]. static const notoSansHanunoo = PartN.notoSansHanunoo; @@ -10486,27 +10435,22 @@ class GoogleFonts { static const notoSansImperialAramaic = PartN.notoSansImperialAramaic; /// See [PartN.notoSansImperialAramaicTextTheme]. - static const notoSansImperialAramaicTextTheme = - PartN.notoSansImperialAramaicTextTheme; + static const notoSansImperialAramaicTextTheme = PartN.notoSansImperialAramaicTextTheme; /// See [PartN.notoSansIndicSiyaqNumbers]. static const notoSansIndicSiyaqNumbers = PartN.notoSansIndicSiyaqNumbers; /// See [PartN.notoSansIndicSiyaqNumbersTextTheme]. - static const notoSansIndicSiyaqNumbersTextTheme = - PartN.notoSansIndicSiyaqNumbersTextTheme; + static const notoSansIndicSiyaqNumbersTextTheme = PartN.notoSansIndicSiyaqNumbersTextTheme; /// See [PartN.notoSansInscriptionalPahlavi]. - static const notoSansInscriptionalPahlavi = - PartN.notoSansInscriptionalPahlavi; + static const notoSansInscriptionalPahlavi = PartN.notoSansInscriptionalPahlavi; /// See [PartN.notoSansInscriptionalPahlaviTextTheme]. - static const notoSansInscriptionalPahlaviTextTheme = - PartN.notoSansInscriptionalPahlaviTextTheme; + static const notoSansInscriptionalPahlaviTextTheme = PartN.notoSansInscriptionalPahlaviTextTheme; /// See [PartN.notoSansInscriptionalParthian]. - static const notoSansInscriptionalParthian = - PartN.notoSansInscriptionalParthian; + static const notoSansInscriptionalParthian = PartN.notoSansInscriptionalParthian; /// See [PartN.notoSansInscriptionalParthianTextTheme]. static const notoSansInscriptionalParthianTextTheme = @@ -10666,8 +10610,7 @@ class GoogleFonts { static const notoSansMasaramGondi = PartN.notoSansMasaramGondi; /// See [PartN.notoSansMasaramGondiTextTheme]. - static const notoSansMasaramGondiTextTheme = - PartN.notoSansMasaramGondiTextTheme; + static const notoSansMasaramGondiTextTheme = PartN.notoSansMasaramGondiTextTheme; /// See [PartN.notoSansMath]. static const notoSansMath = PartN.notoSansMath; @@ -10679,29 +10622,25 @@ class GoogleFonts { static const notoSansMayanNumerals = PartN.notoSansMayanNumerals; /// See [PartN.notoSansMayanNumeralsTextTheme]. - static const notoSansMayanNumeralsTextTheme = - PartN.notoSansMayanNumeralsTextTheme; + static const notoSansMayanNumeralsTextTheme = PartN.notoSansMayanNumeralsTextTheme; /// See [PartN.notoSansMedefaidrin]. static const notoSansMedefaidrin = PartN.notoSansMedefaidrin; /// See [PartN.notoSansMedefaidrinTextTheme]. - static const notoSansMedefaidrinTextTheme = - PartN.notoSansMedefaidrinTextTheme; + static const notoSansMedefaidrinTextTheme = PartN.notoSansMedefaidrinTextTheme; /// See [PartN.notoSansMeeteiMayek]. static const notoSansMeeteiMayek = PartN.notoSansMeeteiMayek; /// See [PartN.notoSansMeeteiMayekTextTheme]. - static const notoSansMeeteiMayekTextTheme = - PartN.notoSansMeeteiMayekTextTheme; + static const notoSansMeeteiMayekTextTheme = PartN.notoSansMeeteiMayekTextTheme; /// See [PartN.notoSansMendeKikakui]. static const notoSansMendeKikakui = PartN.notoSansMendeKikakui; /// See [PartN.notoSansMendeKikakuiTextTheme]. - static const notoSansMendeKikakuiTextTheme = - PartN.notoSansMendeKikakuiTextTheme; + static const notoSansMendeKikakuiTextTheme = PartN.notoSansMendeKikakuiTextTheme; /// See [PartN.notoSansMeroitic]. static const notoSansMeroitic = PartN.notoSansMeroitic; @@ -10761,8 +10700,7 @@ class GoogleFonts { static const notoSansNKoUnjoined = PartN.notoSansNKoUnjoined; /// See [PartN.notoSansNKoUnjoinedTextTheme]. - static const notoSansNKoUnjoinedTextTheme = - PartN.notoSansNKoUnjoinedTextTheme; + static const notoSansNKoUnjoinedTextTheme = PartN.notoSansNKoUnjoinedTextTheme; /// See [PartN.notoSansNabataean]. static const notoSansNabataean = PartN.notoSansNabataean; @@ -10780,8 +10718,7 @@ class GoogleFonts { static const notoSansNandinagari = PartN.notoSansNandinagari; /// See [PartN.notoSansNandinagariTextTheme]. - static const notoSansNandinagariTextTheme = - PartN.notoSansNandinagariTextTheme; + static const notoSansNandinagariTextTheme = PartN.notoSansNandinagariTextTheme; /// See [PartN.notoSansNewTaiLue]. static const notoSansNewTaiLue = PartN.notoSansNewTaiLue; @@ -10817,8 +10754,7 @@ class GoogleFonts { static const notoSansOldHungarian = PartN.notoSansOldHungarian; /// See [PartN.notoSansOldHungarianTextTheme]. - static const notoSansOldHungarianTextTheme = - PartN.notoSansOldHungarianTextTheme; + static const notoSansOldHungarianTextTheme = PartN.notoSansOldHungarianTextTheme; /// See [PartN.notoSansOldItalic]. static const notoSansOldItalic = PartN.notoSansOldItalic; @@ -10830,8 +10766,7 @@ class GoogleFonts { static const notoSansOldNorthArabian = PartN.notoSansOldNorthArabian; /// See [PartN.notoSansOldNorthArabianTextTheme]. - static const notoSansOldNorthArabianTextTheme = - PartN.notoSansOldNorthArabianTextTheme; + static const notoSansOldNorthArabianTextTheme = PartN.notoSansOldNorthArabianTextTheme; /// See [PartN.notoSansOldPermic]. static const notoSansOldPermic = PartN.notoSansOldPermic; @@ -10855,8 +10790,7 @@ class GoogleFonts { static const notoSansOldSouthArabian = PartN.notoSansOldSouthArabian; /// See [PartN.notoSansOldSouthArabianTextTheme]. - static const notoSansOldSouthArabianTextTheme = - PartN.notoSansOldSouthArabianTextTheme; + static const notoSansOldSouthArabianTextTheme = PartN.notoSansOldSouthArabianTextTheme; /// See [PartN.notoSansOldTurkic]. static const notoSansOldTurkic = PartN.notoSansOldTurkic; @@ -10886,8 +10820,7 @@ class GoogleFonts { static const notoSansPahawhHmong = PartN.notoSansPahawhHmong; /// See [PartN.notoSansPahawhHmongTextTheme]. - static const notoSansPahawhHmongTextTheme = - PartN.notoSansPahawhHmongTextTheme; + static const notoSansPahawhHmongTextTheme = PartN.notoSansPahawhHmongTextTheme; /// See [PartN.notoSansPalmyrene]. static const notoSansPalmyrene = PartN.notoSansPalmyrene; @@ -10917,8 +10850,7 @@ class GoogleFonts { static const notoSansPsalterPahlavi = PartN.notoSansPsalterPahlavi; /// See [PartN.notoSansPsalterPahlaviTextTheme]. - static const notoSansPsalterPahlaviTextTheme = - PartN.notoSansPsalterPahlaviTextTheme; + static const notoSansPsalterPahlaviTextTheme = PartN.notoSansPsalterPahlaviTextTheme; /// See [PartN.notoSansRejang]. static const notoSansRejang = PartN.notoSansRejang; @@ -10972,8 +10904,7 @@ class GoogleFonts { static const notoSansSignWriting = PartN.notoSansSignWriting; /// See [PartN.notoSansSignWritingTextTheme]. - static const notoSansSignWritingTextTheme = - PartN.notoSansSignWritingTextTheme; + static const notoSansSignWritingTextTheme = PartN.notoSansSignWritingTextTheme; /// See [PartN.notoSansSinhala]. static const notoSansSinhala = PartN.notoSansSinhala; @@ -10991,8 +10922,7 @@ class GoogleFonts { static const notoSansSoraSompeng = PartN.notoSansSoraSompeng; /// See [PartN.notoSansSoraSompengTextTheme]. - static const notoSansSoraSompengTextTheme = - PartN.notoSansSoraSompengTextTheme; + static const notoSansSoraSompengTextTheme = PartN.notoSansSoraSompengTextTheme; /// See [PartN.notoSansSoyombo]. static const notoSansSoyombo = PartN.notoSansSoyombo; @@ -11016,8 +10946,7 @@ class GoogleFonts { static const notoSansSylotiNagri = PartN.notoSansSylotiNagri; /// See [PartN.notoSansSylotiNagriTextTheme]. - static const notoSansSylotiNagriTextTheme = - PartN.notoSansSylotiNagriTextTheme; + static const notoSansSylotiNagriTextTheme = PartN.notoSansSylotiNagriTextTheme; /// See [PartN.notoSansSymbols]. static const notoSansSymbols = PartN.notoSansSymbols; @@ -11041,15 +10970,13 @@ class GoogleFonts { static const notoSansSyriacEastern = PartN.notoSansSyriacEastern; /// See [PartN.notoSansSyriacEasternTextTheme]. - static const notoSansSyriacEasternTextTheme = - PartN.notoSansSyriacEasternTextTheme; + static const notoSansSyriacEasternTextTheme = PartN.notoSansSyriacEasternTextTheme; /// See [PartN.notoSansSyriacWestern]. static const notoSansSyriacWestern = PartN.notoSansSyriacWestern; /// See [PartN.notoSansSyriacWesternTextTheme]. - static const notoSansSyriacWesternTextTheme = - PartN.notoSansSyriacWesternTextTheme; + static const notoSansSyriacWesternTextTheme = PartN.notoSansSyriacWesternTextTheme; /// See [PartN.notoSansTc]. static const notoSansTc = PartN.notoSansTc; @@ -11103,8 +11030,7 @@ class GoogleFonts { static const notoSansTamilSupplement = PartN.notoSansTamilSupplement; /// See [PartN.notoSansTamilSupplementTextTheme]. - static const notoSansTamilSupplementTextTheme = - PartN.notoSansTamilSupplementTextTheme; + static const notoSansTamilSupplementTextTheme = PartN.notoSansTamilSupplementTextTheme; /// See [PartN.notoSansTangsa]. static const notoSansTangsa = PartN.notoSansTangsa; @@ -11188,8 +11114,7 @@ class GoogleFonts { static const notoSansZanabazarSquare = PartN.notoSansZanabazarSquare; /// See [PartN.notoSansZanabazarSquareTextTheme]. - static const notoSansZanabazarSquareTextTheme = - PartN.notoSansZanabazarSquareTextTheme; + static const notoSansZanabazarSquareTextTheme = PartN.notoSansZanabazarSquareTextTheme; /// See [PartN.notoSerif]. static const notoSerif = PartN.notoSerif; @@ -11225,8 +11150,7 @@ class GoogleFonts { static const notoSerifDevanagari = PartN.notoSerifDevanagari; /// See [PartN.notoSerifDevanagariTextTheme]. - static const notoSerifDevanagariTextTheme = - PartN.notoSerifDevanagariTextTheme; + static const notoSerifDevanagariTextTheme = PartN.notoSerifDevanagariTextTheme; /// See [PartN.notoSerifDisplay]. static const notoSerifDisplay = PartN.notoSerifDisplay; @@ -11238,8 +11162,7 @@ class GoogleFonts { static const notoSerifDivesAkuru = PartN.notoSerifDivesAkuru; /// See [PartN.notoSerifDivesAkuruTextTheme]. - static const notoSerifDivesAkuruTextTheme = - PartN.notoSerifDivesAkuruTextTheme; + static const notoSerifDivesAkuruTextTheme = PartN.notoSerifDivesAkuruTextTheme; /// See [PartN.notoSerifDogra]. static const notoSerifDogra = PartN.notoSerifDogra; @@ -11293,8 +11216,7 @@ class GoogleFonts { static const notoSerifHentaigana = PartN.notoSerifHentaigana; /// See [PartN.notoSerifHentaiganaTextTheme]. - static const notoSerifHentaiganaTextTheme = - PartN.notoSerifHentaiganaTextTheme; + static const notoSerifHentaiganaTextTheme = PartN.notoSerifHentaiganaTextTheme; /// See [PartN.notoSerifJp]. static const notoSerifJp = PartN.notoSerifJp; @@ -11318,8 +11240,7 @@ class GoogleFonts { static const notoSerifKhitanSmallScript = PartN.notoSerifKhitanSmallScript; /// See [PartN.notoSerifKhitanSmallScriptTextTheme]. - static const notoSerifKhitanSmallScriptTextTheme = - PartN.notoSerifKhitanSmallScriptTextTheme; + static const notoSerifKhitanSmallScriptTextTheme = PartN.notoSerifKhitanSmallScriptTextTheme; /// See [PartN.notoSerifKhmer]. static const notoSerifKhmer = PartN.notoSerifKhmer; @@ -11379,8 +11300,7 @@ class GoogleFonts { static const notoSerifOttomanSiyaq = PartN.notoSerifOttomanSiyaq; /// See [PartN.notoSerifOttomanSiyaqTextTheme]. - static const notoSerifOttomanSiyaqTextTheme = - PartN.notoSerifOttomanSiyaqTextTheme; + static const notoSerifOttomanSiyaqTextTheme = PartN.notoSerifOttomanSiyaqTextTheme; /// See [PartN.notoSerifSc]. static const notoSerifSc = PartN.notoSerifSc; @@ -11458,15 +11378,13 @@ class GoogleFonts { static const notoTraditionalNushu = PartN.notoTraditionalNushu; /// See [PartN.notoTraditionalNushuTextTheme]. - static const notoTraditionalNushuTextTheme = - PartN.notoTraditionalNushuTextTheme; + static const notoTraditionalNushuTextTheme = PartN.notoTraditionalNushuTextTheme; /// See [PartN.notoZnamennyMusicalNotation]. static const notoZnamennyMusicalNotation = PartN.notoZnamennyMusicalNotation; /// See [PartN.notoZnamennyMusicalNotationTextTheme]. - static const notoZnamennyMusicalNotationTextTheme = - PartN.notoZnamennyMusicalNotationTextTheme; + static const notoZnamennyMusicalNotationTextTheme = PartN.notoZnamennyMusicalNotationTextTheme; /// See [PartN.novaCut]. static const novaCut = PartN.novaCut; @@ -11598,8 +11516,7 @@ class GoogleFonts { static const oleoScriptSwashCaps = PartO.oleoScriptSwashCaps; /// See [PartO.oleoScriptSwashCapsTextTheme]. - static const oleoScriptSwashCapsTextTheme = - PartO.oleoScriptSwashCapsTextTheme; + static const oleoScriptSwashCapsTextTheme = PartO.oleoScriptSwashCapsTextTheme; /// See [PartO.onest]. static const onest = PartO.onest; @@ -11779,8 +11696,7 @@ class GoogleFonts { static const padyakkeExpandedOne = PartP.padyakkeExpandedOne; /// See [PartP.padyakkeExpandedOneTextTheme]. - static const padyakkeExpandedOneTextTheme = - PartP.padyakkeExpandedOneTextTheme; + static const padyakkeExpandedOneTextTheme = PartP.padyakkeExpandedOneTextTheme; /// See [PartP.palanquin]. static const palanquin = PartP.palanquin; @@ -12086,8 +12002,7 @@ class GoogleFonts { static const playwriteAuNswGuides = PartP.playwriteAuNswGuides; /// See [PartP.playwriteAuNswGuidesTextTheme]. - static const playwriteAuNswGuidesTextTheme = - PartP.playwriteAuNswGuidesTextTheme; + static const playwriteAuNswGuidesTextTheme = PartP.playwriteAuNswGuidesTextTheme; /// See [PartP.playwriteAuQld]. static const playwriteAuQld = PartP.playwriteAuQld; @@ -12099,8 +12014,7 @@ class GoogleFonts { static const playwriteAuQldGuides = PartP.playwriteAuQldGuides; /// See [PartP.playwriteAuQldGuidesTextTheme]. - static const playwriteAuQldGuidesTextTheme = - PartP.playwriteAuQldGuidesTextTheme; + static const playwriteAuQldGuidesTextTheme = PartP.playwriteAuQldGuidesTextTheme; /// See [PartP.playwriteAuSa]. static const playwriteAuSa = PartP.playwriteAuSa; @@ -12112,8 +12026,7 @@ class GoogleFonts { static const playwriteAuSaGuides = PartP.playwriteAuSaGuides; /// See [PartP.playwriteAuSaGuidesTextTheme]. - static const playwriteAuSaGuidesTextTheme = - PartP.playwriteAuSaGuidesTextTheme; + static const playwriteAuSaGuidesTextTheme = PartP.playwriteAuSaGuidesTextTheme; /// See [PartP.playwriteAuTas]. static const playwriteAuTas = PartP.playwriteAuTas; @@ -12125,8 +12038,7 @@ class GoogleFonts { static const playwriteAuTasGuides = PartP.playwriteAuTasGuides; /// See [PartP.playwriteAuTasGuidesTextTheme]. - static const playwriteAuTasGuidesTextTheme = - PartP.playwriteAuTasGuidesTextTheme; + static const playwriteAuTasGuidesTextTheme = PartP.playwriteAuTasGuidesTextTheme; /// See [PartP.playwriteAuVic]. static const playwriteAuVic = PartP.playwriteAuVic; @@ -12138,8 +12050,7 @@ class GoogleFonts { static const playwriteAuVicGuides = PartP.playwriteAuVicGuides; /// See [PartP.playwriteAuVicGuidesTextTheme]. - static const playwriteAuVicGuidesTextTheme = - PartP.playwriteAuVicGuidesTextTheme; + static const playwriteAuVicGuidesTextTheme = PartP.playwriteAuVicGuidesTextTheme; /// See [PartP.playwriteBeVlg]. static const playwriteBeVlg = PartP.playwriteBeVlg; @@ -12151,8 +12062,7 @@ class GoogleFonts { static const playwriteBeVlgGuides = PartP.playwriteBeVlgGuides; /// See [PartP.playwriteBeVlgGuidesTextTheme]. - static const playwriteBeVlgGuidesTextTheme = - PartP.playwriteBeVlgGuidesTextTheme; + static const playwriteBeVlgGuidesTextTheme = PartP.playwriteBeVlgGuidesTextTheme; /// See [PartP.playwriteBeWal]. static const playwriteBeWal = PartP.playwriteBeWal; @@ -12164,8 +12074,7 @@ class GoogleFonts { static const playwriteBeWalGuides = PartP.playwriteBeWalGuides; /// See [PartP.playwriteBeWalGuidesTextTheme]. - static const playwriteBeWalGuidesTextTheme = - PartP.playwriteBeWalGuidesTextTheme; + static const playwriteBeWalGuidesTextTheme = PartP.playwriteBeWalGuidesTextTheme; /// See [PartP.playwriteBr]. static const playwriteBr = PartP.playwriteBr; @@ -12249,8 +12158,7 @@ class GoogleFonts { static const playwriteDeGrundGuides = PartP.playwriteDeGrundGuides; /// See [PartP.playwriteDeGrundGuidesTextTheme]. - static const playwriteDeGrundGuidesTextTheme = - PartP.playwriteDeGrundGuidesTextTheme; + static const playwriteDeGrundGuidesTextTheme = PartP.playwriteDeGrundGuidesTextTheme; /// See [PartP.playwriteDeLa]. static const playwriteDeLa = PartP.playwriteDeLa; @@ -12262,8 +12170,7 @@ class GoogleFonts { static const playwriteDeLaGuides = PartP.playwriteDeLaGuides; /// See [PartP.playwriteDeLaGuidesTextTheme]. - static const playwriteDeLaGuidesTextTheme = - PartP.playwriteDeLaGuidesTextTheme; + static const playwriteDeLaGuidesTextTheme = PartP.playwriteDeLaGuidesTextTheme; /// See [PartP.playwriteDeSas]. static const playwriteDeSas = PartP.playwriteDeSas; @@ -12275,8 +12182,7 @@ class GoogleFonts { static const playwriteDeSasGuides = PartP.playwriteDeSasGuides; /// See [PartP.playwriteDeSasGuidesTextTheme]. - static const playwriteDeSasGuidesTextTheme = - PartP.playwriteDeSasGuidesTextTheme; + static const playwriteDeSasGuidesTextTheme = PartP.playwriteDeSasGuidesTextTheme; /// See [PartP.playwriteDeVa]. static const playwriteDeVa = PartP.playwriteDeVa; @@ -12288,8 +12194,7 @@ class GoogleFonts { static const playwriteDeVaGuides = PartP.playwriteDeVaGuides; /// See [PartP.playwriteDeVaGuidesTextTheme]. - static const playwriteDeVaGuidesTextTheme = - PartP.playwriteDeVaGuidesTextTheme; + static const playwriteDeVaGuidesTextTheme = PartP.playwriteDeVaGuidesTextTheme; /// See [PartP.playwriteDkLoopet]. static const playwriteDkLoopet = PartP.playwriteDkLoopet; @@ -12301,8 +12206,7 @@ class GoogleFonts { static const playwriteDkLoopetGuides = PartP.playwriteDkLoopetGuides; /// See [PartP.playwriteDkLoopetGuidesTextTheme]. - static const playwriteDkLoopetGuidesTextTheme = - PartP.playwriteDkLoopetGuidesTextTheme; + static const playwriteDkLoopetGuidesTextTheme = PartP.playwriteDkLoopetGuidesTextTheme; /// See [PartP.playwriteDkUloopet]. static const playwriteDkUloopet = PartP.playwriteDkUloopet; @@ -12314,8 +12218,7 @@ class GoogleFonts { static const playwriteDkUloopetGuides = PartP.playwriteDkUloopetGuides; /// See [PartP.playwriteDkUloopetGuidesTextTheme]. - static const playwriteDkUloopetGuidesTextTheme = - PartP.playwriteDkUloopetGuidesTextTheme; + static const playwriteDkUloopetGuidesTextTheme = PartP.playwriteDkUloopetGuidesTextTheme; /// See [PartP.playwriteEs]. static const playwriteEs = PartP.playwriteEs; @@ -12333,8 +12236,7 @@ class GoogleFonts { static const playwriteEsDecoGuides = PartP.playwriteEsDecoGuides; /// See [PartP.playwriteEsDecoGuidesTextTheme]. - static const playwriteEsDecoGuidesTextTheme = - PartP.playwriteEsDecoGuidesTextTheme; + static const playwriteEsDecoGuidesTextTheme = PartP.playwriteEsDecoGuidesTextTheme; /// See [PartP.playwriteEsGuides]. static const playwriteEsGuides = PartP.playwriteEsGuides; @@ -12352,8 +12254,7 @@ class GoogleFonts { static const playwriteFrModerneGuides = PartP.playwriteFrModerneGuides; /// See [PartP.playwriteFrModerneGuidesTextTheme]. - static const playwriteFrModerneGuidesTextTheme = - PartP.playwriteFrModerneGuidesTextTheme; + static const playwriteFrModerneGuidesTextTheme = PartP.playwriteFrModerneGuidesTextTheme; /// See [PartP.playwriteFrTrad]. static const playwriteFrTrad = PartP.playwriteFrTrad; @@ -12365,8 +12266,7 @@ class GoogleFonts { static const playwriteFrTradGuides = PartP.playwriteFrTradGuides; /// See [PartP.playwriteFrTradGuidesTextTheme]. - static const playwriteFrTradGuidesTextTheme = - PartP.playwriteFrTradGuidesTextTheme; + static const playwriteFrTradGuidesTextTheme = PartP.playwriteFrTradGuidesTextTheme; /// See [PartP.playwriteGbJ]. static const playwriteGbJ = PartP.playwriteGbJ; @@ -12414,8 +12314,7 @@ class GoogleFonts { static const playwriteHrLijevaGuides = PartP.playwriteHrLijevaGuides; /// See [PartP.playwriteHrLijevaGuidesTextTheme]. - static const playwriteHrLijevaGuidesTextTheme = - PartP.playwriteHrLijevaGuidesTextTheme; + static const playwriteHrLijevaGuidesTextTheme = PartP.playwriteHrLijevaGuidesTextTheme; /// See [PartP.playwriteHu]. static const playwriteHu = PartP.playwriteHu; @@ -12487,8 +12386,7 @@ class GoogleFonts { static const playwriteItModernaGuides = PartP.playwriteItModernaGuides; /// See [PartP.playwriteItModernaGuidesTextTheme]. - static const playwriteItModernaGuidesTextTheme = - PartP.playwriteItModernaGuidesTextTheme; + static const playwriteItModernaGuidesTextTheme = PartP.playwriteItModernaGuidesTextTheme; /// See [PartP.playwriteItTrad]. static const playwriteItTrad = PartP.playwriteItTrad; @@ -12500,8 +12398,7 @@ class GoogleFonts { static const playwriteItTradGuides = PartP.playwriteItTradGuides; /// See [PartP.playwriteItTradGuidesTextTheme]. - static const playwriteItTradGuidesTextTheme = - PartP.playwriteItTradGuidesTextTheme; + static const playwriteItTradGuidesTextTheme = PartP.playwriteItTradGuidesTextTheme; /// See [PartP.playwriteMx]. static const playwriteMx = PartP.playwriteMx; @@ -12525,8 +12422,7 @@ class GoogleFonts { static const playwriteNgModernGuides = PartP.playwriteNgModernGuides; /// See [PartP.playwriteNgModernGuidesTextTheme]. - static const playwriteNgModernGuidesTextTheme = - PartP.playwriteNgModernGuidesTextTheme; + static const playwriteNgModernGuidesTextTheme = PartP.playwriteNgModernGuidesTextTheme; /// See [PartP.playwriteNl]. static const playwriteNl = PartP.playwriteNl; @@ -12646,8 +12542,7 @@ class GoogleFonts { static const playwriteUsModernGuides = PartP.playwriteUsModernGuides; /// See [PartP.playwriteUsModernGuidesTextTheme]. - static const playwriteUsModernGuidesTextTheme = - PartP.playwriteUsModernGuidesTextTheme; + static const playwriteUsModernGuidesTextTheme = PartP.playwriteUsModernGuidesTextTheme; /// See [PartP.playwriteUsTrad]. static const playwriteUsTrad = PartP.playwriteUsTrad; @@ -12659,8 +12554,7 @@ class GoogleFonts { static const playwriteUsTradGuides = PartP.playwriteUsTradGuides; /// See [PartP.playwriteUsTradGuidesTextTheme]. - static const playwriteUsTradGuidesTextTheme = - PartP.playwriteUsTradGuidesTextTheme; + static const playwriteUsTradGuidesTextTheme = PartP.playwriteUsTradGuidesTextTheme; /// See [PartP.playwriteVn]. static const playwriteVn = PartP.playwriteVn; @@ -13146,8 +13040,7 @@ class GoogleFonts { static const redditSansCondensed = PartR.redditSansCondensed; /// See [PartR.redditSansCondensedTextTheme]. - static const redditSansCondensedTextTheme = - PartR.redditSansCondensedTextTheme; + static const redditSansCondensedTextTheme = PartR.redditSansCondensedTextTheme; /// See [PartR.redressed]. static const redressed = PartR.redressed; @@ -13393,8 +13286,7 @@ class GoogleFonts { static const rubikDoodleTriangles = PartR.rubikDoodleTriangles; /// See [PartR.rubikDoodleTrianglesTextTheme]. - static const rubikDoodleTrianglesTextTheme = - PartR.rubikDoodleTrianglesTextTheme; + static const rubikDoodleTrianglesTextTheme = PartR.rubikDoodleTrianglesTextTheme; /// See [PartR.rubikGemstones]. static const rubikGemstones = PartR.rubikGemstones; @@ -13820,8 +13712,7 @@ class GoogleFonts { static const shadowsIntoLightTwo = PartS.shadowsIntoLightTwo; /// See [PartS.shadowsIntoLightTwoTextTheme]. - static const shadowsIntoLightTwoTextTheme = - PartS.shadowsIntoLightTwoTextTheme; + static const shadowsIntoLightTwoTextTheme = PartS.shadowsIntoLightTwoTextTheme; /// See [PartS.shafarik]. static const shafarik = PartS.shafarik; @@ -13995,8 +13886,7 @@ class GoogleFonts { static const sixtyfourConvergence = PartS.sixtyfourConvergence; /// See [PartS.sixtyfourConvergenceTextTheme]. - static const sixtyfourConvergenceTextTheme = - PartS.sixtyfourConvergenceTextTheme; + static const sixtyfourConvergenceTextTheme = PartS.sixtyfourConvergenceTextTheme; /// See [PartS.skranji]. static const skranji = PartS.skranji; @@ -14098,15 +13988,13 @@ class GoogleFonts { static const sofiaSansExtraCondensed = PartS.sofiaSansExtraCondensed; /// See [PartS.sofiaSansExtraCondensedTextTheme]. - static const sofiaSansExtraCondensedTextTheme = - PartS.sofiaSansExtraCondensedTextTheme; + static const sofiaSansExtraCondensedTextTheme = PartS.sofiaSansExtraCondensedTextTheme; /// See [PartS.sofiaSansSemiCondensed]. static const sofiaSansSemiCondensed = PartS.sofiaSansSemiCondensed; /// See [PartS.sofiaSansSemiCondensedTextTheme]. - static const sofiaSansSemiCondensedTextTheme = - PartS.sofiaSansSemiCondensedTextTheme; + static const sofiaSansSemiCondensedTextTheme = PartS.sofiaSansSemiCondensedTextTheme; /// See [PartS.solitreo]. static const solitreo = PartS.solitreo; @@ -14208,15 +14096,13 @@ class GoogleFonts { static const specialGothicCondensedOne = PartS.specialGothicCondensedOne; /// See [PartS.specialGothicCondensedOneTextTheme]. - static const specialGothicCondensedOneTextTheme = - PartS.specialGothicCondensedOneTextTheme; + static const specialGothicCondensedOneTextTheme = PartS.specialGothicCondensedOneTextTheme; /// See [PartS.specialGothicExpandedOne]. static const specialGothicExpandedOne = PartS.specialGothicExpandedOne; /// See [PartS.specialGothicExpandedOneTextTheme]. - static const specialGothicExpandedOneTextTheme = - PartS.specialGothicExpandedOneTextTheme; + static const specialGothicExpandedOneTextTheme = PartS.specialGothicExpandedOneTextTheme; /// See [PartS.spectral]. static const spectral = PartS.spectral; @@ -14282,8 +14168,7 @@ class GoogleFonts { static const sreeKrushnadevaraya = PartS.sreeKrushnadevaraya; /// See [PartS.sreeKrushnadevarayaTextTheme]. - static const sreeKrushnadevarayaTextTheme = - PartS.sreeKrushnadevarayaTextTheme; + static const sreeKrushnadevarayaTextTheme = PartS.sreeKrushnadevarayaTextTheme; /// See [PartS.sriracha]. static const sriracha = PartS.sriracha; @@ -14355,8 +14240,7 @@ class GoogleFonts { static const stintUltraCondensed = PartS.stintUltraCondensed; /// See [PartS.stintUltraCondensedTextTheme]. - static const stintUltraCondensedTextTheme = - PartS.stintUltraCondensedTextTheme; + static const stintUltraCondensedTextTheme = PartS.stintUltraCondensedTextTheme; /// See [PartS.stintUltraExpanded]. static const stintUltraExpanded = PartS.stintUltraExpanded; @@ -14686,22 +14570,19 @@ class GoogleFonts { static const tiroDevanagariHindi = PartT.tiroDevanagariHindi; /// See [PartT.tiroDevanagariHindiTextTheme]. - static const tiroDevanagariHindiTextTheme = - PartT.tiroDevanagariHindiTextTheme; + static const tiroDevanagariHindiTextTheme = PartT.tiroDevanagariHindiTextTheme; /// See [PartT.tiroDevanagariMarathi]. static const tiroDevanagariMarathi = PartT.tiroDevanagariMarathi; /// See [PartT.tiroDevanagariMarathiTextTheme]. - static const tiroDevanagariMarathiTextTheme = - PartT.tiroDevanagariMarathiTextTheme; + static const tiroDevanagariMarathiTextTheme = PartT.tiroDevanagariMarathiTextTheme; /// See [PartT.tiroDevanagariSanskrit]. static const tiroDevanagariSanskrit = PartT.tiroDevanagariSanskrit; /// See [PartT.tiroDevanagariSanskritTextTheme]. - static const tiroDevanagariSanskritTextTheme = - PartT.tiroDevanagariSanskritTextTheme; + static const tiroDevanagariSanskritTextTheme = PartT.tiroDevanagariSanskritTextTheme; /// See [PartT.tiroGurmukhi]. static const tiroGurmukhi = PartT.tiroGurmukhi; @@ -15109,8 +14990,7 @@ class GoogleFonts { static const waitingForTheSunrise = PartW.waitingForTheSunrise; /// See [PartW.waitingForTheSunriseTextTheme]. - static const waitingForTheSunriseTextTheme = - PartW.waitingForTheSunriseTextTheme; + static const waitingForTheSunriseTextTheme = PartW.waitingForTheSunriseTextTheme; /// See [PartW.wallpoet]. static const wallpoet = PartW.wallpoet; @@ -15350,15 +15230,13 @@ class GoogleFonts { static const yujiHentaiganaAkari = PartY.yujiHentaiganaAkari; /// See [PartY.yujiHentaiganaAkariTextTheme]. - static const yujiHentaiganaAkariTextTheme = - PartY.yujiHentaiganaAkariTextTheme; + static const yujiHentaiganaAkariTextTheme = PartY.yujiHentaiganaAkariTextTheme; /// See [PartY.yujiHentaiganaAkebono]. static const yujiHentaiganaAkebono = PartY.yujiHentaiganaAkebono; /// See [PartY.yujiHentaiganaAkebonoTextTheme]. - static const yujiHentaiganaAkebonoTextTheme = - PartY.yujiHentaiganaAkebonoTextTheme; + static const yujiHentaiganaAkebonoTextTheme = PartY.yujiHentaiganaAkebonoTextTheme; /// See [PartY.yujiMai]. static const yujiMai = PartY.yujiMai; @@ -15388,8 +15266,7 @@ class GoogleFonts { static const zcoolQingKeHuangYou = PartZ.zcoolQingKeHuangYou; /// See [PartZ.zcoolQingKeHuangYouTextTheme]. - static const zcoolQingKeHuangYouTextTheme = - PartZ.zcoolQingKeHuangYouTextTheme; + static const zcoolQingKeHuangYouTextTheme = PartZ.zcoolQingKeHuangYouTextTheme; /// See [PartZ.zcoolXiaoWei]. static const zcoolXiaoWei = PartZ.zcoolXiaoWei; @@ -15413,15 +15290,13 @@ class GoogleFonts { static const zalandoSansExpanded = PartZ.zalandoSansExpanded; /// See [PartZ.zalandoSansExpandedTextTheme]. - static const zalandoSansExpandedTextTheme = - PartZ.zalandoSansExpandedTextTheme; + static const zalandoSansExpandedTextTheme = PartZ.zalandoSansExpandedTextTheme; /// See [PartZ.zalandoSansSemiExpanded]. static const zalandoSansSemiExpanded = PartZ.zalandoSansSemiExpanded; /// See [PartZ.zalandoSansSemiExpandedTextTheme]. - static const zalandoSansSemiExpandedTextTheme = - PartZ.zalandoSansSemiExpandedTextTheme; + static const zalandoSansSemiExpandedTextTheme = PartZ.zalandoSansSemiExpandedTextTheme; /// See [PartZ.zenAntique]. static const zenAntique = PartZ.zenAntique; @@ -15445,8 +15320,7 @@ class GoogleFonts { static const zenKakuGothicAntique = PartZ.zenKakuGothicAntique; /// See [PartZ.zenKakuGothicAntiqueTextTheme]. - static const zenKakuGothicAntiqueTextTheme = - PartZ.zenKakuGothicAntiqueTextTheme; + static const zenKakuGothicAntiqueTextTheme = PartZ.zenKakuGothicAntiqueTextTheme; /// See [PartZ.zenKakuGothicNew]. static const zenKakuGothicNew = PartZ.zenKakuGothicNew; diff --git a/packages/google_fonts/lib/src/google_fonts_base.dart b/packages/google_fonts/lib/src/google_fonts_base.dart index d7827e4cbfa9..a2a403f9f5f2 100755 --- a/packages/google_fonts/lib/src/google_fonts_base.dart +++ b/packages/google_fonts/lib/src/google_fonts_base.dart @@ -165,10 +165,7 @@ Future loadFontIfNecessary(GoogleFontsDescriptor descriptor) async { // Attempt to load this font via http, unless disallowed. if (GoogleFonts.config.allowRuntimeFetching) { - byteData = _httpFetchFontAndSaveToDevice( - familyWithVariantString, - descriptor.file, - ); + byteData = _httpFetchFontAndSaveToDevice(familyWithVariantString, descriptor.file); if (await byteData != null) { return await loadFontByteData(familyWithVariantString, byteData); } @@ -206,10 +203,7 @@ Future loadFontIfNecessary(GoogleFontsDescriptor descriptor) async { /// Loads a font with [FontLoader], given its name and byte-representation. @visibleForTesting -Future loadFontByteData( - String familyWithVariantString, - Future? byteData, -) async { +Future loadFontByteData(String familyWithVariantString, Future? byteData) async { if (byteData == null) { return; } @@ -249,10 +243,7 @@ GoogleFontsVariant _closestMatch( /// it is the first time it is being loaded. /// /// This function can return `null` if the font fails to load from the URL. -Future _httpFetchFontAndSaveToDevice( - String fontName, - GoogleFontsFile file, -) async { +Future _httpFetchFontAndSaveToDevice(String fontName, GoogleFontsFile file) async { final Uri? uri = Uri.tryParse(file.url); if (uri == null) { throw Exception('Invalid fontUrl: ${file.url}'); @@ -267,9 +258,7 @@ Future _httpFetchFontAndSaveToDevice( } if (response.statusCode == 200) { if (!_isFileSecure(file, response.bodyBytes)) { - throw Exception( - 'File from ${file.url} did not match expected length and checksum.', - ); + throw Exception('File from ${file.url} did not match expected length and checksum.'); } _unawaited( @@ -314,18 +303,13 @@ String? findFamilyWithVariantAssetPath( } final String apiFilenamePrefix = familyWithVariant.toApiFilenamePrefix(); - final fileTypes = isWeb - ? ['.woff2', '.woff', '.ttf', '.otf'] - : ['.ttf', '.otf']; + final fileTypes = isWeb ? ['.woff2', '.woff', '.ttf', '.otf'] : ['.ttf', '.otf']; // Iterate by file type priority, ensuring preferred formats are selected. for (final fileType in fileTypes) { for (final String asset in manifestValues) { if (asset.endsWith(fileType)) { - final String assetWithoutExtension = asset.substring( - 0, - asset.length - fileType.length, - ); + final String assetWithoutExtension = asset.substring(0, asset.length - fileType.length); if (assetWithoutExtension.endsWith(apiFilenamePrefix)) { return asset; } @@ -339,8 +323,7 @@ String? findFamilyWithVariantAssetPath( bool _isFileSecure(GoogleFontsFile file, Uint8List bytes) { final int actualFileLength = bytes.length; final actualFileHash = sha256.convert(bytes).toString(); - return file.expectedLength == actualFileLength && - file.expectedFileHash == actualFileHash; + return file.expectedLength == actualFileLength && file.expectedFileHash == actualFileHash; } void _unawaited(Future future) {} diff --git a/packages/google_fonts/lib/src/google_fonts_descriptor.dart b/packages/google_fonts/lib/src/google_fonts_descriptor.dart index 126ef9f756fd..62769eb7bc04 100644 --- a/packages/google_fonts/lib/src/google_fonts_descriptor.dart +++ b/packages/google_fonts/lib/src/google_fonts_descriptor.dart @@ -14,10 +14,7 @@ class GoogleFontsDescriptor { /// The [familyWithVariant] describes the font family and variant, while /// the [file] contains information about the font file such as its hash and /// expected length. - const GoogleFontsDescriptor({ - required this.familyWithVariant, - required this.file, - }); + const GoogleFontsDescriptor({required this.familyWithVariant, required this.file}); /// The font family and variant information. /// diff --git a/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart b/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart index 949e9cb61fcf..aa9cdf221b7d 100644 --- a/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart +++ b/packages/google_fonts/lib/src/google_fonts_family_with_variant.dart @@ -7,10 +7,7 @@ import 'google_fonts_variant.dart'; /// Represents a Google Fonts API variant in Flutter-specific types. class GoogleFontsFamilyWithVariant { /// Creates a representation of a Google Fonts family with a specific variant. - const GoogleFontsFamilyWithVariant({ - required this.family, - required this.googleFontsVariant, - }); + const GoogleFontsFamilyWithVariant({required this.family, required this.googleFontsVariant}); /// The name of the Google Fonts family. /// diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart index 1f74da85c894..909c861d2d8d 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_a.dart @@ -5991,19 +5991,11 @@ class PartA { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: alumniSansCollegiateOne(textStyle: textTheme.displayLarge), - displayMedium: alumniSansCollegiateOne( - textStyle: textTheme.displayMedium, - ), + displayMedium: alumniSansCollegiateOne(textStyle: textTheme.displayMedium), displaySmall: alumniSansCollegiateOne(textStyle: textTheme.displaySmall), - headlineLarge: alumniSansCollegiateOne( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: alumniSansCollegiateOne( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: alumniSansCollegiateOne( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: alumniSansCollegiateOne(textStyle: textTheme.headlineLarge), + headlineMedium: alumniSansCollegiateOne(textStyle: textTheme.headlineMedium), + headlineSmall: alumniSansCollegiateOne(textStyle: textTheme.headlineSmall), titleLarge: alumniSansCollegiateOne(textStyle: textTheme.titleLarge), titleMedium: alumniSansCollegiateOne(textStyle: textTheme.titleMedium), titleSmall: alumniSansCollegiateOne(textStyle: textTheme.titleSmall), @@ -9725,9 +9717,7 @@ class PartA { displayMedium: annieUseYourTelescope(textStyle: textTheme.displayMedium), displaySmall: annieUseYourTelescope(textStyle: textTheme.displaySmall), headlineLarge: annieUseYourTelescope(textStyle: textTheme.headlineLarge), - headlineMedium: annieUseYourTelescope( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: annieUseYourTelescope(textStyle: textTheme.headlineMedium), headlineSmall: annieUseYourTelescope(textStyle: textTheme.headlineSmall), titleLarge: annieUseYourTelescope(textStyle: textTheme.titleLarge), titleMedium: annieUseYourTelescope(textStyle: textTheme.titleMedium), @@ -14222,19 +14212,11 @@ class PartA { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: atkinsonHyperlegibleMono(textStyle: textTheme.displayLarge), - displayMedium: atkinsonHyperlegibleMono( - textStyle: textTheme.displayMedium, - ), + displayMedium: atkinsonHyperlegibleMono(textStyle: textTheme.displayMedium), displaySmall: atkinsonHyperlegibleMono(textStyle: textTheme.displaySmall), - headlineLarge: atkinsonHyperlegibleMono( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: atkinsonHyperlegibleMono( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: atkinsonHyperlegibleMono( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: atkinsonHyperlegibleMono(textStyle: textTheme.headlineLarge), + headlineMedium: atkinsonHyperlegibleMono(textStyle: textTheme.headlineMedium), + headlineSmall: atkinsonHyperlegibleMono(textStyle: textTheme.headlineSmall), titleLarge: atkinsonHyperlegibleMono(textStyle: textTheme.titleLarge), titleMedium: atkinsonHyperlegibleMono(textStyle: textTheme.titleMedium), titleSmall: atkinsonHyperlegibleMono(textStyle: textTheme.titleSmall), @@ -14408,19 +14390,11 @@ class PartA { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: atkinsonHyperlegibleNext(textStyle: textTheme.displayLarge), - displayMedium: atkinsonHyperlegibleNext( - textStyle: textTheme.displayMedium, - ), + displayMedium: atkinsonHyperlegibleNext(textStyle: textTheme.displayMedium), displaySmall: atkinsonHyperlegibleNext(textStyle: textTheme.displaySmall), - headlineLarge: atkinsonHyperlegibleNext( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: atkinsonHyperlegibleNext( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: atkinsonHyperlegibleNext( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: atkinsonHyperlegibleNext(textStyle: textTheme.headlineLarge), + headlineMedium: atkinsonHyperlegibleNext(textStyle: textTheme.headlineMedium), + headlineSmall: atkinsonHyperlegibleNext(textStyle: textTheme.headlineSmall), titleLarge: atkinsonHyperlegibleNext(textStyle: textTheme.titleLarge), titleMedium: atkinsonHyperlegibleNext(textStyle: textTheme.titleMedium), titleSmall: atkinsonHyperlegibleNext(textStyle: textTheme.titleSmall), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart index b949b17f1896..a742952e2e92 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_b.dart @@ -8203,9 +8203,7 @@ class PartB { displayMedium: bitcountGridDoubleInk(textStyle: textTheme.displayMedium), displaySmall: bitcountGridDoubleInk(textStyle: textTheme.displaySmall), headlineLarge: bitcountGridDoubleInk(textStyle: textTheme.headlineLarge), - headlineMedium: bitcountGridDoubleInk( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: bitcountGridDoubleInk(textStyle: textTheme.headlineMedium), headlineSmall: bitcountGridDoubleInk(textStyle: textTheme.headlineSmall), titleLarge: bitcountGridDoubleInk(textStyle: textTheme.titleLarge), titleMedium: bitcountGridDoubleInk(textStyle: textTheme.titleMedium), @@ -8491,9 +8489,7 @@ class PartB { displayMedium: bitcountGridSingleInk(textStyle: textTheme.displayMedium), displaySmall: bitcountGridSingleInk(textStyle: textTheme.displaySmall), headlineLarge: bitcountGridSingleInk(textStyle: textTheme.headlineLarge), - headlineMedium: bitcountGridSingleInk( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: bitcountGridSingleInk(textStyle: textTheme.headlineMedium), headlineSmall: bitcountGridSingleInk(textStyle: textTheme.headlineSmall), titleLarge: bitcountGridSingleInk(textStyle: textTheme.titleLarge), titleMedium: bitcountGridSingleInk(textStyle: textTheme.titleMedium), @@ -8922,9 +8918,7 @@ class PartB { displayMedium: bitcountPropDoubleInk(textStyle: textTheme.displayMedium), displaySmall: bitcountPropDoubleInk(textStyle: textTheme.displaySmall), headlineLarge: bitcountPropDoubleInk(textStyle: textTheme.headlineLarge), - headlineMedium: bitcountPropDoubleInk( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: bitcountPropDoubleInk(textStyle: textTheme.headlineMedium), headlineSmall: bitcountPropDoubleInk(textStyle: textTheme.headlineSmall), titleLarge: bitcountPropDoubleInk(textStyle: textTheme.titleLarge), titleMedium: bitcountPropDoubleInk(textStyle: textTheme.titleMedium), @@ -9210,9 +9204,7 @@ class PartB { displayMedium: bitcountPropSingleInk(textStyle: textTheme.displayMedium), displaySmall: bitcountPropSingleInk(textStyle: textTheme.displaySmall), headlineLarge: bitcountPropSingleInk(textStyle: textTheme.headlineLarge), - headlineMedium: bitcountPropSingleInk( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: bitcountPropSingleInk(textStyle: textTheme.headlineMedium), headlineSmall: bitcountPropSingleInk(textStyle: textTheme.headlineSmall), titleLarge: bitcountPropSingleInk(textStyle: textTheme.titleLarge), titleMedium: bitcountPropSingleInk(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart index efbfd5c817db..4b9acf7976ce 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_c.dart @@ -6404,9 +6404,7 @@ class PartC { displayMedium: chocolateClassicalSans(textStyle: textTheme.displayMedium), displaySmall: chocolateClassicalSans(textStyle: textTheme.displaySmall), headlineLarge: chocolateClassicalSans(textStyle: textTheme.headlineLarge), - headlineMedium: chocolateClassicalSans( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: chocolateClassicalSans(textStyle: textTheme.headlineMedium), headlineSmall: chocolateClassicalSans(textStyle: textTheme.headlineSmall), titleLarge: chocolateClassicalSans(textStyle: textTheme.titleLarge), titleMedium: chocolateClassicalSans(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart index c4a76084ef01..0e5e4a828691 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_f.dart @@ -2943,9 +2943,7 @@ class PartF { displayMedium: firaSansExtraCondensed(textStyle: textTheme.displayMedium), displaySmall: firaSansExtraCondensed(textStyle: textTheme.displaySmall), headlineLarge: firaSansExtraCondensed(textStyle: textTheme.headlineLarge), - headlineMedium: firaSansExtraCondensed( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: firaSansExtraCondensed(textStyle: textTheme.headlineMedium), headlineSmall: firaSansExtraCondensed(textStyle: textTheme.headlineSmall), titleLarge: firaSansExtraCondensed(textStyle: textTheme.titleLarge), titleMedium: firaSansExtraCondensed(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart index c26331424302..69edbe87c495 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_i.dart @@ -612,9 +612,7 @@ class PartI { displayMedium: ibmPlexSansDevanagari(textStyle: textTheme.displayMedium), displaySmall: ibmPlexSansDevanagari(textStyle: textTheme.displaySmall), headlineLarge: ibmPlexSansDevanagari(textStyle: textTheme.headlineLarge), - headlineMedium: ibmPlexSansDevanagari( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: ibmPlexSansDevanagari(textStyle: textTheme.headlineMedium), headlineSmall: ibmPlexSansDevanagari(textStyle: textTheme.headlineSmall), titleLarge: ibmPlexSansDevanagari(textStyle: textTheme.titleLarge), titleMedium: ibmPlexSansDevanagari(textStyle: textTheme.titleMedium), @@ -1259,9 +1257,7 @@ class PartI { displayMedium: ibmPlexSansThaiLooped(textStyle: textTheme.displayMedium), displaySmall: ibmPlexSansThaiLooped(textStyle: textTheme.displaySmall), headlineLarge: ibmPlexSansThaiLooped(textStyle: textTheme.headlineLarge), - headlineMedium: ibmPlexSansThaiLooped( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: ibmPlexSansThaiLooped(textStyle: textTheme.headlineMedium), headlineSmall: ibmPlexSansThaiLooped(textStyle: textTheme.headlineSmall), titleLarge: ibmPlexSansThaiLooped(textStyle: textTheme.titleLarge), titleMedium: ibmPlexSansThaiLooped(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart index 5fd34e9b9048..14bdb48ea24a 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_j.dart @@ -516,24 +516,12 @@ class PartJ { static TextTheme jacquardaBastarda9ChartedTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: jacquardaBastarda9Charted( - textStyle: textTheme.displayLarge, - ), - displayMedium: jacquardaBastarda9Charted( - textStyle: textTheme.displayMedium, - ), - displaySmall: jacquardaBastarda9Charted( - textStyle: textTheme.displaySmall, - ), - headlineLarge: jacquardaBastarda9Charted( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: jacquardaBastarda9Charted( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: jacquardaBastarda9Charted( - textStyle: textTheme.headlineSmall, - ), + displayLarge: jacquardaBastarda9Charted(textStyle: textTheme.displayLarge), + displayMedium: jacquardaBastarda9Charted(textStyle: textTheme.displayMedium), + displaySmall: jacquardaBastarda9Charted(textStyle: textTheme.displaySmall), + headlineLarge: jacquardaBastarda9Charted(textStyle: textTheme.headlineLarge), + headlineMedium: jacquardaBastarda9Charted(textStyle: textTheme.headlineMedium), + headlineSmall: jacquardaBastarda9Charted(textStyle: textTheme.headlineSmall), titleLarge: jacquardaBastarda9Charted(textStyle: textTheme.titleLarge), titleMedium: jacquardaBastarda9Charted(textStyle: textTheme.titleMedium), titleSmall: jacquardaBastarda9Charted(textStyle: textTheme.titleSmall), @@ -706,9 +694,7 @@ class PartJ { displayMedium: jacquesFrancoisShadow(textStyle: textTheme.displayMedium), displaySmall: jacquesFrancoisShadow(textStyle: textTheme.displaySmall), headlineLarge: jacquesFrancoisShadow(textStyle: textTheme.headlineLarge), - headlineMedium: jacquesFrancoisShadow( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: jacquesFrancoisShadow(textStyle: textTheme.headlineMedium), headlineSmall: jacquesFrancoisShadow(textStyle: textTheme.headlineSmall), titleLarge: jacquesFrancoisShadow(textStyle: textTheme.titleLarge), titleMedium: jacquesFrancoisShadow(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart index 1d6352735a25..5186f5faa655 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_l.dart @@ -4005,9 +4005,7 @@ class PartL { displayMedium: libertinusSerifDisplay(textStyle: textTheme.displayMedium), displaySmall: libertinusSerifDisplay(textStyle: textTheme.displaySmall), headlineLarge: libertinusSerifDisplay(textStyle: textTheme.headlineLarge), - headlineMedium: libertinusSerifDisplay( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: libertinusSerifDisplay(textStyle: textTheme.headlineMedium), headlineSmall: libertinusSerifDisplay(textStyle: textTheme.headlineSmall), titleLarge: libertinusSerifDisplay(textStyle: textTheme.titleLarge), titleMedium: libertinusSerifDisplay(textStyle: textTheme.titleMedium), @@ -4222,13 +4220,8 @@ class PartL { double? decorationThickness, }) { final fonts = { - const GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ): GoogleFontsFile( - 'a25d156d437de61fd0000652114599b4d454496b7c82a255a6c2ae7fce3052ab', - 7628, - ), + const GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal): + GoogleFontsFile('a25d156d437de61fd0000652114599b4d454496b7c82a255a6c2ae7fce3052ab', 7628), }; return googleFontsTextStyle( @@ -4355,9 +4348,7 @@ class PartL { displayMedium: libreBarcode39Extended(textStyle: textTheme.displayMedium), displaySmall: libreBarcode39Extended(textStyle: textTheme.displaySmall), headlineLarge: libreBarcode39Extended(textStyle: textTheme.headlineLarge), - headlineMedium: libreBarcode39Extended( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: libreBarcode39Extended(textStyle: textTheme.headlineMedium), headlineSmall: libreBarcode39Extended(textStyle: textTheme.headlineSmall), titleLarge: libreBarcode39Extended(textStyle: textTheme.titleLarge), titleMedium: libreBarcode39Extended(textStyle: textTheme.titleMedium), @@ -4440,24 +4431,12 @@ class PartL { static TextTheme libreBarcode39ExtendedTextTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: libreBarcode39ExtendedText( - textStyle: textTheme.displayLarge, - ), - displayMedium: libreBarcode39ExtendedText( - textStyle: textTheme.displayMedium, - ), - displaySmall: libreBarcode39ExtendedText( - textStyle: textTheme.displaySmall, - ), - headlineLarge: libreBarcode39ExtendedText( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: libreBarcode39ExtendedText( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: libreBarcode39ExtendedText( - textStyle: textTheme.headlineSmall, - ), + displayLarge: libreBarcode39ExtendedText(textStyle: textTheme.displayLarge), + displayMedium: libreBarcode39ExtendedText(textStyle: textTheme.displayMedium), + displaySmall: libreBarcode39ExtendedText(textStyle: textTheme.displaySmall), + headlineLarge: libreBarcode39ExtendedText(textStyle: textTheme.headlineLarge), + headlineMedium: libreBarcode39ExtendedText(textStyle: textTheme.headlineMedium), + headlineSmall: libreBarcode39ExtendedText(textStyle: textTheme.headlineSmall), titleLarge: libreBarcode39ExtendedText(textStyle: textTheme.titleLarge), titleMedium: libreBarcode39ExtendedText(textStyle: textTheme.titleMedium), titleSmall: libreBarcode39ExtendedText(textStyle: textTheme.titleSmall), @@ -4630,9 +4609,7 @@ class PartL { displayMedium: libreBarcodeEan13Text(textStyle: textTheme.displayMedium), displaySmall: libreBarcodeEan13Text(textStyle: textTheme.displaySmall), headlineLarge: libreBarcodeEan13Text(textStyle: textTheme.headlineLarge), - headlineMedium: libreBarcodeEan13Text( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: libreBarcodeEan13Text(textStyle: textTheme.headlineMedium), headlineSmall: libreBarcodeEan13Text(textStyle: textTheme.headlineSmall), titleLarge: libreBarcodeEan13Text(textStyle: textTheme.titleLarge), titleMedium: libreBarcodeEan13Text(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart index 0eaeb66d4029..194b71adaf6f 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_n.dart @@ -4332,9 +4332,7 @@ class PartN { displayMedium: notoSansAdlamUnjoined(textStyle: textTheme.displayMedium), displaySmall: notoSansAdlamUnjoined(textStyle: textTheme.displaySmall), headlineLarge: notoSansAdlamUnjoined(textStyle: textTheme.headlineLarge), - headlineMedium: notoSansAdlamUnjoined( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: notoSansAdlamUnjoined(textStyle: textTheme.headlineMedium), headlineSmall: notoSansAdlamUnjoined(textStyle: textTheme.headlineSmall), titleLarge: notoSansAdlamUnjoined(textStyle: textTheme.titleLarge), titleMedium: notoSansAdlamUnjoined(textStyle: textTheme.titleMedium), @@ -4414,41 +4412,23 @@ class PartN { /// /// See: /// * https://fonts.google.com/specimen/Noto+Sans+Anatolian+Hieroglyphs - static TextTheme notoSansAnatolianHieroglyphsTextTheme([ - TextTheme? textTheme, - ]) { + static TextTheme notoSansAnatolianHieroglyphsTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSansAnatolianHieroglyphs( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSansAnatolianHieroglyphs( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSansAnatolianHieroglyphs( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSansAnatolianHieroglyphs( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansAnatolianHieroglyphs( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansAnatolianHieroglyphs( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.displayLarge), + displayMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.displayMedium), + displaySmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.displaySmall), + headlineLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.headlineSmall), titleLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.titleLarge), - titleMedium: notoSansAnatolianHieroglyphs( - textStyle: textTheme.titleMedium, - ), + titleMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.titleMedium), titleSmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.titleSmall), bodyLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.bodyLarge), bodyMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.bodyMedium), bodySmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.bodySmall), labelLarge: notoSansAnatolianHieroglyphs(textStyle: textTheme.labelLarge), - labelMedium: notoSansAnatolianHieroglyphs( - textStyle: textTheme.labelMedium, - ), + labelMedium: notoSansAnatolianHieroglyphs(textStyle: textTheme.labelMedium), labelSmall: notoSansAnatolianHieroglyphs(textStyle: textTheme.labelSmall), ); } @@ -5853,24 +5833,12 @@ class PartN { static TextTheme notoSansCanadianAboriginalTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSansCanadianAboriginal( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSansCanadianAboriginal( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSansCanadianAboriginal( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSansCanadianAboriginal( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansCanadianAboriginal( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansCanadianAboriginal( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoSansCanadianAboriginal(textStyle: textTheme.displayLarge), + displayMedium: notoSansCanadianAboriginal(textStyle: textTheme.displayMedium), + displaySmall: notoSansCanadianAboriginal(textStyle: textTheme.displaySmall), + headlineLarge: notoSansCanadianAboriginal(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansCanadianAboriginal(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansCanadianAboriginal(textStyle: textTheme.headlineSmall), titleLarge: notoSansCanadianAboriginal(textStyle: textTheme.titleLarge), titleMedium: notoSansCanadianAboriginal(textStyle: textTheme.titleMedium), titleSmall: notoSansCanadianAboriginal(textStyle: textTheme.titleSmall), @@ -6039,24 +6007,12 @@ class PartN { static TextTheme notoSansCaucasianAlbanianTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSansCaucasianAlbanian( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSansCaucasianAlbanian( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSansCaucasianAlbanian( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSansCaucasianAlbanian( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansCaucasianAlbanian( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansCaucasianAlbanian( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoSansCaucasianAlbanian(textStyle: textTheme.displayLarge), + displayMedium: notoSansCaucasianAlbanian(textStyle: textTheme.displayMedium), + displaySmall: notoSansCaucasianAlbanian(textStyle: textTheme.displaySmall), + headlineLarge: notoSansCaucasianAlbanian(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansCaucasianAlbanian(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansCaucasianAlbanian(textStyle: textTheme.headlineSmall), titleLarge: notoSansCaucasianAlbanian(textStyle: textTheme.titleLarge), titleMedium: notoSansCaucasianAlbanian(textStyle: textTheme.titleMedium), titleSmall: notoSansCaucasianAlbanian(textStyle: textTheme.titleSmall), @@ -7473,41 +7429,23 @@ class PartN { /// /// See: /// * https://fonts.google.com/specimen/Noto+Sans+Egyptian+Hieroglyphs - static TextTheme notoSansEgyptianHieroglyphsTextTheme([ - TextTheme? textTheme, - ]) { + static TextTheme notoSansEgyptianHieroglyphsTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSansEgyptianHieroglyphs( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSansEgyptianHieroglyphs( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSansEgyptianHieroglyphs( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSansEgyptianHieroglyphs( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansEgyptianHieroglyphs( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansEgyptianHieroglyphs( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.displayLarge), + displayMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.displayMedium), + displaySmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.displaySmall), + headlineLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.headlineSmall), titleLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.titleLarge), - titleMedium: notoSansEgyptianHieroglyphs( - textStyle: textTheme.titleMedium, - ), + titleMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.titleMedium), titleSmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.titleSmall), bodyLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.bodyLarge), bodyMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.bodyMedium), bodySmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.bodySmall), labelLarge: notoSansEgyptianHieroglyphs(textStyle: textTheme.labelLarge), - labelMedium: notoSansEgyptianHieroglyphs( - textStyle: textTheme.labelMedium, - ), + labelMedium: notoSansEgyptianHieroglyphs(textStyle: textTheme.labelMedium), labelSmall: notoSansEgyptianHieroglyphs(textStyle: textTheme.labelSmall), ); } @@ -8864,9 +8802,7 @@ class PartN { displayMedium: notoSansHanifiRohingya(textStyle: textTheme.displayMedium), displaySmall: notoSansHanifiRohingya(textStyle: textTheme.displaySmall), headlineLarge: notoSansHanifiRohingya(textStyle: textTheme.headlineLarge), - headlineMedium: notoSansHanifiRohingya( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: notoSansHanifiRohingya(textStyle: textTheme.headlineMedium), headlineSmall: notoSansHanifiRohingya(textStyle: textTheme.headlineSmall), titleLarge: notoSansHanifiRohingya(textStyle: textTheme.titleLarge), titleMedium: notoSansHanifiRohingya(textStyle: textTheme.titleMedium), @@ -9267,19 +9203,11 @@ class PartN { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: notoSansImperialAramaic(textStyle: textTheme.displayLarge), - displayMedium: notoSansImperialAramaic( - textStyle: textTheme.displayMedium, - ), + displayMedium: notoSansImperialAramaic(textStyle: textTheme.displayMedium), displaySmall: notoSansImperialAramaic(textStyle: textTheme.displaySmall), - headlineLarge: notoSansImperialAramaic( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansImperialAramaic( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansImperialAramaic( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: notoSansImperialAramaic(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansImperialAramaic(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansImperialAramaic(textStyle: textTheme.headlineSmall), titleLarge: notoSansImperialAramaic(textStyle: textTheme.titleLarge), titleMedium: notoSansImperialAramaic(textStyle: textTheme.titleMedium), titleSmall: notoSansImperialAramaic(textStyle: textTheme.titleSmall), @@ -9361,24 +9289,12 @@ class PartN { static TextTheme notoSansIndicSiyaqNumbersTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSansIndicSiyaqNumbers( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSansIndicSiyaqNumbers( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSansIndicSiyaqNumbers( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSansIndicSiyaqNumbers( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansIndicSiyaqNumbers( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansIndicSiyaqNumbers( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoSansIndicSiyaqNumbers(textStyle: textTheme.displayLarge), + displayMedium: notoSansIndicSiyaqNumbers(textStyle: textTheme.displayMedium), + displaySmall: notoSansIndicSiyaqNumbers(textStyle: textTheme.displaySmall), + headlineLarge: notoSansIndicSiyaqNumbers(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansIndicSiyaqNumbers(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansIndicSiyaqNumbers(textStyle: textTheme.headlineSmall), titleLarge: notoSansIndicSiyaqNumbers(textStyle: textTheme.titleLarge), titleMedium: notoSansIndicSiyaqNumbers(textStyle: textTheme.titleMedium), titleSmall: notoSansIndicSiyaqNumbers(textStyle: textTheme.titleSmall), @@ -9457,41 +9373,23 @@ class PartN { /// /// See: /// * https://fonts.google.com/specimen/Noto+Sans+Inscriptional+Pahlavi - static TextTheme notoSansInscriptionalPahlaviTextTheme([ - TextTheme? textTheme, - ]) { + static TextTheme notoSansInscriptionalPahlaviTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSansInscriptionalPahlavi( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSansInscriptionalPahlavi( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSansInscriptionalPahlavi( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSansInscriptionalPahlavi( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansInscriptionalPahlavi( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansInscriptionalPahlavi( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.displayLarge), + displayMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.displayMedium), + displaySmall: notoSansInscriptionalPahlavi(textStyle: textTheme.displaySmall), + headlineLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansInscriptionalPahlavi(textStyle: textTheme.headlineSmall), titleLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.titleLarge), - titleMedium: notoSansInscriptionalPahlavi( - textStyle: textTheme.titleMedium, - ), + titleMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.titleMedium), titleSmall: notoSansInscriptionalPahlavi(textStyle: textTheme.titleSmall), bodyLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.bodyLarge), bodyMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.bodyMedium), bodySmall: notoSansInscriptionalPahlavi(textStyle: textTheme.bodySmall), labelLarge: notoSansInscriptionalPahlavi(textStyle: textTheme.labelLarge), - labelMedium: notoSansInscriptionalPahlavi( - textStyle: textTheme.labelMedium, - ), + labelMedium: notoSansInscriptionalPahlavi(textStyle: textTheme.labelMedium), labelSmall: notoSansInscriptionalPahlavi(textStyle: textTheme.labelSmall), ); } @@ -9562,52 +9460,24 @@ class PartN { /// /// See: /// * https://fonts.google.com/specimen/Noto+Sans+Inscriptional+Parthian - static TextTheme notoSansInscriptionalParthianTextTheme([ - TextTheme? textTheme, - ]) { + static TextTheme notoSansInscriptionalParthianTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSansInscriptionalParthian( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSansInscriptionalParthian( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSansInscriptionalParthian( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSansInscriptionalParthian( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansInscriptionalParthian( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansInscriptionalParthian( - textStyle: textTheme.headlineSmall, - ), - titleLarge: notoSansInscriptionalParthian( - textStyle: textTheme.titleLarge, - ), - titleMedium: notoSansInscriptionalParthian( - textStyle: textTheme.titleMedium, - ), - titleSmall: notoSansInscriptionalParthian( - textStyle: textTheme.titleSmall, - ), + displayLarge: notoSansInscriptionalParthian(textStyle: textTheme.displayLarge), + displayMedium: notoSansInscriptionalParthian(textStyle: textTheme.displayMedium), + displaySmall: notoSansInscriptionalParthian(textStyle: textTheme.displaySmall), + headlineLarge: notoSansInscriptionalParthian(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansInscriptionalParthian(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansInscriptionalParthian(textStyle: textTheme.headlineSmall), + titleLarge: notoSansInscriptionalParthian(textStyle: textTheme.titleLarge), + titleMedium: notoSansInscriptionalParthian(textStyle: textTheme.titleMedium), + titleSmall: notoSansInscriptionalParthian(textStyle: textTheme.titleSmall), bodyLarge: notoSansInscriptionalParthian(textStyle: textTheme.bodyLarge), - bodyMedium: notoSansInscriptionalParthian( - textStyle: textTheme.bodyMedium, - ), + bodyMedium: notoSansInscriptionalParthian(textStyle: textTheme.bodyMedium), bodySmall: notoSansInscriptionalParthian(textStyle: textTheme.bodySmall), - labelLarge: notoSansInscriptionalParthian( - textStyle: textTheme.labelLarge, - ), - labelMedium: notoSansInscriptionalParthian( - textStyle: textTheme.labelMedium, - ), - labelSmall: notoSansInscriptionalParthian( - textStyle: textTheme.labelSmall, - ), + labelLarge: notoSansInscriptionalParthian(textStyle: textTheme.labelLarge), + labelMedium: notoSansInscriptionalParthian(textStyle: textTheme.labelMedium), + labelSmall: notoSansInscriptionalParthian(textStyle: textTheme.labelSmall), ); } @@ -11624,13 +11494,8 @@ class PartN { double? decorationThickness, }) { final fonts = { - const GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ): GoogleFontsFile( - '75575abbe344a6327d36709c771ce18f37609a7875a1486bf4e9eda959d814ee', - 3380, - ), + const GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal): + GoogleFontsFile('75575abbe344a6327d36709c771ce18f37609a7875a1486bf4e9eda959d814ee', 3380), }; return googleFontsTextStyle( @@ -12509,9 +12374,7 @@ class PartN { displayMedium: notoSansMayanNumerals(textStyle: textTheme.displayMedium), displaySmall: notoSansMayanNumerals(textStyle: textTheme.displaySmall), headlineLarge: notoSansMayanNumerals(textStyle: textTheme.headlineLarge), - headlineMedium: notoSansMayanNumerals( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: notoSansMayanNumerals(textStyle: textTheme.headlineMedium), headlineSmall: notoSansMayanNumerals(textStyle: textTheme.headlineSmall), titleLarge: notoSansMayanNumerals(textStyle: textTheme.titleLarge), titleMedium: notoSansMayanNumerals(textStyle: textTheme.titleMedium), @@ -14869,19 +14732,11 @@ class PartN { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: notoSansOldNorthArabian(textStyle: textTheme.displayLarge), - displayMedium: notoSansOldNorthArabian( - textStyle: textTheme.displayMedium, - ), + displayMedium: notoSansOldNorthArabian(textStyle: textTheme.displayMedium), displaySmall: notoSansOldNorthArabian(textStyle: textTheme.displaySmall), - headlineLarge: notoSansOldNorthArabian( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansOldNorthArabian( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansOldNorthArabian( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: notoSansOldNorthArabian(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansOldNorthArabian(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansOldNorthArabian(textStyle: textTheme.headlineSmall), titleLarge: notoSansOldNorthArabian(textStyle: textTheme.titleLarge), titleMedium: notoSansOldNorthArabian(textStyle: textTheme.titleMedium), titleSmall: notoSansOldNorthArabian(textStyle: textTheme.titleSmall), @@ -15225,19 +15080,11 @@ class PartN { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: notoSansOldSouthArabian(textStyle: textTheme.displayLarge), - displayMedium: notoSansOldSouthArabian( - textStyle: textTheme.displayMedium, - ), + displayMedium: notoSansOldSouthArabian(textStyle: textTheme.displayMedium), displaySmall: notoSansOldSouthArabian(textStyle: textTheme.displaySmall), - headlineLarge: notoSansOldSouthArabian( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansOldSouthArabian( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansOldSouthArabian( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: notoSansOldSouthArabian(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansOldSouthArabian(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansOldSouthArabian(textStyle: textTheme.headlineSmall), titleLarge: notoSansOldSouthArabian(textStyle: textTheme.titleLarge), titleMedium: notoSansOldSouthArabian(textStyle: textTheme.titleMedium), titleSmall: notoSansOldSouthArabian(textStyle: textTheme.titleSmall), @@ -16162,9 +16009,7 @@ class PartN { displayMedium: notoSansPsalterPahlavi(textStyle: textTheme.displayMedium), displaySmall: notoSansPsalterPahlavi(textStyle: textTheme.displaySmall), headlineLarge: notoSansPsalterPahlavi(textStyle: textTheme.headlineLarge), - headlineMedium: notoSansPsalterPahlavi( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: notoSansPsalterPahlavi(textStyle: textTheme.headlineMedium), headlineSmall: notoSansPsalterPahlavi(textStyle: textTheme.headlineSmall), titleLarge: notoSansPsalterPahlavi(textStyle: textTheme.titleLarge), titleMedium: notoSansPsalterPahlavi(textStyle: textTheme.titleMedium), @@ -18226,9 +18071,7 @@ class PartN { displayMedium: notoSansSyriacEastern(textStyle: textTheme.displayMedium), displaySmall: notoSansSyriacEastern(textStyle: textTheme.displaySmall), headlineLarge: notoSansSyriacEastern(textStyle: textTheme.headlineLarge), - headlineMedium: notoSansSyriacEastern( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: notoSansSyriacEastern(textStyle: textTheme.headlineMedium), headlineSmall: notoSansSyriacEastern(textStyle: textTheme.headlineSmall), titleLarge: notoSansSyriacEastern(textStyle: textTheme.titleLarge), titleMedium: notoSansSyriacEastern(textStyle: textTheme.titleMedium), @@ -18371,9 +18214,7 @@ class PartN { displayMedium: notoSansSyriacWestern(textStyle: textTheme.displayMedium), displaySmall: notoSansSyriacWestern(textStyle: textTheme.displaySmall), headlineLarge: notoSansSyriacWestern(textStyle: textTheme.headlineLarge), - headlineMedium: notoSansSyriacWestern( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: notoSansSyriacWestern(textStyle: textTheme.headlineMedium), headlineSmall: notoSansSyriacWestern(textStyle: textTheme.headlineSmall), titleLarge: notoSansSyriacWestern(textStyle: textTheme.titleLarge), titleMedium: notoSansSyriacWestern(textStyle: textTheme.titleMedium), @@ -19286,19 +19127,11 @@ class PartN { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: notoSansTamilSupplement(textStyle: textTheme.displayLarge), - displayMedium: notoSansTamilSupplement( - textStyle: textTheme.displayMedium, - ), + displayMedium: notoSansTamilSupplement(textStyle: textTheme.displayMedium), displaySmall: notoSansTamilSupplement(textStyle: textTheme.displaySmall), - headlineLarge: notoSansTamilSupplement( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansTamilSupplement( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansTamilSupplement( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: notoSansTamilSupplement(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansTamilSupplement(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansTamilSupplement(textStyle: textTheme.headlineSmall), titleLarge: notoSansTamilSupplement(textStyle: textTheme.titleLarge), titleMedium: notoSansTamilSupplement(textStyle: textTheme.titleMedium), titleSmall: notoSansTamilSupplement(textStyle: textTheme.titleSmall), @@ -20778,19 +20611,11 @@ class PartN { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: notoSansZanabazarSquare(textStyle: textTheme.displayLarge), - displayMedium: notoSansZanabazarSquare( - textStyle: textTheme.displayMedium, - ), + displayMedium: notoSansZanabazarSquare(textStyle: textTheme.displayMedium), displaySmall: notoSansZanabazarSquare(textStyle: textTheme.displaySmall), - headlineLarge: notoSansZanabazarSquare( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSansZanabazarSquare( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSansZanabazarSquare( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: notoSansZanabazarSquare(textStyle: textTheme.headlineLarge), + headlineMedium: notoSansZanabazarSquare(textStyle: textTheme.headlineMedium), + headlineSmall: notoSansZanabazarSquare(textStyle: textTheme.headlineSmall), titleLarge: notoSansZanabazarSquare(textStyle: textTheme.titleLarge), titleMedium: notoSansZanabazarSquare(textStyle: textTheme.titleMedium), titleSmall: notoSansZanabazarSquare(textStyle: textTheme.titleSmall), @@ -23550,24 +23375,12 @@ class PartN { static TextTheme notoSerifKhitanSmallScriptTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoSerifKhitanSmallScript( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoSerifKhitanSmallScript( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoSerifKhitanSmallScript( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoSerifKhitanSmallScript( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoSerifKhitanSmallScript( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoSerifKhitanSmallScript( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoSerifKhitanSmallScript(textStyle: textTheme.displayLarge), + displayMedium: notoSerifKhitanSmallScript(textStyle: textTheme.displayMedium), + displaySmall: notoSerifKhitanSmallScript(textStyle: textTheme.displaySmall), + headlineLarge: notoSerifKhitanSmallScript(textStyle: textTheme.headlineLarge), + headlineMedium: notoSerifKhitanSmallScript(textStyle: textTheme.headlineMedium), + headlineSmall: notoSerifKhitanSmallScript(textStyle: textTheme.headlineSmall), titleLarge: notoSerifKhitanSmallScript(textStyle: textTheme.titleLarge), titleMedium: notoSerifKhitanSmallScript(textStyle: textTheme.titleMedium), titleSmall: notoSerifKhitanSmallScript(textStyle: textTheme.titleSmall), @@ -24723,9 +24536,7 @@ class PartN { displayMedium: notoSerifOttomanSiyaq(textStyle: textTheme.displayMedium), displaySmall: notoSerifOttomanSiyaq(textStyle: textTheme.displaySmall), headlineLarge: notoSerifOttomanSiyaq(textStyle: textTheme.headlineLarge), - headlineMedium: notoSerifOttomanSiyaq( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: notoSerifOttomanSiyaq(textStyle: textTheme.headlineMedium), headlineSmall: notoSerifOttomanSiyaq(textStyle: textTheme.headlineSmall), titleLarge: notoSerifOttomanSiyaq(textStyle: textTheme.titleLarge), titleMedium: notoSerifOttomanSiyaq(textStyle: textTheme.titleMedium), @@ -26468,41 +26279,23 @@ class PartN { /// /// See: /// * https://fonts.google.com/specimen/Noto+Znamenny+Musical+Notation - static TextTheme notoZnamennyMusicalNotationTextTheme([ - TextTheme? textTheme, - ]) { + static TextTheme notoZnamennyMusicalNotationTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: notoZnamennyMusicalNotation( - textStyle: textTheme.displayLarge, - ), - displayMedium: notoZnamennyMusicalNotation( - textStyle: textTheme.displayMedium, - ), - displaySmall: notoZnamennyMusicalNotation( - textStyle: textTheme.displaySmall, - ), - headlineLarge: notoZnamennyMusicalNotation( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: notoZnamennyMusicalNotation( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: notoZnamennyMusicalNotation( - textStyle: textTheme.headlineSmall, - ), + displayLarge: notoZnamennyMusicalNotation(textStyle: textTheme.displayLarge), + displayMedium: notoZnamennyMusicalNotation(textStyle: textTheme.displayMedium), + displaySmall: notoZnamennyMusicalNotation(textStyle: textTheme.displaySmall), + headlineLarge: notoZnamennyMusicalNotation(textStyle: textTheme.headlineLarge), + headlineMedium: notoZnamennyMusicalNotation(textStyle: textTheme.headlineMedium), + headlineSmall: notoZnamennyMusicalNotation(textStyle: textTheme.headlineSmall), titleLarge: notoZnamennyMusicalNotation(textStyle: textTheme.titleLarge), - titleMedium: notoZnamennyMusicalNotation( - textStyle: textTheme.titleMedium, - ), + titleMedium: notoZnamennyMusicalNotation(textStyle: textTheme.titleMedium), titleSmall: notoZnamennyMusicalNotation(textStyle: textTheme.titleSmall), bodyLarge: notoZnamennyMusicalNotation(textStyle: textTheme.bodyLarge), bodyMedium: notoZnamennyMusicalNotation(textStyle: textTheme.bodyMedium), bodySmall: notoZnamennyMusicalNotation(textStyle: textTheme.bodySmall), labelLarge: notoZnamennyMusicalNotation(textStyle: textTheme.labelLarge), - labelMedium: notoZnamennyMusicalNotation( - textStyle: textTheme.labelMedium, - ), + labelMedium: notoZnamennyMusicalNotation(textStyle: textTheme.labelMedium), labelSmall: notoZnamennyMusicalNotation(textStyle: textTheme.labelSmall), ); } diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart index 9f1ddca3d28e..f32788fc9321 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_p.dart @@ -9034,9 +9034,7 @@ class PartP { displayMedium: playwriteDeGrundGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteDeGrundGuides(textStyle: textTheme.displaySmall), headlineLarge: playwriteDeGrundGuides(textStyle: textTheme.headlineLarge), - headlineMedium: playwriteDeGrundGuides( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: playwriteDeGrundGuides(textStyle: textTheme.headlineMedium), headlineSmall: playwriteDeGrundGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteDeGrundGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteDeGrundGuides(textStyle: textTheme.titleMedium), @@ -9813,19 +9811,11 @@ class PartP { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: playwriteDkLoopetGuides(textStyle: textTheme.displayLarge), - displayMedium: playwriteDkLoopetGuides( - textStyle: textTheme.displayMedium, - ), + displayMedium: playwriteDkLoopetGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteDkLoopetGuides(textStyle: textTheme.displaySmall), - headlineLarge: playwriteDkLoopetGuides( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: playwriteDkLoopetGuides( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: playwriteDkLoopetGuides( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: playwriteDkLoopetGuides(textStyle: textTheme.headlineLarge), + headlineMedium: playwriteDkLoopetGuides(textStyle: textTheme.headlineMedium), + headlineSmall: playwriteDkLoopetGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteDkLoopetGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteDkLoopetGuides(textStyle: textTheme.titleMedium), titleSmall: playwriteDkLoopetGuides(textStyle: textTheme.titleSmall), @@ -10016,19 +10006,11 @@ class PartP { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: playwriteDkUloopetGuides(textStyle: textTheme.displayLarge), - displayMedium: playwriteDkUloopetGuides( - textStyle: textTheme.displayMedium, - ), + displayMedium: playwriteDkUloopetGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteDkUloopetGuides(textStyle: textTheme.displaySmall), - headlineLarge: playwriteDkUloopetGuides( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: playwriteDkUloopetGuides( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: playwriteDkUloopetGuides( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: playwriteDkUloopetGuides(textStyle: textTheme.headlineLarge), + headlineMedium: playwriteDkUloopetGuides(textStyle: textTheme.headlineMedium), + headlineSmall: playwriteDkUloopetGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteDkUloopetGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteDkUloopetGuides(textStyle: textTheme.titleMedium), titleSmall: playwriteDkUloopetGuides(textStyle: textTheme.titleSmall), @@ -10330,9 +10312,7 @@ class PartP { displayMedium: playwriteEsDecoGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteEsDecoGuides(textStyle: textTheme.displaySmall), headlineLarge: playwriteEsDecoGuides(textStyle: textTheme.headlineLarge), - headlineMedium: playwriteEsDecoGuides( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: playwriteEsDecoGuides(textStyle: textTheme.headlineMedium), headlineSmall: playwriteEsDecoGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteEsDecoGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteEsDecoGuides(textStyle: textTheme.titleMedium), @@ -10611,19 +10591,11 @@ class PartP { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: playwriteFrModerneGuides(textStyle: textTheme.displayLarge), - displayMedium: playwriteFrModerneGuides( - textStyle: textTheme.displayMedium, - ), + displayMedium: playwriteFrModerneGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteFrModerneGuides(textStyle: textTheme.displaySmall), - headlineLarge: playwriteFrModerneGuides( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: playwriteFrModerneGuides( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: playwriteFrModerneGuides( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: playwriteFrModerneGuides(textStyle: textTheme.headlineLarge), + headlineMedium: playwriteFrModerneGuides(textStyle: textTheme.headlineMedium), + headlineSmall: playwriteFrModerneGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteFrModerneGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteFrModerneGuides(textStyle: textTheme.titleMedium), titleSmall: playwriteFrModerneGuides(textStyle: textTheme.titleSmall), @@ -10817,9 +10789,7 @@ class PartP { displayMedium: playwriteFrTradGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteFrTradGuides(textStyle: textTheme.displaySmall), headlineLarge: playwriteFrTradGuides(textStyle: textTheme.headlineLarge), - headlineMedium: playwriteFrTradGuides( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: playwriteFrTradGuides(textStyle: textTheme.headlineMedium), headlineSmall: playwriteFrTradGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteFrTradGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteFrTradGuides(textStyle: textTheme.titleMedium), @@ -11666,19 +11636,11 @@ class PartP { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: playwriteHrLijevaGuides(textStyle: textTheme.displayLarge), - displayMedium: playwriteHrLijevaGuides( - textStyle: textTheme.displayMedium, - ), + displayMedium: playwriteHrLijevaGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteHrLijevaGuides(textStyle: textTheme.displaySmall), - headlineLarge: playwriteHrLijevaGuides( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: playwriteHrLijevaGuides( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: playwriteHrLijevaGuides( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: playwriteHrLijevaGuides(textStyle: textTheme.headlineLarge), + headlineMedium: playwriteHrLijevaGuides(textStyle: textTheme.headlineMedium), + headlineSmall: playwriteHrLijevaGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteHrLijevaGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteHrLijevaGuides(textStyle: textTheme.titleMedium), titleSmall: playwriteHrLijevaGuides(textStyle: textTheme.titleSmall), @@ -12844,19 +12806,11 @@ class PartP { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: playwriteItModernaGuides(textStyle: textTheme.displayLarge), - displayMedium: playwriteItModernaGuides( - textStyle: textTheme.displayMedium, - ), + displayMedium: playwriteItModernaGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteItModernaGuides(textStyle: textTheme.displaySmall), - headlineLarge: playwriteItModernaGuides( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: playwriteItModernaGuides( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: playwriteItModernaGuides( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: playwriteItModernaGuides(textStyle: textTheme.headlineLarge), + headlineMedium: playwriteItModernaGuides(textStyle: textTheme.headlineMedium), + headlineSmall: playwriteItModernaGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteItModernaGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteItModernaGuides(textStyle: textTheme.titleMedium), titleSmall: playwriteItModernaGuides(textStyle: textTheme.titleSmall), @@ -13050,9 +13004,7 @@ class PartP { displayMedium: playwriteItTradGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteItTradGuides(textStyle: textTheme.displaySmall), headlineLarge: playwriteItTradGuides(textStyle: textTheme.headlineLarge), - headlineMedium: playwriteItTradGuides( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: playwriteItTradGuides(textStyle: textTheme.headlineMedium), headlineSmall: playwriteItTradGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteItTradGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteItTradGuides(textStyle: textTheme.titleMedium), @@ -13439,19 +13391,11 @@ class PartP { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: playwriteNgModernGuides(textStyle: textTheme.displayLarge), - displayMedium: playwriteNgModernGuides( - textStyle: textTheme.displayMedium, - ), + displayMedium: playwriteNgModernGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteNgModernGuides(textStyle: textTheme.displaySmall), - headlineLarge: playwriteNgModernGuides( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: playwriteNgModernGuides( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: playwriteNgModernGuides( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: playwriteNgModernGuides(textStyle: textTheme.headlineLarge), + headlineMedium: playwriteNgModernGuides(textStyle: textTheme.headlineMedium), + headlineSmall: playwriteNgModernGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteNgModernGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteNgModernGuides(textStyle: textTheme.titleMedium), titleSmall: playwriteNgModernGuides(textStyle: textTheme.titleSmall), @@ -15397,19 +15341,11 @@ class PartP { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: playwriteUsModernGuides(textStyle: textTheme.displayLarge), - displayMedium: playwriteUsModernGuides( - textStyle: textTheme.displayMedium, - ), + displayMedium: playwriteUsModernGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteUsModernGuides(textStyle: textTheme.displaySmall), - headlineLarge: playwriteUsModernGuides( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: playwriteUsModernGuides( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: playwriteUsModernGuides( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: playwriteUsModernGuides(textStyle: textTheme.headlineLarge), + headlineMedium: playwriteUsModernGuides(textStyle: textTheme.headlineMedium), + headlineSmall: playwriteUsModernGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteUsModernGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteUsModernGuides(textStyle: textTheme.titleMedium), titleSmall: playwriteUsModernGuides(textStyle: textTheme.titleSmall), @@ -15603,9 +15539,7 @@ class PartP { displayMedium: playwriteUsTradGuides(textStyle: textTheme.displayMedium), displaySmall: playwriteUsTradGuides(textStyle: textTheme.displaySmall), headlineLarge: playwriteUsTradGuides(textStyle: textTheme.headlineLarge), - headlineMedium: playwriteUsTradGuides( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: playwriteUsTradGuides(textStyle: textTheme.headlineMedium), headlineSmall: playwriteUsTradGuides(textStyle: textTheme.headlineSmall), titleLarge: playwriteUsTradGuides(textStyle: textTheme.titleLarge), titleMedium: playwriteUsTradGuides(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart index 91bedcaf13cb..b79113732ab7 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_s.dart @@ -9404,19 +9404,11 @@ class PartS { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: sofiaSansExtraCondensed(textStyle: textTheme.displayLarge), - displayMedium: sofiaSansExtraCondensed( - textStyle: textTheme.displayMedium, - ), + displayMedium: sofiaSansExtraCondensed(textStyle: textTheme.displayMedium), displaySmall: sofiaSansExtraCondensed(textStyle: textTheme.displaySmall), - headlineLarge: sofiaSansExtraCondensed( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: sofiaSansExtraCondensed( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: sofiaSansExtraCondensed( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: sofiaSansExtraCondensed(textStyle: textTheme.headlineLarge), + headlineMedium: sofiaSansExtraCondensed(textStyle: textTheme.headlineMedium), + headlineSmall: sofiaSansExtraCondensed(textStyle: textTheme.headlineSmall), titleLarge: sofiaSansExtraCondensed(textStyle: textTheme.titleLarge), titleMedium: sofiaSansExtraCondensed(textStyle: textTheme.titleMedium), titleSmall: sofiaSansExtraCondensed(textStyle: textTheme.titleSmall), @@ -9621,9 +9613,7 @@ class PartS { displayMedium: sofiaSansSemiCondensed(textStyle: textTheme.displayMedium), displaySmall: sofiaSansSemiCondensed(textStyle: textTheme.displaySmall), headlineLarge: sofiaSansSemiCondensed(textStyle: textTheme.headlineLarge), - headlineMedium: sofiaSansSemiCondensed( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: sofiaSansSemiCondensed(textStyle: textTheme.headlineMedium), headlineSmall: sofiaSansSemiCondensed(textStyle: textTheme.headlineSmall), titleLarge: sofiaSansSemiCondensed(textStyle: textTheme.titleLarge), titleMedium: sofiaSansSemiCondensed(textStyle: textTheme.titleMedium), @@ -11777,24 +11767,12 @@ class PartS { static TextTheme specialGothicCondensedOneTextTheme([TextTheme? textTheme]) { textTheme ??= ThemeData.light().textTheme; return TextTheme( - displayLarge: specialGothicCondensedOne( - textStyle: textTheme.displayLarge, - ), - displayMedium: specialGothicCondensedOne( - textStyle: textTheme.displayMedium, - ), - displaySmall: specialGothicCondensedOne( - textStyle: textTheme.displaySmall, - ), - headlineLarge: specialGothicCondensedOne( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: specialGothicCondensedOne( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: specialGothicCondensedOne( - textStyle: textTheme.headlineSmall, - ), + displayLarge: specialGothicCondensedOne(textStyle: textTheme.displayLarge), + displayMedium: specialGothicCondensedOne(textStyle: textTheme.displayMedium), + displaySmall: specialGothicCondensedOne(textStyle: textTheme.displaySmall), + headlineLarge: specialGothicCondensedOne(textStyle: textTheme.headlineLarge), + headlineMedium: specialGothicCondensedOne(textStyle: textTheme.headlineMedium), + headlineSmall: specialGothicCondensedOne(textStyle: textTheme.headlineSmall), titleLarge: specialGothicCondensedOne(textStyle: textTheme.titleLarge), titleMedium: specialGothicCondensedOne(textStyle: textTheme.titleMedium), titleSmall: specialGothicCondensedOne(textStyle: textTheme.titleSmall), @@ -11877,19 +11855,11 @@ class PartS { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: specialGothicExpandedOne(textStyle: textTheme.displayLarge), - displayMedium: specialGothicExpandedOne( - textStyle: textTheme.displayMedium, - ), + displayMedium: specialGothicExpandedOne(textStyle: textTheme.displayMedium), displaySmall: specialGothicExpandedOne(textStyle: textTheme.displaySmall), - headlineLarge: specialGothicExpandedOne( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: specialGothicExpandedOne( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: specialGothicExpandedOne( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: specialGothicExpandedOne(textStyle: textTheme.headlineLarge), + headlineMedium: specialGothicExpandedOne(textStyle: textTheme.headlineMedium), + headlineSmall: specialGothicExpandedOne(textStyle: textTheme.headlineSmall), titleLarge: specialGothicExpandedOne(textStyle: textTheme.titleLarge), titleMedium: specialGothicExpandedOne(textStyle: textTheme.titleMedium), titleSmall: specialGothicExpandedOne(textStyle: textTheme.titleSmall), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart index c08be3fe6408..a966d6431f29 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_t.dart @@ -3586,9 +3586,7 @@ class PartT { displayMedium: tiroDevanagariMarathi(textStyle: textTheme.displayMedium), displaySmall: tiroDevanagariMarathi(textStyle: textTheme.displaySmall), headlineLarge: tiroDevanagariMarathi(textStyle: textTheme.headlineLarge), - headlineMedium: tiroDevanagariMarathi( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: tiroDevanagariMarathi(textStyle: textTheme.headlineMedium), headlineSmall: tiroDevanagariMarathi(textStyle: textTheme.headlineSmall), titleLarge: tiroDevanagariMarathi(textStyle: textTheme.titleLarge), titleMedium: tiroDevanagariMarathi(textStyle: textTheme.titleMedium), @@ -3682,9 +3680,7 @@ class PartT { displayMedium: tiroDevanagariSanskrit(textStyle: textTheme.displayMedium), displaySmall: tiroDevanagariSanskrit(textStyle: textTheme.displaySmall), headlineLarge: tiroDevanagariSanskrit(textStyle: textTheme.headlineLarge), - headlineMedium: tiroDevanagariSanskrit( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: tiroDevanagariSanskrit(textStyle: textTheme.headlineMedium), headlineSmall: tiroDevanagariSanskrit(textStyle: textTheme.headlineSmall), titleLarge: tiroDevanagariSanskrit(textStyle: textTheme.titleLarge), titleMedium: tiroDevanagariSanskrit(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart index e0f87da0a946..5f6c4a032231 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_y.dart @@ -2493,9 +2493,7 @@ class PartY { displayMedium: yujiHentaiganaAkebono(textStyle: textTheme.displayMedium), displaySmall: yujiHentaiganaAkebono(textStyle: textTheme.displaySmall), headlineLarge: yujiHentaiganaAkebono(textStyle: textTheme.headlineLarge), - headlineMedium: yujiHentaiganaAkebono( - textStyle: textTheme.headlineMedium, - ), + headlineMedium: yujiHentaiganaAkebono(textStyle: textTheme.headlineMedium), headlineSmall: yujiHentaiganaAkebono(textStyle: textTheme.headlineSmall), titleLarge: yujiHentaiganaAkebono(textStyle: textTheme.titleLarge), titleMedium: yujiHentaiganaAkebono(textStyle: textTheme.titleMedium), diff --git a/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart b/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart index 78e606a2fbde..48938c01d8a1 100644 --- a/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart +++ b/packages/google_fonts/lib/src/google_fonts_parts/part_z.dart @@ -968,19 +968,11 @@ class PartZ { textTheme ??= ThemeData.light().textTheme; return TextTheme( displayLarge: zalandoSansSemiExpanded(textStyle: textTheme.displayLarge), - displayMedium: zalandoSansSemiExpanded( - textStyle: textTheme.displayMedium, - ), + displayMedium: zalandoSansSemiExpanded(textStyle: textTheme.displayMedium), displaySmall: zalandoSansSemiExpanded(textStyle: textTheme.displaySmall), - headlineLarge: zalandoSansSemiExpanded( - textStyle: textTheme.headlineLarge, - ), - headlineMedium: zalandoSansSemiExpanded( - textStyle: textTheme.headlineMedium, - ), - headlineSmall: zalandoSansSemiExpanded( - textStyle: textTheme.headlineSmall, - ), + headlineLarge: zalandoSansSemiExpanded(textStyle: textTheme.headlineLarge), + headlineMedium: zalandoSansSemiExpanded(textStyle: textTheme.headlineMedium), + headlineSmall: zalandoSansSemiExpanded(textStyle: textTheme.headlineSmall), titleLarge: zalandoSansSemiExpanded(textStyle: textTheme.titleLarge), titleMedium: zalandoSansSemiExpanded(textStyle: textTheme.titleMedium), titleSmall: zalandoSansSemiExpanded(textStyle: textTheme.titleSmall), diff --git a/packages/google_fonts/lib/src/google_fonts_variant.dart b/packages/google_fonts/lib/src/google_fonts_variant.dart index d1ed5f0350a2..3ed155192c94 100644 --- a/packages/google_fonts/lib/src/google_fonts_variant.dart +++ b/packages/google_fonts/lib/src/google_fonts_variant.dart @@ -42,13 +42,10 @@ class GoogleFontsVariant { /// See [GoogleFontsVariant.toString] for the inverse function. GoogleFontsVariant.fromString(String variantString) : fontWeight = - FontWeight.values[variantString == _regular || - variantString == _italic + FontWeight.values[variantString == _regular || variantString == _italic ? 3 : (int.parse(variantString.replaceAll(_italic, '')) ~/ 100) - 1], - fontStyle = variantString.contains(_italic) - ? FontStyle.italic - : FontStyle.normal; + fontStyle = variantString.contains(_italic) ? FontStyle.italic : FontStyle.normal; /// The font weight of this variant. /// @@ -139,9 +136,7 @@ class GoogleFontsVariant { /// See [GoogleFontsVariant.toString] for the inverse function. @override String toString() { - final Object fontWeightString = fontWeight == FontWeight.normal - ? '' - : fontWeight.value; + final Object fontWeightString = fontWeight == FontWeight.normal ? '' : fontWeight.value; final String fontStyleString = fontStyle .toString() .replaceAll('FontStyle.', '') @@ -178,15 +173,14 @@ const String _italic = 'italic'; /// Mapping from font weight types to the 'weight' part of the Google Fonts API /// specific filename. -final Map _fontWeightToFilenameWeightParts = - { - FontWeight.w100: 'Thin', - FontWeight.w200: 'ExtraLight', - FontWeight.w300: 'Light', - FontWeight.w400: 'Regular', - FontWeight.w500: 'Medium', - FontWeight.w600: 'SemiBold', - FontWeight.w700: 'Bold', - FontWeight.w800: 'ExtraBold', - FontWeight.w900: 'Black', - }; +final Map _fontWeightToFilenameWeightParts = { + FontWeight.w100: 'Thin', + FontWeight.w200: 'ExtraLight', + FontWeight.w300: 'Light', + FontWeight.w400: 'Regular', + FontWeight.w500: 'Medium', + FontWeight.w600: 'SemiBold', + FontWeight.w700: 'Bold', + FontWeight.w800: 'ExtraBold', + FontWeight.w900: 'Black', +}; diff --git a/packages/google_fonts/test/find_family_with_variant_asset_path_web_test.dart b/packages/google_fonts/test/find_family_with_variant_asset_path_web_test.dart index ed79c6467b46..b79a814dc6cf 100644 --- a/packages/google_fonts/test/find_family_with_variant_asset_path_web_test.dart +++ b/packages/google_fonts/test/find_family_with_variant_asset_path_web_test.dart @@ -39,26 +39,18 @@ void main() { }); test('returns null when font family does not match (web: $isWeb)', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - [ - 'google_fonts/Lato-Regular.ttf', - 'google_fonts/OpenSans-Regular.ttf', - ], - isWeb: isWeb, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Lato-Regular.ttf', + 'google_fonts/OpenSans-Regular.ttf', + ], isWeb: isWeb); expect(result, isNull); }); test('returns null when variant does not match (web: $isWeb)', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - [ - 'google_fonts/Roboto-Bold.ttf', - 'google_fonts/Roboto-Italic.ttf', - ], - isWeb: isWeb, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Bold.ttf', + 'google_fonts/Roboto-Italic.ttf', + ], isWeb: isWeb); expect(result, isNull); }); @@ -70,13 +62,12 @@ void main() { fontStyle: FontStyle.italic, ), ); - final String? result = - findFamilyWithVariantAssetPath(boldItalicVariant, [ - 'google_fonts/Roboto-Regular.ttf', - 'google_fonts/Roboto-Bold.ttf', - 'google_fonts/Roboto-BoldItalic.ttf', - 'google_fonts/Roboto-Italic.ttf', - ], isWeb: isWeb); + final String? result = findFamilyWithVariantAssetPath(boldItalicVariant, [ + 'google_fonts/Roboto-Regular.ttf', + 'google_fonts/Roboto-Bold.ttf', + 'google_fonts/Roboto-BoldItalic.ttf', + 'google_fonts/Roboto-Italic.ttf', + ], isWeb: isWeb); expect(result, equals('google_fonts/Roboto-BoldItalic.ttf')); }); } @@ -84,104 +75,82 @@ void main() { group('on web', () { test('supports woff2 format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - ['google_fonts/Roboto-Regular.woff2'], - isWeb: true, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.woff2', + ], isWeb: true); expect(result, equals('google_fonts/Roboto-Regular.woff2')); }); test('supports woff format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - ['google_fonts/Roboto-Regular.woff'], - isWeb: true, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.woff', + ], isWeb: true); expect(result, equals('google_fonts/Roboto-Regular.woff')); }); test('supports ttf format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - ['google_fonts/Roboto-Regular.ttf'], - isWeb: true, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.ttf', + ], isWeb: true); expect(result, equals('google_fonts/Roboto-Regular.ttf')); }); test('supports otf format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - ['google_fonts/Roboto-Regular.otf'], - isWeb: true, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.otf', + ], isWeb: true); expect(result, equals('google_fonts/Roboto-Regular.otf')); }); test('prefers woff2 over other formats regardless of manifest order', () { // Returns the highest priority file type regardless of the order in // which assets appear in the manifest. - final String? result = - findFamilyWithVariantAssetPath(familyWithVariant, [ - 'google_fonts/Roboto-Regular.ttf', - 'google_fonts/Roboto-Regular.woff2', - 'google_fonts/Roboto-Regular.woff', - ], isWeb: true); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.ttf', + 'google_fonts/Roboto-Regular.woff2', + 'google_fonts/Roboto-Regular.woff', + ], isWeb: true); expect(result, equals('google_fonts/Roboto-Regular.woff2')); }); test('ignores unsupported file extensions', () { - final String? result = - findFamilyWithVariantAssetPath(familyWithVariant, [ - 'google_fonts/Roboto-Regular.eot', - 'google_fonts/Roboto-Regular.svg', - 'google_fonts/Roboto-Regular.woff2', - ], isWeb: true); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.eot', + 'google_fonts/Roboto-Regular.svg', + 'google_fonts/Roboto-Regular.woff2', + ], isWeb: true); expect(result, equals('google_fonts/Roboto-Regular.woff2')); }); }); group('on non-web', () { test('supports ttf format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - ['google_fonts/Roboto-Regular.ttf'], - isWeb: false, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.ttf', + ], isWeb: false); expect(result, equals('google_fonts/Roboto-Regular.ttf')); }); test('supports otf format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - ['google_fonts/Roboto-Regular.otf'], - isWeb: false, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.otf', + ], isWeb: false); expect(result, equals('google_fonts/Roboto-Regular.otf')); }); test('does not select woff2 format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - [ - 'google_fonts/Roboto-Regular.woff2', - 'google_fonts/Roboto-Regular.ttf', - ], - isWeb: false, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.woff2', + 'google_fonts/Roboto-Regular.ttf', + ], isWeb: false); expect(result, equals('google_fonts/Roboto-Regular.ttf')); }); test('does not select woff format', () { - final String? result = findFamilyWithVariantAssetPath( - familyWithVariant, - [ - 'google_fonts/Roboto-Regular.woff', - 'google_fonts/Roboto-Regular.otf', - ], - isWeb: false, - ); + final String? result = findFamilyWithVariantAssetPath(familyWithVariant, [ + 'google_fonts/Roboto-Regular.woff', + 'google_fonts/Roboto-Regular.otf', + ], isWeb: false); expect(result, equals('google_fonts/Roboto-Regular.otf')); }); }); diff --git a/packages/google_fonts/test/generated_font_methods_test.dart b/packages/google_fonts/test/generated_font_methods_test.dart index b05afdaaabd0..b65293fb7675 100644 --- a/packages/google_fonts/test/generated_font_methods_test.dart +++ b/packages/google_fonts/test/generated_font_methods_test.dart @@ -26,103 +26,66 @@ void main() { // Derived fontFamily tests // ////////////////////////////// - testWidgets('Text style with a direct match is used', ( - WidgetTester tester, - ) async { - const inputTextStyle = TextStyle( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ); + testWidgets('Text style with a direct match is used', (WidgetTester tester) async { + const inputTextStyle = TextStyle(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal); - final TextStyle outputTextStyle = GoogleFonts.roboto( - textStyle: inputTextStyle, - ); + final TextStyle outputTextStyle = GoogleFonts.roboto(textStyle: inputTextStyle); expect(outputTextStyle.fontFamily, equals('Roboto_regular')); }); - testWidgets('Text style with an italics direct match is used', ( - WidgetTester tester, - ) async { - const inputTextStyle = TextStyle( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.italic, - ); + testWidgets('Text style with an italics direct match is used', (WidgetTester tester) async { + const inputTextStyle = TextStyle(fontWeight: FontWeight.w400, fontStyle: FontStyle.italic); - final TextStyle outputTextStyle = GoogleFonts.roboto( - textStyle: inputTextStyle, - ); + final TextStyle outputTextStyle = GoogleFonts.roboto(textStyle: inputTextStyle); expect(outputTextStyle.fontFamily, equals('Roboto_italic')); }); - testWidgets( - 'Text style with no direct match picks closest font weight match', - (WidgetTester tester) async { - const inputTextStyle = TextStyle( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.normal, - ); + testWidgets('Text style with no direct match picks closest font weight match', ( + WidgetTester tester, + ) async { + const inputTextStyle = TextStyle(fontWeight: FontWeight.w500, fontStyle: FontStyle.normal); - final TextStyle outputTextStyle = GoogleFonts.robotoFlex( - textStyle: inputTextStyle, - ); + final TextStyle outputTextStyle = GoogleFonts.robotoFlex(textStyle: inputTextStyle); - expect(outputTextStyle.fontFamily, equals('RobotoFlex_regular')); // w400 - }, - ); + expect(outputTextStyle.fontFamily, equals('RobotoFlex_regular')); // w400 + }); testWidgets('Italic text style with no direct match picks closest match', ( WidgetTester tester, ) async { - const inputTextStyle = TextStyle( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + const inputTextStyle = TextStyle(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); - final TextStyle outputTextStyle = GoogleFonts.robotoFlex( - textStyle: inputTextStyle, - ); + final TextStyle outputTextStyle = GoogleFonts.robotoFlex(textStyle: inputTextStyle); expect(outputTextStyle.fontFamily, equals('RobotoFlex_regular')); // w400 }); - testWidgets('Text style prefers matching italics to closer weight', ( - WidgetTester tester, - ) async { + testWidgets('Text style prefers matching italics to closer weight', (WidgetTester tester) async { // Cardo has 400regular, 400italic, and 700 regular. Even though 700 is // closer in weight, when we ask for 600italic, it will give us 400 italic // font family. - const inputTextStyle = TextStyle( - fontWeight: FontWeight.w600, - fontStyle: FontStyle.italic, - ); + const inputTextStyle = TextStyle(fontWeight: FontWeight.w600, fontStyle: FontStyle.italic); - final TextStyle outputTextStyle = GoogleFonts.cardo( - textStyle: inputTextStyle, - ); + final TextStyle outputTextStyle = GoogleFonts.cardo(textStyle: inputTextStyle); expect(outputTextStyle.fontFamily, equals('Cardo_italic')); }); - testWidgets('Defaults to regular when no Text style is passed', ( - WidgetTester tester, - ) async { + testWidgets('Defaults to regular when no Text style is passed', (WidgetTester tester) async { final TextStyle outputTextStyle = GoogleFonts.lato(); expect(outputTextStyle.fontFamily, equals('Lato_regular')); }); - testWidgets( - 'Defaults to regular when a Text style with no weight or style is passed', - (WidgetTester tester) async { - final TextStyle outputTextStyle = GoogleFonts.lato( - textStyle: const TextStyle(), - ); + testWidgets('Defaults to regular when a Text style with no weight or style is passed', ( + WidgetTester tester, + ) async { + final TextStyle outputTextStyle = GoogleFonts.lato(textStyle: const TextStyle()); - expect(outputTextStyle.fontFamily, equals('Lato_regular')); - }, - ); + expect(outputTextStyle.fontFamily, equals('Lato_regular')); + }); /////////////////////////// // TextStyle param tests // @@ -137,12 +100,8 @@ void main() { expect(outputTextStyle.color, equals(const Color(0xDEADBEEF))); }); - testWidgets('color is honored when passed in as a top-level param', ( - WidgetTester tester, - ) async { - final TextStyle outputTextStyle = GoogleFonts.rancho( - color: const Color(0xFACEFEED), - ); + testWidgets('color is honored when passed in as a top-level param', (WidgetTester tester) async { + final TextStyle outputTextStyle = GoogleFonts.rancho(color: const Color(0xFACEFEED)); expect(outputTextStyle.color, equals(const Color(0xFACEFEED))); }); @@ -158,28 +117,22 @@ void main() { expect(outputTextStyle.color, const Color(0xFACEFEED)); }); - testWidgets( - 'backgroundColor is honored when passed in via the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(backgroundColor: Color(0xDEADBEEF)); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - ); + testWidgets('backgroundColor is honored when passed in via the TextStyle param', ( + WidgetTester tester, + ) async { + const textStyle = TextStyle(backgroundColor: Color(0xDEADBEEF)); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle); - expect(outputTextStyle.backgroundColor, equals(const Color(0xDEADBEEF))); - }, - ); + expect(outputTextStyle.backgroundColor, equals(const Color(0xDEADBEEF))); + }); - testWidgets( - 'backgroundColor is honored when passed in as a top-level param', - (WidgetTester tester) async { - final TextStyle outputTextStyle = GoogleFonts.rancho( - backgroundColor: const Color(0xFACEFEED), - ); + testWidgets('backgroundColor is honored when passed in as a top-level param', ( + WidgetTester tester, + ) async { + final TextStyle outputTextStyle = GoogleFonts.rancho(backgroundColor: const Color(0xFACEFEED)); - expect(outputTextStyle.backgroundColor, equals(const Color(0xFACEFEED))); - }, - ); + expect(outputTextStyle.backgroundColor, equals(const Color(0xFACEFEED))); + }); testWidgets('backgroundColor from the top-level param takes precedence over ' 'backgroundColor from TextStyle param', (WidgetTester tester) async { @@ -209,19 +162,13 @@ void main() { expect(outputTextStyle.fontSize, equals(31)); }); - testWidgets( - 'fontSize from the top-level param takes precedence over fontSize ' - 'from the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(fontSize: 37); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - fontSize: 31, - ); + testWidgets('fontSize from the top-level param takes precedence over fontSize ' + 'from the TextStyle param', (WidgetTester tester) async { + const textStyle = TextStyle(fontSize: 37); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle, fontSize: 31); - expect(outputTextStyle.fontSize, equals(31)); - }, - ); + expect(outputTextStyle.fontSize, equals(31)); + }); testWidgets('fontWeight is honored when passed in via the TextStyle param', ( WidgetTester tester, @@ -235,27 +182,22 @@ void main() { testWidgets('fontWeight is honored when passed in as a top-level param', ( WidgetTester tester, ) async { + final TextStyle outputTextStyle = GoogleFonts.rancho(fontWeight: FontWeight.w200); + + expect(outputTextStyle.fontWeight, equals(FontWeight.w200)); + }); + + testWidgets('fontWeight from the top-level param takes precedence over fontWeight ' + 'from the TextStyle param', (WidgetTester tester) async { + const textStyle = TextStyle(fontWeight: FontWeight.w800); final TextStyle outputTextStyle = GoogleFonts.rancho( + textStyle: textStyle, fontWeight: FontWeight.w200, ); expect(outputTextStyle.fontWeight, equals(FontWeight.w200)); }); - testWidgets( - 'fontWeight from the top-level param takes precedence over fontWeight ' - 'from the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(fontWeight: FontWeight.w800); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - fontWeight: FontWeight.w200, - ); - - expect(outputTextStyle.fontWeight, equals(FontWeight.w200)); - }, - ); - testWidgets('fontStyle is honored when passed in via the TextStyle param', ( WidgetTester tester, ) async { @@ -268,38 +210,30 @@ void main() { testWidgets('fontStyle is honored when passed in as a top-level param', ( WidgetTester tester, ) async { + final TextStyle outputTextStyle = GoogleFonts.rancho(fontStyle: FontStyle.italic); + + expect(outputTextStyle.fontStyle, equals(FontStyle.italic)); + }); + + testWidgets('fontStyle from the top-level param takes precedence over fontStyle ' + 'from the TextStyle param', (WidgetTester tester) async { + const textStyle = TextStyle(fontStyle: FontStyle.normal); final TextStyle outputTextStyle = GoogleFonts.rancho( + textStyle: textStyle, fontStyle: FontStyle.italic, ); expect(outputTextStyle.fontStyle, equals(FontStyle.italic)); }); - testWidgets( - 'fontStyle from the top-level param takes precedence over fontStyle ' - 'from the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(fontStyle: FontStyle.normal); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - fontStyle: FontStyle.italic, - ); - - expect(outputTextStyle.fontStyle, equals(FontStyle.italic)); - }, - ); - - testWidgets( - 'letterSpacing is honored when passed in via the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(letterSpacing: 0.4); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - ); - - expect(outputTextStyle.letterSpacing, equals(0.4)); - }, - ); + testWidgets('letterSpacing is honored when passed in via the TextStyle param', ( + WidgetTester tester, + ) async { + const textStyle = TextStyle(letterSpacing: 0.4); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle); + + expect(outputTextStyle.letterSpacing, equals(0.4)); + }); testWidgets('letterSpacing is honored when passed in as a top-level param', ( WidgetTester tester, @@ -312,10 +246,7 @@ void main() { testWidgets('letterSpacing from the top-level param takes precedence over ' 'letterSpacing from the TextStyle param', (WidgetTester tester) async { const textStyle = TextStyle(letterSpacing: 0.4); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - letterSpacing: 0.3, - ); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle, letterSpacing: 0.3); expect(outputTextStyle.letterSpacing, equals(0.3)); }); @@ -337,38 +268,27 @@ void main() { expect(outputTextStyle.wordSpacing, equals(0.3)); }); - testWidgets( - 'wordSpacing from the top-level param takes precedence over wordSpacing ' - 'from the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(wordSpacing: 0.4); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - wordSpacing: 0.3, - ); - - expect(outputTextStyle.wordSpacing, equals(0.3)); - }, - ); - - testWidgets( - 'textBaseline is honored when passed in via the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(textBaseline: TextBaseline.ideographic); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - ); - - expect(outputTextStyle.textBaseline, equals(TextBaseline.ideographic)); - }, - ); + testWidgets('wordSpacing from the top-level param takes precedence over wordSpacing ' + 'from the TextStyle param', (WidgetTester tester) async { + const textStyle = TextStyle(wordSpacing: 0.4); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle, wordSpacing: 0.3); + + expect(outputTextStyle.wordSpacing, equals(0.3)); + }); + + testWidgets('textBaseline is honored when passed in via the TextStyle param', ( + WidgetTester tester, + ) async { + const textStyle = TextStyle(textBaseline: TextBaseline.ideographic); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle); + + expect(outputTextStyle.textBaseline, equals(TextBaseline.ideographic)); + }); testWidgets('textBaseline is honored when passed in as a top-level param', ( WidgetTester tester, ) async { - final TextStyle outputTextStyle = GoogleFonts.rancho( - textBaseline: TextBaseline.alphabetic, - ); + final TextStyle outputTextStyle = GoogleFonts.rancho(textBaseline: TextBaseline.alphabetic); expect(outputTextStyle.textBaseline, equals(TextBaseline.alphabetic)); }); @@ -393,9 +313,7 @@ void main() { expect(outputTextStyle.height, equals(33)); }); - testWidgets('height is honored when passed in as a top-level param', ( - WidgetTester tester, - ) async { + testWidgets('height is honored when passed in as a top-level param', (WidgetTester tester) async { final TextStyle outputTextStyle = GoogleFonts.rancho(height: 37); expect(outputTextStyle.height, equals(37)); @@ -404,10 +322,7 @@ void main() { testWidgets('height from the top-level param takes precedence over height ' 'from the TextStyle param', (WidgetTester tester) async { const textStyle = TextStyle(height: 33); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - height: 37, - ); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle, height: 37); expect(outputTextStyle.height, equals(37)); }); @@ -421,12 +336,8 @@ void main() { expect(outputTextStyle.locale, equals(const Locale('abc'))); }); - testWidgets('locale is honored when passed in as a top-level param', ( - WidgetTester tester, - ) async { - final TextStyle outputTextStyle = GoogleFonts.rancho( - locale: const Locale('xyz'), - ); + testWidgets('locale is honored when passed in as a top-level param', (WidgetTester tester) async { + final TextStyle outputTextStyle = GoogleFonts.rancho(locale: const Locale('xyz')); expect(outputTextStyle.locale, equals(const Locale('xyz'))); }); @@ -461,21 +372,15 @@ void main() { expect(outputTextStyle.foreground, equals(paint)); }); - testWidgets( - 'foreground from the top-level param takes precedence over foreground ' - 'from the TextStyle param', - (WidgetTester tester) async { - final paint1 = Paint()..color = const Color(0xDEADBEEF); - final paint2 = Paint()..color = const Color(0xFACEFEED); - final textStyle = TextStyle(foreground: paint1); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - foreground: paint2, - ); + testWidgets('foreground from the top-level param takes precedence over foreground ' + 'from the TextStyle param', (WidgetTester tester) async { + final paint1 = Paint()..color = const Color(0xDEADBEEF); + final paint2 = Paint()..color = const Color(0xFACEFEED); + final textStyle = TextStyle(foreground: paint1); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle, foreground: paint2); - expect(outputTextStyle.foreground, equals(paint2)); - }, - ); + expect(outputTextStyle.foreground, equals(paint2)); + }); testWidgets('background is honored when passed in via the TextStyle param', ( WidgetTester tester, @@ -496,21 +401,15 @@ void main() { expect(outputTextStyle.background, equals(paint)); }); - testWidgets( - 'background from the top-level param takes precedence over background ' - 'from the TextStyle param', - (WidgetTester tester) async { - final paint1 = Paint()..color = const Color(0xDEADBEEF); - final paint2 = Paint()..color = const Color(0xFACEFEED); - final textStyle = TextStyle(background: paint1); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - background: paint2, - ); + testWidgets('background from the top-level param takes precedence over background ' + 'from the TextStyle param', (WidgetTester tester) async { + final paint1 = Paint()..color = const Color(0xDEADBEEF); + final paint2 = Paint()..color = const Color(0xFACEFEED); + final textStyle = TextStyle(background: paint1); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle, background: paint2); - expect(outputTextStyle.background, equals(paint2)); - }, - ); + expect(outputTextStyle.background, equals(paint2)); + }); testWidgets('shadows is honored when passed in via the TextStyle param', ( WidgetTester tester, @@ -536,34 +435,26 @@ void main() { const shadows1 = [Shadow(blurRadius: 1)]; const shadows2 = [Shadow(blurRadius: 2)]; const textStyle = TextStyle(shadows: shadows1); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - shadows: shadows2, - ); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle, shadows: shadows2); expect(outputTextStyle.shadows, equals(shadows2)); }); - testWidgets( - 'fontFeatures is honored when passed in via the TextStyle param', - (WidgetTester tester) async { - const fontFeatures = [FontFeature.slashedZero()]; - const textStyle = TextStyle(fontFeatures: fontFeatures); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - ); + testWidgets('fontFeatures is honored when passed in via the TextStyle param', ( + WidgetTester tester, + ) async { + const fontFeatures = [FontFeature.slashedZero()]; + const textStyle = TextStyle(fontFeatures: fontFeatures); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle); - expect(outputTextStyle.fontFeatures, equals(fontFeatures)); - }, - ); + expect(outputTextStyle.fontFeatures, equals(fontFeatures)); + }); testWidgets('fontFeatures is honored when passed in as a top-level param', ( WidgetTester tester, ) async { const fontFeatures = [FontFeature.oldstyleFigures()]; - final TextStyle outputTextStyle = GoogleFonts.rancho( - fontFeatures: fontFeatures, - ); + final TextStyle outputTextStyle = GoogleFonts.rancho(fontFeatures: fontFeatures); expect(outputTextStyle.fontFeatures, equals(fontFeatures)); }); @@ -595,9 +486,7 @@ void main() { WidgetTester tester, ) async { const TextDecoration decoration = TextDecoration.overline; - final TextStyle outputTextStyle = GoogleFonts.rancho( - decoration: decoration, - ); + final TextStyle outputTextStyle = GoogleFonts.rancho(decoration: decoration); expect(outputTextStyle.decoration, equals(decoration)); }); @@ -615,28 +504,22 @@ void main() { expect(outputTextStyle.decoration, equals(decoration2)); }); - testWidgets( - 'decorationColor is honored when passed in via the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(decorationColor: Color(0xDEADBEEF)); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - ); + testWidgets('decorationColor is honored when passed in via the TextStyle param', ( + WidgetTester tester, + ) async { + const textStyle = TextStyle(decorationColor: Color(0xDEADBEEF)); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle); - expect(outputTextStyle.decorationColor, const Color(0xDEADBEEF)); - }, - ); + expect(outputTextStyle.decorationColor, const Color(0xDEADBEEF)); + }); - testWidgets( - 'decorationColor is honored when passed in as a top-level param', - (WidgetTester tester) async { - final TextStyle outputTextStyle = GoogleFonts.rancho( - decorationColor: const Color(0xFACEFEED), - ); + testWidgets('decorationColor is honored when passed in as a top-level param', ( + WidgetTester tester, + ) async { + final TextStyle outputTextStyle = GoogleFonts.rancho(decorationColor: const Color(0xFACEFEED)); - expect(outputTextStyle.decorationColor, equals(const Color(0xFACEFEED))); - }, - ); + expect(outputTextStyle.decorationColor, equals(const Color(0xFACEFEED))); + }); testWidgets('decorationColor from the top-level param takes precedence over ' 'decorationColor from the TextStyle param', (WidgetTester tester) async { @@ -649,31 +532,24 @@ void main() { expect(outputTextStyle.decorationColor, equals(const Color(0xFACEFEED))); }); - testWidgets( - 'decorationStyle is honored when passed in via the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(decorationStyle: TextDecorationStyle.dashed); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - ); - - expect(outputTextStyle.decorationStyle, TextDecorationStyle.dashed); - }, - ); - - testWidgets( - 'decorationStyle is honored when passed in as a top-level param', - (WidgetTester tester) async { - final TextStyle outputTextStyle = GoogleFonts.rancho( - decorationStyle: TextDecorationStyle.dotted, - ); - - expect( - outputTextStyle.decorationStyle, - equals(TextDecorationStyle.dotted), - ); - }, - ); + testWidgets('decorationStyle is honored when passed in via the TextStyle param', ( + WidgetTester tester, + ) async { + const textStyle = TextStyle(decorationStyle: TextDecorationStyle.dashed); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle); + + expect(outputTextStyle.decorationStyle, TextDecorationStyle.dashed); + }); + + testWidgets('decorationStyle is honored when passed in as a top-level param', ( + WidgetTester tester, + ) async { + final TextStyle outputTextStyle = GoogleFonts.rancho( + decorationStyle: TextDecorationStyle.dotted, + ); + + expect(outputTextStyle.decorationStyle, equals(TextDecorationStyle.dotted)); + }); testWidgets('decorationStyle from the top-level param takes precedence over ' 'decorationStyle from the TextStyle param', (WidgetTester tester) async { @@ -686,78 +562,49 @@ void main() { expect(outputTextStyle.decorationStyle, equals(TextDecorationStyle.dotted)); }); - testWidgets( - 'decorationThickness is honored when passed in via the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(decorationThickness: 2); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - ); - - expect(outputTextStyle.decorationThickness, 2); - }, - ); - - testWidgets( - 'decorationThickness is honored when passed in as a top-level param', - (WidgetTester tester) async { - final TextStyle outputTextStyle = GoogleFonts.rancho( - decorationThickness: 3, - ); - - expect(outputTextStyle.decorationThickness, equals(3)); - }, - ); - - testWidgets( - 'decorationThickness from the top-level param takes precedence over ' - 'decorationThickness from the TextStyle param', - (WidgetTester tester) async { - const textStyle = TextStyle(decorationThickness: 2); - final TextStyle outputTextStyle = GoogleFonts.rancho( - textStyle: textStyle, - decorationThickness: 3, - ); - - expect(outputTextStyle.decorationThickness, equals(3)); - }, - ); + testWidgets('decorationThickness is honored when passed in via the TextStyle param', ( + WidgetTester tester, + ) async { + const textStyle = TextStyle(decorationThickness: 2); + final TextStyle outputTextStyle = GoogleFonts.rancho(textStyle: textStyle); + + expect(outputTextStyle.decorationThickness, 2); + }); + + testWidgets('decorationThickness is honored when passed in as a top-level param', ( + WidgetTester tester, + ) async { + final TextStyle outputTextStyle = GoogleFonts.rancho(decorationThickness: 3); + + expect(outputTextStyle.decorationThickness, equals(3)); + }); + + testWidgets('decorationThickness from the top-level param takes precedence over ' + 'decorationThickness from the TextStyle param', (WidgetTester tester) async { + const textStyle = TextStyle(decorationThickness: 2); + final TextStyle outputTextStyle = GoogleFonts.rancho( + textStyle: textStyle, + decorationThickness: 3, + ); + + expect(outputTextStyle.decorationThickness, equals(3)); + }); ///////////////////// // TextTheme tests // ///////////////////// - testWidgets('TextTheme method works in the default case', ( - WidgetTester tester, - ) async { + testWidgets('TextTheme method works in the default case', (WidgetTester tester) async { final TextTheme textTheme = GoogleFonts.oswaldTextTheme(); const expectedFamilyWithVariant = 'Oswald_regular'; - expect( - textTheme.displayLarge!.fontFamily, - equals(expectedFamilyWithVariant), - ); - expect( - textTheme.displayMedium!.fontFamily, - equals(expectedFamilyWithVariant), - ); - expect( - textTheme.displaySmall!.fontFamily, - equals(expectedFamilyWithVariant), - ); - expect( - textTheme.headlineMedium!.fontFamily, - equals(expectedFamilyWithVariant), - ); - expect( - textTheme.headlineSmall!.fontFamily, - equals(expectedFamilyWithVariant), - ); + expect(textTheme.displayLarge!.fontFamily, equals(expectedFamilyWithVariant)); + expect(textTheme.displayMedium!.fontFamily, equals(expectedFamilyWithVariant)); + expect(textTheme.displaySmall!.fontFamily, equals(expectedFamilyWithVariant)); + expect(textTheme.headlineMedium!.fontFamily, equals(expectedFamilyWithVariant)); + expect(textTheme.headlineSmall!.fontFamily, equals(expectedFamilyWithVariant)); expect(textTheme.titleLarge!.fontFamily, equals(expectedFamilyWithVariant)); - expect( - textTheme.titleMedium!.fontFamily, - equals(expectedFamilyWithVariant), - ); + expect(textTheme.titleMedium!.fontFamily, equals(expectedFamilyWithVariant)); expect(textTheme.titleSmall!.fontFamily, equals(expectedFamilyWithVariant)); expect(textTheme.bodyLarge!.fontFamily, equals(expectedFamilyWithVariant)); expect(textTheme.bodyMedium!.fontFamily, equals(expectedFamilyWithVariant)); @@ -766,9 +613,7 @@ void main() { expect(textTheme.labelSmall!.fontFamily, equals(expectedFamilyWithVariant)); }); - testWidgets('TextTheme method works with a base textTheme', ( - WidgetTester tester, - ) async { + testWidgets('TextTheme method works with a base textTheme', (WidgetTester tester) async { // In app this is usually obtained by Theme.of(context).textTheme. final baseTextTheme = TextTheme( displaySmall: const TextStyle(fontWeight: FontWeight.w700), @@ -780,10 +625,7 @@ void main() { const expectedFamilyWithVariant = 'Oswald_regular'; // Default is preserved. - expect( - textTheme.headlineMedium!.fontFamily, - equals(expectedFamilyWithVariant), - ); + expect(textTheme.headlineMedium!.fontFamily, equals(expectedFamilyWithVariant)); // Different font family gets overridden by oswald. expect(textTheme.bodyMedium!.fontFamily, equals(expectedFamilyWithVariant)); // Weight is preserved. @@ -793,9 +635,7 @@ void main() { }); // Regression test for https://github.com/material-foundation/flutter-packages/issues/215 - testWidgets('TextTheme equality when used in a ThemeData', ( - WidgetTester tester, - ) async { + testWidgets('TextTheme equality when used in a ThemeData', (WidgetTester tester) async { final myAppTheme = ThemeData(textTheme: GoogleFonts.poppinsTextTheme()); expect(myAppTheme.textTheme, equals(GoogleFonts.poppinsTextTheme())); @@ -805,9 +645,7 @@ void main() { // Method tests // ////////////////// - testWidgets('getFont works with all fonts in GoogleFonts.asMap', ( - WidgetTester tester, - ) async { + testWidgets('getFont works with all fonts in GoogleFonts.asMap', (WidgetTester tester) async { final Iterable allFonts = GoogleFonts.asMap().keys; for (final fontFamily in allFonts) { @@ -838,9 +676,7 @@ void main() { expect(allFonts, isNotEmpty); }); - testWidgets('getTextTheme returns the correct text theme', ( - WidgetTester tester, - ) async { + testWidgets('getTextTheme returns the correct text theme', (WidgetTester tester) async { final TextTheme dynamicTheme = GoogleFonts.getTextTheme('Roboto Mono'); final TextTheme methodTheme = GoogleFonts.robotoMonoTextTheme(); diff --git a/packages/google_fonts/test/google_fonts_family_with_variant_test.dart b/packages/google_fonts/test/google_fonts_family_with_variant_test.dart index 853ef86796b8..1de66bdd40c7 100644 --- a/packages/google_fonts/test/google_fonts_family_with_variant_test.dart +++ b/packages/google_fonts/test/google_fonts_family_with_variant_test.dart @@ -32,9 +32,7 @@ void main() { expect(familyWithVariant.toString(), equals('Foo_100italic')); }); - testWidgets('toApiFilenamePrefix() works for italic w100', ( - WidgetTester tester, - ) async { + testWidgets('toApiFilenamePrefix() works for italic w100', (WidgetTester tester) async { const familyWithVariant = GoogleFontsFamilyWithVariant( family: 'Foo', googleFontsVariant: GoogleFontsVariant( @@ -46,9 +44,7 @@ void main() { expect(familyWithVariant.toApiFilenamePrefix(), equals('Foo-ThinItalic')); }); - testWidgets('toApiFilenamePrefix() works for regular', ( - WidgetTester tester, - ) async { + testWidgets('toApiFilenamePrefix() works for regular', (WidgetTester tester) async { const familyWithVariant = GoogleFontsFamilyWithVariant( family: 'Foo', googleFontsVariant: GoogleFontsVariant( diff --git a/packages/google_fonts/test/google_fonts_text_style_test.dart b/packages/google_fonts/test/google_fonts_text_style_test.dart index 9d1a102c1568..dc2f3226b571 100644 --- a/packages/google_fonts/test/google_fonts_text_style_test.dart +++ b/packages/google_fonts/test/google_fonts_text_style_test.dart @@ -16,11 +16,7 @@ import 'package:mockito/mockito.dart'; class MockHttpClient extends Mock implements http.Client { Future gets(dynamic uri, {dynamic headers}) { super.noSuchMethod( - Invocation.method( - #get, - [uri], - {#headers: headers}, - ), + Invocation.method(#get, [uri], {#headers: headers}), ); return Future.value(http.Response('', 200)); } @@ -35,21 +31,17 @@ const String _fakeResponse = 'fake response body - success'; // The number of bytes in _fakeResponse. const int _fakeResponseLengthInBytes = 28; // Computed by converting _fakeResponse to bytes and getting sha 256 hash. -const String _fakeResponseHash = - '1194f6ffe4d2f05258573616a77932c38041f3102763096c19437c3db1818a04'; +const String _fakeResponseHash = '1194f6ffe4d2f05258573616a77932c38041f3102763096c19437c3db1818a04'; final GoogleFontsFile _fakeResponseFile = GoogleFontsFile( _fakeResponseHash, _fakeResponseLengthInBytes, ); -final Map fakeFonts = - { - const GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ): _fakeResponseFile, - }; +final Map fakeFonts = { + const GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal): + _fakeResponseFile, +}; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/packages/google_fonts/test/google_fonts_variant_test.dart b/packages/google_fonts/test/google_fonts_variant_test.dart index bbc1fb458574..282760681579 100644 --- a/packages/google_fonts/test/google_fonts_variant_test.dart +++ b/packages/google_fonts/test/google_fonts_variant_test.dart @@ -8,80 +8,54 @@ import 'package:google_fonts/src/google_fonts_variant.dart'; void main() { testWidgets('toString() works for normal w400', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal); expect(variant.toString(), equals('regular')); }); testWidgets('toString() works for italic w400', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.italic, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.italic); expect(variant.toString(), equals('italic')); }); testWidgets('toString() works for normal w500', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.normal, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.normal); expect(variant.toString(), equals('500')); }); testWidgets('toString() works for italic w500', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); expect(variant.toString(), equals('500italic')); }); testWidgets('fromString() works for regular', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal); expect(GoogleFontsVariant.fromString('regular'), equals(variant)); }); testWidgets('fromString() works for italic', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.italic, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.italic); expect(GoogleFontsVariant.fromString('italic'), equals(variant)); }); testWidgets('fromString() works for 500', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.normal, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.normal); expect(GoogleFontsVariant.fromString('500'), equals(variant)); }); testWidgets('fromString() works for 500italic', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); expect(GoogleFontsVariant.fromString('500italic'), equals(variant)); }); - testWidgets('toApiFilenamePart() works for all normal combintaions', ( - WidgetTester tester, - ) async { + testWidgets('toApiFilenamePart() works for all normal combintaions', (WidgetTester tester) async { expect( const GoogleFontsVariant( fontWeight: FontWeight.w100, @@ -155,9 +129,7 @@ void main() { ); }); - testWidgets('toApiFilenamePart() works for all italic combintaions', ( - WidgetTester tester, - ) async { + testWidgets('toApiFilenamePart() works for all italic combintaions', (WidgetTester tester) async { expect( const GoogleFontsVariant( fontWeight: FontWeight.w100, @@ -236,92 +208,47 @@ void main() { ) async { expect( GoogleFontsVariant.fromApiFilenamePart('Thin'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w100, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w100, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('ExtraLight'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w200, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w200, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('Light'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w300, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w300, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('Regular'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('Medium'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('SemiBold'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w600, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w600, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('Bold'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w700, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w700, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('ExtraBold'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w800, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w800, fontStyle: FontStyle.normal)), ); expect( GoogleFontsVariant.fromApiFilenamePart('Black'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w900, - fontStyle: FontStyle.normal, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w900, fontStyle: FontStyle.normal)), ); }); @@ -330,112 +257,59 @@ void main() { ) async { expect( GoogleFontsVariant.fromApiFilenamePart('ThinItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w100, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w100, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('ExtraLightItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w200, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w200, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('LightItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w300, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w300, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('Italic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w400, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('MediumItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('SemiBoldItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w600, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w600, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('BoldItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w700, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w700, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('ExtraBoldItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w800, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w800, fontStyle: FontStyle.italic)), ); expect( GoogleFontsVariant.fromApiFilenamePart('BlackItalic'), - equals( - const GoogleFontsVariant( - fontWeight: FontWeight.w900, - fontStyle: FontStyle.italic, - ), - ), + equals(const GoogleFontsVariant(fontWeight: FontWeight.w900, fontStyle: FontStyle.italic)), ); }); - testWidgets('== works for for identical variants', ( - WidgetTester tester, - ) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + testWidgets('== works for for identical variants', (WidgetTester tester) async { + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); const otherVariant = variant; expect(variant == otherVariant, isTrue); }); testWidgets('== works for for clone variants', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); const otherVariant = GoogleFontsVariant( fontWeight: FontWeight.w500, fontStyle: FontStyle.italic, @@ -443,13 +317,8 @@ void main() { expect(variant == otherVariant, isTrue); }); - testWidgets('== fails for different fontWeights', ( - WidgetTester tester, - ) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + testWidgets('== fails for different fontWeights', (WidgetTester tester) async { + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); const otherVariant = GoogleFontsVariant( fontWeight: FontWeight.w900, fontStyle: FontStyle.italic, @@ -458,10 +327,7 @@ void main() { }); testWidgets('== fails for different fontStyles', (WidgetTester tester) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); const otherVariant = GoogleFontsVariant( fontWeight: FontWeight.w500, fontStyle: FontStyle.normal, @@ -472,10 +338,7 @@ void main() { testWidgets('== fails for different fontWeights and different fontStyles', ( WidgetTester tester, ) async { - const variant = GoogleFontsVariant( - fontWeight: FontWeight.w500, - fontStyle: FontStyle.italic, - ); + const variant = GoogleFontsVariant(fontWeight: FontWeight.w500, fontStyle: FontStyle.italic); const otherVariant = GoogleFontsVariant( fontWeight: FontWeight.w900, fontStyle: FontStyle.normal, diff --git a/packages/google_fonts/test/load_font_if_necessary_test.dart b/packages/google_fonts/test/load_font_if_necessary_test.dart index fe35623b230c..9cd97b84a9e1 100644 --- a/packages/google_fonts/test/load_font_if_necessary_test.dart +++ b/packages/google_fonts/test/load_font_if_necessary_test.dart @@ -25,11 +25,7 @@ import 'package:plugin_platform_interface/plugin_platform_interface.dart'; class MockHttpClient extends Mock implements http.Client { Future gets(dynamic uri, {dynamic headers}) { super.noSuchMethod( - Invocation.method( - #get, - [uri], - {#headers: headers}, - ), + Invocation.method(#get, [uri], {#headers: headers}), ); return Future.value(http.Response('', 200)); } @@ -59,8 +55,7 @@ const String _fakeResponse = 'fake response body - success'; // The number of bytes in _fakeResponse. const int _fakeResponseLengthInBytes = 28; // Computed by converting _fakeResponse to bytes and getting sha 256 hash. -const String _fakeResponseHash = - '1194f6ffe4d2f05258573616a77932c38041f3102763096c19437c3db1818a04'; +const String _fakeResponseHash = '1194f6ffe4d2f05258573616a77932c38041f3102763096c19437c3db1818a04'; const String expectedCachedFile = 'Foo_regular_1194f6ffe4d2f05258573616a77932c38041f3102763096c19437c3db1818a04.ttf'; // ignore: unused_element @@ -160,10 +155,7 @@ void main() { overridePrint(() async { await loadFontIfNecessary(descriptorInAssets); expect(printLog.length, 1); - expect( - printLog[0], - startsWith('google_fonts was unable to load font Foo-BlackItalic'), - ); + expect(printLog[0], startsWith('google_fonts was unable to load font Foo-BlackItalic')); }); }); @@ -185,10 +177,7 @@ void main() { overridePrint(() async { await loadFontIfNecessary(fakeDescriptor); expect(printLog.length, 1); - expect( - printLog[0], - startsWith('google_fonts was unable to load font Foo-Regular'), - ); + expect(printLog[0], startsWith('google_fonts was unable to load font Foo-Regular')); expect( printLog[0], endsWith( @@ -247,35 +236,29 @@ void main() { verify(mockHttpClient.gets(anything)).called(1); }); - test( - 'loadFontIfNecessary makes second attempt if the first attempt failed ', - () async { - final fakeDescriptor = GoogleFontsDescriptor( - familyWithVariant: const GoogleFontsFamilyWithVariant( - family: 'Foo', - googleFontsVariant: GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ), + test('loadFontIfNecessary makes second attempt if the first attempt failed ', () async { + final fakeDescriptor = GoogleFontsDescriptor( + familyWithVariant: const GoogleFontsFamilyWithVariant( + family: 'Foo', + googleFontsVariant: GoogleFontsVariant( + fontWeight: FontWeight.w400, + fontStyle: FontStyle.normal, ), - file: _fakeResponseFile, - ); + ), + file: _fakeResponseFile, + ); - // Have the first call throw an error. - when(mockHttpClient.gets(any)).thenThrow('some error'); - await expectLater( - loadFontIfNecessary(fakeDescriptor), - throwsA(const TypeMatcher()), - ); + // Have the first call throw an error. + when(mockHttpClient.gets(any)).thenThrow('some error'); + await expectLater(loadFontIfNecessary(fakeDescriptor), throwsA(const TypeMatcher())); - // The second call will retry the http fetch. - when(mockHttpClient.gets(any)).thenAnswer((_) async { - return http.Response(_fakeResponse, 200); - }); - await loadFontIfNecessary(fakeDescriptor); - verify(mockHttpClient.gets(any)).called(2); - }, - ); + // The second call will retry the http fetch. + when(mockHttpClient.gets(any)).thenAnswer((_) async { + return http.Response(_fakeResponse, 200); + }); + await loadFontIfNecessary(fakeDescriptor); + verify(mockHttpClient.gets(any)).called(2); + }); test('loadFontIfNecessary method correctly stores in cache', () async { Directory directoryContents = await getApplicationSupportDirectory(); @@ -288,10 +271,7 @@ void main() { expect(directoryContents.listSync().isNotEmpty, isTrue); - expect( - directoryContents.listSync().single.toString(), - contains(expectedCachedFile), - ); + expect(directoryContents.listSync().single.toString(), contains(expectedCachedFile)); }); test('loadFontIfNecessary method correctly uses cache', () async { @@ -328,10 +308,7 @@ void main() { // Give enough time for the file to be saved await Future.delayed(const Duration(seconds: 1), () {}); expect(directoryContents.listSync().length == 2, isTrue); - expect( - directoryContents.listSync().toString(), - contains(expectedDifferentCachedFile), - ); + expect(directoryContents.listSync().toString(), contains(expectedDifferentCachedFile)); // Should use cache from now on. await loadFontIfNecessary(fakeDescriptorDifferentFile); @@ -340,59 +317,46 @@ void main() { verifyNever(mockHttpClient.gets(anything)); }); - test( - 'loadFontIfNecessary does not save anything to disk if the file does not ' - 'match the expected hash', - () async { - when(mockHttpClient.gets(any)).thenAnswer((_) async { - return http.Response('malicious intercepted response', 200); - }); - final fakeDescriptor = GoogleFontsDescriptor( - familyWithVariant: const GoogleFontsFamilyWithVariant( - family: 'Foo', - googleFontsVariant: GoogleFontsVariant( - fontWeight: FontWeight.w400, - fontStyle: FontStyle.normal, - ), + test('loadFontIfNecessary does not save anything to disk if the file does not ' + 'match the expected hash', () async { + when(mockHttpClient.gets(any)).thenAnswer((_) async { + return http.Response('malicious intercepted response', 200); + }); + final fakeDescriptor = GoogleFontsDescriptor( + familyWithVariant: const GoogleFontsFamilyWithVariant( + family: 'Foo', + googleFontsVariant: GoogleFontsVariant( + fontWeight: FontWeight.w400, + fontStyle: FontStyle.normal, ), - file: _fakeResponseFile, - ); + ), + file: _fakeResponseFile, + ); - Directory directoryContents = await getApplicationSupportDirectory(); - expect(directoryContents.listSync().isEmpty, isTrue); + Directory directoryContents = await getApplicationSupportDirectory(); + expect(directoryContents.listSync().isEmpty, isTrue); - overridePrint(() async { - await loadFontIfNecessary(fakeDescriptor); - expect(printLog.length, 1); - expect( - printLog[0], - startsWith('google_fonts was unable to load font Foo-BlackItalic'), - ); - directoryContents = await getApplicationSupportDirectory(); - expect(directoryContents.listSync().isEmpty, isTrue); - }); - }, - ); + overridePrint(() async { + await loadFontIfNecessary(fakeDescriptor); + expect(printLog.length, 1); + expect(printLog[0], startsWith('google_fonts was unable to load font Foo-BlackItalic')); + directoryContents = await getApplicationSupportDirectory(); + expect(directoryContents.listSync().isEmpty, isTrue); + }); + }); test("loadFontByteData doesn't fail", () { expect( - () async => - loadFontByteData('fontFamily', Future.value(ByteData(0))), - returnsNormally, - ); - expect( - () async => loadFontByteData('fontFamily', Future.value()), + () async => loadFontByteData('fontFamily', Future.value(ByteData(0))), returnsNormally, ); + expect(() async => loadFontByteData('fontFamily', Future.value()), returnsNormally); expect(() async => loadFontByteData('fontFamily', null), returnsNormally); expect( () async => loadFontByteData( 'fontFamily', - Future.delayed( - const Duration(milliseconds: 100), - () => null, - ), + Future.delayed(const Duration(milliseconds: 100), () => null), ), returnsNormally, ); diff --git a/packages/google_fonts/test/load_font_if_necessary_with_local_fonts_test.dart b/packages/google_fonts/test/load_font_if_necessary_with_local_fonts_test.dart index 5182e8dc880a..ddda38f9ed3e 100644 --- a/packages/google_fonts/test/load_font_if_necessary_with_local_fonts_test.dart +++ b/packages/google_fonts/test/load_font_if_necessary_with_local_fonts_test.dart @@ -24,11 +24,7 @@ import 'package:plugin_platform_interface/plugin_platform_interface.dart'; class MockHttpClient extends Mock implements http.Client { Future gets(dynamic uri, {dynamic headers}) { super.noSuchMethod( - Invocation.method( - #get, - [uri], - {#headers: headers}, - ), + Invocation.method(#get, [uri], {#headers: headers}), ); return Future.value(http.Response('', 200)); } @@ -58,8 +54,7 @@ const String _fakeResponse = 'fake response body - success'; // The number of bytes in _fakeResponse. const int _fakeResponseLengthInBytes = 28; // Computed by converting _fakeResponse to bytes and getting sha 256 hash. -const String _fakeResponseHash = - '1194f6ffe4d2f05258573616a77932c38041f3102763096c19437c3db1818a04'; +const String _fakeResponseHash = '1194f6ffe4d2f05258573616a77932c38041f3102763096c19437c3db1818a04'; final GoogleFontsFile _fakeResponseFile = GoogleFontsFile( _fakeResponseHash, _fakeResponseLengthInBytes, @@ -85,14 +80,16 @@ void main() { }); // Add Foo-BlackItalic to mock asset bundle. - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMessageHandler('flutter/assets', (ByteData? message) { - final Uint8List encoded = utf8.encoder.convert( - '{"google_fonts/Foo-BlackItalic.ttf":' - '["google_fonts/Foo-BlackItalic.ttf"]}', - ); - return Future.value(encoded.buffer.asByteData()); - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( + 'flutter/assets', + (ByteData? message) { + final Uint8List encoded = utf8.encoder.convert( + '{"google_fonts/Foo-BlackItalic.ttf":' + '["google_fonts/Foo-BlackItalic.ttf"]}', + ); + return Future.value(encoded.buffer.asByteData()); + }, + ); directory = await Directory.systemTemp.createTemp(); PathProviderPlatform.instance = FakePathProviderPlatform(directory.path); diff --git a/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart b/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart index 8f3ee3568706..f8ace9b4b19b 100644 --- a/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart +++ b/packages/google_identity_services_web/example/integration_test/js_interop_id_test.dart @@ -56,8 +56,9 @@ void main() async { use_fedcm_for_prompt: true, ); - final utils.ExpectConfigValueFn expectConfigValue = utils - .createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils.createExpectConfigValue( + config as JSObject, + ); expectConfigValue('client_id', 'testing_1-2-3'); expectConfigValue('auto_select', false); @@ -65,19 +66,13 @@ void main() async { expectConfigValue('login_uri', 'https://www.example.com/login'); expectConfigValue('native_callback', utils.isAJs('function')); expectConfigValue('cancel_on_tap_outside', false); - expectConfigValue('allowed_parent_origin', [ - 'allowed', - 'another', - ]); + expectConfigValue('allowed_parent_origin', ['allowed', 'another']); expectConfigValue('prompt_parent_id', 'some_dom_id'); expectConfigValue('nonce', 's0m3_r4ndOM_vALu3'); expectConfigValue('context', 'signin'); expectConfigValue('state_cookie_domain', 'subdomain.example.com'); expectConfigValue('ux_mode', 'popup'); - expectConfigValue( - 'intermediate_iframe_close_callback', - utils.isAJs('function'), - ); + expectConfigValue('intermediate_iframe_close_callback', utils.isAJs('function')); expectConfigValue('itp_support', true); expectConfigValue('login_hint', 'login-hint@example.com'); expectConfigValue('hd', 'hd_value'); @@ -86,40 +81,34 @@ void main() async { }); group('prompt', () { - testWidgets( - 'supports a moment notification callback with correct type and reason', - (_) async { - id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); - utils.setMockMomentNotification('skipped', 'user_cancel'); + testWidgets('supports a moment notification callback with correct type and reason', (_) async { + id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); + utils.setMockMomentNotification('skipped', 'user_cancel'); - final controller = StreamController(); + final controller = StreamController(); - id.prompt(controller.add); + id.prompt(controller.add); - final PromptMomentNotification moment = await controller.stream.first; + final PromptMomentNotification moment = await controller.stream.first; - expect(moment.getMomentType(), MomentType.skipped); - expect(moment.getSkippedReason(), MomentSkippedReason.user_cancel); - }, - ); + expect(moment.getMomentType(), MomentType.skipped); + expect(moment.getSkippedReason(), MomentSkippedReason.user_cancel); + }); - testWidgets( - 'supports a moment notification callback while handling invalid reason ' - 'value gracefully', - (_) async { - id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); - utils.setMockMomentNotification('skipped', 'random_invalid_reason'); + testWidgets('supports a moment notification callback while handling invalid reason ' + 'value gracefully', (_) async { + id.initialize(IdConfiguration(client_id: 'testing_1-2-3')); + utils.setMockMomentNotification('skipped', 'random_invalid_reason'); - final controller = StreamController(); + final controller = StreamController(); - id.prompt(controller.add); + id.prompt(controller.add); - final PromptMomentNotification moment = await controller.stream.first; + final PromptMomentNotification moment = await controller.stream.first; - expect(moment.getMomentType(), MomentType.skipped); - expect(moment.getSkippedReason(), isNull); - }, - ); + expect(moment.getMomentType(), MomentType.skipped); + expect(moment.getSkippedReason(), isNull); + }); testWidgets('calls config callback with credential response', (_) async { const expected = 'should_be_a_proper_jwt_token'; @@ -127,9 +116,7 @@ void main() async { final controller = StreamController(); - id.initialize( - IdConfiguration(client_id: 'testing_1-2-3', callback: controller.add), - ); + id.initialize(IdConfiguration(client_id: 'testing_1-2-3', callback: controller.add)); id.prompt(); diff --git a/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart b/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart index 729de5b58765..42f89dad709a 100644 --- a/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart +++ b/packages/google_identity_services_web/example/integration_test/js_interop_oauth_test.dart @@ -37,8 +37,9 @@ void main() async { error_callback: (GoogleIdentityServicesError? _) {}, ); - final utils.ExpectConfigValueFn expectConfigValue = utils - .createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils.createExpectConfigValue( + config as JSObject, + ); expectConfigValue('client_id', 'testing_1-2-3'); expectConfigValue('callback', utils.isAJs('function')); @@ -62,8 +63,9 @@ void main() async { state: 'some-state', ); - final utils.ExpectConfigValueFn expectConfigValue = utils - .createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils.createExpectConfigValue( + config as JSObject, + ); expectConfigValue('scope', 'one two three'); expectConfigValue('include_granted_scopes', true); @@ -89,8 +91,9 @@ void main() async { error_callback: (GoogleIdentityServicesError? _) {}, ); - final utils.ExpectConfigValueFn expectConfigValue = utils - .createExpectConfigValue(config as JSObject); + final utils.ExpectConfigValueFn expectConfigValue = utils.createExpectConfigValue( + config as JSObject, + ); expectConfigValue('scope', 'one two three'); expectConfigValue('include_granted_scopes', true); @@ -127,11 +130,7 @@ void main() async { final scopes = ['some_scope', 'another', 'more']; final TokenClient client = oauth2.initTokenClient( - TokenClientConfig( - client_id: 'for-tests', - callback: controller.add, - scope: scopes, - ), + TokenClientConfig(client_id: 'for-tests', callback: controller.add, scope: scopes), ); utils.setMockTokenResponse(client, 'some-non-null-auth-token-value'); diff --git a/packages/google_identity_services_web/example/integration_test/utils.dart b/packages/google_identity_services_web/example/integration_test/utils.dart index 00c0d521db46..7dc07872461b 100644 --- a/packages/google_identity_services_web/example/integration_test/utils.dart +++ b/packages/google_identity_services_web/example/integration_test/utils.dart @@ -30,9 +30,7 @@ ExpectConfigValueFn createExpectConfigValue(JSObject config) { } else if (matcher is List) { final List old = matcher; matcher = isA().having( - (JSAny? p0) => (p0 as JSArray?)?.toDart - .map((JSAny? e) => e.dartify()) - .toList(), + (JSAny? p0) => (p0 as JSArray?)?.toDart.map((JSAny? e) => e.dartify()).toList(), 'Array with matching values', old, ); @@ -44,11 +42,8 @@ ExpectConfigValueFn createExpectConfigValue(JSObject config) { /// A matcher that checks if: value typeof [thing] == true (in JS). /// /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof -Matcher isAJs(String thing) => isA().having( - (JSAny? p0) => p0.typeofEquals(thing), - 'typeof "$thing"', - isTrue, -); +Matcher isAJs(String thing) => + isA().having((JSAny? p0) => p0.typeofEquals(thing), 'typeof "$thing"', isTrue); /// Installs mock-gis.js in the page. /// Returns a future that completes when the 'load' event of the script fires. @@ -73,11 +68,7 @@ Future installGisMock() { Future fakeAuthZWithScopes(List scopes) { final controller = StreamController(); final TokenClient client = oauth2.initTokenClient( - TokenClientConfig( - client_id: 'for-tests', - callback: controller.add, - scope: scopes, - ), + TokenClientConfig(client_id: 'for-tests', callback: controller.add, scope: scopes), ); setMockTokenResponse(client, 'some-non-null-auth-token-value'); client.requestAccessToken(); @@ -112,25 +103,18 @@ void setMockCredentialResponse([String value = 'default_value']) { /// Sets a mock moment notification in `google.accounts.id`. void setMockMomentNotification(String momentType, String reason) { - _getGoogleAccountsId().setMockMomentNotification( - momentType.toJS, - reason.toJS, - ); + _getGoogleAccountsId().setMockMomentNotification(momentType.toJS, reason.toJS); } GoogleAccountsId _getGoogleAccountsId() { - return _getDeepProperty( - web.window as JSObject, - 'google.accounts.id', - ); + return _getDeepProperty(web.window as JSObject, 'google.accounts.id'); } // Attempts to retrieve a deeply nested property from a jsObject (or die tryin') T _getDeepProperty(JSObject jsObject, String deepProperty) { final List properties = deepProperty.split('.'); return properties.fold( - jsObject, - (JSObject? jsObj, String prop) => jsObj?[prop] as JSObject?, - ) - as T; + jsObject, + (JSObject? jsObj, String prop) => jsObj?[prop] as JSObject?, + ) as T; } diff --git a/packages/google_identity_services_web/example/lib/main.dart b/packages/google_identity_services_web/example/lib/main.dart index b12980289658..b84c075b53a7 100644 --- a/packages/google_identity_services_web/example/lib/main.dart +++ b/packages/google_identity_services_web/example/lib/main.dart @@ -28,6 +28,7 @@ void main() async { id.prompt(onPromptMoment); // #docregion use-loader } + // #enddocregion use-loader /// Handles the ID token returned from the One Tap prompt. diff --git a/packages/google_identity_services_web/example/lib/main_oauth.dart b/packages/google_identity_services_web/example/lib/main_oauth.dart index ee822d8305b2..461c74d63f75 100644 --- a/packages/google_identity_services_web/example/lib/main_oauth.dart +++ b/packages/google_identity_services_web/example/lib/main_oauth.dart @@ -42,9 +42,7 @@ void main() async { error_callback: onError, ); - final overridableCfg = OverridableTokenClientConfig( - scope: scopes + myConnectionsScopes, - ); + final overridableCfg = OverridableTokenClientConfig(scope: scopes + myConnectionsScopes); final TokenClient client = oauth2.initTokenClient(config); @@ -99,9 +97,7 @@ Future get(TokenResponse token, String url) async { final Uri uri = Uri.parse(url); final http.Response response = await http.get( uri, - headers: { - 'Authorization': '${token.token_type} ${token.access_token}', - }, + headers: {'Authorization': '${token.token_type} ${token.access_token}'}, ); if (response.statusCode != 200) { diff --git a/packages/google_identity_services_web/example/lib/src/jwt.dart b/packages/google_identity_services_web/example/lib/src/jwt.dart index 1d01c6cbb34b..de236f501325 100644 --- a/packages/google_identity_services_web/example/lib/src/jwt.dart +++ b/packages/google_identity_services_web/example/lib/src/jwt.dart @@ -42,8 +42,7 @@ Map? decodePayload(String? token) { Map? _decodeJwtPayload(String? payload) { try { // Payload must be normalized before passing it to the codec - return _jwtCodec.decode(base64.normalize(payload!)) - as Map?; + return _jwtCodec.decode(base64.normalize(payload!)) as Map?; } catch (_) { // Do nothing, we always return null for any failure. } diff --git a/packages/google_identity_services_web/lib/oauth2.dart b/packages/google_identity_services_web/lib/oauth2.dart index cdb748747c0b..54262add7c28 100644 --- a/packages/google_identity_services_web/lib/oauth2.dart +++ b/packages/google_identity_services_web/lib/oauth2.dart @@ -3,5 +3,4 @@ // found in the LICENSE file. export 'src/js_interop/google_accounts_oauth2.dart'; -export 'src/js_interop/shared.dart' - show GoogleIdentityServicesErrorType, UxMode; +export 'src/js_interop/shared.dart' show GoogleIdentityServicesErrorType, UxMode; diff --git a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart index 984ca10bfec3..7e34fe477652 100644 --- a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart +++ b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart @@ -110,10 +110,7 @@ extension type GoogleAccountsId._(JSObject _) implements JSObject { @JS('renderButton') external void _renderButton(JSObject parent); @JS('renderButton') - external void _renderButtonWithOptions( - JSObject parent, - GsiButtonConfiguration options, - ); + external void _renderButtonWithOptions(JSObject parent, GsiButtonConfiguration options); /// Record when the user signs out of your website in cookies. /// @@ -141,10 +138,7 @@ extension type GoogleAccountsId._(JSObject _) implements JSObject { @JS('storeCredential') external void _jsStoreCredential(Credential credential); @JS('storeCredential') - external void _jsStoreCredentialWithCallback( - Credential credential, - JSFunction callback, - ); + external void _jsStoreCredentialWithCallback(Credential credential, JSFunction callback); /// Cancels the One Tap flow. /// @@ -310,12 +304,8 @@ extension type IdConfiguration._(JSObject _) implements JSObject { context: context?.toString().toJS, state_cookie_domain: state_cookie_domain?.toJS, ux_mode: ux_mode?.toString().toJS, - allowed_parent_origin: allowed_parent_origin - ?.map((String s) => s.toJS) - .toList() - .toJS, - intermediate_iframe_close_callback: - intermediate_iframe_close_callback?.toJS, + allowed_parent_origin: allowed_parent_origin?.map((String s) => s.toJS).toList().toJS, + intermediate_iframe_close_callback: intermediate_iframe_close_callback?.toJS, itp_support: itp_support?.toJS, login_hint: login_hint?.toJS, hd: hd?.toJS, @@ -379,16 +369,13 @@ extension type PromptMomentNotification._(JSObject _) implements JSObject { external JSBoolean _isDismissedMoment(); /// The moment type. - MomentType getMomentType() => - MomentType.values.byName(_getMomentType().toDart); + MomentType getMomentType() => MomentType.values.byName(_getMomentType().toDart); @JS('getMomentType') external JSString _getMomentType(); /// The detailed reason why the UI isn't displayed. - MomentNotDisplayedReason? getNotDisplayedReason() => maybeEnum( - _getNotDisplayedReason()?.toDart, - MomentNotDisplayedReason.values, - ); + MomentNotDisplayedReason? getNotDisplayedReason() => + maybeEnum(_getNotDisplayedReason()?.toDart, MomentNotDisplayedReason.values); @JS('getNotDisplayedReason') external JSString? _getNotDisplayedReason(); @@ -439,8 +426,7 @@ extension type CredentialResponse._(JSObject _) implements JSObject { /// to set the value. /// /// See more: https://developers.google.com/identity/gsi/web/reference/js-reference#select_by - CredentialSelectBy? get select_by => - maybeEnum(_select_by?.toDart, CredentialSelectBy.values); + CredentialSelectBy? get select_by => maybeEnum(_select_by?.toDart, CredentialSelectBy.values); @JS('select_by') external JSString? get _select_by; } @@ -581,8 +567,7 @@ typedef NativeCallbackFn = void Function(Credential credential); /// The type of the `callback` function passed to [revoke], to be notified of /// the success of the revocation operation. -typedef RevocationResponseHandlerFn = - void Function(RevocationResponse revocationResponse); +typedef RevocationResponseHandlerFn = void Function(RevocationResponse revocationResponse); /// The parameter passed to the `callback` of the [revoke] function. /// diff --git a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart index f2e94da1d28d..fedbe70d4708 100644 --- a/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart +++ b/packages/google_identity_services_web/lib/src/js_interop/google_accounts_oauth2.dart @@ -45,9 +45,7 @@ extension type GoogleAccountsOauth2._(JSObject _) implements JSObject { /// Method: google.accounts.oauth2.hasGrantedAllScopes /// https://developers.google.com/identity/oauth2/web/reference/js-reference#google.accounts.oauth2.hasGrantedAllScopes bool hasGrantedAllScopes(TokenResponse tokenResponse, List scopes) { - return scopes.every( - (String scope) => _hasGrantedScope(tokenResponse, scope.toJS), - ); + return scopes.every((String scope) => _hasGrantedScope(tokenResponse, scope.toJS)); } /// Checks if hte user has granted **all** the specified [scopes]. @@ -57,9 +55,7 @@ extension type GoogleAccountsOauth2._(JSObject _) implements JSObject { /// Method: google.accounts.oauth2.hasGrantedAllScopes /// https://developers.google.com/identity/oauth2/web/reference/js-reference#google.accounts.oauth2.hasGrantedAllScopes bool hasGrantedAnyScopes(TokenResponse tokenResponse, List scopes) { - return scopes.any( - (String scope) => _hasGrantedScope(tokenResponse, scope.toJS), - ); + return scopes.any((String scope) => _hasGrantedScope(tokenResponse, scope.toJS)); } /// Revokes all of the scopes that the user granted to the app. @@ -100,8 +96,7 @@ extension type CodeClientConfig._(JSObject _) implements JSObject { CodeClientCallbackFn? callback, String? state, bool? enable_granular_consent, - @Deprecated('Use `enable_granular_consent` instead.') - bool? enable_serial_consent, + @Deprecated('Use `enable_granular_consent` instead.') bool? enable_serial_consent, String? login_hint, String? hd, UxMode? ux_mode, @@ -212,8 +207,7 @@ extension type TokenClientConfig._(JSObject _) implements JSObject { bool? include_granted_scopes, String? prompt, bool? enable_granular_consent, - @Deprecated('Use `enable_granular_consent` instead.') - bool? enable_serial_consent, + @Deprecated('Use `enable_granular_consent` instead.') bool? enable_serial_consent, String? login_hint, String? hd, String? state, @@ -268,9 +262,7 @@ extension type TokenClient._(JSObject _) implements JSObject { @JS('requestAccessToken') external void _requestAccessToken(); @JS('requestAccessToken') - external void _requestAccessTokenWithConfig( - OverridableTokenClientConfig config, - ); + external void _requestAccessTokenWithConfig(OverridableTokenClientConfig config); } /// The overridable configuration object for the [TokenClientExtension.requestAccessToken] method. @@ -314,8 +306,7 @@ extension type OverridableTokenClientConfig._(JSObject _) implements JSObject { /// in your next application update. /// /// See: https://developers.googleblog.com/2018/10/more-granular-google-account.html - @Deprecated('Use `enable_granular_consent` instead.') - bool? enable_serial_consent, + @Deprecated('Use `enable_granular_consent` instead.') bool? enable_serial_consent, /// When your app knows which user it is trying to authenticate, it can /// provide this parameter as a hint to the authentication server. Passing diff --git a/packages/google_identity_services_web/lib/src/js_loader.dart b/packages/google_identity_services_web/lib/src/js_loader.dart index 04798d043cae..c0355741b2ff 100644 --- a/packages/google_identity_services_web/lib/src/js_loader.dart +++ b/packages/google_identity_services_web/lib/src/js_loader.dart @@ -39,15 +39,11 @@ Future loadWebSdk({ // If TrustedTypes are available, prepare a trusted URL. web.TrustedScriptURL? trustedUrl; if (web.window.nullableTrustedTypes != null) { - web.console.debug( - 'TrustedTypes available. Creating policy: $trustedTypePolicyName'.toJS, - ); + web.console.debug('TrustedTypes available. Creating policy: $trustedTypePolicyName'.toJS); try { final web.TrustedTypePolicy policy = web.window.trustedTypes.createPolicy( trustedTypePolicyName, - web.TrustedTypePolicyOptions( - createScriptURL: ((JSString url) => _url).toJS, - ), + web.TrustedTypePolicyOptions(createScriptURL: ((JSString url) => _url).toJS), ); trustedUrl = policy.createScriptURLNoArgs(_url); } catch (e) { @@ -84,15 +80,12 @@ String? _getNonce({String? suppliedNonce, web.Window? window}) { } final web.Window currentWindow = window ?? web.window; - final web.NodeList elements = currentWindow.document.querySelectorAll( - 'script', - ); + final web.NodeList elements = currentWindow.document.querySelectorAll('script'); for (var i = 0; i < elements.length; i++) { if (elements.item(i) case final web.HTMLScriptElement element) { // Chrome may return an empty string instead of null. - final String nonce = - element.nullableNonce ?? element.getAttribute('nonce') ?? ''; + final String nonce = element.nullableNonce ?? element.getAttribute('nonce') ?? ''; if (nonce.isNotEmpty) { return nonce; } diff --git a/packages/google_identity_services_web/test/js_loader_test.dart b/packages/google_identity_services_web/test/js_loader_test.dart index 533faf3dcc3b..c4c405f436e1 100644 --- a/packages/google_identity_services_web/test/js_loader_test.dart +++ b/packages/google_identity_services_web/test/js_loader_test.dart @@ -86,8 +86,7 @@ void main() { test('when explicitly set overrides the default', () async { const expectedNonce = 'third-random-nonce'; - final otherScript = web.HTMLScriptElement() - ..nonce = 'this-is-the-wrong-nonce'; + final otherScript = web.HTMLScriptElement()..nonce = 'this-is-the-wrong-nonce'; web.document.head?.appendChild(otherScript); // This test doesn't simulate the callback that completes the future, and @@ -102,8 +101,7 @@ void main() { }); test('when null disables the feature', () async { - final otherScript = web.HTMLScriptElement() - ..nonce = 'this-is-the-wrong-nonce'; + final otherScript = web.HTMLScriptElement()..nonce = 'this-is-the-wrong-nonce'; web.document.head?.appendChild(otherScript); // This test doesn't simulate the callback that completes the future, and diff --git a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart index a114cbe04631..7a65092598a4 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_controller.dart @@ -40,8 +40,7 @@ void runTests() { ), ), ); - final GoogleMapController mapController = - await mapControllerCompleter.future; + final GoogleMapController mapController = await mapControllerCompleter.future; await tester.pumpAndSettle(); @@ -50,8 +49,9 @@ void runTests() { // https://github.com/flutter/flutter/issues/54758 await Future.delayed(const Duration(seconds: 1)); - final ScreenCoordinate coordinate = await mapController - .getScreenCoordinate(kInitialCameraPosition.target); + final ScreenCoordinate coordinate = await mapController.getScreenCoordinate( + kInitialCameraPosition.target, + ); final Rect rect = tester.getRect(find.byKey(key)); if (isIOS || isWeb) { // On iOS, the coordinate value from the GoogleMapSdk doesn't include the devicePixelRatio`. @@ -61,13 +61,11 @@ void runTests() { } else { expect( coordinate.x, - ((rect.center.dx - rect.topLeft.dx) * tester.view.devicePixelRatio) - .round(), + ((rect.center.dx - rect.topLeft.dx) * tester.view.devicePixelRatio).round(), ); expect( coordinate.y, - ((rect.center.dy - rect.topLeft.dy) * tester.view.devicePixelRatio) - .round(), + ((rect.center.dy - rect.topLeft.dy) * tester.view.devicePixelRatio).round(), ); } await tester.binding.setSurfaceSize(null); @@ -105,8 +103,7 @@ void runTests() { ), ); await tester.pumpAndSettle(); - final GoogleMapController mapController = - await mapControllerCompleter.future; + final GoogleMapController mapController = await mapControllerCompleter.future; // Wait for the visible region to be non-zero. final LatLngBounds firstVisibleRegion = @@ -137,21 +134,15 @@ void runTests() { expect(firstVisibleRegion.contains(northEast), isFalse); expect(firstVisibleRegion.contains(southWest), isFalse); - final latLngBounds = LatLngBounds( - southwest: southWest, - northeast: northEast, - ); + final latLngBounds = LatLngBounds(southwest: southWest, northeast: northEast); // TODO(iskakaushik): non-zero padding is needed for some device configurations // https://github.com/flutter/flutter/issues/30575 const double padding = 0; - await mapController.moveCamera( - CameraUpdate.newLatLngBounds(latLngBounds, padding), - ); + await mapController.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController.getVisibleRegion(); expect(secondVisibleRegion, isNot(zeroLatLngBounds)); @@ -178,16 +169,13 @@ void runTests() { ); final GoogleMapController controller = await controllerCompleter.future; - const mapStyle = - '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; + const mapStyle = '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; // Intentionally testing the deprecated code path. // ignore: deprecated_member_use await controller.setMapStyle(mapStyle); }); - testWidgets('testSetMapStyle invalid Json String', ( - WidgetTester tester, - ) async { + testWidgets('testSetMapStyle invalid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -257,13 +245,8 @@ void runTests() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng topLeft = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); + final LatLng topLeft = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); expect(topLeft, northWest); }); @@ -329,13 +312,8 @@ void runTests() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); - final ScreenCoordinate topLeft = await controller.getScreenCoordinate( - northWest, - ); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); + final ScreenCoordinate topLeft = await controller.getScreenCoordinate(northWest); expect(topLeft, const ScreenCoordinate(x: 0, y: 0)); }, // TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825 @@ -411,9 +389,7 @@ void runTests() { // re-evaluated when that issue is fixed. await Future.delayed(const Duration(seconds: 1)); - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, false); await controller.showMarkerInfoWindow(marker.markerId); @@ -450,16 +426,11 @@ void runTests() { }); testWidgets('markerWithAssetMapBitmapCreate', (WidgetTester tester) async { - final imageConfiguration = ImageConfiguration( - devicePixelRatio: tester.view.devicePixelRatio, - ); + final imageConfiguration = ImageConfiguration(devicePixelRatio: tester.view.devicePixelRatio); final markers = { Marker( markerId: const MarkerId('1'), - icon: await AssetMapBitmap.create( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await AssetMapBitmap.create(imageConfiguration, 'assets/red_square.png'), ), }; await pumpMap( @@ -476,10 +447,7 @@ void runTests() { final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; await pumpMap( @@ -502,10 +470,7 @@ void runTests() { markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. // ignore: deprecated_member_use - icon: await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await BitmapDescriptor.fromAssetImage(imageConfiguration, 'assets/red_square.png'), ), }; await pumpMap( diff --git a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_inspector.dart b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_inspector.dart index 06588979e29c..80f809dce6b6 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_inspector.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/maps_inspector.dart @@ -26,8 +26,9 @@ final LatLngBounds _testCameraBounds = LatLngBounds( northeast: const LatLng(50, -65), southwest: const LatLng(28.5, -123), ); -final ValueVariant _cameraUpdateTypeVariants = - ValueVariant(CameraUpdateType.values.toSet()); +final ValueVariant _cameraUpdateTypeVariants = ValueVariant( + CameraUpdateType.values.toSet(), +); /// Integration Tests that use the [GoogleMapsInspectorPlatform]. void main() { @@ -38,8 +39,7 @@ void main() { void runTests() { GoogleMapsFlutterPlatform.instance.enableDebugInspection(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; testWidgets('testCompassToggle', (WidgetTester tester) async { final Key key = GlobalKey(); @@ -142,8 +142,9 @@ void runTests() { final GoogleMapController controller = await controllerCompleter.future; if (isIOS) { - final MinMaxZoomPreference zoomLevel = await inspector - .getMinMaxZoomLevels(mapId: controller.mapId); + final MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( + mapId: controller.mapId, + ); expect(zoomLevel, equals(initialZoomLevel)); } else if (isAndroid) { await controller.moveCamera(CameraUpdate.zoomTo(15)); @@ -170,8 +171,9 @@ void runTests() { ); if (isIOS) { - final MinMaxZoomPreference zoomLevel = await inspector - .getMinMaxZoomLevels(mapId: controller.mapId); + final MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( + mapId: controller.mapId, + ); expect(zoomLevel, equals(finalZoomLevel)); } else { await controller.moveCamera(CameraUpdate.zoomTo(15)); @@ -203,9 +205,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled( - mapId: mapId, - ); + bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled(mapId: mapId); expect(zoomGesturesEnabled, false); await pumpMap( @@ -239,9 +239,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + bool zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); expect(zoomControlsEnabled, !isIOS); /// Zoom Controls functionality is not available on iOS at the moment. @@ -258,9 +256,7 @@ void runTests() { ), ); - zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); expect(zoomControlsEnabled, false); } }); @@ -317,9 +313,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, false); await pumpMap( @@ -333,9 +327,7 @@ void runTests() { ), ); - rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, !isWeb); }); @@ -356,9 +348,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled( - mapId: mapId, - ); + bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled(mapId: mapId); expect(tiltGesturesEnabled, false); await pumpMap( @@ -393,9 +383,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, false); await pumpMap( @@ -409,9 +397,7 @@ void runTests() { ), ); - scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, true); }); @@ -466,9 +452,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final bool isBuildingsEnabled = await inspector.areBuildingsEnabled( - mapId: mapId, - ); + final bool isBuildingsEnabled = await inspector.areBuildingsEnabled(mapId: mapId); expect(isBuildingsEnabled, !isWeb); }); @@ -491,9 +475,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); await pumpMap( @@ -508,15 +490,11 @@ void runTests() { ), ); - myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value false', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value false', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -533,14 +511,11 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value true', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value true', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -556,8 +531,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); }); }, skip: !isIOS); @@ -581,10 +555,7 @@ void runTests() { final marker = Marker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - kInitialMapCenter.latitude + i, - kInitialMapCenter.longitude, - ), + position: LatLng(kInitialMapCenter.latitude + i, kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -607,8 +578,7 @@ void runTests() { final GoogleMapController controller = await controllerCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -650,8 +620,7 @@ void runTests() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -663,8 +632,7 @@ void runTests() { key: key, initialCameraPosition: kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { cameraIdleCompleter.complete(); } }, @@ -699,9 +667,7 @@ void runTests() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - beforeFinishedPosition = await inspector.getCameraPosition( - mapId: controller.mapId, - ); + beforeFinishedPosition = await inspector.getCameraPosition(mapId: controller.mapId); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -720,8 +686,9 @@ void runTests() { // has moved as expected. if (inspector.supportsGettingGameraPosition()) { // After onCameraIdle event, the camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -754,8 +721,7 @@ void runTests() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -779,8 +745,7 @@ void runTests() { key: key, initialCameraPosition: kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { stopwatch.stop(); cameraIdleCompleter.complete(); } @@ -824,15 +789,10 @@ void runTests() { // For short animation duration, check that the animation is completed // faster than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - lessThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, lessThan(animationDurationMiddlePoint)); // Reset camera to initial position before testing long duration. - await controller.moveCamera( - CameraUpdate.newCameraPosition(kInitialCameraPosition), - ); + await controller.moveCamera(CameraUpdate.newCameraPosition(kInitialCameraPosition)); await tester.pumpAndSettle(); // Create completer for camera idle event. @@ -859,9 +819,7 @@ void runTests() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - beforeFinishedPosition = await inspector.getCameraPosition( - mapId: controller.mapId, - ); + beforeFinishedPosition = await inspector.getCameraPosition(mapId: controller.mapId); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -878,17 +836,15 @@ void runTests() { // For longer animation duration, check that the animation is completed // slower than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - greaterThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, greaterThan(animationDurationMiddlePoint)); // If platform supportes getting camera position, check that the camera // has moved as expected. if (inspector.supportsGettingGameraPosition()) { // Camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -911,10 +867,7 @@ void runTests() { ); } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, @@ -938,23 +891,15 @@ Marker _copyMarkerWithClusterManagerId( CameraUpdate _getCameraUpdateForType(CameraUpdateType type) { return switch (type) { - CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition( - _kTestCameraPosition, - ), + CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition(_kTestCameraPosition), CameraUpdateType.newLatLng => CameraUpdate.newLatLng(_kTestMapCenter), - CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds( - _testCameraBounds, - 0, - ), + CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds(_testCameraBounds, 0), CameraUpdateType.newLatLngZoom => CameraUpdate.newLatLngZoom( _kTestMapCenter, _kTestCameraZoomLevel, ), CameraUpdateType.scrollBy => CameraUpdate.scrollBy(10, 10), - CameraUpdateType.zoomBy => CameraUpdate.zoomBy( - _kTestZoomByAmount, - const Offset(1, 1), - ), + CameraUpdateType.zoomBy => CameraUpdate.zoomBy(_kTestZoomByAmount, const Offset(1, 1)), CameraUpdateType.zoomTo => CameraUpdate.zoomTo(_kTestCameraZoomLevel), CameraUpdateType.zoomIn => CameraUpdate.zoomIn(), CameraUpdateType.zoomOut => CameraUpdate.zoomOut(), @@ -974,29 +919,16 @@ Future _checkCameraUpdateByType( switch (type) { case CameraUpdateType.newCameraPosition: - expect( - currentPosition.bearing, - wrapMatcher(equals(_kTestCameraPosition.bearing)), - ); - expect( - currentPosition.zoom, - wrapMatcher(equals(_kTestCameraPosition.zoom)), - ); - expect( - currentPosition.tilt, - wrapMatcher(equals(_kTestCameraPosition.tilt)), - ); + expect(currentPosition.bearing, wrapMatcher(equals(_kTestCameraPosition.bearing))); + expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraPosition.zoom))); + expect(currentPosition.tilt, wrapMatcher(equals(_kTestCameraPosition.tilt))); expect( currentPosition.target.latitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.latitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.latitude, latLngThreshold)), ); expect( currentPosition.target.longitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLng: expect( @@ -1011,15 +943,11 @@ Future _checkCameraUpdateByType( final LatLngBounds bounds = await controller.getVisibleRegion(); expect( bounds.northeast.longitude, - wrapMatcher( - closeTo(_testCameraBounds.northeast.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.northeast.longitude, latLngThreshold)), ); expect( bounds.southwest.longitude, - wrapMatcher( - closeTo(_testCameraBounds.southwest.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.southwest.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLngZoom: expect( @@ -1034,20 +962,11 @@ Future _checkCameraUpdateByType( case CameraUpdateType.scrollBy: // For scrollBy, just check that the location has changed. if (oldPosition != null) { - expect( - currentPosition.target.latitude, - isNot(equals(oldPosition.target.latitude)), - ); - expect( - currentPosition.target.longitude, - isNot(equals(oldPosition.target.longitude)), - ); + expect(currentPosition.target.latitude, isNot(equals(oldPosition.target.latitude))); + expect(currentPosition.target.longitude, isNot(equals(oldPosition.target.longitude))); } case CameraUpdateType.zoomBy: - expect( - currentPosition.zoom, - wrapMatcher(equals(kInitialZoomLevel + _kTestZoomByAmount)), - ); + expect(currentPosition.zoom, wrapMatcher(equals(kInitialZoomLevel + _kTestZoomByAmount))); case CameraUpdateType.zoomTo: expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraZoomLevel))); case CameraUpdateType.zoomIn: diff --git a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart index 3af595236c25..68cd678de478 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/shared.dart @@ -28,8 +28,7 @@ const String kMapId = '000000000000000'; // Dummy map ID. final bool isIOS = defaultTargetPlatform == TargetPlatform.iOS; /// True if the test is running in an Android device -final bool isAndroid = - defaultTargetPlatform == TargetPlatform.android && !kIsWeb; +final bool isAndroid = defaultTargetPlatform == TargetPlatform.android && !kIsWeb; /// True if the test is running in a web browser. const bool isWeb = kIsWeb; diff --git a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart index c6641a806b20..5b10e92cad5f 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/integration_test/src/tiles_inspector.dart @@ -25,8 +25,7 @@ void runTests() { GoogleMapsFlutterPlatform.instance.enableDebugInspection(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; group('Tiles', () { testWidgets('set tileOverlay correctly', (WidgetTester tester) async { @@ -73,18 +72,12 @@ void runTests() { expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.2, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); - expect( - tileOverlayInfo2.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }); @@ -156,10 +149,7 @@ void runTests() { expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); @@ -216,10 +206,7 @@ void runTests() { group('Heatmaps', () { /// Check that two lists of [WeightedLatLng] are more or less equal. - void expectHeatmapDataMoreOrLessEquals( - List data1, - List data2, - ) { + void expectHeatmapDataMoreOrLessEquals(List data1, List data2) { expect(data1.length, data2.length); for (var i = 0; i < data1.length; i++) { final WeightedLatLng wll1 = data1[i]; @@ -246,10 +233,7 @@ void runTests() { final HeatmapGradientColor color1 = gradient1.colors[i]; final HeatmapGradientColor color2 = gradient2.colors[i]; expect(color1.color, color2.color); - expect( - color1.startPoint, - moreOrLessEquals(color2.startPoint, epsilon: floatTolerance), - ); + expect(color1.startPoint, moreOrLessEquals(color2.startPoint, epsilon: floatTolerance)); } expect(gradient1.colorMapSize, gradient2.colorMapSize); @@ -257,10 +241,7 @@ void runTests() { void expectHeatmapEquals(Heatmap heatmap1, Heatmap heatmap2) { expectHeatmapDataMoreOrLessEquals(heatmap1.data, heatmap2.data); - expectHeatmapGradientMoreOrLessEquals( - heatmap1.gradient, - heatmap2.gradient, - ); + expectHeatmapGradientMoreOrLessEquals(heatmap1.gradient, heatmap2.gradient); // Only Android supports `maxIntensity` // so the platform value is undefined on others. @@ -277,10 +258,7 @@ void runTests() { if (canHandleMaxIntensity()) { expect(heatmap1.maxIntensity, heatmap2.maxIntensity); } - expect( - heatmap1.opacity, - moreOrLessEquals(heatmap2.opacity, epsilon: floatTolerance), - ); + expect(heatmap1.opacity, moreOrLessEquals(heatmap2.opacity, epsilon: floatTolerance)); expect(heatmap1.radius, heatmap2.radius); if (canHandleZoomIntensity()) { expect(heatmap1.minimumZoomIntensity, heatmap2.minimumZoomIntensity); @@ -350,8 +328,7 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingHeatmapInfo()) { final Heatmap heatmapInfo1 = (await inspector.getHeatmapInfo( @@ -388,8 +365,7 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final Heatmap heatmap1New = heatmap1.copyWith( dataParam: heatmap1.data.sublist(5), @@ -448,8 +424,7 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -467,10 +442,7 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingHeatmapInfo()) { - final Heatmap? heatmapInfo1 = await inspector.getHeatmapInfo( - heatmap1.mapsId, - mapId: mapId, - ); + final Heatmap? heatmapInfo1 = await inspector.getHeatmapInfo(heatmap1.mapsId, mapId: mapId); expect(heatmapInfo1, isNull); } @@ -513,22 +485,13 @@ void runTests() { zoomLevel: 14.0, ); - void expectGroundOverlayEquals( - GroundOverlay source, - GroundOverlay response, - ) { + void expectGroundOverlayEquals(GroundOverlay source, GroundOverlay response) { expect(response.groundOverlayId, source.groundOverlayId); - expect( - response.transparency, - moreOrLessEquals(source.transparency, epsilon: floatTolerance), - ); + expect(response.transparency, moreOrLessEquals(source.transparency, epsilon: floatTolerance)); // Web does not support bearing. if (!isWeb) { - expect( - response.bearing, - moreOrLessEquals(source.bearing, epsilon: floatTolerance), - ); + expect(response.bearing, moreOrLessEquals(source.bearing, epsilon: floatTolerance)); } // Only test bounds if it was given in the original object. @@ -561,14 +524,8 @@ void runTests() { // Only Android (using position) and iOS supports `anchor`. if ((isAndroid && source.position != null) || isIOS) { - expect( - response.anchor?.dx, - moreOrLessEquals(source.anchor!.dx, epsilon: floatTolerance), - ); - expect( - response.anchor?.dy, - moreOrLessEquals(source.anchor!.dy, epsilon: floatTolerance), - ); + expect(response.anchor?.dx, moreOrLessEquals(source.anchor!.dx, epsilon: floatTolerance)); + expect(response.anchor?.dy, moreOrLessEquals(source.anchor!.dy, epsilon: floatTolerance)); } } @@ -600,42 +557,33 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayBoundsInfo2 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; - - expectGroundOverlayEquals( - groundOverlayBounds1, - groundOverlayBoundsInfo1, - ); - expectGroundOverlayEquals( - groundOverlayBounds2, - groundOverlayBoundsInfo2, - ); + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds2.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1, groundOverlayBoundsInfo1); + expectGroundOverlayEquals(groundOverlayBounds2, groundOverlayBoundsInfo2); // Web does not support position-based ground overlays. if (!isWeb) { - final GroundOverlay groundOverlayPositionInfo1 = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - expectGroundOverlayEquals( - groundOverlayPosition1, - groundOverlayPositionInfo1, - ); + final GroundOverlay groundOverlayPositionInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + expectGroundOverlayEquals(groundOverlayPosition1, groundOverlayPositionInfo1); } } }); - testWidgets('update ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('update ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -659,26 +607,23 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - - final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1 - .copyWith( - bearingParam: 10, - clickableParam: false, - visibleParam: false, - transparencyParam: 0.5, - zIndexParam: 10, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; - final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1 - .copyWith( - bearingParam: 10, - clickableParam: false, - visibleParam: false, - transparencyParam: 0.5, - zIndexParam: 10, - ); + final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1.copyWith( + bearingParam: 10, + clickableParam: false, + visibleParam: false, + transparencyParam: 0.5, + zIndexParam: 10, + ); + + final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1.copyWith( + bearingParam: 10, + clickableParam: false, + visibleParam: false, + transparencyParam: 0.5, + zIndexParam: 10, + ); await tester.pumpWidget( Directionality( @@ -701,33 +646,26 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; + final GroundOverlay groundOverlayBounds1Info = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; - expectGroundOverlayEquals( - groundOverlayBounds1New, - groundOverlayBounds1Info, - ); + expectGroundOverlayEquals(groundOverlayBounds1New, groundOverlayBounds1Info); // Web does not support position-based ground overlays. if (!isWeb) { - final GroundOverlay groundOverlayPosition1Info = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayPosition1New, - groundOverlayPosition1Info, - ); + final GroundOverlay groundOverlayPosition1Info = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayPosition1New, groundOverlayPosition1Info); } } }); - testWidgets('remove ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('remove ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -751,8 +689,7 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -770,17 +707,18 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay? groundOverlayBounds1Info = await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId); + final GroundOverlay? groundOverlayBounds1Info = await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ); expect(groundOverlayBounds1Info, isNull); // Web does not support position-based ground overlays. if (!isWeb) { - final GroundOverlay? groundOverlayPositionInfo = await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ); + final GroundOverlay? groundOverlayPositionInfo = await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ); expect(groundOverlayPositionInfo, isNull); } } @@ -806,22 +744,14 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_marker_icons.dart index 93c68e130cf1..a5c3dee3d9f2 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_marker_icons.dart @@ -32,8 +32,7 @@ class _AdvancedMarkerIconsBody extends StatefulWidget { final String? mapId; @override - State<_AdvancedMarkerIconsBody> createState() => - _AdvancedMarkerIconsBodyState(); + State<_AdvancedMarkerIconsBody> createState() => _AdvancedMarkerIconsBodyState(); } class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { @@ -50,10 +49,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { child: GoogleMap( mapId: widget.mapId, markerType: GoogleMapMarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: (GoogleMapController controller) { setState(() { @@ -72,29 +68,22 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { const ImageConfiguration(size: Size(12, 12)), 'assets/red_square.png', ); - final AssetMapBitmap largeAsset = - await BitmapDescriptor.asset( - const ImageConfiguration(size: Size(36, 36)), - 'assets/red_square.png', - ); + final AssetMapBitmap largeAsset = await BitmapDescriptor.asset( + const ImageConfiguration(size: Size(36, 36)), + 'assets/red_square.png', + ); setState(() { _markers.addAll([ // Default icon AdvancedMarker( markerId: const MarkerId('1'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude + 1), ), // Custom pin colors AdvancedMarker( markerId: const MarkerId('2'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.black, @@ -104,26 +93,17 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Pin with text AdvancedMarker( markerId: const MarkerId('3'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude + 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.blue, backgroundColor: Colors.white, - glyph: const TextGlyph( - text: 'Hi!', - textColor: Colors.blue, - ), + glyph: const TextGlyph(text: 'Hi!', textColor: Colors.blue), ), ), // Pin with bitmap AdvancedMarker( markerId: const MarkerId('4'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.white, @@ -133,10 +113,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Custom marker icon AdvancedMarker( markerId: const MarkerId('5'), - position: LatLng( - _kMapCenter.latitude, - _kMapCenter.longitude, - ), + position: LatLng(_kMapCenter.latitude, _kMapCenter.longitude), icon: largeAsset, ), ]); diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_markers_clustering.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_markers_clustering.dart index d9612ef93ec0..a1ca7fff7bfd 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_markers_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/advanced_markers_clustering.dart @@ -16,10 +16,7 @@ import 'place_advanced_marker.dart'; class AdvancedMarkersClustering extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkersClustering({super.key, required this.mapId}) - : super( - const Icon(Icons.place_outlined), - 'Manage clusters of advanced markers', - ); + : super(const Icon(Icons.place_outlined), 'Manage clusters of advanced markers'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -72,8 +69,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { GoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -119,17 +115,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; }); } @@ -161,8 +151,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -171,14 +160,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -222,9 +208,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); @@ -267,8 +251,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { TextButton( onPressed: clusterManagers.isEmpty ? null - : () => - _removeClusterManager(clusterManagers.values.last), + : () => _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -276,8 +259,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { Wrap( alignment: WrapAlignment.spaceEvenly, children: [ - for (final MapEntry - clusterEntry + for (final MapEntry clusterEntry in clusterManagers.entries) TextButton( onPressed: () => _addMarkersToCluster(clusterEntry.value), @@ -300,9 +282,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { child: const Text('Remove selected marker'), ), TextButton( - onPressed: markers.isEmpty - ? null - : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty ? null : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart index 07458f88e3c3..385e351bbf23 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/animate_camera.dart @@ -11,8 +11,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class AnimateCameraPage extends GoogleMapExampleAppPage { - const AnimateCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control, animated'); + const AnimateCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control, animated'); @override Widget build(BuildContext context) { @@ -58,9 +57,7 @@ class AnimateCameraState extends State { height: 200.0, child: GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -88,9 +85,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), duration: _cameraUpdateAnimationDuration, ); }, @@ -114,10 +109,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), duration: _cameraUpdateAnimationDuration, ); }, diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart index 9678c1da0f74..0685c76b19e1 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/clustering.dart @@ -12,8 +12,7 @@ import 'page.dart'; /// Page for demonstrating marker clustering support. class ClusteringPage extends GoogleMapExampleAppPage { /// Default Constructor. - const ClusteringPage({super.key}) - : super(const Icon(Icons.place), 'Manage clustering'); + const ClusteringPage({super.key}) : super(const Icon(Icons.place), 'Manage clustering'); @override Widget build(BuildContext context) { @@ -60,8 +59,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { GoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -104,10 +102,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -143,8 +138,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -153,14 +147,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -199,9 +190,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); @@ -239,8 +228,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { TextButton( onPressed: clusterManagers.isEmpty ? null - : () => - _removeClusterManager(clusterManagers.values.last), + : () => _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -248,8 +236,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { Wrap( alignment: WrapAlignment.spaceEvenly, children: [ - for (final MapEntry - clusterEntry + for (final MapEntry clusterEntry in clusterManagers.entries) TextButton( onPressed: () => _addMarkersToCluster(clusterEntry.value), @@ -272,9 +259,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { child: const Text('Remove selected marker'), ), TextButton( - onPressed: markers.isEmpty - ? null - : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty ? null : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/collision_behavior.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/collision_behavior.dart index 09ed5741bfdc..352df6ccd2c3 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/collision_behavior.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/collision_behavior.dart @@ -14,10 +14,7 @@ import 'place_advanced_marker.dart'; class AdvancedMarkerCollisionBehaviorPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkerCollisionBehaviorPage({super.key, required this.mapId}) - : super( - const Icon(Icons.not_listed_location), - 'Advanced marker collision behavior', - ); + : super(const Icon(Icons.not_listed_location), 'Advanced marker collision behavior'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -34,12 +31,10 @@ class _CollisionBehaviorPageBody extends StatefulWidget { final String? mapId; @override - State<_CollisionBehaviorPageBody> createState() => - _CollisionBehaviorPageBodyState(); + State<_CollisionBehaviorPageBody> createState() => _CollisionBehaviorPageBodyState(); } -class _CollisionBehaviorPageBodyState - extends State<_CollisionBehaviorPageBody> { +class _CollisionBehaviorPageBodyState extends State<_CollisionBehaviorPageBody> { static const LatLng center = LatLng(-33.86711, 151.1947171); static const double zoomOutLevel = 9; static const double zoomInLevel = 12; @@ -77,10 +72,7 @@ class _CollisionBehaviorPageBodyState child: GoogleMap( mapId: widget.mapId, markerType: GoogleMapMarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: center, - zoom: zoomInLevel, - ), + initialCameraPosition: const CameraPosition(target: center, zoom: zoomInLevel), markers: Set.of(markers), tiltGesturesEnabled: false, zoomGesturesEnabled: false, diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/custom_marker_icon.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/custom_marker_icon.dart index 548146c6206c..3391ba1bcba2 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/custom_marker_icon.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/custom_marker_icon.dart @@ -20,9 +20,7 @@ Future createCustomMarkerIconImage({required Size size}) async { size.height.floor(), ); - final ByteData? bytes = await image.toByteData( - format: ui.ImageByteFormat.png, - ); + final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); return bytes!; } diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart index 5142cb8395d5..8b459ce0619c 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/ground_overlay.dart @@ -13,8 +13,7 @@ import 'page.dart'; enum _GroundOverlayPlacing { position, bounds } class GroundOverlayPage extends GoogleMapExampleAppPage { - const GroundOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Ground overlay'); + const GroundOverlayPage({super.key}) : super(const Icon(Icons.map), 'Ground overlay'); @override Widget build(BuildContext context) { @@ -134,9 +133,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { _groundOverlay = _groundOverlay!.copyWith( - bearingParam: _groundOverlay!.bearing >= 350 - ? 0 - : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, ); }); } @@ -145,9 +142,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { final transparency = _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; - _groundOverlay = _groundOverlay!.copyWith( - transparencyParam: transparency, - ); + _groundOverlay = _groundOverlay!.copyWith(transparencyParam: transparency); }); } @@ -183,8 +178,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.bounds); setState(() { - _currentGroundOverlayBounds = - _currentGroundOverlayBounds == _groundOverlayBounds1 + _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 ? _groundOverlayBounds2 : _groundOverlayBounds1; }); @@ -197,9 +191,7 @@ class GroundOverlayBodyState extends State { void _toggleVisible() { assert(_groundOverlay != null); setState(() { - _groundOverlay = _groundOverlay!.copyWith( - visibleParam: !_groundOverlay!.visible, - ); + _groundOverlay = _groundOverlay!.copyWith(visibleParam: !_groundOverlay!.visible); }); } @@ -238,9 +230,7 @@ class GroundOverlayBodyState extends State { @override Widget build(BuildContext context) { - final overlays = { - if (_groundOverlay != null) _groundOverlay!, - }; + final overlays = {if (_groundOverlay != null) _groundOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -248,10 +238,7 @@ class GroundOverlayBodyState extends State { children: [ Expanded( child: GoogleMap( - initialCameraPosition: CameraPosition( - target: _mapCenter, - zoom: 14.0, - ), + initialCameraPosition: CameraPosition(target: _mapCenter, zoom: 14.0), groundOverlays: overlays, onMapCreated: _onMapCreated, ), @@ -273,9 +260,7 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeTransparency(), + onPressed: _groundOverlay == null ? null : () => _changeTransparency(), child: const Text('change transparency'), ), if (!kIsWeb) @@ -289,49 +274,37 @@ class GroundOverlayBodyState extends State { ), if (!kIsWeb) TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeZIndex(), + onPressed: _groundOverlay == null ? null : () => _changeZIndex(), child: const Text('change zIndex'), ), if (!kIsWeb) TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeAnchor(), + onPressed: _groundOverlay == null ? null : () => _changeAnchor(), child: const Text('change anchor'), ), if (!kIsWeb) TextButton( onPressed: _groundOverlay == null ? null : () => _changeType(), child: Text( - _placingType == _GroundOverlayPlacing.position - ? 'use bounds' - : 'use position', + _placingType == _GroundOverlayPlacing.position ? 'use bounds' : 'use position', ), ), if (!kIsWeb) TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changePosition(), child: const Text('change position'), ), if (defaultTargetPlatform == TargetPlatform.android) TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changeDimensions(), child: const Text('change dimensions'), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.bounds || _groundOverlay == null ? null : () => _changeBounds(), child: const Text('change bounds'), diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart index 12288074c79a..c0caa9a4e87b 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/heatmap.dart @@ -94,10 +94,7 @@ class HeatmapBodyState extends State { width: 350.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: sanFrancisco, - zoom: 13, - ), + initialCameraPosition: const CameraPosition(target: sanFrancisco, zoom: 13), heatmaps: { Heatmap( heatmapId: const HeatmapId('test'), @@ -126,15 +123,11 @@ class HeatmapBodyState extends State { Column( children: [ TextButton( - onPressed: disabledPoints.isNotEmpty - ? _addPoint - : null, + onPressed: disabledPoints.isNotEmpty ? _addPoint : null, child: const Text('Add point'), ), TextButton( - onPressed: enabledPoints.isNotEmpty - ? _removePoint - : null, + onPressed: enabledPoints.isNotEmpty ? _removePoint : null, child: const Text('Remove point'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/lite_mode.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/lite_mode.dart index a92bac367eee..e876762e4b0b 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/lite_mode.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/lite_mode.dart @@ -34,10 +34,7 @@ class _LiteModeBody extends StatelessWidget { child: SizedBox( width: 300.0, height: 300.0, - child: GoogleMap( - initialCameraPosition: _kInitialPosition, - liteModeEnabled: true, - ), + child: GoogleMap(initialCameraPosition: _kInitialPosition, liteModeEnabled: true), ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart index 227672f319a8..a56108b9f14a 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/main.dart @@ -96,8 +96,7 @@ class MapsDemo extends StatelessWidget { } void main() { - final GoogleMapsFlutterPlatform mapsImplementation = - GoogleMapsFlutterPlatform.instance; + final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { initializeMapRenderer(); } @@ -120,15 +119,13 @@ Future initializeMapRenderer() async { WidgetsFlutterBinding.ensureInitialized(); - final GoogleMapsFlutterPlatform mapsImplementation = - GoogleMapsFlutterPlatform.instance; + final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { unawaited( mapsImplementation .initializeWithRenderer(AndroidMapRenderer.latest) .then( - (AndroidMapRenderer initializedRenderer) => - completer.complete(initializedRenderer), + (AndroidMapRenderer initializedRenderer) => completer.complete(initializedRenderer), ), ); } else { diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_click.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_click.dart index 286f078e7e43..de3f13912cf7 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_click.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_click.dart @@ -56,42 +56,25 @@ class _MapClickBodyState extends State<_MapClickBody> { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; if (mapController != null) { final lastTap = 'Tap:\n${_lastTap ?? ""}\n'; final lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; + columnChildren.add(Center(child: Text(lastTap, textAlign: TextAlign.center))); columnChildren.add( - Center(child: Text(lastTap, textAlign: TextAlign.center)), - ); - columnChildren.add( - Center( - child: Text( - _lastTap != null ? 'Tapped' : '', - textAlign: TextAlign.center, - ), - ), - ); - columnChildren.add( - Center(child: Text(lastLongPress, textAlign: TextAlign.center)), + Center(child: Text(_lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center)), ); + columnChildren.add(Center(child: Text(lastLongPress, textAlign: TextAlign.center))); columnChildren.add( Center( - child: Text( - _lastLongPress != null ? 'Long pressed' : '', - textAlign: TextAlign.center, - ), + child: Text(_lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } Future onMapCreated(GoogleMapController controller) async { diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_coordinates.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_coordinates.dart index 91a6073e0d66..414a91967002 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_coordinates.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_coordinates.dart @@ -14,8 +14,7 @@ const CameraPosition _kInitialPosition = CameraPosition( ); class MapCoordinatesPage extends GoogleMapExampleAppPage { - const MapCoordinatesPage({super.key}) - : super(const Icon(Icons.map), 'Map coordinates'); + const MapCoordinatesPage({super.key}) : super(const Icon(Icons.map), 'Map coordinates'); @override Widget build(BuildContext context) { @@ -44,8 +43,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { final googleMap = GoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, - onCameraIdle: - _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 + onCameraIdle: _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 ); return NotificationListener( @@ -57,9 +55,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { children: [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), if (mapController != null) Center( diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart index 270a521cd4a5..c911604ec5d5 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_map_id.dart @@ -14,8 +14,7 @@ import 'main.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { - const MapIdPage({super.key}) - : super(const Icon(Icons.map), 'Cloud-based maps styling'); + const MapIdPage({super.key}) : super(const Icon(Icons.map), 'Cloud-based maps styling'); @override Widget build(BuildContext context) { @@ -77,10 +76,7 @@ class MapIdBodyState extends State { Widget build(BuildContext context) { final googleMap = GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), key: _key, mapId: _mapId, ); @@ -88,9 +84,7 @@ class MapIdBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), Padding( padding: const EdgeInsets.all(10.0), @@ -106,9 +100,7 @@ class MapIdBodyState extends State { child: const Text('Press to use specified map Id'), ), ), - if (!kIsWeb && - Platform.isAndroid && - _initializedRenderer != AndroidMapRenderer.latest) + if (!kIsWeb && Platform.isAndroid && _initializedRenderer != AndroidMapRenderer.latest) Padding( padding: const EdgeInsets.all(10.0), child: Text( @@ -118,10 +110,7 @@ class MapIdBodyState extends State { ), ]; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } @override diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart index 51ef0e9bb6c6..7f6f2f111465 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/map_ui.dart @@ -75,9 +75,7 @@ class MapUiBodyState extends State { Widget _webCameraControlToggler() { return TextButton( - child: Text( - '${_webCameraControlEnabled ? 'disable' : 'enable'} web camera control', - ), + child: Text('${_webCameraControlEnabled ? 'disable' : 'enable'} web camera control'), onPressed: () { setState(() { _webCameraControlEnabled = !_webCameraControlEnabled; @@ -101,11 +99,10 @@ class MapUiBodyState extends State { value: _webCameraControlPosition, items: WebCameraControlPosition.values .map( - (WebCameraControlPosition e) => - DropdownMenuItem( - value: e, - child: Text(e.name), - ), + (WebCameraControlPosition e) => DropdownMenuItem( + value: e, + child: Text(e.name), + ), ) .toList(), onChanged: (WebCameraControlPosition? value) { @@ -154,9 +151,7 @@ class MapUiBodyState extends State { Widget _latLngBoundsToggler() { return TextButton( child: Text( - _cameraTargetBounds.bounds == null - ? 'bound camera target' - : 'release camera target', + _cameraTargetBounds.bounds == null ? 'bound camera target' : 'release camera target', ), onPressed: () { setState(() { @@ -170,9 +165,7 @@ class MapUiBodyState extends State { Widget _zoomBoundsToggler() { return TextButton( - child: Text( - _minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom', - ), + child: Text(_minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom'), onPressed: () { setState(() { _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null @@ -184,8 +177,7 @@ class MapUiBodyState extends State { } Widget _mapTypeCycler() { - final MapType nextType = - MapType.values[(_mapType.index + 1) % MapType.values.length]; + final MapType nextType = MapType.values[(_mapType.index + 1) % MapType.values.length]; return TextButton( child: Text('change map type to $nextType'), onPressed: () { @@ -242,9 +234,7 @@ class MapUiBodyState extends State { Widget _zoomControlsToggler() { return TextButton( - child: Text( - '${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls', - ), + child: Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'), onPressed: () { setState(() { _zoomControlsEnabled = !_zoomControlsEnabled; @@ -266,9 +256,7 @@ class MapUiBodyState extends State { Widget _myLocationToggler() { return TextButton( - child: Text( - '${_myLocationEnabled ? 'disable' : 'enable'} my location marker', - ), + child: Text('${_myLocationEnabled ? 'disable' : 'enable'} my location marker'), onPressed: () { setState(() { _myLocationEnabled = !_myLocationEnabled; @@ -279,9 +267,7 @@ class MapUiBodyState extends State { Widget _myLocationButtonToggler() { return TextButton( - child: Text( - '${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button', - ), + child: Text('${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'), onPressed: () { setState(() { _myLocationButtonEnabled = !_myLocationButtonEnabled; @@ -312,9 +298,7 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = _nightMode - ? await _getFileData('assets/night_mode.json') - : ''; + final String style = _nightMode ? await _getFileData('assets/night_mode.json') : ''; setState(() { _mapStyle = style; }); @@ -350,9 +334,7 @@ class MapUiBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; @@ -386,18 +368,14 @@ class MapUiBodyState extends State { _nightModeToggler(), if (kIsWeb) ...[ _webCameraControlToggler(), - if (_webCameraControlEnabled) - _webCameraControlPositionToggler(), + if (_webCameraControlEnabled) _webCameraControlPositionToggler(), ], ], ), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _updateCameraPosition(CameraPosition position) { diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart index ce6edd942aee..80146699e253 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/marker_icons.dart @@ -15,8 +15,7 @@ import 'custom_marker_icon.dart'; import 'page.dart'; class MarkerIconsPage extends GoogleMapExampleAppPage { - const MarkerIconsPage({super.key}) - : super(const Icon(Icons.image), 'Marker icons'); + const MarkerIconsPage({super.key}) : super(const Icon(Icons.image), 'Marker icons'); @override Widget build(BuildContext context) { @@ -45,8 +44,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { AssetMapBitmap? _markerIconAsset; BytesMapBitmap? _markerIconBytes; final int _markersAmountPerType = 15; - bool get _customSizeEnabled => - _currentSizeOption != _MarkerSizeOption.original; + bool get _customSizeEnabled => _currentSizeOption != _MarkerSizeOption.original; @override Widget build(BuildContext context) { @@ -63,10 +61,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { width: 350.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: _onMapCreated, ), @@ -74,11 +69,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { ), TextButton( onPressed: () => _toggleScaling(context), - child: Text( - _scalingEnabled - ? 'Disable auto scaling' - : 'Enable auto scaling', - ), + child: Text(_scalingEnabled ? 'Disable auto scaling' : 'Enable auto scaling'), ), if (_scalingEnabled) ...[ Container( @@ -90,10 +81,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { 'Reference box with size of ${referenceSize.width} x ${referenceSize.height} in logical pixels.', ), const SizedBox(height: 10), - Image.asset( - 'assets/red_square.png', - scale: _mipMapsEnabled ? null : 1.0, - ), + Image.asset('assets/red_square.png', scale: _mipMapsEnabled ? null : 1.0), const Text('Asset image rendered with flutter'), const SizedBox(height: 10), Row( @@ -111,9 +99,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { }); } }, - items: _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { + items: _MarkerSizeOption.values.map((_MarkerSizeOption option) { return DropdownMenuItem<_MarkerSizeOption>( value: option, child: Text(_getMarkerSizeOptionName(option)), @@ -125,9 +111,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { ], TextButton( onPressed: () => _toggleMipMaps(context), - child: Text( - _mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps', - ), + child: Text(_mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps'), ), ], ), @@ -178,15 +162,9 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { if (width != null && height != null) { return Size(width, height); } else if (width != null) { - return Size( - width, - width * _markerAssetImageSize.height / _markerAssetImageSize.width, - ); + return Size(width, width * _markerAssetImageSize.height / _markerAssetImageSize.width); } else if (height != null) { - return Size( - height * _markerAssetImageSize.width / _markerAssetImageSize.height, - height, - ); + return Size(height * _markerAssetImageSize.width / _markerAssetImageSize.height, height); } else { return _markerAssetImageSize; } @@ -209,10 +187,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createAssetMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude - 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude - 1); return Marker( markerId: MarkerId('marker_asset_$index'), @@ -222,10 +197,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createBytesMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude + 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude + 1); return Marker( markerId: MarkerId('marker_bytes_$index'), @@ -251,26 +223,20 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { - final ImageConfiguration imageConfiguration = - createLocalImageConfiguration(context); + final ImageConfiguration imageConfiguration = createLocalImageConfiguration(context); assetMapBitmap = await AssetMapBitmap.create( imageConfiguration, 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -280,9 +246,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } @@ -290,9 +254,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { } Future _updateMarkerBytesImage(BuildContext context) async { - final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf( - context, - ); + final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context); final Size bitmapLogicalSize = _getMarkerReferenceSize(); final double? imagePixelRatio = _scalingEnabled ? devicePixelRatio : null; @@ -306,10 +268,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); @@ -318,9 +277,7 @@ class MarkerIconsBodyState extends State<_MarkerIconsBody> { imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/move_camera.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/move_camera.dart index 7e042be8be0e..a3f30bb0132e 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/move_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/move_camera.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class MoveCameraPage extends GoogleMapExampleAppPage { - const MoveCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control'); + const MoveCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control'); @override Widget build(BuildContext context) { @@ -45,9 +44,7 @@ class MoveCameraState extends State { height: 200.0, child: GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -74,9 +71,7 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -98,19 +93,14 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.moveCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), @@ -120,9 +110,7 @@ class MoveCameraState extends State { children: [ TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0)), - ); + mapController?.moveCamera(CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0))); }, child: const Text('zoomBy with focus'), ), diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/padding.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/padding.dart index bf88171bdc94..23820dc0c74a 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/padding.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/padding.dart @@ -9,8 +9,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PaddingPage extends GoogleMapExampleAppPage { - const PaddingPage({super.key}) - : super(const Icon(Icons.map), 'Add padding to the map'); + const PaddingPage({super.key}) : super(const Icon(Icons.map), 'Add padding to the map'); @override Widget build(BuildContext context) { @@ -36,19 +35,14 @@ class MarkerIconsBodyState extends State { Widget build(BuildContext context) { final googleMap = GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), padding: _padding, ); final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), const Padding( padding: EdgeInsets.only(top: 20), @@ -63,10 +57,7 @@ class MarkerIconsBodyState extends State { columnChildren.addAll([_paddingInput(), _buttons()]); - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _onMapCreated(GoogleMapController controllerParam) { diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_advanced_marker.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_advanced_marker.dart index 790c0d4491af..40c27d92b124 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_advanced_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_advanced_marker.dart @@ -56,17 +56,11 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; markerPosition = null; @@ -91,10 +85,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -160,16 +151,10 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { void _changePosition(MarkerId markerId) { final AdvancedMarker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -222,9 +207,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -232,9 +215,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -249,9 +230,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -272,9 +251,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { /// Performs customizations of the [marker] to mark it as selected or not. AdvancedMarker copyWithSelectedState(AdvancedMarker marker, bool isSelected) { - return marker.copyWith( - iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected), - ); + return marker.copyWith(iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected)); } @override @@ -304,9 +281,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -315,70 +290,49 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( onPressed: selectedId == null ? null - : () => - _setMarkerIcon(selectedId, _getMarkerIcon(context)), + : () => _setMarkerIcon(selectedId, _getMarkerIcon(context)), child: const Text('set glyph text'), ), ], @@ -420,12 +374,10 @@ class AdvancedMarkersCapabilityStatus extends StatefulWidget { final GoogleMapController? controller; @override - State createState() => - _AdvancedMarkersCapabilityStatusState(); + State createState() => _AdvancedMarkersCapabilityStatusState(); } -class _AdvancedMarkersCapabilityStatusState - extends State { +class _AdvancedMarkersCapabilityStatusState extends State { /// Whether map supports advanced markers. Null indicates capability check /// is in progress. bool? _isAdvancedMarkersAvailable; @@ -449,8 +401,7 @@ class _AdvancedMarkersCapabilityStatusState child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart index 14cece83db68..f57a66084f04 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_circle.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { - const PlaceCirclePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place circle'); + const PlaceCirclePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place circle'); @override Widget build(BuildContext context) { @@ -37,12 +36,7 @@ class PlaceCircleBodyState extends State { // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling circle stroke width int widthsIndex = 0; @@ -132,9 +126,7 @@ class PlaceCircleBodyState extends State { void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { - circles[circleId] = circle.copyWith( - strokeWidthParam: widths[++widthsIndex % widths.length], - ); + circles[circleId] = circle.copyWith(strokeWidthParam: widths[++widthsIndex % widths.length]); }); } @@ -170,15 +162,11 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart index d1c7e046f74c..c91653675e10 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_marker.dart @@ -15,8 +15,7 @@ import 'custom_marker_icon.dart'; import 'page.dart'; class PlaceMarkerPage extends GoogleMapExampleAppPage { - const PlaceMarkerPage({super.key}) - : super(const Icon(Icons.place), 'Place marker'); + const PlaceMarkerPage({super.key}) : super(const Icon(Icons.place), 'Place marker'); @override Widget build(BuildContext context) { @@ -53,10 +52,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -85,10 +81,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -145,16 +138,10 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { void _changePosition(MarkerId markerId) { final Marker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -207,9 +194,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -217,9 +202,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -234,9 +217,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -286,9 +267,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -297,63 +276,43 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart index 2f07af11af22..d5f793f02b2c 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PlacePolygonPage extends GoogleMapExampleAppPage { - const PlacePolygonPage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polygon'); + const PlacePolygonPage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polygon'); @override Widget build(BuildContext context) { @@ -38,12 +37,7 @@ class PlacePolygonBodyState extends State { // Values when toggling polygon color int strokeColorsIndex = 0; int fillColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polygon width int widthsIndex = 0; @@ -148,9 +142,7 @@ class PlacePolygonBodyState extends State { void _addHoles(PolygonId polygonId) { final Polygon polygon = polygons[polygonId]!; setState(() { - polygons[polygonId] = polygon.copyWith( - holesParam: _createHoles(polygonId), - ); + polygons[polygonId] = polygon.copyWith(holesParam: _createHoles(polygonId)); }); } @@ -193,15 +185,11 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -231,9 +219,7 @@ class PlacePolygonBodyState extends State { child: const Text('remove holes'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart index 2abbbc4d4c93..bf75a67f4e83 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polyline.dart @@ -11,8 +11,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PlacePolylinePage extends GoogleMapExampleAppPage { - const PlacePolylinePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polyline'); + const PlacePolylinePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polyline'); @override Widget build(BuildContext context) { @@ -37,23 +36,14 @@ class PlacePolylineBodyState extends State { // Values when toggling polyline color int colorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polyline width int widthsIndex = 0; List widths = [10, 20, 5]; int jointTypesIndex = 0; - List jointTypes = [ - JointType.mitered, - JointType.bevel, - JointType.round, - ]; + List jointTypes = [JointType.mitered, JointType.bevel, JointType.round]; // Values when toggling polyline end cap type int endCapsIndex = 0; @@ -132,36 +122,28 @@ class PlacePolylineBodyState extends State { void _toggleGeodesic(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - geodesicParam: !polyline.geodesic, - ); + polylines[polylineId] = polyline.copyWith(geodesicParam: !polyline.geodesic); }); } void _toggleVisible(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - visibleParam: !polyline.visible, - ); + polylines[polylineId] = polyline.copyWith(visibleParam: !polyline.visible); }); } void _changeColor(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - colorParam: colors[++colorsIndex % colors.length], - ); + polylines[polylineId] = polyline.copyWith(colorParam: colors[++colorsIndex % colors.length]); }); } void _changeWidth(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - widthParam: widths[++widthsIndex % widths.length], - ); + polylines[polylineId] = polyline.copyWith(widthParam: widths[++widthsIndex % widths.length]); }); } @@ -236,15 +218,11 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -258,15 +236,11 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) ? null : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( @@ -288,9 +262,7 @@ class PlacePolylineBodyState extends State { child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) ? null : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample.dart index 2458e617c185..7cd836844cb4 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample.dart @@ -16,10 +16,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Flutter Google Maps Demo', - home: MapSample(), - ); + return const MaterialApp(title: 'Flutter Google Maps Demo', home: MapSample()); } } @@ -32,8 +29,7 @@ class MapSample extends StatefulWidget { } class MapSampleState extends State { - final Completer _controller = - Completer(); + final Completer _controller = Completer(); static const CameraPosition _kGooglePlex = CameraPosition( target: LatLng(37.42796133580664, -122.085749655962), diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample_advanced_markers.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample_advanced_markers.dart index 2582450fb7bf..84a8dad44c59 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample_advanced_markers.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/readme_sample_advanced_markers.dart @@ -14,10 +14,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Flutter Google Maps Demo', - home: AdvancedMarkersSample(), - ); + return const MaterialApp(title: 'Flutter Google Maps Demo', home: AdvancedMarkersSample()); } } diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart index 90b9ba2bdd5d..54b59ed0bbd8 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/scrolling_map.dart @@ -14,8 +14,7 @@ import 'page.dart'; const LatLng _center = LatLng(32.080664, 34.9563837); class ScrollingMapPage extends GoogleMapExampleAppPage { - const ScrollingMapPage({super.key}) - : super(const Icon(Icons.map), 'Scrolling map'); + const ScrollingMapPage({super.key}) : super(const Icon(Icons.map), 'Scrolling map'); @override Widget build(BuildContext context) { @@ -44,15 +43,10 @@ class ScrollingMapBody extends StatelessWidget { width: 300.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), gestureRecognizers: // >{ - Factory( - () => EagerGestureRecognizer(), - ), + Factory(() => EagerGestureRecognizer()), }, ), ), @@ -69,19 +63,14 @@ class ScrollingMapBody extends StatelessWidget { const Text("This map doesn't consume the vertical drags."), const Padding( padding: EdgeInsets.only(bottom: 12.0), - child: Text( - 'It still gets other gestures (e.g scale or tap).', - ), + child: Text('It still gets other gestures (e.g scale or tap).'), ), Center( child: SizedBox( width: 300.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), markers: { Marker( markerId: const MarkerId('test_marker_id'), @@ -92,12 +81,9 @@ class ScrollingMapBody extends StatelessWidget { ), ), }, - gestureRecognizers: - >{ - Factory( - () => ScaleGestureRecognizer(), - ), - }, + gestureRecognizers: >{ + Factory(() => ScaleGestureRecognizer()), + }, ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart index cb86d19a0c8f..4f083aa40899 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/snapshot.dart @@ -44,16 +44,12 @@ class _SnapshotBodyState extends State<_SnapshotBody> { children: [ SizedBox( height: 180, - child: GoogleMap( - onMapCreated: onMapCreated, - initialCameraPosition: _kInitialPosition, - ), + child: GoogleMap(onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition), ), TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = await _mapController - ?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter/example/lib/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter/example/lib/tile_overlay.dart index 5cc04da4d9b2..44ccd2809390 100644 --- a/packages/google_maps_flutter/google_maps_flutter/example/lib/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter/example/lib/tile_overlay.dart @@ -13,8 +13,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class TileOverlayPage extends GoogleMapExampleAppPage { - const TileOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Tile overlay'); + const TileOverlayPage({super.key}) : super(const Icon(Icons.map), 'Tile overlay'); @override Widget build(BuildContext context) { @@ -89,18 +88,9 @@ class TileOverlayBodyState extends State { ), ), ), - TextButton( - onPressed: _addTileOverlay, - child: const Text('Add tile overlay'), - ), - TextButton( - onPressed: _removeTileOverlay, - child: const Text('Remove tile overlay'), - ), - TextButton( - onPressed: _clearTileCache, - child: const Text('Clear tile cache'), - ), + TextButton(onPressed: _addTileOverlay, child: const Text('Add tile overlay')), + TextButton(onPressed: _removeTileOverlay, child: const Text('Remove tile overlay')), + TextButton(onPressed: _clearTileCache, child: const Text('Clear tile cache')), ], ); } @@ -124,22 +114,14 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/google_maps_flutter/lib/src/controller.dart b/packages/google_maps_flutter/google_maps_flutter/lib/src/controller.dart index 80f019d5a006..32ed8a26671f 100644 --- a/packages/google_maps_flutter/google_maps_flutter/lib/src/controller.dart +++ b/packages/google_maps_flutter/google_maps_flutter/lib/src/controller.dart @@ -20,8 +20,7 @@ class GoogleMapController { /// This list keeps track of all event subscriptions created for the map, /// including camera movements, marker interactions, and other map events. /// These subscriptions should be disposed when the controller is disposed. - final List> _streamSubscriptions = - >[]; + final List> _streamSubscriptions = >[]; /// Initialize control of a [GoogleMap] with [id]. /// @@ -50,10 +49,7 @@ class GoogleMapController { _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance .onCameraMove(mapId: mapId) - .listen( - (CameraMoveEvent e) => - _googleMapState.widget.onCameraMove!(e.value), - ), + .listen((CameraMoveEvent e) => _googleMapState.widget.onCameraMove!(e.value)), ); } if (_googleMapState.widget.onCameraIdle != null) { @@ -72,39 +68,28 @@ class GoogleMapController { GoogleMapsFlutterPlatform.instance .onMarkerDragStart(mapId: mapId) .listen( - (MarkerDragStartEvent e) => - _googleMapState.onMarkerDragStart(e.value, e.position), + (MarkerDragStartEvent e) => _googleMapState.onMarkerDragStart(e.value, e.position), ), ); _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance .onMarkerDrag(mapId: mapId) - .listen( - (MarkerDragEvent e) => - _googleMapState.onMarkerDrag(e.value, e.position), - ), + .listen((MarkerDragEvent e) => _googleMapState.onMarkerDrag(e.value, e.position)), ); _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance .onMarkerDragEnd(mapId: mapId) - .listen( - (MarkerDragEndEvent e) => - _googleMapState.onMarkerDragEnd(e.value, e.position), - ), + .listen((MarkerDragEndEvent e) => _googleMapState.onMarkerDragEnd(e.value, e.position)), ); _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance .onInfoWindowTap(mapId: mapId) - .listen( - (InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value), - ), + .listen((InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value)), ); _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance .onPolylineTap(mapId: mapId) - .listen( - (PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value), - ), + .listen((PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value)), ); _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance @@ -124,9 +109,7 @@ class GoogleMapController { _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance .onLongPress(mapId: mapId) - .listen( - (MapLongPressEvent e) => _googleMapState.onLongPress(e.position), - ), + .listen((MapLongPressEvent e) => _googleMapState.onLongPress(e.position)), ); _streamSubscriptions.add( GoogleMapsFlutterPlatform.instance @@ -142,10 +125,7 @@ class GoogleMapController { /// /// The returned [Future] completes after listeners have been notified. Future _updateMapConfiguration(MapConfiguration update) { - return GoogleMapsFlutterPlatform.instance.updateMapConfiguration( - update, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMapConfiguration(update, mapId: mapId); } /// Updates marker configuration. @@ -155,10 +135,7 @@ class GoogleMapController { /// /// The returned [Future] completes after listeners have been notified. Future _updateMarkers(MarkerUpdates markerUpdates) { - return GoogleMapsFlutterPlatform.instance.updateMarkers( - markerUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMarkers(markerUpdates, mapId: mapId); } /// Updates cluster manager configuration. @@ -167,9 +144,7 @@ class GoogleMapController { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future _updateClusterManagers( - ClusterManagerUpdates clusterManagerUpdates, - ) { + Future _updateClusterManagers(ClusterManagerUpdates clusterManagerUpdates) { return GoogleMapsFlutterPlatform.instance.updateClusterManagers( clusterManagerUpdates, mapId: mapId, @@ -182,9 +157,7 @@ class GoogleMapController { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future _updateGroundOverlays( - GroundOverlayUpdates groundOverlayUpdates, - ) { + Future _updateGroundOverlays(GroundOverlayUpdates groundOverlayUpdates) { return GoogleMapsFlutterPlatform.instance.updateGroundOverlays( groundOverlayUpdates, mapId: mapId, @@ -198,10 +171,7 @@ class GoogleMapController { /// /// The returned [Future] completes after listeners have been notified. Future _updatePolygons(PolygonUpdates polygonUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolygons( - polygonUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolygons(polygonUpdates, mapId: mapId); } /// Updates polyline configuration. @@ -211,10 +181,7 @@ class GoogleMapController { /// /// The returned [Future] completes after listeners have been notified. Future _updatePolylines(PolylineUpdates polylineUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolylines( - polylineUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolylines(polylineUpdates, mapId: mapId); } /// Updates circle configuration. @@ -224,10 +191,7 @@ class GoogleMapController { /// /// The returned [Future] completes after listeners have been notified. Future _updateCircles(CircleUpdates circleUpdates) { - return GoogleMapsFlutterPlatform.instance.updateCircles( - circleUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateCircles(circleUpdates, mapId: mapId); } /// Updates heatmap configuration. @@ -237,10 +201,7 @@ class GoogleMapController { /// /// The returned [Future] completes after listeners have been notified. Future _updateHeatmaps(HeatmapUpdates heatmapUpdates) { - return GoogleMapsFlutterPlatform.instance.updateHeatmaps( - heatmapUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateHeatmaps(heatmapUpdates, mapId: mapId); } /// Updates tile overlays configuration. @@ -265,10 +226,7 @@ class GoogleMapController { /// should implement an on-disk cache. Future clearTileCache(TileOverlayId tileOverlayId) async { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.clearTileCache( - tileOverlayId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.clearTileCache(tileOverlayId, mapId: mapId); } /// Starts an animated change of the map camera position. @@ -293,10 +251,7 @@ class GoogleMapController { /// platform side. Future moveCamera(CameraUpdate cameraUpdate) { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.moveCamera( - cameraUpdate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.moveCamera(cameraUpdate, mapId: mapId); } /// Sets the styling of the base map. @@ -315,10 +270,7 @@ class GoogleMapController { @Deprecated('Use GoogleMap.style instead.') Future setMapStyle(String? mapStyle) { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.setMapStyle( - mapStyle, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.setMapStyle(mapStyle, mapId: mapId); } /// Returns the last style error, if any. @@ -340,10 +292,7 @@ class GoogleMapController { /// of the map, not necessarily of the whole screen. Future getScreenCoordinate(LatLng latLng) { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.getScreenCoordinate( - latLng, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getScreenCoordinate(latLng, mapId: mapId); } /// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view. @@ -352,10 +301,7 @@ class GoogleMapController { /// pixels (not display pixels) relative to the top left of the map, not top left of the whole screen. Future getLatLng(ScreenCoordinate screenCoordinate) { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.getLatLng( - screenCoordinate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getLatLng(screenCoordinate, mapId: mapId); } /// Programmatically show the Info Window for a [Marker]. @@ -368,10 +314,7 @@ class GoogleMapController { /// * [isMarkerInfoWindowShown] to check if the Info Window is showing. Future showMarkerInfoWindow(MarkerId markerId) { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow(markerId, mapId: mapId); } /// Programmatically hide the Info Window for a [Marker]. @@ -384,10 +327,7 @@ class GoogleMapController { /// * [isMarkerInfoWindowShown] to check if the Info Window is showing. Future hideMarkerInfoWindow(MarkerId markerId) { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow(markerId, mapId: mapId); } /// Returns `true` when the [InfoWindow] is showing, `false` otherwise. @@ -400,10 +340,7 @@ class GoogleMapController { /// * [hideMarkerInfoWindow] to hide the Info Window. Future isMarkerInfoWindowShown(MarkerId markerId) { _checkWidgetMountedOrThrow(); - return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown(markerId, mapId: mapId); } /// Returns the current zoom level of the map @@ -420,8 +357,7 @@ class GoogleMapController { /// Disposes of the platform resources void dispose() { - for (final StreamSubscription streamSubscription - in _streamSubscriptions) { + for (final StreamSubscription streamSubscription in _streamSubscriptions) { streamSubscription.cancel(); } _streamSubscriptions.clear(); diff --git a/packages/google_maps_flutter/google_maps_flutter/lib/src/google_map.dart b/packages/google_maps_flutter/google_maps_flutter/lib/src/google_map.dart index ba2ea7601379..3bd76b784571 100644 --- a/packages/google_maps_flutter/google_maps_flutter/lib/src/google_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter/lib/src/google_map.dart @@ -40,13 +40,9 @@ class UnknownMapObjectIdError extends Error { } /// Android specific settings for [GoogleMap]. -@Deprecated( - 'See https://pub.dev/packages/google_maps_flutter_android#display-mode', -) +@Deprecated('See https://pub.dev/packages/google_maps_flutter_android#display-mode') class AndroidGoogleMapsFlutter { - @Deprecated( - 'See https://pub.dev/packages/google_maps_flutter_android#display-mode', - ) + @Deprecated('See https://pub.dev/packages/google_maps_flutter_android#display-mode') AndroidGoogleMapsFlutter._(); /// Whether to render [GoogleMap] with a [AndroidViewSurface] to build the Google Maps widget. @@ -56,12 +52,9 @@ class AndroidGoogleMapsFlutter { /// versions below 10. See /// https://docs.flutter.dev/platform-integration/android/platform-views#performance for more /// information. - @Deprecated( - 'See https://pub.dev/packages/google_maps_flutter_android#display-mode', - ) + @Deprecated('See https://pub.dev/packages/google_maps_flutter_android#display-mode') static bool get useAndroidViewSurface { - final GoogleMapsFlutterPlatform platform = - GoogleMapsFlutterPlatform.instance; + final GoogleMapsFlutterPlatform platform = GoogleMapsFlutterPlatform.instance; if (platform is GoogleMapsFlutterAndroid) { return platform.useAndroidViewSurface; } @@ -75,12 +68,9 @@ class AndroidGoogleMapsFlutter { /// versions below 10. See /// https://docs.flutter.dev/platform-integration/android/platform-views#performance for more /// information. - @Deprecated( - 'See https://pub.dev/packages/google_maps_flutter_android#display-mode', - ) + @Deprecated('See https://pub.dev/packages/google_maps_flutter_android#display-mode') static set useAndroidViewSurface(bool useAndroidViewSurface) { - final GoogleMapsFlutterPlatform platform = - GoogleMapsFlutterPlatform.instance; + final GoogleMapsFlutterPlatform platform = GoogleMapsFlutterPlatform.instance; if (platform is GoogleMapsFlutterAndroid) { platform.useAndroidViewSurface = useAndroidViewSurface; } @@ -146,8 +136,7 @@ class GoogleMap extends StatefulWidget { this.markerType = GoogleMapMarkerType.marker, this.colorScheme, String? mapId, - @Deprecated('cloudMapId is deprecated. Use mapId instead.') - String? cloudMapId, + @Deprecated('cloudMapId is deprecated. Use mapId instead.') String? cloudMapId, }) : assert( mapId == null || cloudMapId == null, '''A value may be provided for either mapId or cloudMapId, or neither, but not for both.''', @@ -429,18 +418,15 @@ class GoogleMap extends StatefulWidget { class _GoogleMapState extends State { final int _mapId = _nextMapCreationId++; - final Completer _controller = - Completer(); + final Completer _controller = Completer(); Map _markers = {}; Map _polygons = {}; Map _polylines = {}; Map _circles = {}; - Map _clusterManagers = - {}; + Map _clusterManagers = {}; Map _heatmaps = {}; - Map _groundOverlays = - {}; + Map _groundOverlays = {}; late MapConfiguration _mapConfiguration; @override @@ -450,9 +436,7 @@ class _GoogleMapState extends State { onPlatformViewCreated, widgetConfiguration: MapWidgetConfiguration( textDirection: - widget.layoutDirection ?? - Directionality.maybeOf(context) ?? - TextDirection.ltr, + widget.layoutDirection ?? Directionality.maybeOf(context) ?? TextDirection.ltr, initialCameraPosition: widget.initialCameraPosition, gestureRecognizers: widget.gestureRecognizers, ), @@ -529,9 +513,7 @@ class _GoogleMapState extends State { void _updateMarkers(GoogleMapController controller) { unawaited( - controller._updateMarkers( - MarkerUpdates.from(_markers.values.toSet(), widget.markers), - ), + controller._updateMarkers(MarkerUpdates.from(_markers.values.toSet(), widget.markers)), ); _markers = keyByMarkerId(widget.markers); } @@ -539,10 +521,7 @@ class _GoogleMapState extends State { void _updateClusterManagers(GoogleMapController controller) { unawaited( controller._updateClusterManagers( - ClusterManagerUpdates.from( - _clusterManagers.values.toSet(), - widget.clusterManagers, - ), + ClusterManagerUpdates.from(_clusterManagers.values.toSet(), widget.clusterManagers), ), ); _clusterManagers = keyByClusterManagerId(widget.clusterManagers); @@ -551,10 +530,7 @@ class _GoogleMapState extends State { void _updateGroundOverlays(GoogleMapController controller) { unawaited( controller._updateGroundOverlays( - GroundOverlayUpdates.from( - _groundOverlays.values.toSet(), - widget.groundOverlays, - ), + GroundOverlayUpdates.from(_groundOverlays.values.toSet(), widget.groundOverlays), ), ); _groundOverlays = keyByGroundOverlayId(widget.groundOverlays); @@ -562,9 +538,7 @@ class _GoogleMapState extends State { void _updatePolygons(GoogleMapController controller) { unawaited( - controller._updatePolygons( - PolygonUpdates.from(_polygons.values.toSet(), widget.polygons), - ), + controller._updatePolygons(PolygonUpdates.from(_polygons.values.toSet(), widget.polygons)), ); _polygons = keyByPolygonId(widget.polygons); } @@ -580,18 +554,14 @@ class _GoogleMapState extends State { void _updateCircles(GoogleMapController controller) { unawaited( - controller._updateCircles( - CircleUpdates.from(_circles.values.toSet(), widget.circles), - ), + controller._updateCircles(CircleUpdates.from(_circles.values.toSet(), widget.circles)), ); _circles = keyByCircleId(widget.circles); } void _updateHeatmaps(GoogleMapController controller) { unawaited( - controller._updateHeatmaps( - HeatmapUpdates.from(_heatmaps.values.toSet(), widget.heatmaps), - ), + controller._updateHeatmaps(HeatmapUpdates.from(_heatmaps.values.toSet(), widget.heatmaps)), ); _heatmaps = keyByHeatmapId(widget.heatmaps); } @@ -730,14 +700,9 @@ class _GoogleMapState extends State { } void onClusterTap(Cluster cluster) { - final ClusterManager? clusterManager = - _clusterManagers[cluster.clusterManagerId]; + final ClusterManager? clusterManager = _clusterManagers[cluster.clusterManagerId]; if (clusterManager == null) { - throw UnknownMapObjectIdError( - 'clusterManager', - cluster.clusterManagerId, - 'onClusterTap', - ); + throw UnknownMapObjectIdError('clusterManager', cluster.clusterManagerId, 'onClusterTap'); } final ArgumentCallback? onClusterTap = clusterManager.onClusterTap; if (onClusterTap != null) { diff --git a/packages/google_maps_flutter/google_maps_flutter/test/camera_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/camera_test.dart index 07350dd69568..19efdc93ea17 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/camera_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/camera_test.dart @@ -25,9 +25,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), onMapCreated: (GoogleMapController controller) { controllerCompleter.complete(controller); }, @@ -38,19 +36,14 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.animateCameraConfiguration, isNull); - final CameraUpdate newCameraUpdate = CameraUpdate.newLatLng( - const LatLng(20.0, 25.0), - ); + final CameraUpdate newCameraUpdate = CameraUpdate.newLatLng(const LatLng(20.0, 25.0)); const updateDuration = Duration(seconds: 10); await controller.animateCamera(newCameraUpdate, duration: updateDuration); expect(map.animateCameraConfiguration, isNotNull); expect(map.animateCameraConfiguration!.cameraUpdate, newCameraUpdate); - expect( - map.animateCameraConfiguration!.configuration?.duration, - updateDuration, - ); + expect(map.animateCameraConfiguration!.configuration?.duration, updateDuration); /// Tests that the camera update respects the default behavior when the /// duration is null. diff --git a/packages/google_maps_flutter/google_maps_flutter/test/clustermanager_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/clustermanager_updates_test.dart index 1e466e7c9624..3ec051192f65 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/clustermanager_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/clustermanager_updates_test.dart @@ -37,14 +37,8 @@ void main() { final ClusterManager initializedHeatmap = map.clusterManagerUpdates.last.clusterManagersToAdd.first; expect(initializedHeatmap, equals(cm1)); - expect( - map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, - true, - ); - expect( - map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, - true, - ); + expect(map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, true); + expect(map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, true); }); testWidgets('Adding a cluster manager', (WidgetTester tester) async { @@ -52,9 +46,7 @@ void main() { const cm2 = ClusterManager(clusterManagerId: ClusterManagerId('cm_2')); await tester.pumpWidget(_mapWithClusterManagers({cm1})); - await tester.pumpWidget( - _mapWithClusterManagers({cm1, cm2}), - ); + await tester.pumpWidget(_mapWithClusterManagers({cm1, cm2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.clusterManagerUpdates.last.clusterManagersToAdd.length, 1); @@ -63,15 +55,9 @@ void main() { map.clusterManagerUpdates.last.clusterManagersToAdd.first; expect(addedClusterManager, equals(cm2)); - expect( - map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, - true, - ); + expect(map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, true); - expect( - map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, - true, - ); + expect(map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, true); }); testWidgets('Removing a cluster manager', (WidgetTester tester) async { @@ -87,10 +73,7 @@ void main() { equals(cm1.clusterManagerId), ); - expect( - map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, - true, - ); + expect(map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, true); expect(map.clusterManagerUpdates.last.clusterManagersToAdd.isEmpty, true); }); @@ -99,9 +82,7 @@ void main() { // properties to change, it should not trigger any updates. If new properties // are added to [ClusterManager] in the future, this test will need to be // updated accordingly to check that changes are triggered. - testWidgets('Updating a cluster manager with same data', ( - WidgetTester tester, - ) async { + testWidgets('Updating a cluster manager with same data', (WidgetTester tester) async { const cm1 = ClusterManager(clusterManagerId: ClusterManagerId('cm_1')); const cm2 = ClusterManager(clusterManagerId: ClusterManagerId('cm_1')); @@ -112,14 +93,8 @@ void main() { // As cluster manager does not have any properties to change, // it should not populate the clusterManagersToChange set. - expect( - map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, - true, - ); - expect( - map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, - true, - ); + expect(map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, true); + expect(map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, true); expect(map.clusterManagerUpdates.last.clusterManagersToAdd.isEmpty, true); }); @@ -144,10 +119,7 @@ void main() { // As cluster manager does not have any properties to change, // it should not populate the clusterManagersToChange set. expect(map.clusterManagerUpdates.last.clusterManagersToAdd.isEmpty, true); - expect( - map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, - true, - ); + expect(map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, true); expect(map.clusterManagerUpdates.last.clusterManagersToAdd.isEmpty, true); }); @@ -159,9 +131,7 @@ void main() { testWidgets('Partial update with same data', (WidgetTester tester) async { const cm1 = ClusterManager(clusterManagerId: ClusterManagerId('heatmap_1')); const cm2 = ClusterManager(clusterManagerId: ClusterManagerId('heatmap_2')); - var cm3 = const ClusterManager( - clusterManagerId: ClusterManagerId('heatmap_3'), - ); + var cm3 = const ClusterManager(clusterManagerId: ClusterManagerId('heatmap_3')); final prev = {cm1, cm2, cm3}; cm3 = const ClusterManager(clusterManagerId: ClusterManagerId('heatmap_3')); final cur = {cm1, cm2, cm3}; @@ -173,14 +143,8 @@ void main() { // As cluster manager does not have any properties to change, // it should not populate the clusterManagersToChange set. - expect( - map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, - true, - ); - expect( - map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, - true, - ); + expect(map.clusterManagerUpdates.last.clusterManagersToChange.isEmpty, true); + expect(map.clusterManagerUpdates.last.clusterManagerIdsToRemove.isEmpty, true); expect(map.clusterManagerUpdates.last.clusterManagersToAdd.isEmpty, true); }); } diff --git a/packages/google_maps_flutter/google_maps_flutter/test/controller_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/controller_test.dart index 69734e6dc163..545664410abe 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/controller_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/controller_test.dart @@ -14,9 +14,7 @@ import 'fake_google_maps_flutter_platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - testWidgets('Subscriptions are canceled on dispose', ( - WidgetTester tester, - ) async { + testWidgets('Subscriptions are canceled on dispose', (WidgetTester tester) async { final platform = FakeGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; @@ -30,9 +28,7 @@ void main() { initialCameraPosition: const CameraPosition(target: LatLng(0, 0)), ); - await tester.pumpWidget( - Directionality(textDirection: TextDirection.ltr, child: googleMap), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: googleMap)); await tester.pump(); diff --git a/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart index fe0439d6c69d..fae706bdb4ed 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/fake_google_maps_flutter_platform.dart @@ -17,8 +17,7 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { List createdIds = []; /// A map of creation IDs to fake map instances. - Map mapInstances = - {}; + Map mapInstances = {}; PlatformMapStateRecorder get lastCreatedMap => mapInstances[createdIds.last]!; @@ -44,55 +43,37 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { Future init(int mapId) async => initCompleter?.future; @override - Future updateMapConfiguration( - MapConfiguration update, { - required int mapId, - }) async { + Future updateMapConfiguration(MapConfiguration update, {required int mapId}) async { mapInstances[mapId]?.mapConfiguration = update; await _fakeDelay(); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { mapInstances[mapId]?.markerUpdates.add(markerUpdates); await _fakeDelay(); } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { mapInstances[mapId]?.polygonUpdates.add(polygonUpdates); await _fakeDelay(); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { mapInstances[mapId]?.polylineUpdates.add(polylineUpdates); await _fakeDelay(); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { mapInstances[mapId]?.circleUpdates.add(circleUpdates); await _fakeDelay(); } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) async { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) async { mapInstances[mapId]?.heatmapUpdates.add(heatmapUpdates); await _fakeDelay(); } @@ -125,21 +106,14 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async {} + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async {} @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async { - mapInstances[mapId]?.animateCameraConfiguration = - CameraUpdateWithConfiguration( - cameraUpdate: cameraUpdate, - configuration: null, - ); + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async { + mapInstances[mapId]?.animateCameraConfiguration = CameraUpdateWithConfiguration( + cameraUpdate: cameraUpdate, + configuration: null, + ); await _fakeDelay(); } @@ -149,64 +123,42 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { CameraUpdateAnimationConfiguration configuration, { required int mapId, }) async { - mapInstances[mapId]?.animateCameraConfiguration = - CameraUpdateWithConfiguration( - cameraUpdate: cameraUpdate, - configuration: configuration, - ); + mapInstances[mapId]?.animateCameraConfiguration = CameraUpdateWithConfiguration( + cameraUpdate: cameraUpdate, + configuration: configuration, + ); await _fakeDelay(); } @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future setMapStyle(String? mapStyle, {required int mapId}) async {} @override Future getVisibleRegion({required int mapId}) async { - return LatLngBounds( - southwest: const LatLng(0, 0), - northeast: const LatLng(0, 0), - ); + return LatLngBounds(southwest: const LatLng(0, 0), northeast: const LatLng(0, 0)); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return const ScreenCoordinate(x: 0, y: 0); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return const LatLng(0, 0); } @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return false; } @@ -338,28 +290,16 @@ class PlatformMapStateRecorder { this.mapConfiguration = const MapConfiguration(), }) { clusterManagerUpdates.add( - ClusterManagerUpdates.from( - const {}, - mapObjects.clusterManagers, - ), + ClusterManagerUpdates.from(const {}, mapObjects.clusterManagers), ); groundOverlayUpdates.add( - GroundOverlayUpdates.from( - const {}, - mapObjects.groundOverlays, - ), + GroundOverlayUpdates.from(const {}, mapObjects.groundOverlays), ); markerUpdates.add(MarkerUpdates.from(const {}, mapObjects.markers)); - polygonUpdates.add( - PolygonUpdates.from(const {}, mapObjects.polygons), - ); - polylineUpdates.add( - PolylineUpdates.from(const {}, mapObjects.polylines), - ); + polygonUpdates.add(PolygonUpdates.from(const {}, mapObjects.polygons)); + polylineUpdates.add(PolylineUpdates.from(const {}, mapObjects.polylines)); circleUpdates.add(CircleUpdates.from(const {}, mapObjects.circles)); - heatmapUpdates.add( - HeatmapUpdates.from(const {}, mapObjects.heatmaps), - ); + heatmapUpdates.add(HeatmapUpdates.from(const {}, mapObjects.heatmaps)); tileOverlaySets.add(mapObjects.tileOverlays); } @@ -374,18 +314,13 @@ class PlatformMapStateRecorder { final List circleUpdates = []; final List heatmapUpdates = []; final List> tileOverlaySets = >[]; - final List clusterManagerUpdates = - []; - final List groundOverlayUpdates = - []; + final List clusterManagerUpdates = []; + final List groundOverlayUpdates = []; } /// Helper class to store animateCameraWithConfiguration data. class CameraUpdateWithConfiguration { - CameraUpdateWithConfiguration({ - required this.cameraUpdate, - required this.configuration, - }); + CameraUpdateWithConfiguration({required this.cameraUpdate, required this.configuration}); final CameraUpdate cameraUpdate; final CameraUpdateAnimationConfiguration? configuration; diff --git a/packages/google_maps_flutter/google_maps_flutter/test/google_map_controller_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/google_map_controller_test.dart index 079b536a9038..023ce1e9b8a5 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/google_map_controller_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/google_map_controller_test.dart @@ -17,9 +17,7 @@ void main() { GoogleMapsFlutterPlatform.instance = platform; }); - testWidgets('onMapCreated is called with controller', ( - WidgetTester tester, - ) async { + testWidgets('onMapCreated is called with controller', (WidgetTester tester) async { GoogleMapController? controller; await tester.pumpWidget( @@ -36,9 +34,7 @@ void main() { await expectLater(controller?.getZoomLevel(), isNotNull); }); - testWidgets('controller throws when used after dispose', ( - WidgetTester tester, - ) async { + testWidgets('controller throws when used after dispose', (WidgetTester tester) async { GoogleMapController? controller; await tester.pumpWidget( @@ -54,9 +50,6 @@ void main() { // Now dispose of the map... await tester.pumpWidget(Container()); - await expectLater( - () => controller?.getZoomLevel(), - throwsA(isA()), - ); + await expectLater(() => controller?.getZoomLevel(), throwsA(isA())); }); } diff --git a/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart index 9d3167e86af5..722a4390bb65 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart @@ -23,9 +23,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -37,24 +35,18 @@ void main() { ); }); - testWidgets('Initial camera position change is a no-op', ( - WidgetTester tester, - ) async { + testWidgets('Initial camera position change is a no-op', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 16.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 16.0))), ), ); @@ -84,9 +76,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -111,9 +101,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -125,14 +113,9 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), cameraTargetBounds: CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10.0, 20.0), - northeast: const LatLng(30.0, 40.0), - ), + LatLngBounds(southwest: const LatLng(10.0, 20.0), northeast: const LatLng(30.0, 40.0)), ), ), ), @@ -143,10 +126,7 @@ void main() { expect( map.mapConfiguration.cameraTargetBounds, CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10.0, 20.0), - northeast: const LatLng(30.0, 40.0), - ), + LatLngBounds(southwest: const LatLng(10.0, 20.0), northeast: const LatLng(30.0, 40.0)), ), ); @@ -154,14 +134,9 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), cameraTargetBounds: CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(16.0, 20.0), - northeast: const LatLng(30.0, 40.0), - ), + LatLngBounds(southwest: const LatLng(16.0, 20.0), northeast: const LatLng(30.0, 40.0)), ), ), ), @@ -170,10 +145,7 @@ void main() { expect( map.mapConfiguration.cameraTargetBounds, CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(16.0, 20.0), - northeast: const LatLng(30.0, 40.0), - ), + LatLngBounds(southwest: const LatLng(16.0, 20.0), northeast: const LatLng(30.0, 40.0)), ), ); }); @@ -219,24 +191,16 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; - expect( - map.mapConfiguration.minMaxZoomPreference, - const MinMaxZoomPreference(1.0, 3.0), - ); + expect(map.mapConfiguration.minMaxZoomPreference, const MinMaxZoomPreference(1.0, 3.0)); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); - expect( - map.mapConfiguration.minMaxZoomPreference, - MinMaxZoomPreference.unbounded, - ); + expect(map.mapConfiguration.minMaxZoomPreference, MinMaxZoomPreference.unbounded); }); testWidgets('Can update rotateGesturesEnabled', (WidgetTester tester) async { @@ -257,9 +221,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -284,9 +246,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -311,9 +271,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -324,9 +282,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -338,9 +294,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), onCameraMove: (CameraPosition position) {}, ), ), @@ -367,9 +321,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -394,9 +346,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -407,9 +357,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -430,15 +378,11 @@ void main() { expect(map.mapConfiguration.myLocationEnabled, true); }); - testWidgets('Can update myLocationButtonEnabled', ( - WidgetTester tester, - ) async { + testWidgets('Can update myLocationButtonEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -463,9 +407,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -478,9 +420,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -498,10 +438,7 @@ void main() { ), ); - expect( - map.mapConfiguration.padding, - const EdgeInsets.fromLTRB(10, 20, 30, 40), - ); + expect(map.mapConfiguration.padding, const EdgeInsets.fromLTRB(10, 20, 30, 40)); await tester.pumpWidget( const Directionality( @@ -513,19 +450,14 @@ void main() { ), ); - expect( - map.mapConfiguration.padding, - const EdgeInsets.fromLTRB(50, 60, 70, 80), - ); + expect(map.mapConfiguration.padding, const EdgeInsets.fromLTRB(50, 60, 70, 80)); }); testWidgets('Can update traffic', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -564,9 +496,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -592,30 +522,22 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); expect(map.mapConfiguration.style, ''); }); - testWidgets('Update state from widget only when mounted', ( - WidgetTester tester, - ) async { + testWidgets('Update state from widget only when mounted', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); - final State googleMapState = tester.state( - find.byType(GoogleMap), - ); + final State googleMapState = tester.state(find.byType(GoogleMap)); await tester.pumpWidget(Container()); @@ -643,9 +565,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -664,9 +584,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -703,9 +621,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); expect(map.mapConfiguration.markerType, MarkerType.marker); @@ -715,9 +631,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); @@ -726,9 +640,7 @@ void main() { expect(map.mapConfiguration.colorScheme, null); }); - testWidgets('Can set color scheme to non-default', ( - WidgetTester tester, - ) async { + testWidgets('Can set color scheme to non-default', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, @@ -774,9 +686,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); expect(map.mapConfiguration.mapId, ''); @@ -813,9 +723,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ), + child: GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))), ), ); expect(map.mapConfiguration.cloudMapId, ''); @@ -834,9 +742,7 @@ void main() { }, throwsAssertionError); }); - testWidgets("Providing mapId doesn't thrown an exception", ( - WidgetTester tester, - ) async { + testWidgets("Providing mapId doesn't thrown an exception", (WidgetTester tester) async { expect(() { const GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), @@ -845,9 +751,7 @@ void main() { }, returnsNormally); }); - testWidgets("Providing cloudMapid doesn't thrown an exception", ( - WidgetTester tester, - ) async { + testWidgets("Providing cloudMapid doesn't thrown an exception", (WidgetTester tester) async { expect(() { const GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), @@ -856,9 +760,7 @@ void main() { }, returnsNormally); }); - testWidgets('Getting deprecated cloudMapId returns the mapId', ( - WidgetTester tester, - ) async { + testWidgets('Getting deprecated cloudMapId returns the mapId', (WidgetTester tester) async { const mapId = 'mapId'; const map = GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), @@ -871,9 +773,7 @@ void main() { WidgetTester tester, ) async { expect(() { - const GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), - ); + const GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0))); }, returnsNormally); }); } diff --git a/packages/google_maps_flutter/google_maps_flutter/test/google_maps_flutter_export_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/google_maps_flutter_export_test.dart index d26c951737f6..decbeee5292c 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/google_maps_flutter_export_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/google_maps_flutter_export_test.dart @@ -9,63 +9,60 @@ import 'package:google_maps_flutter/google_maps_flutter.dart' as main_file; void main() { group('google_maps_flutter exports', () { - test( - 'ensure google_maps_flutter.dart exports classes from platform interface', - () { - main_file.AdvancedMarker; - main_file.AdvancedMarkerGlyph; - main_file.ArgumentCallback; - main_file.ArgumentCallbacks; - main_file.AssetMapBitmap; - main_file.BitmapDescriptor; - main_file.BitmapGlyph; - main_file.BytesMapBitmap; - main_file.CameraPosition; - main_file.CameraPositionCallback; - main_file.CameraTargetBounds; - main_file.CameraUpdate; - main_file.Cap; - main_file.Circle; - main_file.CircleGlyph; - main_file.CircleId; - main_file.Cluster; - main_file.ClusterManager; - main_file.ClusterManagerId; - main_file.GroundOverlay; - main_file.GroundOverlayId; - main_file.Heatmap; - main_file.HeatmapGradient; - main_file.HeatmapGradientColor; - main_file.HeatmapId; - main_file.HeatmapRadius; - main_file.InfoWindow; - main_file.JointType; - main_file.LatLng; - main_file.LatLngBounds; - main_file.MapBitmapScaling; - main_file.MapColorScheme; - main_file.MapStyleException; - main_file.MapType; - main_file.Marker; - main_file.MarkerCollisionBehavior; - main_file.MarkerId; - main_file.MinMaxZoomPreference; - main_file.PatternItem; - main_file.PinConfig; - main_file.Polygon; - main_file.PolygonId; - main_file.Polyline; - main_file.PolylineId; - main_file.ScreenCoordinate; - main_file.TextGlyph; - main_file.Tile; - main_file.TileOverlay; - main_file.TileOverlayId; - main_file.TileProvider; - main_file.WebCameraControlPosition; - main_file.WebGestureHandling; - main_file.WeightedLatLng; - }, - ); + test('ensure google_maps_flutter.dart exports classes from platform interface', () { + main_file.AdvancedMarker; + main_file.AdvancedMarkerGlyph; + main_file.ArgumentCallback; + main_file.ArgumentCallbacks; + main_file.AssetMapBitmap; + main_file.BitmapDescriptor; + main_file.BitmapGlyph; + main_file.BytesMapBitmap; + main_file.CameraPosition; + main_file.CameraPositionCallback; + main_file.CameraTargetBounds; + main_file.CameraUpdate; + main_file.Cap; + main_file.Circle; + main_file.CircleGlyph; + main_file.CircleId; + main_file.Cluster; + main_file.ClusterManager; + main_file.ClusterManagerId; + main_file.GroundOverlay; + main_file.GroundOverlayId; + main_file.Heatmap; + main_file.HeatmapGradient; + main_file.HeatmapGradientColor; + main_file.HeatmapId; + main_file.HeatmapRadius; + main_file.InfoWindow; + main_file.JointType; + main_file.LatLng; + main_file.LatLngBounds; + main_file.MapBitmapScaling; + main_file.MapColorScheme; + main_file.MapStyleException; + main_file.MapType; + main_file.Marker; + main_file.MarkerCollisionBehavior; + main_file.MarkerId; + main_file.MinMaxZoomPreference; + main_file.PatternItem; + main_file.PinConfig; + main_file.Polygon; + main_file.PolygonId; + main_file.Polyline; + main_file.PolylineId; + main_file.ScreenCoordinate; + main_file.TextGlyph; + main_file.Tile; + main_file.TileOverlay; + main_file.TileOverlayId; + main_file.TileProvider; + main_file.WebCameraControlPosition; + main_file.WebGestureHandling; + main_file.WeightedLatLng; + }); }); } diff --git a/packages/google_maps_flutter/google_maps_flutter/test/groundoverlay_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/groundoverlay_updates_test.dart index b67118e81d35..758fc64c72d6 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/groundoverlay_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/groundoverlay_updates_test.dart @@ -73,10 +73,7 @@ void main() { expect(initializedGroundOverlays.first, equals(go1)); expect(initializedGroundOverlays.last, equals(go2)); - expect( - map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, - true, - ); + expect(map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, true); expect(map.groundOverlayUpdates.last.groundOverlaysToChange.isEmpty, true); }); @@ -117,14 +114,10 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.groundOverlayUpdates.last.groundOverlaysToAdd.length, 1); - final GroundOverlay addedMarker = - map.groundOverlayUpdates.last.groundOverlaysToAdd.first; + final GroundOverlay addedMarker = map.groundOverlayUpdates.last.groundOverlaysToAdd.first; expect(addedMarker, equals(go2)); - expect( - map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, - true, - ); + expect(map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, true); expect(map.groundOverlayUpdates.last.groundOverlaysToChange.isEmpty, true); }); @@ -178,15 +171,9 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.groundOverlayUpdates.last.groundOverlaysToChange.length, 1); - expect( - map.groundOverlayUpdates.last.groundOverlaysToChange.first, - equals(go2), - ); + expect(map.groundOverlayUpdates.last.groundOverlaysToChange.first, equals(go2)); - expect( - map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, - true, - ); + expect(map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, true); expect(map.groundOverlayUpdates.last.groundOverlaysToAdd.isEmpty, true); }); @@ -232,10 +219,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.groundOverlayUpdates.last.groundOverlaysToChange, cur); - expect( - map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, - true, - ); + expect(map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, true); expect(map.groundOverlayUpdates.last.groundOverlaysToAdd.isEmpty, true); }); @@ -302,14 +286,8 @@ void main() { expect(map.groundOverlayUpdates.last.groundOverlaysToAdd.length, 1); expect(map.groundOverlayUpdates.last.groundOverlayIdsToRemove.length, 1); - expect( - map.groundOverlayUpdates.last.groundOverlaysToChange.first, - equals(go2), - ); - expect( - map.groundOverlayUpdates.last.groundOverlaysToAdd.first, - equals(go1), - ); + expect(map.groundOverlayUpdates.last.groundOverlaysToChange.first, equals(go2)); + expect(map.groundOverlayUpdates.last.groundOverlaysToAdd.first, equals(go1)); expect( map.groundOverlayUpdates.last.groundOverlayIdsToRemove.first, equals(go3.groundOverlayId), @@ -372,14 +350,8 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; - expect( - map.groundOverlayUpdates.last.groundOverlaysToChange, - {go3}, - ); - expect( - map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, - true, - ); + expect(map.groundOverlayUpdates.last.groundOverlaysToChange, {go3}); + expect(map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, true); expect(map.groundOverlayUpdates.last.groundOverlaysToAdd.isEmpty, true); }); @@ -406,10 +378,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.groundOverlayUpdates.last.groundOverlaysToChange.isEmpty, true); - expect( - map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, - true, - ); + expect(map.groundOverlayUpdates.last.groundOverlayIdsToRemove.isEmpty, true); expect(map.groundOverlayUpdates.last.groundOverlaysToAdd.isEmpty, true); }); @@ -475,24 +444,16 @@ void main() { expect(map.groundOverlayUpdates.length, 3); expect(map.groundOverlayUpdates[0].groundOverlaysToChange.isEmpty, true); - expect(map.groundOverlayUpdates[0].groundOverlaysToAdd, { - go1, - go2, - }); + expect(map.groundOverlayUpdates[0].groundOverlaysToAdd, {go1, go2}); expect(map.groundOverlayUpdates[0].groundOverlayIdsToRemove.isEmpty, true); expect(map.groundOverlayUpdates[1].groundOverlaysToChange.isEmpty, true); - expect(map.groundOverlayUpdates[1].groundOverlaysToAdd, { - go3, + expect(map.groundOverlayUpdates[1].groundOverlaysToAdd, {go3}); + expect(map.groundOverlayUpdates[1].groundOverlayIdsToRemove, { + go2.groundOverlayId, }); - expect( - map.groundOverlayUpdates[1].groundOverlayIdsToRemove, - {go2.groundOverlayId}, - ); - expect(map.groundOverlayUpdates[2].groundOverlaysToChange, { - go3updated, - }); + expect(map.groundOverlayUpdates[2].groundOverlaysToChange, {go3updated}); expect(map.groundOverlayUpdates[2].groundOverlaysToAdd.isEmpty, true); expect(map.groundOverlayUpdates[2].groundOverlayIdsToRemove.isEmpty, true); diff --git a/packages/google_maps_flutter/google_maps_flutter/test/heatmap_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/heatmap_updates_test.dart index 891468ced66d..bd39e8fa3b3f 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/heatmap_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/heatmap_updates_test.dart @@ -55,8 +55,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.heatmapUpdates.last.heatmapsToAdd.length, 1); - final Heatmap initializedHeatmap = - map.heatmapUpdates.last.heatmapsToAdd.first; + final Heatmap initializedHeatmap = map.heatmapUpdates.last.heatmapsToAdd.first; expect(initializedHeatmap, equals(h1)); expect(map.heatmapUpdates.last.heatmapIdsToRemove.isEmpty, true); expect(map.heatmapUpdates.last.heatmapsToChange.isEmpty, true); @@ -100,10 +99,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.heatmapUpdates.last.heatmapIdsToRemove.length, 1); - expect( - map.heatmapUpdates.last.heatmapIdsToRemove.first, - equals(h1.heatmapId), - ); + expect(map.heatmapUpdates.last.heatmapIdsToRemove.first, equals(h1.heatmapId)); expect(map.heatmapUpdates.last.heatmapsToChange.isEmpty, true); expect(map.heatmapUpdates.last.heatmapsToAdd.isEmpty, true); @@ -227,10 +223,7 @@ void main() { expect(map.heatmapUpdates.last.heatmapsToChange.first, equals(h2)); expect(map.heatmapUpdates.last.heatmapsToAdd.first, equals(h1)); - expect( - map.heatmapUpdates.last.heatmapIdsToRemove.first, - equals(h3.heatmapId), - ); + expect(map.heatmapUpdates.last.heatmapIdsToRemove.first, equals(h3.heatmapId)); }); testWidgets('Partial Update', (WidgetTester tester) async { diff --git a/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart index 665e2e41801e..2bc729c8ea7c 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/map_creation_test.dart @@ -28,16 +28,8 @@ void main() { textDirection: TextDirection.ltr, child: Column( children: [ - GoogleMap( - initialCameraPosition: CameraPosition( - target: LatLng(43.362, -5.849), - ), - ), - GoogleMap( - initialCameraPosition: CameraPosition( - target: LatLng(47.649, -122.350), - ), - ), + GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(43.362, -5.849))), + GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(47.649, -122.350))), ], ), ), @@ -49,13 +41,9 @@ void main() { expect(platform.createdIds[1], 1); }); - testWidgets('Calls platform.dispose when GoogleMap is disposed of', ( - WidgetTester tester, - ) async { + testWidgets('Calls platform.dispose when GoogleMap is disposed of', (WidgetTester tester) async { await tester.pumpWidget( - const GoogleMap( - initialCameraPosition: CameraPosition(target: LatLng(43.3608, -5.8702)), - ), + const GoogleMap(initialCameraPosition: CameraPosition(target: LatLng(43.3608, -5.8702))), ); // Now dispose of the map... diff --git a/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart index 73755e4603fc..3cbb3e239912 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/marker_updates_test.dart @@ -168,11 +168,7 @@ void main() { testWidgets('Update non platform related attr', (WidgetTester tester) async { var m1 = const Marker(markerId: MarkerId('marker_1')); final prev = {m1}; - m1 = Marker( - markerId: const MarkerId('marker_1'), - onTap: () {}, - onDragEnd: (LatLng latLng) {}, - ); + m1 = Marker(markerId: const MarkerId('marker_1'), onTap: () {}, onDragEnd: (LatLng latLng) {}); final cur = {m1}; await tester.pumpWidget(_mapWithMarkers(prev)); diff --git a/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart index e174d9d10de5..9ffdd6c5c674 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/polygon_updates_test.dart @@ -19,10 +19,7 @@ Widget _mapWithPolygons(Set polygons) { ); } -List _rectPoints({ - required double size, - LatLng center = const LatLng(0, 0), -}) { +List _rectPoints({required double size, LatLng center = const LatLng(0, 0)}) { final double halfSize = size / 2; return [ @@ -57,8 +54,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToAdd.length, 1); - final Polygon initializedPolygon = - map.polygonUpdates.last.polygonsToAdd.first; + final Polygon initializedPolygon = map.polygonUpdates.last.polygonsToAdd.first; expect(initializedPolygon, equals(p1)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); @@ -90,10 +86,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1); - expect( - map.polygonUpdates.last.polygonIdsToRemove.first, - equals(p1.polygonId), - ); + expect(map.polygonUpdates.last.polygonIdsToRemove.first, equals(p1.polygonId)); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); @@ -169,10 +162,7 @@ void main() { expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2)); expect(map.polygonUpdates.last.polygonsToAdd.first, equals(p1)); - expect( - map.polygonUpdates.last.polygonIdsToRemove.first, - equals(p3.polygonId), - ); + expect(map.polygonUpdates.last.polygonIdsToRemove.first, equals(p3.polygonId)); }); testWidgets('Partial Update', (WidgetTester tester) async { @@ -209,25 +199,20 @@ void main() { expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); - testWidgets('Initializing a polygon with points and hole', ( - WidgetTester tester, - ) async { + testWidgets('Initializing a polygon with points and hole', (WidgetTester tester) async { final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); await tester.pumpWidget(_mapWithPolygons({p1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonsToAdd.length, 1); - final Polygon initializedPolygon = - map.polygonUpdates.last.polygonsToAdd.first; + final Polygon initializedPolygon = map.polygonUpdates.last.polygonsToAdd.first; expect(initializedPolygon, equals(p1)); expect(map.polygonUpdates.last.polygonIdsToRemove.isEmpty, true); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); }); - testWidgets('Adding a polygon with points and hole', ( - WidgetTester tester, - ) async { + testWidgets('Adding a polygon with points and hole', (WidgetTester tester) async { const p1 = Polygon(polygonId: PolygonId('polygon_1')); final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_2')); @@ -245,9 +230,7 @@ void main() { expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); }); - testWidgets('Removing a polygon with points and hole', ( - WidgetTester tester, - ) async { + testWidgets('Removing a polygon with points and hole', (WidgetTester tester) async { final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); await tester.pumpWidget(_mapWithPolygons({p1})); @@ -255,18 +238,13 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polygonUpdates.last.polygonIdsToRemove.length, 1); - expect( - map.polygonUpdates.last.polygonIdsToRemove.first, - equals(p1.polygonId), - ); + expect(map.polygonUpdates.last.polygonIdsToRemove.first, equals(p1.polygonId)); expect(map.polygonUpdates.last.polygonsToChange.isEmpty, true); expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); - testWidgets('Updating a polygon by adding points and hole', ( - WidgetTester tester, - ) async { + testWidgets('Updating a polygon by adding points and hole', (WidgetTester tester) async { const p1 = Polygon(polygonId: PolygonId('polygon_1')); final Polygon p2 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); @@ -281,9 +259,7 @@ void main() { expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); - testWidgets('Mutate a polygon with points and holes', ( - WidgetTester tester, - ) async { + testWidgets('Mutate a polygon with points and holes', (WidgetTester tester) async { final p1 = Polygon( polygonId: const PolygonId('polygon_1'), points: _rectPoints(size: 1), @@ -307,9 +283,7 @@ void main() { expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); - testWidgets('Multi Update polygons with points and hole', ( - WidgetTester tester, - ) async { + testWidgets('Multi Update polygons with points and hole', (WidgetTester tester) async { var p1 = const Polygon(polygonId: PolygonId('polygon_1')); var p2 = Polygon( polygonId: const PolygonId('polygon_2'), @@ -334,9 +308,7 @@ void main() { expect(map.polygonUpdates.last.polygonsToAdd.isEmpty, true); }); - testWidgets('Multi Update polygons with points and hole', ( - WidgetTester tester, - ) async { + testWidgets('Multi Update polygons with points and hole', (WidgetTester tester) async { var p2 = Polygon( polygonId: const PolygonId('polygon_2'), points: _rectPoints(size: 2), @@ -364,15 +336,10 @@ void main() { expect(map.polygonUpdates.last.polygonsToChange.first, equals(p2)); expect(map.polygonUpdates.last.polygonsToAdd.first, equals(p1)); - expect( - map.polygonUpdates.last.polygonIdsToRemove.first, - equals(p3.polygonId), - ); + expect(map.polygonUpdates.last.polygonIdsToRemove.first, equals(p3.polygonId)); }); - testWidgets('Partial Update polygons with points and hole', ( - WidgetTester tester, - ) async { + testWidgets('Partial Update polygons with points and hole', (WidgetTester tester) async { final Polygon p1 = _polygonWithPointsAndHole(const PolygonId('polygon_1')); const p2 = Polygon(polygonId: PolygonId('polygon_2')); var p3 = Polygon( @@ -403,10 +370,7 @@ void main() { const p1 = Polygon(polygonId: PolygonId('polygon_1')); const p2 = Polygon(polygonId: PolygonId('polygon_2')); const p3 = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1); - const p3updated = Polygon( - polygonId: PolygonId('polygon_3'), - strokeWidth: 2, - ); + const p3updated = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithPolygons({p1, p2})); diff --git a/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart index 42da2d46945f..de1012dc01ae 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart @@ -34,8 +34,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToAdd.length, 1); - final Polyline initializedPolyline = - map.polylineUpdates.last.polylinesToAdd.first; + final Polyline initializedPolyline = map.polylineUpdates.last.polylinesToAdd.first; expect(initializedPolyline, equals(p1)); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true); @@ -51,8 +50,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToAdd.length, 1); - final Polyline addedPolyline = - map.polylineUpdates.last.polylinesToAdd.first; + final Polyline addedPolyline = map.polylineUpdates.last.polylinesToAdd.first; expect(addedPolyline, equals(p2)); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); @@ -68,10 +66,7 @@ void main() { final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylineIdsToRemove.length, 1); - expect( - map.polylineUpdates.last.polylineIdsToRemove.first, - equals(p1.polylineId), - ); + expect(map.polylineUpdates.last.polylineIdsToRemove.first, equals(p1.polylineId)); expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true); expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true); @@ -109,10 +104,7 @@ void main() { testWidgets('Mutate a polyline', (WidgetTester tester) async { final points = [const LatLng(0.0, 0.0)]; - final p1 = Polyline( - polylineId: const PolylineId('polyline_1'), - points: points, - ); + final p1 = Polyline(polylineId: const PolylineId('polyline_1'), points: points); await tester.pumpWidget(_mapWithPolylines({p1})); p1.points.add(const LatLng(1.0, 1.0)); @@ -165,10 +157,7 @@ void main() { expect(map.polylineUpdates.last.polylinesToChange.first, equals(p2)); expect(map.polylineUpdates.last.polylinesToAdd.first, equals(p1)); - expect( - map.polylineUpdates.last.polylineIdsToRemove.first, - equals(p3.polylineId), - ); + expect(map.polylineUpdates.last.polylineIdsToRemove.first, equals(p3.polylineId)); }); testWidgets('Partial Update', (WidgetTester tester) async { @@ -228,9 +217,7 @@ void main() { expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[1].polylinesToAdd, {p3}); - expect(map.polylineUpdates[1].polylineIdsToRemove, { - p2.polylineId, - }); + expect(map.polylineUpdates[1].polylineIdsToRemove, {p2.polylineId}); expect(map.polylineUpdates[2].polylinesToChange, {p3updated}); expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true); diff --git a/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart index ff9889eed39b..17f287d6c1c2 100644 --- a/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter/test/tile_overlay_updates_test.dart @@ -58,10 +58,7 @@ void main() { testWidgets('Updating a tile overlay', (WidgetTester tester) async { const t1 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1')); - const t2 = TileOverlay( - tileOverlayId: TileOverlayId('tile_overlay_1'), - zIndex: 10, - ); + const t2 = TileOverlay(tileOverlayId: TileOverlayId('tile_overlay_1'), zIndex: 10); await tester.pumpWidget(_mapWithTileOverlays({t1})); await tester.pumpWidget(_mapWithTileOverlays({t2})); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/google_maps_test.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/google_maps_test.dart index 4dc0ed693198..6b2ebdd8c2c2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/google_maps_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/integration_test/google_maps_test.dart @@ -42,8 +42,9 @@ final LatLngBounds _testCameraBounds = LatLngBounds( northeast: const LatLng(50, -65), southwest: const LatLng(28.5, -123), ); -final ValueVariant _cameraUpdateTypeVariants = - ValueVariant(CameraUpdateType.values.toSet()); +final ValueVariant _cameraUpdateTypeVariants = ValueVariant( + CameraUpdateType.values.toSet(), +); void main() { late AndroidMapRenderer initializedRenderer; @@ -51,11 +52,8 @@ void main() { GoogleMapsFlutterPlatform.instance.enableDebugInspection(); setUpAll(() async { - final instance = - GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; - initializedRenderer = await instance.initializeWithRenderer( - AndroidMapRenderer.latest, - ); + final instance = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; + initializedRenderer = await instance.initializeWithRenderer(AndroidMapRenderer.latest); }); testWidgets('initialized with latest renderer', (WidgetTester _) async { @@ -74,8 +72,7 @@ void main() { testWidgets('throws PlatformException on multiple renderer initializations', ( WidgetTester _, ) async { - final instance = - GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; + final instance = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; expect( () async => instance.initializeWithRenderer(AndroidMapRenderer.latest), throwsA( @@ -114,10 +111,8 @@ void main() { } testWidgets('uses surface view', (WidgetTester tester) async { - final instance = - GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; - final bool previousUseAndroidViewSurfaceValue = - instance.useAndroidViewSurface; + final instance = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; + final bool previousUseAndroidViewSurfaceValue = instance.useAndroidViewSurface; instance.useAndroidViewSurface = true; final Key key = GlobalKey(); @@ -139,8 +134,7 @@ void main() { await mapIdCompleter.future; // Wait for the placeholder to be replaced by the actual view. - while (!tester.any(find.byType(AndroidViewSurface)) && - !tester.any(find.byType(AndroidView))) { + while (!tester.any(find.byType(AndroidViewSurface)) && !tester.any(find.byType(AndroidView))) { await tester.pump(); } @@ -167,8 +161,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool compassEnabled = await inspector.isCompassEnabled(mapId: mapId); expect(compassEnabled, false); @@ -208,8 +201,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool mapToolbarEnabled = await inspector.isMapToolbarEnabled(mapId: mapId); expect(mapToolbarEnabled, false); @@ -251,8 +243,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; // On Android, zooming with zoomTo is constrained by the min/max. await controller.moveCamera(CameraUpdate.zoomTo(15)); @@ -309,11 +300,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled(mapId: mapId); expect(zoomGesturesEnabled, false); await tester.pumpWidget( @@ -351,11 +339,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); expect(zoomControlsEnabled, true); await tester.pumpWidget( @@ -394,8 +379,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool liteModeEnabled = await inspector.isLiteModeEnabled(mapId: mapId); expect(liteModeEnabled, false); @@ -436,11 +420,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, false); await tester.pumpWidget( @@ -456,9 +437,7 @@ void main() { ), ); - rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, true); }); @@ -481,11 +460,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled(mapId: mapId); expect(tiltGesturesEnabled, false); await tester.pumpWidget( @@ -524,11 +500,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, false); await tester.pumpWidget( @@ -544,9 +517,7 @@ void main() { ), ); - scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, true); }); @@ -567,8 +538,7 @@ void main() { ), ), ); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; await tester.pumpAndSettle(); @@ -584,13 +554,11 @@ void main() { final Rect rect = tester.getRect(find.byKey(key)); expect( coordinate.x, - ((rect.center.dx - rect.topLeft.dx) * tester.view.devicePixelRatio) - .round(), + ((rect.center.dx - rect.topLeft.dx) * tester.view.devicePixelRatio).round(), ); expect( coordinate.y, - ((rect.center.dy - rect.topLeft.dy) * tester.view.devicePixelRatio) - .round(), + ((rect.center.dy - rect.topLeft.dy) * tester.view.devicePixelRatio).round(), ); await tester.binding.setSurfaceSize(null); }); @@ -618,8 +586,7 @@ void main() { ); await tester.pumpAndSettle(); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; // Wait for the visible region to be non-zero. final LatLngBounds firstVisibleRegion = @@ -627,8 +594,7 @@ void main() { tester, () => mapController.getVisibleRegion(), (LatLngBounds bounds) => - bounds != zeroLatLngBounds && - bounds.northeast != bounds.southwest, + bounds != zeroLatLngBounds && bounds.northeast != bounds.southwest, ) ?? zeroLatLngBounds; expect(firstVisibleRegion, isNot(zeroLatLngBounds)); @@ -652,21 +618,15 @@ void main() { expect(firstVisibleRegion.contains(northEast), isFalse); expect(firstVisibleRegion.contains(southWest), isFalse); - final latLngBounds = LatLngBounds( - southwest: southWest, - northeast: northEast, - ); + final latLngBounds = LatLngBounds(southwest: southWest, northeast: northEast); // TODO(iskakaushik): non-zero padding is needed for some device configurations // https://github.com/flutter/flutter/issues/30575 const double padding = 0; - await mapController.moveCamera( - CameraUpdate.newLatLngBounds(latLngBounds, padding), - ); + await mapController.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController.getVisibleRegion(); expect(secondVisibleRegion, isNot(zeroLatLngBounds)); @@ -693,8 +653,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool isTrafficEnabled = await inspector.isTrafficEnabled(mapId: mapId); expect(isTrafficEnabled, true); @@ -733,11 +692,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool isBuildingsEnabled = await inspector.areBuildingsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool isBuildingsEnabled = await inspector.areBuildingsEnabled(mapId: mapId); expect(isBuildingsEnabled, true); }); @@ -761,11 +717,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); await tester.pumpWidget( @@ -782,9 +735,7 @@ void main() { ), ); - myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }, // Location button tests are skipped in Android because we don't have location permission to test. @@ -812,10 +763,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }, // Location button tests are skipped in Android because we don't have location permission to test. @@ -842,10 +791,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); }, // Location button tests are skipped in Android because we don't have location permission to test. @@ -869,19 +816,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - const mapStyle = - '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - mapStyle, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + const mapStyle = '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; + await GoogleMapsFlutterPlatform.instance.setMapStyle(mapStyle, mapId: controller.mapId); }); - testWidgets('testSetMapStyle invalid Json String', ( - WidgetTester tester, - ) async { + testWidgets('testSetMapStyle invalid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -898,8 +838,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; try { await GoogleMapsFlutterPlatform.instance.setMapStyle( @@ -930,12 +869,8 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - null, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + await GoogleMapsFlutterPlatform.instance.setMapStyle(null, mapId: controller.mapId); }); testWidgets('testGetLatLng', (WidgetTester tester) async { @@ -955,8 +890,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -965,13 +899,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng topLeft = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); + final LatLng topLeft = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); expect(topLeft, northWest); }); @@ -993,8 +922,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -1027,8 +955,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -1037,13 +964,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); - final ScreenCoordinate topLeft = await controller.getScreenCoordinate( - northWest, - ); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); + final ScreenCoordinate topLeft = await controller.getScreenCoordinate(northWest); expect(topLeft, const ScreenCoordinate(x: 0, y: 0)); }); @@ -1063,8 +985,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpWidget( Directionality( @@ -1100,9 +1021,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController googleMapController) { controllerCompleter.complete(googleMapController); @@ -1111,8 +1030,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); @@ -1122,9 +1040,7 @@ void main() { // re-evaluated when that issue is fixed. await Future.delayed(const Duration(seconds: 1)); - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, false); await controller.showMarkerInfoWindow(marker.markerId); @@ -1163,8 +1079,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final Uint8List? bytes = await controller.takeSnapshot(); expect(bytes?.isNotEmpty, true); }, @@ -1205,8 +1120,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( tileOverlay1.mapsId, @@ -1219,18 +1133,12 @@ void main() { expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.2, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); - expect( - tileOverlayInfo2.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }); @@ -1265,8 +1173,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final tileOverlay1New = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), @@ -1304,10 +1211,7 @@ void main() { expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); @@ -1338,8 +1242,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1382,10 +1285,7 @@ void main() { final marker = Marker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1408,11 +1308,9 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1469,10 +1367,7 @@ void main() { final marker = AdvancedMarker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1480,8 +1375,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1499,8 +1393,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1515,10 +1408,7 @@ void main() { // Remove markers from clusterManagers and test that clusterManagers are empty. for (final MapEntry entry in markers.entries) { - markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId( - entry.value, - null, - ); + markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId(entry.value, null); } await tester.pumpWidget( Directionality( @@ -1582,8 +1472,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; String? error = await controller.getStyleError(); for (var i = 0; i < 1000 && error == null; i++) { await Future.delayed(const Duration(milliseconds: 10)); @@ -1592,9 +1481,7 @@ void main() { expect(error, isNotNull); }); - testWidgets('getStyleError returns null for a valid style', ( - WidgetTester tester, - ) async { + testWidgets('getStyleError returns null for a valid style', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -1613,8 +1500,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNull); }); @@ -1630,9 +1516,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1640,25 +1524,18 @@ void main() { }); testWidgets('markerWithAssetMapBitmapCreate', (WidgetTester tester) async { - final imageConfiguration = ImageConfiguration( - devicePixelRatio: tester.view.devicePixelRatio, - ); + final imageConfiguration = ImageConfiguration(devicePixelRatio: tester.view.devicePixelRatio); final markers = { Marker( markerId: const MarkerId('1'), - icon: await AssetMapBitmap.create( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await AssetMapBitmap.create(imageConfiguration, 'assets/red_square.png'), ), }; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1670,19 +1547,14 @@ void main() { final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1700,19 +1572,14 @@ void main() { markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. // ignore: deprecated_member_use - icon: await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await BitmapDescriptor.fromAssetImage(imageConfiguration, 'assets/red_square.png'), ), }; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1736,9 +1603,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1776,19 +1641,13 @@ void main() { ), ); - void expectGroundOverlayEquals( - GroundOverlay source, - GroundOverlay response, - ) { + void expectGroundOverlayEquals(GroundOverlay source, GroundOverlay response) { expect(response.groundOverlayId, source.groundOverlayId); expect( response.transparency, moreOrLessEquals(source.transparency, epsilon: _floatTolerance), ); - expect( - response.bearing, - moreOrLessEquals(source.bearing, epsilon: _floatTolerance), - ); + expect(response.bearing, moreOrLessEquals(source.bearing, epsilon: _floatTolerance)); // Only test bounds if it was given in the original object if (source.bounds != null) { @@ -1806,14 +1665,8 @@ void main() { expect(response.width, source.width); expect(response.height, source.height); if (source.position != null) { - expect( - response.anchor?.dx, - moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance), - ); - expect( - response.anchor?.dy, - moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance), - ); + expect(response.anchor?.dx, moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance)); + expect(response.anchor?.dy, moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance)); } } @@ -1844,38 +1697,29 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayBoundsInfo2 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPositionInfo1 = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1, - groundOverlayBoundsInfo1, - ); - expectGroundOverlayEquals( - groundOverlayBounds2, - groundOverlayBoundsInfo2, - ); - expectGroundOverlayEquals( - groundOverlayPosition1, - groundOverlayPositionInfo1, - ); + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds2.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPositionInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1, groundOverlayBoundsInfo1); + expectGroundOverlayEquals(groundOverlayBounds2, groundOverlayBoundsInfo2); + expectGroundOverlayEquals(groundOverlayPosition1, groundOverlayPositionInfo1); } }); - testWidgets('update ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('update ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1885,10 +1729,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1897,26 +1738,23 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - - final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); - - final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + + final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); + + final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); await tester.pumpWidget( Directionality( @@ -1924,10 +1762,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1New, - groundOverlayPosition1New, - }, + groundOverlays: {groundOverlayBounds1New, groundOverlayPosition1New}, onMapCreated: (ExampleGoogleMapController controller) { fail('update: OnMapCreated should get called only once.'); }, @@ -1938,28 +1773,21 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPosition1Info = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1New, - groundOverlayBounds1Info, - ); - expectGroundOverlayEquals( - groundOverlayPosition1New, - groundOverlayPosition1Info, - ); + final GroundOverlay groundOverlayBounds1Info = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPosition1Info = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1New, groundOverlayBounds1Info); + expectGroundOverlayEquals(groundOverlayPosition1New, groundOverlayPosition1Info); } }); - testWidgets('remove ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('remove ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1969,10 +1797,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1981,8 +1806,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -2000,10 +1824,14 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay? groundOverlayBounds1Info = await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId); - final GroundOverlay? groundOverlayPositionInfo = await inspector - .getGroundOverlayInfo(groundOverlayPosition1.mapsId, mapId: mapId); + final GroundOverlay? groundOverlayBounds1Info = await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ); + final GroundOverlay? groundOverlayPositionInfo = await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ); expect(groundOverlayBounds1Info, isNull); expect(groundOverlayPositionInfo, isNull); @@ -2016,8 +1844,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -2029,8 +1856,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { cameraIdleCompleter.complete(); } }, @@ -2041,8 +1867,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -2062,8 +1887,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -2078,8 +1904,9 @@ void main() { await cameraIdleCompleter.future; // After onCameraIdle event, the camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2110,8 +1937,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -2135,8 +1961,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { stopwatch.stop(); cameraIdleCompleter.complete(); } @@ -2148,8 +1973,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -2181,15 +2005,10 @@ void main() { // For short animation duration, check that the animation is completed // faster than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - lessThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, lessThan(animationDurationMiddlePoint)); // Reset camera to initial position before testing long duration. - await controller.moveCamera( - CameraUpdate.newCameraPosition(_kInitialCameraPosition), - ); + await controller.moveCamera(CameraUpdate.newCameraPosition(_kInitialCameraPosition)); await tester.pumpAndSettle(); // Create completer for camera idle event. @@ -2212,8 +2031,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -2229,14 +2049,12 @@ void main() { // For longer animation duration, check that the animation is completed // slower than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - greaterThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, greaterThan(animationDurationMiddlePoint)); // Camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2271,9 +2089,7 @@ void main() { Directionality( textDirection: ui.TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 20.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 20.0)), markers: markers, markerType: MarkerType.advancedMarker, onMapCreated: (ExampleGoogleMapController controller) => @@ -2303,31 +2119,20 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, @@ -2353,23 +2158,15 @@ Marker _copyMarkerWithClusterManagerId( CameraUpdate _getCameraUpdateForType(CameraUpdateType type) { return switch (type) { - CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition( - _kTestCameraPosition, - ), + CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition(_kTestCameraPosition), CameraUpdateType.newLatLng => CameraUpdate.newLatLng(_kTestMapCenter), - CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds( - _testCameraBounds, - 0, - ), + CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds(_testCameraBounds, 0), CameraUpdateType.newLatLngZoom => CameraUpdate.newLatLngZoom( _kTestMapCenter, _kTestCameraZoomLevel, ), CameraUpdateType.scrollBy => CameraUpdate.scrollBy(10, 10), - CameraUpdateType.zoomBy => CameraUpdate.zoomBy( - _kTestZoomByAmount, - const Offset(1, 1), - ), + CameraUpdateType.zoomBy => CameraUpdate.zoomBy(_kTestZoomByAmount, const Offset(1, 1)), CameraUpdateType.zoomTo => CameraUpdate.zoomTo(_kTestCameraZoomLevel), CameraUpdateType.zoomIn => CameraUpdate.zoomIn(), CameraUpdateType.zoomOut => CameraUpdate.zoomOut(), @@ -2389,29 +2186,16 @@ Future _checkCameraUpdateByType( switch (type) { case CameraUpdateType.newCameraPosition: - expect( - currentPosition.bearing, - wrapMatcher(equals(_kTestCameraPosition.bearing)), - ); - expect( - currentPosition.zoom, - wrapMatcher(equals(_kTestCameraPosition.zoom)), - ); - expect( - currentPosition.tilt, - wrapMatcher(equals(_kTestCameraPosition.tilt)), - ); + expect(currentPosition.bearing, wrapMatcher(equals(_kTestCameraPosition.bearing))); + expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraPosition.zoom))); + expect(currentPosition.tilt, wrapMatcher(equals(_kTestCameraPosition.tilt))); expect( currentPosition.target.latitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.latitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.latitude, latLngThreshold)), ); expect( currentPosition.target.longitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLng: expect( @@ -2426,15 +2210,11 @@ Future _checkCameraUpdateByType( final LatLngBounds bounds = await controller.getVisibleRegion(); expect( bounds.northeast.longitude, - wrapMatcher( - closeTo(_testCameraBounds.northeast.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.northeast.longitude, latLngThreshold)), ); expect( bounds.southwest.longitude, - wrapMatcher( - closeTo(_testCameraBounds.southwest.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.southwest.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLngZoom: expect( @@ -2449,20 +2229,11 @@ Future _checkCameraUpdateByType( case CameraUpdateType.scrollBy: // For scrollBy, just check that the location has changed. if (oldPosition != null) { - expect( - currentPosition.target.latitude, - isNot(equals(oldPosition.target.latitude)), - ); - expect( - currentPosition.target.longitude, - isNot(equals(oldPosition.target.longitude)), - ); + expect(currentPosition.target.latitude, isNot(equals(oldPosition.target.latitude))); + expect(currentPosition.target.longitude, isNot(equals(oldPosition.target.longitude))); } case CameraUpdateType.zoomBy: - expect( - currentPosition.zoom, - wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount)), - ); + expect(currentPosition.zoom, wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount))); case CameraUpdateType.zoomTo: expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraZoomLevel))); case CameraUpdateType.zoomIn: diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_marker_icons.dart index 6277e7ccc418..eac5ffbd8a56 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_marker_icons.dart @@ -33,8 +33,7 @@ class _AdvancedMarkerIconsBody extends StatefulWidget { final String? mapId; @override - State<_AdvancedMarkerIconsBody> createState() => - _AdvancedMarkerIconsBodyState(); + State<_AdvancedMarkerIconsBody> createState() => _AdvancedMarkerIconsBodyState(); } class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { @@ -51,10 +50,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: (ExampleGoogleMapController controller) { setState(() { @@ -73,29 +69,22 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { const ImageConfiguration(size: Size(12, 12)), 'assets/red_square.png', ); - final AssetMapBitmap largeAsset = - await BitmapDescriptor.asset( - const ImageConfiguration(size: Size(36, 36)), - 'assets/red_square.png', - ); + final AssetMapBitmap largeAsset = await BitmapDescriptor.asset( + const ImageConfiguration(size: Size(36, 36)), + 'assets/red_square.png', + ); setState(() { _markers.addAll([ // Default icon AdvancedMarker( markerId: const MarkerId('1'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude + 1), ), // Custom pin colors AdvancedMarker( markerId: const MarkerId('2'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.black, @@ -105,26 +94,17 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Pin with text AdvancedMarker( markerId: const MarkerId('3'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude + 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.blue, backgroundColor: Colors.white, - glyph: const TextGlyph( - text: 'Hi!', - textColor: Colors.blue, - ), + glyph: const TextGlyph(text: 'Hi!', textColor: Colors.blue), ), ), // Pin with bitmap AdvancedMarker( markerId: const MarkerId('4'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.white, @@ -134,10 +114,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Custom marker icon AdvancedMarker( markerId: const MarkerId('5'), - position: LatLng( - _kMapCenter.latitude, - _kMapCenter.longitude, - ), + position: LatLng(_kMapCenter.latitude, _kMapCenter.longitude), icon: largeAsset, ), ]); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_markers_clustering.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_markers_clustering.dart index d7d305864f65..694acb91fcd9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_markers_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/advanced_markers_clustering.dart @@ -17,10 +17,7 @@ import 'place_advanced_marker.dart'; class AdvancedMarkersClusteringPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkersClusteringPage({super.key, required this.mapId}) - : super( - const Icon(Icons.place_outlined), - 'Manage clusters of advanced markers', - ); + : super(const Icon(Icons.place_outlined), 'Manage clusters of advanced markers'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -79,8 +76,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -108,17 +104,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; }); } @@ -160,14 +150,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -211,9 +198,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/animate_camera.dart index 001006fb54be..d278e2c5b3b6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/animate_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class AnimateCameraPage extends GoogleMapExampleAppPage { - const AnimateCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control, animated'); + const AnimateCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control, animated'); @override Widget build(BuildContext context) { @@ -58,9 +57,7 @@ class AnimateCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -88,9 +85,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), duration: _cameraUpdateAnimationDuration, ); }, @@ -114,10 +109,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), duration: _cameraUpdateAnimationDuration, ); }, diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/clustering.dart index b684d0ff6476..80f2be81c39e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/clustering.dart @@ -13,8 +13,7 @@ import 'page.dart'; /// Page for demonstrating marker clustering support. class ClusteringPage extends GoogleMapExampleAppPage { /// Default Constructor. - const ClusteringPage({super.key}) - : super(const Icon(Icons.place), 'Manage clustering'); + const ClusteringPage({super.key}) : super(const Icon(Icons.place), 'Manage clustering'); @override Widget build(BuildContext context) { @@ -67,8 +66,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -101,10 +99,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = _copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = _copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -140,8 +135,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -150,14 +144,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -196,9 +187,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/collision_behavior.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/collision_behavior.dart index 202bb0c203d3..3709bfab2c87 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/collision_behavior.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/collision_behavior.dart @@ -15,10 +15,7 @@ import 'place_advanced_marker.dart'; class AdvancedMarkerCollisionBehaviorPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkerCollisionBehaviorPage({super.key, required this.mapId}) - : super( - const Icon(Icons.not_listed_location), - 'Advanced marker collision behavior', - ); + : super(const Icon(Icons.not_listed_location), 'Advanced marker collision behavior'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -35,12 +32,10 @@ class _CollisionBehaviorPageBody extends StatefulWidget { final String? mapId; @override - State<_CollisionBehaviorPageBody> createState() => - _CollisionBehaviorPageBodyState(); + State<_CollisionBehaviorPageBody> createState() => _CollisionBehaviorPageBodyState(); } -class _CollisionBehaviorPageBodyState - extends State<_CollisionBehaviorPageBody> { +class _CollisionBehaviorPageBodyState extends State<_CollisionBehaviorPageBody> { static const LatLng center = LatLng(-33.86711, 151.1947171); static const double zoomOutLevel = 9; static const double zoomInLevel = 12; @@ -78,10 +73,7 @@ class _CollisionBehaviorPageBodyState child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: center, - zoom: zoomInLevel, - ), + initialCameraPosition: const CameraPosition(target: center, zoom: zoomInLevel), markers: Set.of(markers), tiltGesturesEnabled: false, zoomGesturesEnabled: false, diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/custom_marker_icon.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/custom_marker_icon.dart index 548146c6206c..3391ba1bcba2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/custom_marker_icon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/custom_marker_icon.dart @@ -20,9 +20,7 @@ Future createCustomMarkerIconImage({required Size size}) async { size.height.floor(), ); - final ByteData? bytes = await image.toByteData( - format: ui.ImageByteFormat.png, - ); + final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); return bytes!; } diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/example_google_map.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/example_google_map.dart index 4df40931fc18..35707b95bcb9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/example_google_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/example_google_map.dart @@ -47,10 +47,7 @@ class ExampleGoogleMapController { if (_googleMapState.widget.onCameraMove != null) { GoogleMapsFlutterPlatform.instance .onCameraMove(mapId: mapId) - .listen( - (CameraMoveEvent e) => - _googleMapState.widget.onCameraMove!(e.value), - ); + .listen((CameraMoveEvent e) => _googleMapState.widget.onCameraMove!(e.value)); } if (_googleMapState.widget.onCameraIdle != null) { GoogleMapsFlutterPlatform.instance @@ -62,27 +59,16 @@ class ExampleGoogleMapController { .listen((MarkerTapEvent e) => _googleMapState.onMarkerTap(e.value)); GoogleMapsFlutterPlatform.instance .onMarkerDragStart(mapId: mapId) - .listen( - (MarkerDragStartEvent e) => - _googleMapState.onMarkerDragStart(e.value, e.position), - ); + .listen((MarkerDragStartEvent e) => _googleMapState.onMarkerDragStart(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDrag(mapId: mapId) - .listen( - (MarkerDragEvent e) => - _googleMapState.onMarkerDrag(e.value, e.position), - ); + .listen((MarkerDragEvent e) => _googleMapState.onMarkerDrag(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDragEnd(mapId: mapId) - .listen( - (MarkerDragEndEvent e) => - _googleMapState.onMarkerDragEnd(e.value, e.position), - ); + .listen((MarkerDragEndEvent e) => _googleMapState.onMarkerDragEnd(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onInfoWindowTap(mapId: mapId) - .listen( - (InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value), - ); + .listen((InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value)); GoogleMapsFlutterPlatform.instance .onPolylineTap(mapId: mapId) .listen((PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value)); @@ -94,18 +80,13 @@ class ExampleGoogleMapController { .listen((CircleTapEvent e) => _googleMapState.onCircleTap(e.value)); GoogleMapsFlutterPlatform.instance .onGroundOverlayTap(mapId: mapId) - .listen( - (GroundOverlayTapEvent e) => - _googleMapState.onGroundOverlayTap(e.value), - ); + .listen((GroundOverlayTapEvent e) => _googleMapState.onGroundOverlayTap(e.value)); GoogleMapsFlutterPlatform.instance .onTap(mapId: mapId) .listen((MapTapEvent e) => _googleMapState.onTap(e.position)); GoogleMapsFlutterPlatform.instance .onLongPress(mapId: mapId) - .listen( - (MapLongPressEvent e) => _googleMapState.onLongPress(e.position), - ); + .listen((MapLongPressEvent e) => _googleMapState.onLongPress(e.position)); GoogleMapsFlutterPlatform.instance .onClusterTap(mapId: mapId) .listen((ClusterTapEvent e) => _googleMapState.onClusterTap(e.value)); @@ -113,24 +94,16 @@ class ExampleGoogleMapController { /// Updates configuration options of the map user interface. Future _updateMapConfiguration(MapConfiguration update) { - return GoogleMapsFlutterPlatform.instance.updateMapConfiguration( - update, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMapConfiguration(update, mapId: mapId); } /// Updates marker configuration. Future _updateMarkers(MarkerUpdates markerUpdates) { - return GoogleMapsFlutterPlatform.instance.updateMarkers( - markerUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMarkers(markerUpdates, mapId: mapId); } /// Updates cluster manager configuration. - Future _updateClusterManagers( - ClusterManagerUpdates clusterManagerUpdates, - ) { + Future _updateClusterManagers(ClusterManagerUpdates clusterManagerUpdates) { return GoogleMapsFlutterPlatform.instance.updateClusterManagers( clusterManagerUpdates, mapId: mapId, @@ -138,9 +111,7 @@ class ExampleGoogleMapController { } /// Updates ground overlay configuration. - Future _updateGroundOverlays( - GroundOverlayUpdates groundOverlayUpdates, - ) { + Future _updateGroundOverlays(GroundOverlayUpdates groundOverlayUpdates) { return GoogleMapsFlutterPlatform.instance.updateGroundOverlays( groundOverlayUpdates, mapId: mapId, @@ -149,26 +120,17 @@ class ExampleGoogleMapController { /// Updates polygon configuration. Future _updatePolygons(PolygonUpdates polygonUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolygons( - polygonUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolygons(polygonUpdates, mapId: mapId); } /// Updates polyline configuration. Future _updatePolylines(PolylineUpdates polylineUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolylines( - polylineUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolylines(polylineUpdates, mapId: mapId); } /// Updates circle configuration. Future _updateCircles(CircleUpdates circleUpdates) { - return GoogleMapsFlutterPlatform.instance.updateCircles( - circleUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateCircles(circleUpdates, mapId: mapId); } /// Updates tile overlays configuration. @@ -182,10 +144,7 @@ class ExampleGoogleMapController { /// Clears the tile cache so that all tiles will be requested again from the /// [TileProvider]. Future clearTileCache(TileOverlayId tileOverlayId) async { - return GoogleMapsFlutterPlatform.instance.clearTileCache( - tileOverlayId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.clearTileCache(tileOverlayId, mapId: mapId); } /// Starts an animated change of the map camera position. @@ -199,10 +158,7 @@ class ExampleGoogleMapController { /// Changes the map camera position. Future moveCamera(CameraUpdate cameraUpdate) { - return GoogleMapsFlutterPlatform.instance.moveCamera( - cameraUpdate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.moveCamera(cameraUpdate, mapId: mapId); } /// Return [LatLngBounds] defining the region that is visible in a map. @@ -212,42 +168,27 @@ class ExampleGoogleMapController { /// Return [ScreenCoordinate] of the [LatLng] in the current map view. Future getScreenCoordinate(LatLng latLng) { - return GoogleMapsFlutterPlatform.instance.getScreenCoordinate( - latLng, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getScreenCoordinate(latLng, mapId: mapId); } /// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view. Future getLatLng(ScreenCoordinate screenCoordinate) { - return GoogleMapsFlutterPlatform.instance.getLatLng( - screenCoordinate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getLatLng(screenCoordinate, mapId: mapId); } /// Programmatically show the Info Window for a [Marker]. Future showMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow(markerId, mapId: mapId); } /// Programmatically hide the Info Window for a [Marker]. Future hideMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow(markerId, mapId: mapId); } /// Returns `true` when the [InfoWindow] is showing, `false` otherwise. Future isMarkerInfoWindowShown(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown(markerId, mapId: mapId); } /// Returns the current zoom level of the map @@ -447,17 +388,14 @@ class ExampleGoogleMap extends StatefulWidget { class _ExampleGoogleMapState extends State { final int _mapId = _nextMapCreationId++; - final Completer _controller = - Completer(); + final Completer _controller = Completer(); Map _markers = {}; Map _polygons = {}; Map _polylines = {}; Map _circles = {}; - Map _clusterManagers = - {}; - Map _groundOverlays = - {}; + Map _clusterManagers = {}; + Map _groundOverlays = {}; late MapConfiguration _mapConfiguration; @override @@ -467,9 +405,7 @@ class _ExampleGoogleMapState extends State { onPlatformViewCreated, widgetConfiguration: MapWidgetConfiguration( textDirection: - widget.layoutDirection ?? - Directionality.maybeOf(context) ?? - TextDirection.ltr, + widget.layoutDirection ?? Directionality.maybeOf(context) ?? TextDirection.ltr, initialCameraPosition: widget.initialCameraPosition, gestureRecognizers: widget.gestureRecognizers, ), @@ -499,9 +435,7 @@ class _ExampleGoogleMapState extends State { @override void dispose() { - _controller.future.then( - (ExampleGoogleMapController controller) => controller.dispose(), - ); + _controller.future.then((ExampleGoogleMapController controller) => controller.dispose()); super.dispose(); } @@ -532,9 +466,7 @@ class _ExampleGoogleMapState extends State { Future _updateMarkers() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateMarkers( - MarkerUpdates.from(_markers.values.toSet(), widget.markers), - ), + controller._updateMarkers(MarkerUpdates.from(_markers.values.toSet(), widget.markers)), ); _markers = keyByMarkerId(widget.markers); } @@ -543,10 +475,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateClusterManagers( - ClusterManagerUpdates.from( - _clusterManagers.values.toSet(), - widget.clusterManagers, - ), + ClusterManagerUpdates.from(_clusterManagers.values.toSet(), widget.clusterManagers), ), ); _clusterManagers = keyByClusterManagerId(widget.clusterManagers); @@ -556,10 +485,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateGroundOverlays( - GroundOverlayUpdates.from( - _groundOverlays.values.toSet(), - widget.groundOverlays, - ), + GroundOverlayUpdates.from(_groundOverlays.values.toSet(), widget.groundOverlays), ), ); _groundOverlays = keyByGroundOverlayId(widget.groundOverlays); @@ -568,9 +494,7 @@ class _ExampleGoogleMapState extends State { Future _updatePolygons() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updatePolygons( - PolygonUpdates.from(_polygons.values.toSet(), widget.polygons), - ), + controller._updatePolygons(PolygonUpdates.from(_polygons.values.toSet(), widget.polygons)), ); _polygons = keyByPolygonId(widget.polygons); } @@ -588,9 +512,7 @@ class _ExampleGoogleMapState extends State { Future _updateCircles() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateCircles( - CircleUpdates.from(_circles.values.toSet(), widget.circles), - ), + controller._updateCircles(CircleUpdates.from(_circles.values.toSet(), widget.circles)), ); _circles = keyByCircleId(widget.circles); } @@ -601,12 +523,11 @@ class _ExampleGoogleMapState extends State { } Future onPlatformViewCreated(int id) async { - final ExampleGoogleMapController controller = - await ExampleGoogleMapController._init( - id, - widget.initialCameraPosition, - this, - ); + final ExampleGoogleMapController controller = await ExampleGoogleMapController._init( + id, + widget.initialCameraPosition, + this, + ); _controller.complete(controller); unawaited(_updateTileOverlays()); widget.onMapCreated?.call(controller); @@ -657,8 +578,7 @@ class _ExampleGoogleMapState extends State { } void onClusterTap(Cluster cluster) { - final ClusterManager? clusterManager = - _clusterManagers[cluster.clusterManagerId]; + final ClusterManager? clusterManager = _clusterManagers[cluster.clusterManagerId]; clusterManager?.onClusterTap?.call(cluster); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/ground_overlay.dart index c311e40c02c5..572622a5674a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/ground_overlay.dart @@ -13,8 +13,7 @@ import 'page.dart'; enum _GroundOverlayPlacing { position, bounds } class GroundOverlayPage extends GoogleMapExampleAppPage { - const GroundOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Ground overlay'); + const GroundOverlayPage({super.key}) : super(const Icon(Icons.map), 'Ground overlay'); @override Widget build(BuildContext context) { @@ -135,9 +134,7 @@ class GroundOverlayBodyState extends State { // Adjusts the bearing by 10 degrees, wrapping around at 360 degrees. // 10 is the increment, 350 degrees of the full circle -10. _groundOverlay = _groundOverlay!.copyWith( - bearingParam: _groundOverlay!.bearing >= 350 - ? 0 - : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, ); }); } @@ -146,9 +143,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { final transparency = _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; - _groundOverlay = _groundOverlay!.copyWith( - transparencyParam: transparency, - ); + _groundOverlay = _groundOverlay!.copyWith(transparencyParam: transparency); }); } @@ -184,8 +179,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.bounds); setState(() { - _currentGroundOverlayBounds = - _currentGroundOverlayBounds == _groundOverlayBounds1 + _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 ? _groundOverlayBounds2 : _groundOverlayBounds1; }); @@ -198,9 +192,7 @@ class GroundOverlayBodyState extends State { void _toggleVisible() { assert(_groundOverlay != null); setState(() { - _groundOverlay = _groundOverlay!.copyWith( - visibleParam: !_groundOverlay!.visible, - ); + _groundOverlay = _groundOverlay!.copyWith(visibleParam: !_groundOverlay!.visible); }); } @@ -240,9 +232,7 @@ class GroundOverlayBodyState extends State { @override Widget build(BuildContext context) { - final overlays = { - if (_groundOverlay != null) _groundOverlay!, - }; + final overlays = {if (_groundOverlay != null) _groundOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -250,10 +240,7 @@ class GroundOverlayBodyState extends State { children: [ Expanded( child: ExampleGoogleMap( - initialCameraPosition: CameraPosition( - target: _mapCenter, - zoom: 14.0, - ), + initialCameraPosition: CameraPosition(target: _mapCenter, zoom: 14.0), groundOverlays: overlays, onMapCreated: _onMapCreated, ), @@ -275,9 +262,7 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeTransparency(), + onPressed: _groundOverlay == null ? null : () => _changeTransparency(), child: const Text('change transparency'), ), TextButton( @@ -299,31 +284,23 @@ class GroundOverlayBodyState extends State { TextButton( onPressed: _groundOverlay == null ? null : () => _changeType(), child: Text( - _placingType == _GroundOverlayPlacing.position - ? 'use bounds' - : 'use position', + _placingType == _GroundOverlayPlacing.position ? 'use bounds' : 'use position', ), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changePosition(), child: const Text('change position'), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changeDimensions(), child: const Text('change dimensions'), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.bounds || _groundOverlay == null ? null : () => _changeBounds(), child: const Text('change bounds'), diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/main.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/main.dart index 3ead3a00e9b4..54c6f67ed445 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/main.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/main.dart @@ -115,15 +115,11 @@ Future initializeMapRenderer() async { WidgetsFlutterBinding.ensureInitialized(); - final platform = - GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; + final platform = GoogleMapsFlutterPlatform.instance as GoogleMapsFlutterAndroid; unawaited( platform .initializeWithRenderer(AndroidMapRenderer.latest) - .then( - (AndroidMapRenderer initializedRenderer) => - completer.complete(initializedRenderer), - ) + .then((AndroidMapRenderer initializedRenderer) => completer.complete(initializedRenderer)) .then((_) => platform.warmup()), ); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_click.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_click.dart index a786197d5205..49ecd2656bab 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_click.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_click.dart @@ -58,42 +58,25 @@ class _MapClickBodyState extends State<_MapClickBody> { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; if (mapController != null) { final lastTap = 'Tap:\n${_lastTap ?? ""}\n'; final lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; + columnChildren.add(Center(child: Text(lastTap, textAlign: TextAlign.center))); columnChildren.add( - Center(child: Text(lastTap, textAlign: TextAlign.center)), - ); - columnChildren.add( - Center( - child: Text( - _lastTap != null ? 'Tapped' : '', - textAlign: TextAlign.center, - ), - ), - ); - columnChildren.add( - Center(child: Text(lastLongPress, textAlign: TextAlign.center)), + Center(child: Text(_lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center)), ); + columnChildren.add(Center(child: Text(lastLongPress, textAlign: TextAlign.center))); columnChildren.add( Center( - child: Text( - _lastLongPress != null ? 'Long pressed' : '', - textAlign: TextAlign.center, - ), + child: Text(_lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } Future onMapCreated(ExampleGoogleMapController controller) async { diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_coordinates.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_coordinates.dart index 085366918f07..a26bce01fc7e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_coordinates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_coordinates.dart @@ -16,8 +16,7 @@ const CameraPosition _kInitialPosition = CameraPosition( ); class MapCoordinatesPage extends GoogleMapExampleAppPage { - const MapCoordinatesPage({super.key}) - : super(const Icon(Icons.map), 'Map coordinates'); + const MapCoordinatesPage({super.key}) : super(const Icon(Icons.map), 'Map coordinates'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { final googleMap = ExampleGoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, - onCameraIdle: - _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 + onCameraIdle: _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 ); return NotificationListener( @@ -59,9 +57,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { children: [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), if (mapController != null) Center( diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_map_id.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_map_id.dart index 4317a2d15cd4..dbeb2f4ba093 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_map_id.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_map_id.dart @@ -13,8 +13,7 @@ import 'main.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { - const MapIdPage({super.key}) - : super(const Icon(Icons.map), 'Cloud-based maps styling'); + const MapIdPage({super.key}) : super(const Icon(Icons.map), 'Cloud-based maps styling'); @override Widget build(BuildContext context) { @@ -76,10 +75,7 @@ class MapIdBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), key: _key, mapId: _mapId, ); @@ -87,9 +83,7 @@ class MapIdBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), Padding( padding: const EdgeInsets.all(10.0), @@ -115,10 +109,7 @@ class MapIdBodyState extends State { ), ]; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_ui.dart index 8358f661109b..990c3bcd491b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_ui.dart @@ -96,9 +96,7 @@ class MapUiBodyState extends State { Widget _latLngBoundsToggler() { return TextButton( child: Text( - _cameraTargetBounds.bounds == null - ? 'bound camera target' - : 'release camera target', + _cameraTargetBounds.bounds == null ? 'bound camera target' : 'release camera target', ), onPressed: () { setState(() { @@ -112,9 +110,7 @@ class MapUiBodyState extends State { Widget _zoomBoundsToggler() { return TextButton( - child: Text( - _minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom', - ), + child: Text(_minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom'), onPressed: () { setState(() { _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null @@ -126,8 +122,7 @@ class MapUiBodyState extends State { } Widget _mapTypeCycler() { - final MapType nextType = - MapType.values[(_mapType.index + 1) % MapType.values.length]; + final MapType nextType = MapType.values[(_mapType.index + 1) % MapType.values.length]; return TextButton( child: Text('change map type to $nextType'), onPressed: () { @@ -184,9 +179,7 @@ class MapUiBodyState extends State { Widget _zoomControlsToggler() { return TextButton( - child: Text( - '${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls', - ), + child: Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'), onPressed: () { setState(() { _zoomControlsEnabled = !_zoomControlsEnabled; @@ -208,9 +201,7 @@ class MapUiBodyState extends State { Widget _myLocationToggler() { return TextButton( - child: Text( - '${_myLocationEnabled ? 'disable' : 'enable'} my location marker', - ), + child: Text('${_myLocationEnabled ? 'disable' : 'enable'} my location marker'), onPressed: () { setState(() { _myLocationEnabled = !_myLocationEnabled; @@ -221,9 +212,7 @@ class MapUiBodyState extends State { Widget _myLocationButtonToggler() { return TextButton( - child: Text( - '${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button', - ), + child: Text('${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'), onPressed: () { setState(() { _myLocationButtonEnabled = !_myLocationButtonEnabled; @@ -252,9 +241,7 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = _nightMode - ? await _getFileData('assets/night_mode.json') - : ''; + final String style = _nightMode ? await _getFileData('assets/night_mode.json') : ''; setState(() { _mapStyle = style; }); @@ -288,9 +275,7 @@ class MapUiBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; @@ -327,10 +312,7 @@ class MapUiBodyState extends State { ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _updateCameraPosition(CameraPosition position) { diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/marker_icons.dart index d4ac8d6ac597..84d13ac32e89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/marker_icons.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MarkerIconsPage extends GoogleMapExampleAppPage { - const MarkerIconsPage({super.key}) - : super(const Icon(Icons.image), 'Marker icons'); + const MarkerIconsPage({super.key}) : super(const Icon(Icons.image), 'Marker icons'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { AssetMapBitmap? _markerIconAsset; BytesMapBitmap? _markerIconBytes; final int _markersAmountPerType = 15; - bool get _customSizeEnabled => - _currentSizeOption != _MarkerSizeOption.original; + bool get _customSizeEnabled => _currentSizeOption != _MarkerSizeOption.original; @override Widget build(BuildContext context) { @@ -64,10 +62,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { width: 350.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: _onMapCreated, ), @@ -75,11 +70,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ), TextButton( onPressed: () => _toggleScaling(context), - child: Text( - _scalingEnabled - ? 'Disable auto scaling' - : 'Enable auto scaling', - ), + child: Text(_scalingEnabled ? 'Disable auto scaling' : 'Enable auto scaling'), ), if (_scalingEnabled) ...[ Container( @@ -91,10 +82,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'Reference box with size of ${referenceSize.width} x ${referenceSize.height} in logical pixels.', ), const SizedBox(height: 10), - Image.asset( - 'assets/red_square.png', - scale: _mipMapsEnabled ? null : 1.0, - ), + Image.asset('assets/red_square.png', scale: _mipMapsEnabled ? null : 1.0), const Text('Asset image rendered with flutter'), const SizedBox(height: 10), Row( @@ -112,9 +100,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { }); } }, - items: _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { + items: _MarkerSizeOption.values.map((_MarkerSizeOption option) { return DropdownMenuItem<_MarkerSizeOption>( value: option, child: Text(_getMarkerSizeOptionName(option)), @@ -126,9 +112,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ], TextButton( onPressed: () => _toggleMipMaps(context), - child: Text( - _mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps', - ), + child: Text(_mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps'), ), ], ), @@ -179,15 +163,9 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { if (width != null && height != null) { return Size(width, height); } else if (width != null) { - return Size( - width, - width * _markerAssetImageSize.height / _markerAssetImageSize.width, - ); + return Size(width, width * _markerAssetImageSize.height / _markerAssetImageSize.width); } else if (height != null) { - return Size( - height * _markerAssetImageSize.width / _markerAssetImageSize.height, - height, - ); + return Size(height * _markerAssetImageSize.width / _markerAssetImageSize.height, height); } else { return _markerAssetImageSize; } @@ -210,10 +188,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createAssetMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude - 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude - 1); return Marker( markerId: MarkerId('marker_asset_$index'), @@ -223,10 +198,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createBytesMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude + 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude + 1); return Marker( markerId: MarkerId('marker_bytes_$index'), @@ -252,26 +224,20 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { - final ImageConfiguration imageConfiguration = - createLocalImageConfiguration(context); + final ImageConfiguration imageConfiguration = createLocalImageConfiguration(context); assetMapBitmap = await AssetMapBitmap.create( imageConfiguration, 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -281,9 +247,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } @@ -291,9 +255,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Future _updateMarkerBytesImage(BuildContext context) async { - final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf( - context, - ); + final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context); final Size bitmapLogicalSize = _getMarkerReferenceSize(); final double? imagePixelRatio = _scalingEnabled ? devicePixelRatio : null; @@ -307,10 +269,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); @@ -319,9 +278,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/move_camera.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/move_camera.dart index 5fc48e659246..28ce96f2b55f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/move_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/move_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MoveCameraPage extends GoogleMapExampleAppPage { - const MoveCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control'); + const MoveCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control'); @override Widget build(BuildContext context) { @@ -46,9 +45,7 @@ class MoveCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -75,9 +72,7 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -99,19 +94,14 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.moveCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), @@ -121,9 +111,7 @@ class MoveCameraState extends State { children: [ TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0)), - ); + mapController?.moveCamera(CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0))); }, child: const Text('zoomBy with focus'), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/padding.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/padding.dart index a0f4f8521c8e..82136d27cd8c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/padding.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/padding.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PaddingPage extends GoogleMapExampleAppPage { - const PaddingPage({super.key}) - : super(const Icon(Icons.map), 'Add padding to the map'); + const PaddingPage({super.key}) : super(const Icon(Icons.map), 'Add padding to the map'); @override Widget build(BuildContext context) { @@ -38,19 +37,14 @@ class MarkerIconsBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), padding: _padding, ); final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), const Padding( padding: EdgeInsets.only(top: 20), @@ -65,10 +59,7 @@ class MarkerIconsBodyState extends State { columnChildren.addAll([_paddingInput(), _buttons()]); - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _onMapCreated(ExampleGoogleMapController controllerParam) { diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_advanced_marker.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_advanced_marker.dart index 19ff25976194..d772469b4e3c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_advanced_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_advanced_marker.dart @@ -56,17 +56,11 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; markerPosition = null; @@ -91,10 +85,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -160,16 +151,10 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { void _changePosition(MarkerId markerId) { final AdvancedMarker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -222,9 +207,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -232,9 +215,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -249,9 +230,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -272,9 +251,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { /// Performs customizations of the [marker] to mark it as selected or not. AdvancedMarker copyWithSelectedState(AdvancedMarker marker, bool isSelected) { - return marker.copyWith( - iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected), - ); + return marker.copyWith(iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected)); } @override @@ -304,9 +281,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -315,70 +290,49 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( onPressed: selectedId == null ? null - : () => - _setMarkerIcon(selectedId, _getMarkerIcon(context)), + : () => _setMarkerIcon(selectedId, _getMarkerIcon(context)), child: const Text('set glyph text'), ), ], @@ -420,12 +374,10 @@ class AdvancedMarkersCapabilityStatus extends StatefulWidget { final ExampleGoogleMapController? controller; @override - State createState() => - _AdvancedMarkersCapabilityStatusState(); + State createState() => _AdvancedMarkersCapabilityStatusState(); } -class _AdvancedMarkersCapabilityStatusState - extends State { +class _AdvancedMarkersCapabilityStatusState extends State { /// Whether map supports advanced markers. bool? _isAdvancedMarkersAvailable; @@ -446,21 +398,19 @@ class _AdvancedMarkersCapabilityStatusState void _checkCapabilityIfNeeded() { final ExampleGoogleMapController? controller = widget.controller; - if (controller != null && - _isAdvancedMarkersAvailable == null && - !_isFetching) { + if (controller != null && _isAdvancedMarkersAvailable == null && !_isFetching) { _isFetching = true; - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - _isFetching = false; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; + _isFetching = false; + }); + }); } } @@ -471,8 +421,7 @@ class _AdvancedMarkersCapabilityStatusState child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_circle.dart index 3c0335bfd18b..6bd22df33ef2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_circle.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { - const PlaceCirclePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place circle'); + const PlaceCirclePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place circle'); @override Widget build(BuildContext context) { @@ -38,12 +37,7 @@ class PlaceCircleBodyState extends State { // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling circle stroke width int widthsIndex = 0; @@ -133,9 +127,7 @@ class PlaceCircleBodyState extends State { void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { - circles[circleId] = circle.copyWith( - strokeWidthParam: widths[++widthsIndex % widths.length], - ); + circles[circleId] = circle.copyWith(strokeWidthParam: widths[++widthsIndex % widths.length]); }); } @@ -171,15 +163,11 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_marker.dart index 3f6509d1c2f7..913ecd4a9f8a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_marker.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceMarkerPage extends GoogleMapExampleAppPage { - const PlaceMarkerPage({super.key}) - : super(const Icon(Icons.place), 'Place marker'); + const PlaceMarkerPage({super.key}) : super(const Icon(Icons.place), 'Place marker'); @override Widget build(BuildContext context) { @@ -61,10 +60,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = _copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = _copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -93,10 +89,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -153,16 +146,10 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { void _changePosition(MarkerId markerId) { final Marker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -215,9 +202,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -225,9 +210,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -242,9 +225,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -294,9 +275,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -305,63 +284,43 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polygon.dart index 70ad42c93724..d7c518cdf48d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polygon.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolygonPage extends GoogleMapExampleAppPage { - const PlacePolygonPage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polygon'); + const PlacePolygonPage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polygon'); @override Widget build(BuildContext context) { @@ -39,12 +38,7 @@ class PlacePolygonBodyState extends State { // Values when toggling polygon color int strokeColorsIndex = 0; int fillColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polygon width int widthsIndex = 0; @@ -149,9 +143,7 @@ class PlacePolygonBodyState extends State { void _addHoles(PolygonId polygonId) { final Polygon polygon = polygons[polygonId]!; setState(() { - polygons[polygonId] = polygon.copyWith( - holesParam: _createHoles(polygonId), - ); + polygons[polygonId] = polygon.copyWith(holesParam: _createHoles(polygonId)); }); } @@ -194,15 +186,11 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -232,9 +220,7 @@ class PlacePolygonBodyState extends State { child: const Text('remove holes'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polyline.dart index 8703ffcbd68f..a60d106bbe0b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_polyline.dart @@ -12,8 +12,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolylinePage extends GoogleMapExampleAppPage { - const PlacePolylinePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polyline'); + const PlacePolylinePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polyline'); @override Widget build(BuildContext context) { @@ -38,23 +37,14 @@ class PlacePolylineBodyState extends State { // Values when toggling polyline color int colorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polyline width int widthsIndex = 0; List widths = [10, 20, 5]; int jointTypesIndex = 0; - List jointTypes = [ - JointType.mitered, - JointType.bevel, - JointType.round, - ]; + List jointTypes = [JointType.mitered, JointType.bevel, JointType.round]; // Values when toggling polyline end cap type int endCapsIndex = 0; @@ -133,36 +123,28 @@ class PlacePolylineBodyState extends State { void _toggleGeodesic(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - geodesicParam: !polyline.geodesic, - ); + polylines[polylineId] = polyline.copyWith(geodesicParam: !polyline.geodesic); }); } void _toggleVisible(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - visibleParam: !polyline.visible, - ); + polylines[polylineId] = polyline.copyWith(visibleParam: !polyline.visible); }); } void _changeColor(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - colorParam: colors[++colorsIndex % colors.length], - ); + polylines[polylineId] = polyline.copyWith(colorParam: colors[++colorsIndex % colors.length]); }); } void _changeWidth(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - widthParam: widths[++widthsIndex % widths.length], - ); + polylines[polylineId] = polyline.copyWith(widthParam: widths[++widthsIndex % widths.length]); }); } @@ -237,15 +219,11 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -259,15 +237,11 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) ? null : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( @@ -289,9 +263,7 @@ class PlacePolylineBodyState extends State { child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) ? null : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart index d24c2f8a6d17..2f00b6780a64 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart @@ -11,8 +11,7 @@ import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platf void main() { // Require Hybrid Composition mode on Android. - final GoogleMapsFlutterPlatform mapsImplementation = - GoogleMapsFlutterPlatform.instance; + final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { // Force Hybrid Composition mode. mapsImplementation.useAndroidViewSurface = true; @@ -21,6 +20,7 @@ void main() { runApp(const MyApp()); // #docregion DisplayMode } + // #enddocregion DisplayMode class MyApp extends StatefulWidget { @@ -47,13 +47,10 @@ class _MyAppState extends State { Future initializeLatestMapRenderer() async { // #docregion MapRenderer - final GoogleMapsFlutterPlatform mapsImplementation = - GoogleMapsFlutterPlatform.instance; + final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { WidgetsFlutterBinding.ensureInitialized(); - mapRenderer = await mapsImplementation.initializeWithRenderer( - AndroidMapRenderer.latest, - ); + mapRenderer = await mapsImplementation.initializeWithRenderer(AndroidMapRenderer.latest); } // #enddocregion MapRenderer } diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/scrolling_map.dart index e5a8ec2ce5a6..443544402c31 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/scrolling_map.dart @@ -15,8 +15,7 @@ import 'page.dart'; const LatLng _center = LatLng(32.080664, 34.9563837); class ScrollingMapPage extends GoogleMapExampleAppPage { - const ScrollingMapPage({super.key}) - : super(const Icon(Icons.map), 'Scrolling map'); + const ScrollingMapPage({super.key}) : super(const Icon(Icons.map), 'Scrolling map'); @override Widget build(BuildContext context) { @@ -45,15 +44,10 @@ class ScrollingMapBody extends StatelessWidget { width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), gestureRecognizers: // >{ - Factory( - () => EagerGestureRecognizer(), - ), + Factory(() => EagerGestureRecognizer()), }, ), ), @@ -70,19 +64,14 @@ class ScrollingMapBody extends StatelessWidget { const Text("This map doesn't consume the vertical drags."), const Padding( padding: EdgeInsets.only(bottom: 12.0), - child: Text( - 'It still gets other gestures (e.g scale or tap).', - ), + child: Text('It still gets other gestures (e.g scale or tap).'), ), Center( child: SizedBox( width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), markers: { Marker( markerId: const MarkerId('test_marker_id'), @@ -93,12 +82,9 @@ class ScrollingMapBody extends StatelessWidget { ), ), }, - gestureRecognizers: - >{ - Factory( - () => ScaleGestureRecognizer(), - ), - }, + gestureRecognizers: >{ + Factory(() => ScaleGestureRecognizer()), + }, ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/snapshot.dart index 6f1624234ec4..906b3de2ecff 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/snapshot.dart @@ -53,8 +53,7 @@ class _SnapshotBodyState extends State<_SnapshotBody> { TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = await _mapController - ?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/tile_overlay.dart index cefa70eb34d5..3f3a26b6ab89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/lib/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/lib/tile_overlay.dart @@ -14,8 +14,7 @@ import 'example_google_map.dart'; import 'page.dart'; class TileOverlayPage extends GoogleMapExampleAppPage { - const TileOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Tile overlay'); + const TileOverlayPage({super.key}) : super(const Icon(Icons.map), 'Tile overlay'); @override Widget build(BuildContext context) { @@ -90,18 +89,9 @@ class TileOverlayBodyState extends State { ), ), ), - TextButton( - onPressed: _addTileOverlay, - child: const Text('Add tile overlay'), - ), - TextButton( - onPressed: _removeTileOverlay, - child: const Text('Remove tile overlay'), - ), - TextButton( - onPressed: _clearTileCache, - child: const Text('Clear tile cache'), - ), + TextButton(onPressed: _addTileOverlay, child: const Text('Add tile overlay')), + TextButton(onPressed: _removeTileOverlay, child: const Text('Remove tile overlay')), + TextButton(onPressed: _clearTileCache, child: const Text('Clear tile cache')), ], ); } @@ -125,22 +115,14 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/test/example_google_map_test.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/test/example_google_map_test.dart index 261fc473e8bb..6aa25acb4b63 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/test/example_google_map_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/test/example_google_map_test.dart @@ -107,17 +107,12 @@ void main() { const p1 = Polygon(polygonId: PolygonId('polygon_1')); const p2 = Polygon(polygonId: PolygonId('polygon_2')); const p3 = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1); - const p3updated = Polygon( - polygonId: PolygonId('polygon_3'), - strokeWidth: 2, - ); + const p3updated = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polygons: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polygons: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -149,9 +144,7 @@ void main() { // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polylines: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polylines: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -163,9 +156,7 @@ void main() { expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[1].polylinesToAdd, {p3}); - expect(map.polylineUpdates[1].polylineIdsToRemove, { - p2.polylineId, - }); + expect(map.polylineUpdates[1].polylineIdsToRemove, {p2.polylineId}); expect(map.polylineUpdates[2].polylinesToChange, {p3updated}); expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/example/test/fake_google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter_android/example/test/fake_google_maps_flutter_platform.dart index a589658f5c6e..654c0b80a4e4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/example/test/fake_google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/example/test/fake_google_maps_flutter_platform.dart @@ -17,8 +17,7 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { List createdIds = []; /// A map of creation IDs to fake map instances. - Map mapInstances = - {}; + Map mapInstances = {}; PlatformMapStateRecorder get lastCreatedMap => mapInstances[createdIds.last]!; @@ -41,46 +40,31 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { Future init(int mapId) async {} @override - Future updateMapConfiguration( - MapConfiguration update, { - required int mapId, - }) async { + Future updateMapConfiguration(MapConfiguration update, {required int mapId}) async { mapInstances[mapId]?.mapConfiguration = update; await _fakeDelay(); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { mapInstances[mapId]?.markerUpdates.add(markerUpdates); await _fakeDelay(); } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { mapInstances[mapId]?.polygonUpdates.add(polygonUpdates); await _fakeDelay(); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { mapInstances[mapId]?.polylineUpdates.add(polylineUpdates); await _fakeDelay(); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { mapInstances[mapId]?.circleUpdates.add(circleUpdates); await _fakeDelay(); } @@ -113,16 +97,10 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async {} + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async {} @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future animateCameraWithConfiguration( @@ -132,55 +110,34 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { }) async {} @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future setMapStyle(String? mapStyle, {required int mapId}) async {} @override Future getVisibleRegion({required int mapId}) async { - return LatLngBounds( - southwest: const LatLng(0, 0), - northeast: const LatLng(0, 0), - ); + return LatLngBounds(southwest: const LatLng(0, 0), northeast: const LatLng(0, 0)); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return const ScreenCoordinate(x: 0, y: 0); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return const LatLng(0, 0); } @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return false; } @@ -312,24 +269,14 @@ class PlatformMapStateRecorder { this.mapConfiguration = const MapConfiguration(), }) { clusterManagerUpdates.add( - ClusterManagerUpdates.from( - const {}, - mapObjects.clusterManagers, - ), + ClusterManagerUpdates.from(const {}, mapObjects.clusterManagers), ); groundOverlayUpdates.add( - GroundOverlayUpdates.from( - const {}, - mapObjects.groundOverlays, - ), + GroundOverlayUpdates.from(const {}, mapObjects.groundOverlays), ); markerUpdates.add(MarkerUpdates.from(const {}, mapObjects.markers)); - polygonUpdates.add( - PolygonUpdates.from(const {}, mapObjects.polygons), - ); - polylineUpdates.add( - PolylineUpdates.from(const {}, mapObjects.polylines), - ); + polygonUpdates.add(PolygonUpdates.from(const {}, mapObjects.polygons)); + polylineUpdates.add(PolylineUpdates.from(const {}, mapObjects.polylines)); circleUpdates.add(CircleUpdates.from(const {}, mapObjects.circles)); tileOverlaySets.add(mapObjects.tileOverlays); } @@ -343,8 +290,6 @@ class PlatformMapStateRecorder { final List polylineUpdates = []; final List circleUpdates = []; final List> tileOverlaySets = >[]; - final List clusterManagerUpdates = - []; - final List groundOverlayUpdates = - []; + final List clusterManagerUpdates = []; + final List groundOverlayUpdates = []; } diff --git a/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_map_inspector_android.dart b/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_map_inspector_android.dart index 0c09c6d789eb..8733dba36bec 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_map_inspector_android.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_map_inspector_android.dart @@ -15,9 +15,8 @@ import 'messages.g.dart'; class GoogleMapsInspectorAndroid extends GoogleMapsInspectorPlatform { /// Creates an inspector API instance for a given map ID from /// [inspectorProvider]. - GoogleMapsInspectorAndroid( - MapsInspectorApi? Function(int mapId) inspectorProvider, - ) : _inspectorProvider = inspectorProvider; + GoogleMapsInspectorAndroid(MapsInspectorApi? Function(int mapId) inspectorProvider) + : _inspectorProvider = inspectorProvider; final MapsInspectorApi? Function(int mapId) _inspectorProvider; @@ -53,17 +52,12 @@ class GoogleMapsInspectorAndroid extends GoogleMapsInspectorPlatform { @override Future getMinMaxZoomLevels({required int mapId}) async { - final PlatformZoomRange zoomLevels = await _inspectorProvider( - mapId, - )!.getZoomRange(); + final PlatformZoomRange zoomLevels = await _inspectorProvider(mapId)!.getZoomRange(); return MinMaxZoomPreference(zoomLevels.min, zoomLevels.max); } @override - Future getTileOverlayInfo( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) async { final PlatformTileLayer? tileInfo = await _inspectorProvider( mapId, )!.getTileOverlayInfo(tileOverlayId.value); @@ -121,23 +115,14 @@ class GoogleMapsInspectorAndroid extends GoogleMapsInspectorPlatform { transparency: groundOverlayInfo.transparency, visible: groundOverlayInfo.visible, clickable: groundOverlayInfo.clickable, - anchor: Offset( - groundOverlayInfo.anchor!.x, - groundOverlayInfo.anchor!.y, - ), + anchor: Offset(groundOverlayInfo.anchor!.x, groundOverlayInfo.anchor!.y), ); } else if (bounds != null) { return GroundOverlay.fromBounds( groundOverlayId: groundOverlayId, bounds: LatLngBounds( - southwest: LatLng( - bounds.southwest.latitude, - bounds.southwest.longitude, - ), - northeast: LatLng( - bounds.northeast.latitude, - bounds.northeast.longitude, - ), + southwest: LatLng(bounds.southwest.latitude, bounds.southwest.longitude), + northeast: LatLng(bounds.northeast.latitude, bounds.northeast.longitude), ), image: dummyImage, zIndex: groundOverlayInfo.zIndex, @@ -181,9 +166,7 @@ class GoogleMapsInspectorAndroid extends GoogleMapsInspectorPlatform { required int mapId, required ClusterManagerId clusterManagerId, }) async { - return (await _inspectorProvider( - mapId, - )!.getClusters(clusterManagerId.value)) + return (await _inspectorProvider(mapId)!.getClusters(clusterManagerId.value)) // See comment in messages.dart for why the force unwrap is okay. .map( (PlatformCluster? cluster) => @@ -201,10 +184,7 @@ class GoogleMapsInspectorAndroid extends GoogleMapsInspectorPlatform { mapId, )!.getCameraPosition(); return CameraPosition( - target: LatLng( - cameraPosition.target.latitude, - cameraPosition.target.longitude, - ), + target: LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude), bearing: cameraPosition.bearing, tilt: cameraPosition.tilt, zoom: cameraPosition.zoom, diff --git a/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_maps_flutter_android.dart b/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_maps_flutter_android.dart index bdad55260cc1..9403484d2289 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_maps_flutter_android.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/lib/src/google_maps_flutter_android.dart @@ -81,8 +81,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { /// The per-map handlers for callbacks from the host side. @visibleForTesting - final Map hostMapHandlers = - {}; + final Map hostMapHandlers = {}; /// Accesses the MapsApi associated to the passed mapId. MapsApi _hostApi(int mapId) { @@ -106,8 +105,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { mapId, _mapEventStreamController, tileOverlayProvider: (TileOverlayId tileOverlayId) { - final Map? tileOverlaysForMap = - _tileOverlays[mapId]; + final Map? tileOverlaysForMap = _tileOverlays[mapId]; return tileOverlaysForMap?[tileOverlayId]; }, ); @@ -149,9 +147,8 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { StreamController>.broadcast(); // Returns a filtered view of the events in the _controller, by mapId. - Stream> _events(int mapId) => _mapEventStreamController - .stream - .where((MapEvent event) => event.mapId == mapId); + Stream> _events(int mapId) => + _mapEventStreamController.stream.where((MapEvent event) => event.mapId == mapId); @override Stream onCameraMoveStarted({required int mapId}) { @@ -229,30 +226,21 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } @override - Future updateMapConfiguration( - MapConfiguration configuration, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromMapConfiguration(configuration), - ); + Future updateMapConfiguration(MapConfiguration configuration, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromMapConfiguration(configuration)); } @override - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromOptionsJson(optionsUpdate), - ); + Future updateMapOptions(Map optionsUpdate, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromOptionsJson(optionsUpdate)); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) { return _hostApi(mapId).updateMarkers( markerUpdates.markersToAdd.map(_platformMarkerFromMarker).toList(), markerUpdates.markersToChange.map(_platformMarkerFromMarker).toList(), @@ -261,42 +249,25 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) { return _hostApi(mapId).updatePolygons( polygonUpdates.polygonsToAdd.map(_platformPolygonFromPolygon).toList(), polygonUpdates.polygonsToChange.map(_platformPolygonFromPolygon).toList(), - polygonUpdates.polygonIdsToRemove - .map((PolygonId id) => id.value) - .toList(), + polygonUpdates.polygonIdsToRemove.map((PolygonId id) => id.value).toList(), ); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) { return _hostApi(mapId).updatePolylines( - polylineUpdates.polylinesToAdd - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylinesToChange - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylineIdsToRemove - .map((PolylineId id) => id.value) - .toList(), + polylineUpdates.polylinesToAdd.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylinesToChange.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylineIdsToRemove.map((PolylineId id) => id.value).toList(), ); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) { return _hostApi(mapId).updateCircles( circleUpdates.circlesToAdd.map(_platformCircleFromCircle).toList(), circleUpdates.circlesToChange.map(_platformCircleFromCircle).toList(), @@ -305,41 +276,26 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) { return _hostApi(mapId).updateHeatmaps( heatmapUpdates.heatmapsToAdd.map(_platformHeatmapFromHeatmap).toList(), heatmapUpdates.heatmapsToChange.map(_platformHeatmapFromHeatmap).toList(), - heatmapUpdates.heatmapIdsToRemove - .map((HeatmapId id) => id.value) - .toList(), + heatmapUpdates.heatmapIdsToRemove.map((HeatmapId id) => id.value).toList(), ); } @override - Future updateTileOverlays({ - required Set newTileOverlays, - required int mapId, - }) { - final Map? currentTileOverlays = - _tileOverlays[mapId]; + Future updateTileOverlays({required Set newTileOverlays, required int mapId}) { + final Map? currentTileOverlays = _tileOverlays[mapId]; final Set previousSet = currentTileOverlays != null ? currentTileOverlays.values.toSet() : {}; final updates = _TileOverlayUpdates.from(previousSet, newTileOverlays); _tileOverlays[mapId] = keyTileOverlayId(newTileOverlays); return _hostApi(mapId).updateTileOverlays( - updates.tileOverlaysToAdd - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlaysToChange - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlayIdsToRemove - .map((TileOverlayId id) => id.value) - .toList(), + updates.tileOverlaysToAdd.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlaysToChange.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlayIdsToRemove.map((TileOverlayId id) => id.value).toList(), ); } @@ -378,17 +334,12 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { groundOverlayUpdates.groundOverlaysToChange .map(_platformGroundOverlayFromGroundOverlay) .toList(), - groundOverlayUpdates.groundOverlayIdsToRemove - .map((GroundOverlayId id) => id.value) - .toList(), + groundOverlayUpdates.groundOverlayIdsToRemove.map((GroundOverlayId id) => id.value).toList(), ); } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) { return _hostApi(mapId).clearTileCache(tileOverlayId.value); } @@ -415,9 +366,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { @override Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) { - return _hostApi( - mapId, - ).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); + return _hostApi(mapId).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); } @override @@ -430,32 +379,20 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { @override Future getVisibleRegion({required int mapId}) async { - return _latLngBoundsFromPlatformLatLngBounds( - await _hostApi(mapId).getVisibleRegion(), - ); + return _latLngBoundsFromPlatformLatLngBounds(await _hostApi(mapId).getVisibleRegion()); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return _screenCoordinateFromPlatformPoint( - await _hostApi( - mapId, - ).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), + await _hostApi(mapId).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), ); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return _latLngFromPlatformLatLng( - await _hostApi( - mapId, - ).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), + await _hostApi(mapId).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), ); } @@ -470,10 +407,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) { return _hostApi(mapId).isInfoWindowShown(markerId.value); } @@ -489,9 +423,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { @override Future getStyleError({required int mapId}) async { - return (await _hostApi(mapId).didLastStyleSucceed()) - ? null - : _setStyleFailureMessage; + return (await _hostApi(mapId).didLastStyleSucceed()) ? null : _setStyleFailureMessage; } @override @@ -519,9 +451,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { /// /// The returned [Future] completes after renderer has been initialized. /// Initialized [AndroidMapRenderer] type is returned. - Future initializeWithRenderer( - AndroidMapRenderer? rendererType, - ) async { + Future initializeWithRenderer(AndroidMapRenderer? rendererType) async { PlatformRendererType? preferredRenderer; switch (rendererType) { case AndroidMapRenderer.latest: @@ -568,21 +498,11 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { widgetConfiguration.initialCameraPosition, ), mapConfiguration: mapConfiguration, - initialMarkers: mapObjects.markers - .map(_platformMarkerFromMarker) - .toList(), - initialPolygons: mapObjects.polygons - .map(_platformPolygonFromPolygon) - .toList(), - initialPolylines: mapObjects.polylines - .map(_platformPolylineFromPolyline) - .toList(), - initialCircles: mapObjects.circles - .map(_platformCircleFromCircle) - .toList(), - initialHeatmaps: mapObjects.heatmaps - .map(_platformHeatmapFromHeatmap) - .toList(), + initialMarkers: mapObjects.markers.map(_platformMarkerFromMarker).toList(), + initialPolygons: mapObjects.polygons.map(_platformPolygonFromPolygon).toList(), + initialPolylines: mapObjects.polylines.map(_platformPolylineFromPolyline).toList(), + initialCircles: mapObjects.circles.map(_platformCircleFromCircle).toList(), + initialHeatmaps: mapObjects.heatmaps.map(_platformHeatmapFromHeatmap).toList(), initialTileOverlays: mapObjects.tileOverlays .map(_platformTileOverlayFromTileOverlay) .toList(), @@ -598,27 +518,23 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { if (useAndroidViewSurface) { return PlatformViewLink( viewType: viewType, - surfaceFactory: - (BuildContext context, PlatformViewController controller) { - return AndroidViewSurface( - controller: controller as AndroidViewController, - gestureRecognizers: widgetConfiguration.gestureRecognizers, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - ); - }, + surfaceFactory: (BuildContext context, PlatformViewController controller) { + return AndroidViewSurface( + controller: controller as AndroidViewController, + gestureRecognizers: widgetConfiguration.gestureRecognizers, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + ); + }, onCreatePlatformView: (PlatformViewCreationParams params) { - final AndroidViewController controller = - PlatformViewsService.initExpensiveAndroidView( - id: params.id, - viewType: viewType, - layoutDirection: widgetConfiguration.textDirection, - creationParams: creationParams, - creationParamsCodec: MapsApi.pigeonChannelCodec, - onFocus: () => params.onFocusChanged(true), - ); - controller.addOnPlatformViewCreatedListener( - params.onPlatformViewCreated, + final AndroidViewController controller = PlatformViewsService.initExpensiveAndroidView( + id: params.id, + viewType: viewType, + layoutDirection: widgetConfiguration.textDirection, + creationParams: creationParams, + creationParamsCodec: MapsApi.pigeonChannelCodec, + onFocus: () => params.onFocusChanged(true), ); + controller.addOnPlatformViewCreatedListener(params.onPlatformViewCreated); controller.addOnPlatformViewCreatedListener(onPlatformViewCreated); controller.create(); @@ -650,9 +566,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { onPlatformViewCreated, widgetConfiguration: widgetConfiguration, mapObjects: mapObjects, - mapConfiguration: _platformMapConfigurationFromMapConfiguration( - mapConfiguration, - ), + mapConfiguration: _platformMapConfigurationFromMapConfiguration(mapConfiguration), ); } @@ -742,10 +656,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } static PlatformLatLng _platformLatLngFromLatLng(LatLng latLng) { - return PlatformLatLng( - latitude: latLng.latitude, - longitude: latLng.longitude, - ); + return PlatformLatLng(latitude: latLng.latitude, longitude: latLng.longitude); } static PlatformDoublePair _platformPairFromOffset(Offset offset) { @@ -756,15 +667,11 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { return PlatformDoublePair(x: size.width, y: size.height); } - static ScreenCoordinate _screenCoordinateFromPlatformPoint( - PlatformPoint point, - ) { + static ScreenCoordinate _screenCoordinateFromPlatformPoint(PlatformPoint point) { return ScreenCoordinate(x: point.x, y: point.y); } - static PlatformPoint _platformPointFromScreenCoordinate( - ScreenCoordinate coordinate, - ) { + static PlatformPoint _platformPointFromScreenCoordinate(ScreenCoordinate coordinate) { return PlatformPoint(x: coordinate.x, y: coordinate.y); } @@ -786,9 +693,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { final HeatmapGradient? gradient = heatmap.gradient; return PlatformHeatmap( heatmapId: heatmap.heatmapId.value, - data: heatmap.data - .map(_platformWeightedLatLngFromWeightedLatLng) - .toList(), + data: heatmap.data.map(_platformWeightedLatLngFromWeightedLatLng).toList(), gradient: _platformHeatmapGradientFromHeatmapGradient(gradient), opacity: heatmap.opacity, radius: heatmap.radius.radius, @@ -804,14 +709,9 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } return PlatformHeatmapGradient( colors: gradient.colors - .map( - (HeatmapGradientColor c) => - PlatformColor(argbValue: c.color.toARGB32()), - ) - .toList(), - startPoints: gradient.colors - .map((HeatmapGradientColor c) => c.startPoint) + .map((HeatmapGradientColor c) => PlatformColor(argbValue: c.color.toARGB32())) .toList(), + startPoints: gradient.colors.map((HeatmapGradientColor c) => c.startPoint).toList(), colorMapSize: gradient.colorMapSize, ); } @@ -819,14 +719,10 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { static PlatformClusterManager _platformClusterManagerFromClusterManager( ClusterManager clusterManager, ) { - return PlatformClusterManager( - identifier: clusterManager.clusterManagerId.value, - ); + return PlatformClusterManager(identifier: clusterManager.clusterManagerId.value); } - static PlatformInfoWindow _platformInfoWindowFromInfoWindow( - InfoWindow window, - ) { + static PlatformInfoWindow _platformInfoWindowFromInfoWindow(InfoWindow window) { return PlatformInfoWindow( title: window.title, snippet: window.snippet, @@ -861,9 +757,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { ) { return PlatformGroundOverlay( groundOverlayId: groundOverlay.groundOverlayId.value, - anchor: groundOverlay.anchor != null - ? _platformPairFromOffset(groundOverlay.anchor!) - : null, + anchor: groundOverlay.anchor != null ? _platformPairFromOffset(groundOverlay.anchor!) : null, image: platformBitmapFromBitmapDescriptor(groundOverlay.image), position: groundOverlay.position != null ? _platformLatLngFromLatLng(groundOverlay.position!) @@ -880,12 +774,8 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } static PlatformPolygon _platformPolygonFromPolygon(Polygon polygon) { - final List points = polygon.points - .map(_platformLatLngFromLatLng) - .toList(); - final List> holes = polygon.holes.map(( - List hole, - ) { + final List points = polygon.points.map(_platformLatLngFromLatLng).toList(); + final List> holes = polygon.holes.map((List hole) { return hole.map(_platformLatLngFromLatLng).toList(); }).toList(); return PlatformPolygon( @@ -903,9 +793,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { } static PlatformPolyline _platformPolylineFromPolyline(Polyline polyline) { - final List points = polyline.points - .map(_platformLatLngFromLatLng) - .toList(); + final List points = polyline.points.map(_platformLatLngFromLatLng).toList(); final List pattern = polyline.patterns .map(platformPatternItemFromPatternItem) .toList(); @@ -925,9 +813,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { ); } - static PlatformTileOverlay _platformTileOverlayFromTileOverlay( - TileOverlay tileOverlay, - ) { + static PlatformTileOverlay _platformTileOverlayFromTileOverlay(TileOverlay tileOverlay) { return PlatformTileOverlay( tileOverlayId: tileOverlay.tileOverlayId.value, fadeIn: tileOverlay.fadeIn, @@ -938,17 +824,13 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { ); } - static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate( - CameraUpdate update, - ) { + static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate(CameraUpdate update) { switch (update.updateType) { case CameraUpdateType.newCameraPosition: update as CameraUpdateNewCameraPosition; return PlatformCameraUpdate( cameraUpdate: PlatformCameraUpdateNewCameraPosition( - cameraPosition: _platformCameraPositionFromCameraPosition( - update.cameraPosition, - ), + cameraPosition: _platformCameraPositionFromCameraPosition(update.cameraPosition), ), ); case CameraUpdateType.newLatLng: @@ -976,45 +858,32 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomTo: update as CameraUpdateZoomTo; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom)); case CameraUpdateType.zoomBy: update as CameraUpdateZoomBy; return PlatformCameraUpdate( cameraUpdate: PlatformCameraUpdateZoomBy( amount: update.amount, - focus: update.focus == null - ? null - : _platformPairFromOffset(update.focus!), + focus: update.focus == null ? null : _platformPairFromOffset(update.focus!), ), ); case CameraUpdateType.zoomIn: update as CameraUpdateZoomIn; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: false), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: false)); case CameraUpdateType.zoomOut: update as CameraUpdateZoomOut; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: true), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: true)); case CameraUpdateType.scrollBy: update as CameraUpdateScrollBy; return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateScrollBy( - dx: update.dx, - dy: update.dy, - ), + cameraUpdate: PlatformCameraUpdateScrollBy(dx: update.dx, dy: update.dy), ); } } /// Convert [MapBitmapScaling] from platform interface to [PlatformMapBitmapScaling] Pigeon. @visibleForTesting - static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling( - MapBitmapScaling scaling, - ) { + static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling(MapBitmapScaling scaling) { switch (scaling) { case MapBitmapScaling.auto: return PlatformMapBitmapScaling.auto; @@ -1033,23 +902,17 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { /// Convert [BitmapDescriptor] from platform interface to [PlatformBitmap] pigeon. @visibleForTesting - static PlatformBitmap platformBitmapFromBitmapDescriptor( - BitmapDescriptor bitmap, - ) { + static PlatformBitmap platformBitmapFromBitmapDescriptor(BitmapDescriptor bitmap) { switch (bitmap) { case final DefaultMarker marker: - return PlatformBitmap( - bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble()), - ); + return PlatformBitmap(bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble())); // Clients may still use this deprecated format, so it must be supported. // ignore: deprecated_member_use case final BytesBitmap bytes: return PlatformBitmap( bitmap: PlatformBitmapBytes( byteData: bytes.byteData, - size: (bytes.size == null) - ? null - : _platformPairFromSize(bytes.size!), + size: (bytes.size == null) ? null : _platformPairFromSize(bytes.size!), ), ); case final AssetBitmap asset: @@ -1063,18 +926,14 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { bitmap: PlatformBitmapAssetImage( name: asset.name, scale: asset.scale, - size: (asset.size == null) - ? null - : _platformPairFromSize(asset.size!), + size: (asset.size == null) ? null : _platformPairFromSize(asset.size!), ), ); case final AssetMapBitmap asset: return PlatformBitmap( bitmap: PlatformBitmapAssetMap( assetName: asset.assetName, - bitmapScaling: platformMapBitmapScalingFromScaling( - asset.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(asset.bitmapScaling), imagePixelRatio: asset.imagePixelRatio, width: asset.width, height: asset.height, @@ -1084,9 +943,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapBytesMap( byteData: bytes.byteData, - bitmapScaling: platformMapBitmapScalingFromScaling( - bytes.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(bytes.bitmapScaling), imagePixelRatio: bytes.imagePixelRatio, width: bytes.width, height: bytes.height, @@ -1115,9 +972,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapPinConfig( backgroundColor: pinConfig.backgroundColor != null - ? PlatformColor( - argbValue: pinConfig.backgroundColor!.toARGB32(), - ) + ? PlatformColor(argbValue: pinConfig.backgroundColor!.toARGB32()) : null, borderColor: pinConfig.borderColor != null ? PlatformColor(argbValue: pinConfig.borderColor!.toARGB32()) @@ -1131,10 +986,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { ), ); default: - throw ArgumentError( - 'Unrecognized type of bitmap ${bitmap.runtimeType}', - 'bitmap', - ); + throw ArgumentError('Unrecognized type of bitmap ${bitmap.runtimeType}', 'bitmap'); } } @@ -1152,9 +1004,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { cap as CustomCap; return PlatformCap( type: PlatformCapType.customCap, - bitmapDescriptor: platformBitmapFromBitmapDescriptor( - cap.bitmapDescriptor, - ), + bitmapDescriptor: platformBitmapFromBitmapDescriptor(cap.bitmapDescriptor), refWidth: cap.refWidth, ); } @@ -1166,11 +1016,7 @@ class GoogleMapsFlutterAndroid extends GoogleMapsFlutterPlatform { class HostMapMessageHandler implements MapsCallbackApi { /// Creates a new handler that listens for events from map [mapId], and /// broadcasts them to [streamController]. - HostMapMessageHandler( - this.mapId, - this.streamController, { - required this.tileOverlayProvider, - }) { + HostMapMessageHandler(this.mapId, this.streamController, {required this.tileOverlayProvider}) { MapsCallbackApi.setUp(this, messageChannelSuffix: mapId.toString()); } @@ -1195,9 +1041,7 @@ class HostMapMessageHandler implements MapsCallbackApi { PlatformPoint location, int zoom, ) async { - final TileOverlay? tileOverlay = tileOverlayProvider( - TileOverlayId(tileOverlayId), - ); + final TileOverlay? tileOverlay = tileOverlayProvider(TileOverlayId(tileOverlayId)); final TileProvider? tileProvider = tileOverlay?.tileProvider; final Tile tile = tileProvider == null ? TileProvider.noTile @@ -1258,41 +1102,27 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onLongPress(PlatformLatLng position) { - streamController.add( - MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position))); } @override void onMarkerDrag(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragStart(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragStartEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragStartEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragEnd(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEndEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEndEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @@ -1313,16 +1143,12 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onGroundOverlayTap(String groundOverlayId) { - streamController.add( - GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId)), - ); + streamController.add(GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId))); } @override void onTap(PlatformLatLng position) { - streamController.add( - MapTapEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapTapEvent(mapId, _latLngFromPlatformLatLng(position))); } } @@ -1330,9 +1156,7 @@ LatLng _latLngFromPlatformLatLng(PlatformLatLng latLng) { return LatLng(latLng.latitude, latLng.longitude); } -LatLngBounds _latLngBoundsFromPlatformLatLngBounds( - PlatformLatLngBounds bounds, -) { +LatLngBounds _latLngBoundsFromPlatformLatLngBounds(PlatformLatLngBounds bounds) { return LatLngBounds( southwest: _latLngFromPlatformLatLng(bounds.southwest), northeast: _latLngFromPlatformLatLng(bounds.northeast), @@ -1347,9 +1171,7 @@ PlatformLatLng _platformLatLngFromLatLng(LatLng latLng) { return PlatformLatLng(latitude: latLng.latitude, longitude: latLng.longitude); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( - LatLngBounds? bounds, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds(LatLngBounds? bounds) { if (bounds == null) { return null; } @@ -1359,9 +1181,7 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( ); } -PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng( - WeightedLatLng weightedLatLng, -) { +PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng(WeightedLatLng weightedLatLng) { return PlatformWeightedLatLng( point: _platformLatLngFromLatLng(weightedLatLng.point), weight: weightedLatLng.weight, @@ -1373,9 +1193,7 @@ PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBounds( ) { return bounds == null ? null - : PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds), - ); + : PlatformCameraTargetBounds(bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds)); } PlatformMapType? _platformMapTypeFromMapType(MapType? type) { @@ -1402,12 +1220,8 @@ PlatformMapType? _platformMapTypeFromMapType(MapType? type) { return PlatformMapType.normal; } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference( - MinMaxZoomPreference? zoomPref, -) { - return zoomPref == null - ? null - : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference(MinMaxZoomPreference? zoomPref) { + return zoomPref == null ? null : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); } PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { @@ -1428,18 +1242,14 @@ PlatformMarkerType _platformMarkerTypeFromMarkerType(MarkerType markerType) { }; } -PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( - MapConfiguration config, -) { +PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration(MapConfiguration config) { return PlatformMapConfiguration( compassEnabled: config.compassEnabled, cameraTargetBounds: _platformCameraTargetBoundsFromCameraTargetBounds( config.cameraTargetBounds, ), mapType: _platformMapTypeFromMapType(config.mapType), - minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference( - config.minMaxZoomPreference, - ), + minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference(config.minMaxZoomPreference), mapToolbarEnabled: config.mapToolbarEnabled, rotateGesturesEnabled: config.rotateGesturesEnabled, scrollGesturesEnabled: config.scrollGesturesEnabled, @@ -1454,23 +1264,18 @@ PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( trafficEnabled: config.trafficEnabled, buildingsEnabled: config.buildingsEnabled, liteModeEnabled: config.liteModeEnabled, - markerType: _platformMarkerTypeFromMarkerType( - config.markerType ?? MarkerType.marker, - ), + markerType: _platformMarkerTypeFromMarkerType(config.markerType ?? MarkerType.marker), mapId: config.mapId, style: config.style, ); } // For supporting the deprecated updateMapOptions API. -PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( - Map options, -) { +PlatformMapConfiguration _platformMapConfigurationFromOptionsJson(Map options) { // All of these hard-coded values and structures come from // google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart // to support this legacy API that relied on cross-package magic strings. - final List? padding = (options['padding'] as List?) - ?.cast(); + final List? padding = (options['padding'] as List?)?.cast(); final mapType = options['mapType'] as int?; return PlatformMapConfiguration( compassEnabled: options['compassEnabled'] as bool?, @@ -1508,9 +1313,7 @@ PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( ); } -PlatformCameraPosition _platformCameraPositionFromCameraPosition( - CameraPosition position, -) { +PlatformCameraPosition _platformCameraPositionFromCameraPosition(CameraPosition position) { return PlatformCameraPosition( bearing: position.bearing, target: _platformLatLngFromLatLng(position.target), @@ -1538,9 +1341,7 @@ PlatformLatLng _platformLatLngFromLatLngJson(Object latLngJson) { return PlatformLatLng(latitude: list[0], longitude: list[1]); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( - Object? boundsJson, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson(Object? boundsJson) { if (boundsJson == null) { return null; } @@ -1552,28 +1353,24 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( ); } -PlatformCameraTargetBounds? -_platformCameraTargetBoundsFromCameraTargetBoundsJson(Object? targetJson) { +PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBoundsJson( + Object? targetJson, +) { if (targetJson == null) { return null; } // See `CameraTargetBounds.toJson`. return PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBoundsJson( - (targetJson as List)[0], - ), + bounds: _platformLatLngBoundsFromLatLngBoundsJson((targetJson as List)[0]), ); } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson( - Object? zoomPrefsJson, -) { +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson(Object? zoomPrefsJson) { if (zoomPrefsJson == null) { return null; } // See `MinMaxZoomPreference.toJson`. - final List minMaxZoom = (zoomPrefsJson as List) - .cast(); + final List minMaxZoom = (zoomPrefsJson as List).cast(); return PlatformZoomRange(min: minMaxZoom[0], max: minMaxZoom[1]); } @@ -1606,16 +1403,10 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { return PlatformPatternItem(type: PlatformPatternItemType.dot); case PatternItemType.dash: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.dash, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.dash, length: length); case PatternItemType.gap: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.gap, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.gap, length: length); } // The enum comes from a different package, which could get a new value at @@ -1630,9 +1421,7 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { /// Converts a Marker's collision behavior to Pigeon's /// PlatformMarkerCollisionBehavior. @visibleForTesting -PlatformMarkerCollisionBehavior platformMarkerCollisionBehaviorFromMarker( - Marker marker, -) { +PlatformMarkerCollisionBehavior platformMarkerCollisionBehaviorFromMarker(Marker marker) { if (marker is! AdvancedMarker) { return PlatformMarkerCollisionBehavior.requiredDisplay; } @@ -1652,15 +1441,13 @@ PlatformMarkerCollisionBehavior platformMarkerCollisionBehaviorFromMarker( // interface, and remove this copy. class _TileOverlayUpdates extends MapsObjectUpdates { /// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s. - _TileOverlayUpdates.from(super.previous, super.current) - : super.from(objectName: 'tileOverlay'); + _TileOverlayUpdates.from(super.previous, super.current) : super.from(objectName: 'tileOverlay'); /// Set of TileOverlays to be added in this update. Set get tileOverlaysToAdd => objectsToAdd; /// Set of TileOverlayIds to be removed in this update. - Set get tileOverlayIdsToRemove => - objectIdsToRemove.cast(); + Set get tileOverlayIdsToRemove => objectIdsToRemove.cast(); /// Set of TileOverlays to be changed in this update. Set get tileOverlaysToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_android/lib/src/messages.g.dart b/packages/google_maps_flutter/google_maps_flutter_android/lib/src/messages.g.dart index 0a6d16953c98..857e1aeb7337 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/lib/src/messages.g.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/lib/src/messages.g.dart @@ -37,11 +37,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -63,9 +59,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -262,8 +256,7 @@ class PlatformCameraUpdateNewCameraPosition { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewCameraPosition || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewCameraPosition || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -299,8 +292,7 @@ class PlatformCameraUpdateNewLatLng { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLng || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLng || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -316,10 +308,7 @@ class PlatformCameraUpdateNewLatLng { /// Pigeon equivalent of NewLatLngBounds class PlatformCameraUpdateNewLatLngBounds { - PlatformCameraUpdateNewLatLngBounds({ - required this.bounds, - required this.padding, - }); + PlatformCameraUpdateNewLatLngBounds({required this.bounds, required this.padding}); PlatformLatLngBounds bounds; @@ -344,15 +333,13 @@ class PlatformCameraUpdateNewLatLngBounds { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { return true; } - return _deepEquals(bounds, other.bounds) && - _deepEquals(padding, other.padding); + return _deepEquals(bounds, other.bounds) && _deepEquals(padding, other.padding); } @override @@ -387,8 +374,7 @@ class PlatformCameraUpdateNewLatLngZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -420,17 +406,13 @@ class PlatformCameraUpdateScrollBy { static PlatformCameraUpdateScrollBy decode(Object result) { result as List; - return PlatformCameraUpdateScrollBy( - dx: result[0]! as double, - dy: result[1]! as double, - ); + return PlatformCameraUpdateScrollBy(dx: result[0]! as double, dy: result[1]! as double); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateScrollBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateScrollBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -471,8 +453,7 @@ class PlatformCameraUpdateZoomBy { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -508,8 +489,7 @@ class PlatformCameraUpdateZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -545,8 +525,7 @@ class PlatformCameraUpdateZoomTo { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomTo || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomTo || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1454,14 +1433,7 @@ class PlatformTileOverlay { int tileSize; List _toList() { - return [ - tileOverlayId, - fadeIn, - transparency, - zIndex, - visible, - tileSize, - ]; + return [tileOverlayId, fadeIn, transparency, zIndex, visible, tileSize]; } Object encode() { @@ -1575,10 +1547,7 @@ class PlatformLatLng { static PlatformLatLng decode(Object result) { result as List; - return PlatformLatLng( - latitude: result[0]! as double, - longitude: result[1]! as double, - ); + return PlatformLatLng(latitude: result[0]! as double, longitude: result[1]! as double); } @override @@ -1590,8 +1559,7 @@ class PlatformLatLng { if (identical(this, other)) { return true; } - return _deepEquals(latitude, other.latitude) && - _deepEquals(longitude, other.longitude); + return _deepEquals(latitude, other.latitude) && _deepEquals(longitude, other.longitude); } @override @@ -1632,8 +1600,7 @@ class PlatformLatLngBounds { if (identical(this, other)) { return true; } - return _deepEquals(northeast, other.northeast) && - _deepEquals(southwest, other.southwest); + return _deepEquals(northeast, other.northeast) && _deepEquals(southwest, other.southwest); } @override @@ -1823,16 +1790,13 @@ class PlatformCameraTargetBounds { static PlatformCameraTargetBounds decode(Object result) { result as List; - return PlatformCameraTargetBounds( - bounds: result[0] as PlatformLatLngBounds?, - ); + return PlatformCameraTargetBounds(bounds: result[0] as PlatformLatLngBounds?); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraTargetBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraTargetBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1910,20 +1874,16 @@ class PlatformMapViewCreationParams { initialPolygons: (result[4]! as List).cast(), initialPolylines: (result[5]! as List).cast(), initialHeatmaps: (result[6]! as List).cast(), - initialTileOverlays: (result[7]! as List) - .cast(), - initialClusterManagers: (result[8]! as List) - .cast(), - initialGroundOverlays: (result[9]! as List) - .cast(), + initialTileOverlays: (result[7]! as List).cast(), + initialClusterManagers: (result[8]! as List).cast(), + initialGroundOverlays: (result[9]! as List).cast(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapViewCreationParams || - other.runtimeType != runtimeType) { + if (other is! PlatformMapViewCreationParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2074,8 +2034,7 @@ class PlatformMapConfiguration { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapConfiguration || - other.runtimeType != runtimeType) { + if (other is! PlatformMapConfiguration || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2220,10 +2179,7 @@ class PlatformZoomRange { static PlatformZoomRange decode(Object result) { result as List; - return PlatformZoomRange( - min: result[0] as double?, - max: result[1] as double?, - ); + return PlatformZoomRange(min: result[0] as double?, max: result[1] as double?); } @override @@ -2311,8 +2267,7 @@ class PlatformBitmapDefaultMarker { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapDefaultMarker || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapDefaultMarker || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2360,8 +2315,7 @@ class PlatformBitmapBytes { if (identical(this, other)) { return true; } - return _deepEquals(byteData, other.byteData) && - _deepEquals(size, other.size); + return _deepEquals(byteData, other.byteData) && _deepEquals(size, other.size); } @override @@ -2388,10 +2342,7 @@ class PlatformBitmapAsset { static PlatformBitmapAsset decode(Object result) { result as List; - return PlatformBitmapAsset( - name: result[0]! as String, - pkg: result[1] as String?, - ); + return PlatformBitmapAsset(name: result[0]! as String, pkg: result[1] as String?); } @override @@ -2414,11 +2365,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. See /// https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/model/BitmapDescriptorFactory#public-static-bitmapdescriptor-fromasset-string-assetname class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); String name; @@ -2446,8 +2393,7 @@ class PlatformBitmapAssetImage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapAssetImage || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapAssetImage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2836,9 +2782,7 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PlatformRendererType.values[value]; case 131: final value = readValue(buffer) as int?; - return value == null - ? null - : PlatformMarkerCollisionBehavior.values[value]; + return value == null ? null : PlatformMarkerCollisionBehavior.values[value]; case 132: final value = readValue(buffer) as int?; return value == null ? null : PlatformJointType.values[value]; @@ -2978,20 +2922,14 @@ class MapsApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the map's configuration options. /// /// Only non-null configuration values will result in updates; options with /// null values will remain unchanged. - Future updateMapConfiguration( - PlatformMapConfiguration configuration, - ) async { + Future updateMapConfiguration(PlatformMapConfiguration configuration) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_android.MapsApi.updateMapConfiguration$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2999,16 +2937,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [configuration], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([configuration]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of circles on the map. @@ -3024,16 +2956,14 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of heatmaps on the map. @@ -3049,16 +2979,14 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of custer managers for clusters on the map. @@ -3073,16 +3001,13 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of markers on the map. @@ -3098,16 +3023,14 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of polygonss on the map. @@ -3123,16 +3046,14 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of polylines on the map. @@ -3148,16 +3069,14 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of tile overlays on the map. @@ -3173,16 +3092,14 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Updates the set of ground overlays on the map. @@ -3198,16 +3115,14 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Gets the screen coordinate for the given map location. @@ -3219,9 +3134,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [latLng], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([latLng]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3241,9 +3154,9 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [screenCoordinate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + screenCoordinate, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3284,24 +3197,15 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraUpdate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. - Future animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ) async { + Future animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_android.MapsApi.animateCamera$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3309,16 +3213,13 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate, durationMilliseconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraUpdate, + durationMilliseconds, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Gets the current map zoom level. @@ -3350,16 +3251,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Hide the info window for the marker with the given ID. @@ -3371,16 +3266,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Returns true if the marker with the given ID is currently displaying its @@ -3393,9 +3282,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3419,9 +3306,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [style], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([style]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3488,16 +3373,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Takes a snapshot of the map and returns its image data. @@ -3570,20 +3449,14 @@ abstract class MapsCallbackApi { void onGroundOverlayTap(String groundOverlayId); /// Called to get data for a map tile. - Future getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + Future getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); static void setUp( MapsCallbackApi? api, { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.google_maps_flutter_android.MapsCallbackApi.onCameraMoveStarted$messageChannelSuffix', @@ -3618,8 +3491,7 @@ abstract class MapsCallbackApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final PlatformCameraPosition arg_cameraPosition = - args[0]! as PlatformCameraPosition; + final PlatformCameraPosition arg_cameraPosition = args[0]! as PlatformCameraPosition; try { api.onCameraMove(arg_cameraPosition); return wrapResponse(empty: true); @@ -3998,13 +3870,11 @@ class MapsInitializerApi { /// Constructor for [MapsInitializerApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsInitializerApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsInitializerApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4017,9 +3887,7 @@ class MapsInitializerApi { /// /// Calling this more than once in the lifetime of an application will result /// in an error. - Future initializeWithPreferredRenderer( - PlatformRendererType? type, - ) async { + Future initializeWithPreferredRenderer(PlatformRendererType? type) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_android.MapsInitializerApi.initializeWithPreferredRenderer$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4027,9 +3895,7 @@ class MapsInitializerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [type], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([type]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4053,11 +3919,7 @@ class MapsInitializerApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } } @@ -4068,13 +3930,11 @@ class MapsPlatformViewApi { /// Constructor for [MapsPlatformViewApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsPlatformViewApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsPlatformViewApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4089,16 +3949,10 @@ class MapsPlatformViewApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [type], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([type]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } } @@ -4107,13 +3961,11 @@ class MapsInspectorApi { /// Constructor for [MapsInspectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsInspectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsInspectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4337,9 +4189,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4350,9 +4200,7 @@ class MapsInspectorApi { return pigeonVar_replyValue as PlatformTileLayer?; } - Future getGroundOverlayInfo( - String groundOverlayId, - ) async { + Future getGroundOverlayInfo(String groundOverlayId) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_android.MapsInspectorApi.getGroundOverlayInfo$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4360,9 +4208,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [groundOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([groundOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4400,9 +4246,9 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [clusterManagerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + clusterManagerId, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( diff --git a/packages/google_maps_flutter/google_maps_flutter_android/pigeons/messages.dart b/packages/google_maps_flutter/google_maps_flutter_android/pigeons/messages.dart index 32d2ba809b6b..2b14821fb396 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/pigeons/messages.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/pigeons/messages.dart @@ -8,8 +8,7 @@ import 'package:pigeon/pigeon.dart'; PigeonOptions( dartOut: 'lib/src/messages.g.dart', kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.googlemaps'), - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/googlemaps/Messages.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/googlemaps/Messages.kt', copyrightHeader: 'pigeons/copyright.txt', ), ) @@ -609,11 +608,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. See /// https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/model/BitmapDescriptorFactory#public-static-bitmapdescriptor-fromasset-string-assetname class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); final String name; final double scale; final PlatformDoublePair? size; @@ -706,10 +701,7 @@ abstract class MapsApi { ); /// Updates the set of custer managers for clusters on the map. - void updateClusterManagers( - List toAdd, - List idsToRemove, - ); + void updateClusterManagers(List toAdd, List idsToRemove); /// Updates the set of markers on the map. void updateMarkers( @@ -761,10 +753,7 @@ abstract class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. - void animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ); + void animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds); /// Gets the current map zoom level. double getZoomLevel(); @@ -856,11 +845,7 @@ abstract class MapsCallbackApi { /// Called to get data for a map tile. @async - PlatformTile getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + PlatformTile getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); } /// Interface for global SDK initialization. @@ -873,9 +858,7 @@ abstract class MapsInitializerApi { /// Calling this more than once in the lifetime of an application will result /// in an error. @async - PlatformRendererType initializeWithPreferredRenderer( - PlatformRendererType? type, - ); + PlatformRendererType initializeWithPreferredRenderer(PlatformRendererType? type); /// Attempts to trigger any thread-blocking work /// the Google Maps SDK normally does when a map is shown for the first time. diff --git a/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.dart b/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.dart index 78da24961a1d..e9f933f0d73a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.dart @@ -15,10 +15,7 @@ import 'package:mockito/mockito.dart'; import 'google_maps_flutter_android_test.mocks.dart'; -@GenerateNiceMocks(>[ - MockSpec(), - MockSpec(), -]) +@GenerateNiceMocks(>[MockSpec(), MockSpec()]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -37,10 +34,7 @@ void main() { test('normal usage does not call MapsInitializerApi', () async { final api = MockMapsApi(); final initializerApi = MockMapsInitializerApi(); - final maps = GoogleMapsFlutterAndroid( - apiProvider: (_) => api, - initializerApi: initializerApi, - ); + final maps = GoogleMapsFlutterAndroid(apiProvider: (_) => api, initializerApi: initializerApi); const mapId = 1; maps.ensureApiInitialized(mapId); await maps.init(1); @@ -48,32 +42,19 @@ void main() { verifyZeroInteractions(initializerApi); }); - test( - 'initializeWithPreferredRenderer forwards the initialization call', - () async { - final api = MockMapsApi(); - final initializerApi = MockMapsInitializerApi(); - final maps = GoogleMapsFlutterAndroid( - apiProvider: (_) => api, - initializerApi: initializerApi, - ); - await maps.initializeWithRenderer(AndroidMapRenderer.latest); + test('initializeWithPreferredRenderer forwards the initialization call', () async { + final api = MockMapsApi(); + final initializerApi = MockMapsInitializerApi(); + final maps = GoogleMapsFlutterAndroid(apiProvider: (_) => api, initializerApi: initializerApi); + await maps.initializeWithRenderer(AndroidMapRenderer.latest); - verify( - initializerApi.initializeWithPreferredRenderer( - PlatformRendererType.latest, - ), - ); - }, - ); + verify(initializerApi.initializeWithPreferredRenderer(PlatformRendererType.latest)); + }); test('warmup forwards the initialization call', () async { final api = MockMapsApi(); final initializerApi = MockMapsInitializerApi(); - final maps = GoogleMapsFlutterAndroid( - apiProvider: (_) => api, - initializerApi: initializerApi, - ); + final maps = GoogleMapsFlutterAndroid(apiProvider: (_) => api, initializerApi: initializerApi); await maps.warmup(); verify(initializerApi.warmup()); @@ -90,25 +71,18 @@ void main() { test('getScreenCoordinate converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const latLng = LatLng(10, 20); const expectedCoord = ScreenCoordinate(x: 30, y: 40); - when(api.getScreenCoordinate(any)).thenAnswer( - (_) async => PlatformPoint(x: expectedCoord.x, y: expectedCoord.y), - ); + when( + api.getScreenCoordinate(any), + ).thenAnswer((_) async => PlatformPoint(x: expectedCoord.x, y: expectedCoord.y)); - final ScreenCoordinate coord = await maps.getScreenCoordinate( - latLng, - mapId: mapId, - ); + final ScreenCoordinate coord = await maps.getScreenCoordinate(latLng, mapId: mapId); expect(coord, expectedCoord); - final VerificationResult verification = verify( - api.getScreenCoordinate(captureAny), - ); + final VerificationResult verification = verify(api.getScreenCoordinate(captureAny)); final passedLatLng = verification.captured[0] as PlatformLatLng; expect(passedLatLng.latitude, latLng.latitude); expect(passedLatLng.longitude, latLng.longitude); @@ -116,18 +90,14 @@ void main() { test('getLatLng converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const expectedLatLng = LatLng(10, 20); const coord = ScreenCoordinate(x: 30, y: 40); when(api.getLatLng(any)).thenAnswer( - (_) async => PlatformLatLng( - latitude: expectedLatLng.latitude, - longitude: expectedLatLng.longitude, - ), + (_) async => + PlatformLatLng(latitude: expectedLatLng.latitude, longitude: expectedLatLng.longitude), ); final LatLng latLng = await maps.getLatLng(coord, mapId: mapId); @@ -140,9 +110,7 @@ void main() { test('getVisibleRegion converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. final expectedBounds = LatLngBounds( @@ -168,9 +136,7 @@ void main() { test('moveCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.moveCamera(update, mapId: mapId); @@ -185,16 +151,12 @@ void main() { test('animateCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.animateCamera(update, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -206,24 +168,14 @@ void main() { test('animateCameraWithConfiguration calls through', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); - const configuration = CameraUpdateAnimationConfiguration( - duration: Duration(seconds: 1), - ); + const configuration = CameraUpdateAnimationConfiguration(duration: Duration(seconds: 1)); expect(configuration.duration?.inSeconds, 1); - await maps.animateCameraWithConfiguration( - update, - configuration, - mapId: mapId, - ); + await maps.animateCameraWithConfiguration(update, configuration, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -236,9 +188,7 @@ void main() { test('getZoomLevel passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const expectedZoom = 4.2; when(api.getZoomLevel()).thenAnswer((_) async => expectedZoom); @@ -249,9 +199,7 @@ void main() { test('showInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.showMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -261,9 +209,7 @@ void main() { test('hideInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.hideMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -273,27 +219,17 @@ void main() { test('isInfoWindowShown calls through', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; when(api.isInfoWindowShown(markedId)).thenAnswer((_) async => true); - expect( - await maps.isMarkerInfoWindowShown( - const MarkerId(markedId), - mapId: mapId, - ), - true, - ); + expect(await maps.isMarkerInfoWindowShown(const MarkerId(markedId), mapId: mapId), true); }); test('takeSnapshot calls through', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final fakeSnapshot = Uint8List(10); when(api.takeSnapshot()).thenAnswer((_) async => fakeSnapshot); @@ -303,9 +239,7 @@ void main() { test('clearTileCache calls through', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const tileOverlayId = 'overlay'; await maps.clearTileCache(const TileOverlayId(tileOverlayId), mapId: mapId); @@ -315,29 +249,21 @@ void main() { test('isAdvancedMarkersAvailable calls through', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); when(api.isAdvancedMarkersAvailable()).thenAnswer((_) async => true); await maps.isAdvancedMarkersAvailable(mapId: mapId); - final bool isAdvancedMarkersAvailable = await api - .isAdvancedMarkersAvailable(); + final bool isAdvancedMarkersAvailable = await api.isAdvancedMarkersAvailable(); expect(isAdvancedMarkersAvailable, isTrue); }); test('updateMapConfiguration passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = MapConfiguration( compassEnabled: true, @@ -346,9 +272,7 @@ void main() { ); await maps.updateMapConfiguration(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -377,16 +301,11 @@ void main() { test('updateMapOptions passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = { 'compassEnabled': true, @@ -395,9 +314,7 @@ void main() { }; await maps.updateMapOptions(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -426,19 +343,14 @@ void main() { test('updateCircles passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Circle(circleId: CircleId('1')); const object2old = Circle(circleId: CircleId('2')); final Circle object2new = object2old.copyWith(radiusParam: 42); const object3 = Circle(circleId: CircleId('3')); await maps.updateCircles( - CircleUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + CircleUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -457,10 +369,7 @@ void main() { final PlatformCircle firstChanged = toChange.first; expect(firstChanged.consumeTapEvents, object2new.consumeTapEvents); expect(firstChanged.fillColor.argbValue, object2new.fillColor.toARGB32()); - expect( - firstChanged.strokeColor.argbValue, - object2new.strokeColor.toARGB32(), - ); + expect(firstChanged.strokeColor.argbValue, object2new.strokeColor.toARGB32()); expect(firstChanged.visible, object2new.visible); expect(firstChanged.strokeWidth, object2new.strokeWidth); expect(firstChanged.zIndex, object2new.zIndex.toDouble()); @@ -488,17 +397,12 @@ void main() { test('updateClusterManagers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = ClusterManager(clusterManagerId: ClusterManagerId('1')); const object3 = ClusterManager(clusterManagerId: ClusterManagerId('3')); await maps.updateClusterManagers( - ClusterManagerUpdates.from( - {object1}, - {object3}, - ), + ClusterManagerUpdates.from({object1}, {object3}), mapId: mapId, ); @@ -519,19 +423,14 @@ void main() { test('updateMarkers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Marker(markerId: MarkerId('1')); const object2old = Marker(markerId: MarkerId('2')); final Marker object2new = object2old.copyWith(rotationParam: 42); const object3 = Marker(markerId: MarkerId('3')); await maps.updateMarkers( - MarkerUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + MarkerUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -606,16 +505,13 @@ void main() { test('updateMarkers passes expected arguments (AdvancedMarkers)', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final object1 = AdvancedMarker(markerId: const MarkerId('1')); final object2old = AdvancedMarker(markerId: const MarkerId('2')); final AdvancedMarker object2new = object2old.copyWith( rotationParam: 42, - collisionBehaviorParam: - MarkerCollisionBehavior.optionalAndHidesLowerPriority, + collisionBehaviorParam: MarkerCollisionBehavior.optionalAndHidesLowerPriority, ); final object3 = AdvancedMarker( markerId: const MarkerId('3'), @@ -665,10 +561,7 @@ void main() { expect(firstChanged.zIndex, object2new.zIndexInt); expect(firstChanged.markerId, object2new.markerId.value); expect(firstChanged.clusterManagerId, object2new.clusterManagerId?.value); - expect( - firstChanged.collisionBehavior, - platformMarkerCollisionBehaviorFromMarker(object2new), - ); + expect(firstChanged.collisionBehavior, platformMarkerCollisionBehaviorFromMarker(object2new)); } // Object 3 should be added. { @@ -697,28 +590,20 @@ void main() { expect(firstAdded.zIndex, object3.zIndexInt); expect(firstAdded.markerId, object3.markerId.value); expect(firstAdded.clusterManagerId, object3.clusterManagerId?.value); - expect( - firstAdded.collisionBehavior, - platformMarkerCollisionBehaviorFromMarker(object3), - ); + expect(firstAdded.collisionBehavior, platformMarkerCollisionBehaviorFromMarker(object3)); } }); test('updatePolygons passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polygon(polygonId: PolygonId('1')); const object2old = Polygon(polygonId: PolygonId('2')); final Polygon object2new = object2old.copyWith(strokeWidthParam: 42); const object3 = Polygon(polygonId: PolygonId('3')); await maps.updatePolygons( - PolygonUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolygonUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -765,9 +650,7 @@ void main() { test('updatePolylines passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polyline(polylineId: PolylineId('1')); const object2old = Polyline(polylineId: PolylineId('2')); @@ -776,20 +659,14 @@ void main() { startCapParam: Cap.squareCap, endCapParam: Cap.buttCap, ); - final Cap customCap = Cap.customCapFromBitmap( - BitmapDescriptor.defaultMarker, - refWidth: 15, - ); + final Cap customCap = Cap.customCapFromBitmap(BitmapDescriptor.defaultMarker, refWidth: 15); final object3 = Polyline( polylineId: const PolylineId('3'), startCap: customCap, endCap: Cap.roundCap, ); await maps.updatePolylines( - PolylineUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolylineUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -804,10 +681,7 @@ void main() { expect(actual.consumesTapEvents, expected.consumeTapEvents); expect(actual.color.argbValue, expected.color.toARGB32()); expect(actual.geodesic, expected.geodesic); - expect( - actual.jointType, - platformJointTypeFromJointType(expected.jointType), - ); + expect(actual.jointType, platformJointTypeFromJointType(expected.jointType)); expect(actual.visible, expected.visible); expect(actual.width, expected.width); expect(actual.zIndex, expected.zIndex); @@ -817,17 +691,18 @@ void main() { expect(point?.longitude, actual.points[i].longitude); } expect(actual.patterns.length, expected.patterns.length); - for (final (int i, PlatformPatternItem? pattern) - in actual.patterns.indexed) { + for (final (int i, PlatformPatternItem? pattern) in actual.patterns.indexed) { expect( pattern?.encode(), platformPatternItemFromPatternItem(expected.patterns[i]).encode(), ); } - final PlatformCap expectedStartCap = - GoogleMapsFlutterAndroid.platformCapFromCap(expected.startCap); - final PlatformCap expectedEndCap = - GoogleMapsFlutterAndroid.platformCapFromCap(expected.endCap); + final PlatformCap expectedStartCap = GoogleMapsFlutterAndroid.platformCapFromCap( + expected.startCap, + ); + final PlatformCap expectedEndCap = GoogleMapsFlutterAndroid.platformCapFromCap( + expected.endCap, + ); expect(actual.startCap.type, expectedStartCap.type); expect(actual.startCap.refWidth, expectedStartCap.refWidth); expect( @@ -855,9 +730,7 @@ void main() { test('updateTileOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = TileOverlay(tileOverlayId: TileOverlayId('1')); const object2old = TileOverlay(tileOverlayId: TileOverlayId('2')); @@ -904,9 +777,7 @@ void main() { test('updateGroundOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final image = AssetMapBitmap( 'assets/red_square.png', @@ -916,18 +787,12 @@ void main() { final object1 = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('1'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final object2old = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('2'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final GroundOverlay object2new = object2old.copyWith( @@ -968,22 +833,10 @@ void main() { expect(firstChanged.anchor?.x, object2new.anchor?.dx); expect(firstChanged.anchor?.y, object2new.anchor?.dy); expect(firstChanged.bearing, object2new.bearing); - expect( - firstChanged.bounds?.northeast.latitude, - object2new.bounds?.northeast.latitude, - ); - expect( - firstChanged.bounds?.northeast.longitude, - object2new.bounds?.northeast.longitude, - ); - expect( - firstChanged.bounds?.southwest.latitude, - object2new.bounds?.southwest.latitude, - ); - expect( - firstChanged.bounds?.southwest.longitude, - object2new.bounds?.southwest.longitude, - ); + expect(firstChanged.bounds?.northeast.latitude, object2new.bounds?.northeast.latitude); + expect(firstChanged.bounds?.northeast.longitude, object2new.bounds?.northeast.longitude); + expect(firstChanged.bounds?.southwest.latitude, object2new.bounds?.southwest.latitude); + expect(firstChanged.bounds?.southwest.longitude, object2new.bounds?.southwest.longitude); expect(firstChanged.visible, object2new.visible); expect(firstChanged.clickable, object2new.clickable); expect(firstChanged.zIndex, object2new.zIndex); @@ -1006,22 +859,10 @@ void main() { expect(firstAdded.anchor?.x, object3.anchor?.dx); expect(firstAdded.anchor?.y, object3.anchor?.dy); expect(firstAdded.bearing, object3.bearing); - expect( - firstAdded.bounds?.northeast.latitude, - object3.bounds?.northeast.latitude, - ); - expect( - firstAdded.bounds?.northeast.longitude, - object3.bounds?.northeast.longitude, - ); - expect( - firstAdded.bounds?.southwest.latitude, - object3.bounds?.southwest.latitude, - ); - expect( - firstAdded.bounds?.southwest.longitude, - object3.bounds?.southwest.longitude, - ); + expect(firstAdded.bounds?.northeast.latitude, object3.bounds?.northeast.latitude); + expect(firstAdded.bounds?.northeast.longitude, object3.bounds?.northeast.longitude); + expect(firstAdded.bounds?.southwest.latitude, object3.bounds?.southwest.latitude); + expect(firstAdded.bounds?.southwest.longitude, object3.bounds?.southwest.longitude); expect(firstAdded.visible, object3.visible); expect(firstAdded.clickable, object3.clickable); expect(firstAdded.zIndex, object3.zIndex); @@ -1039,56 +880,47 @@ void main() { } }); - test( - 'updateGroundOverlays throws assertion error on unsupported ground overlays', - () async { - const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + test('updateGroundOverlays throws assertion error on unsupported ground overlays', () async { + const mapId = 1; + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); - final image = AssetMapBitmap( - 'assets/red_square.png', - imagePixelRatio: 1.0, - bitmapScaling: MapBitmapScaling.none, - ); + final image = AssetMapBitmap( + 'assets/red_square.png', + imagePixelRatio: 1.0, + bitmapScaling: MapBitmapScaling.none, + ); - final groundOverlay = GroundOverlay.fromPosition( - groundOverlayId: const GroundOverlayId('1'), - position: const LatLng(10, 20), - // Assert should be thrown because width is not set for position-based - // ground overlay on Android. - // ignore: avoid_redundant_argument_values - width: null, - image: image, - ); + final groundOverlay = GroundOverlay.fromPosition( + groundOverlayId: const GroundOverlayId('1'), + position: const LatLng(10, 20), + // Assert should be thrown because width is not set for position-based + // ground overlay on Android. + // ignore: avoid_redundant_argument_values + width: null, + image: image, + ); - expect( - () async => maps.updateGroundOverlays( - GroundOverlayUpdates.from(const {}, { - groundOverlay, - }), - mapId: mapId, - ), - throwsAssertionError, - ); + expect( + () async => maps.updateGroundOverlays( + GroundOverlayUpdates.from(const {}, {groundOverlay}), + mapId: mapId, + ), + throwsAssertionError, + ); - expect( - () async => maps.buildViewWithConfiguration( - 1, - (int _) {}, - widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition(target: LatLng(0, 0)), - textDirection: TextDirection.ltr, - ), - mapObjects: MapObjects( - groundOverlays: {groundOverlay}, - ), + expect( + () async => maps.buildViewWithConfiguration( + 1, + (int _) {}, + widgetConfiguration: const MapWidgetConfiguration( + initialCameraPosition: CameraPosition(target: LatLng(0, 0)), + textDirection: TextDirection.ltr, ), - throwsAssertionError, - ); - }, - ); + mapObjects: MapObjects(groundOverlays: {groundOverlay}), + ), + throwsAssertionError, + ); + }); test('markers send drag event to correct streams', () async { const mapId = 1; @@ -1098,19 +930,13 @@ void main() { final fakePosition = PlatformLatLng(latitude: 1.0, longitude: 1.0); final maps = GoogleMapsFlutterAndroid(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final markerDragStartStream = StreamQueue( maps.onMarkerDragStart(mapId: mapId), ); - final markerDragStream = StreamQueue( - maps.onMarkerDrag(mapId: mapId), - ); - final markerDragEndStream = StreamQueue( - maps.onMarkerDragEnd(mapId: mapId), - ); + final markerDragStream = StreamQueue(maps.onMarkerDrag(mapId: mapId)); + final markerDragEndStream = StreamQueue(maps.onMarkerDragEnd(mapId: mapId)); // Simulate messages from the native side. callbackHandler.onMarkerDragStart(dragStartId, fakePosition); @@ -1127,9 +953,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterAndroid(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onMarkerTap(mapId: mapId)); @@ -1144,9 +968,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterAndroid(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onCircleTap(mapId: mapId)); @@ -1173,13 +995,9 @@ void main() { ); final maps = GoogleMapsFlutterAndroid(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onClusterTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onClusterTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onClusterTap(cluster); @@ -1189,15 +1007,9 @@ void main() { expect(eventValue.position.latitude, fakePosition.latitude); expect(eventValue.position.longitude, fakePosition.longitude); expect(eventValue.bounds.southwest.latitude, fakeBounds.southwest.latitude); - expect( - eventValue.bounds.southwest.longitude, - fakeBounds.southwest.longitude, - ); + expect(eventValue.bounds.southwest.longitude, fakeBounds.southwest.longitude); expect(eventValue.bounds.northeast.latitude, fakeBounds.northeast.latitude); - expect( - eventValue.bounds.northeast.longitude, - fakeBounds.northeast.longitude, - ); + expect(eventValue.bounds.northeast.longitude, fakeBounds.northeast.longitude); expect(eventValue.markerIds.length, markerIds.length); expect(eventValue.markerIds.first.value, markerIds.first); }); @@ -1207,13 +1019,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterAndroid(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolygonTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolygonTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolygonTap(objectId); @@ -1226,13 +1034,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterAndroid(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolylineTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolylineTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolylineTap(objectId); @@ -1245,13 +1049,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterAndroid(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onGroundOverlayTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onGroundOverlayTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onGroundOverlayTap(objectId); @@ -1276,9 +1076,7 @@ void main() { test('moveCamera calls through with expected newCameraPosition', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); const position = CameraPosition(target: latLng); @@ -1287,24 +1085,15 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; update as CameraUpdateNewCameraPosition; - expect( - typedUpdate.cameraPosition.target.latitude, - update.cameraPosition.target.latitude, - ); - expect( - typedUpdate.cameraPosition.target.longitude, - update.cameraPosition.target.longitude, - ); + expect(typedUpdate.cameraPosition.target.latitude, update.cameraPosition.target.latitude); + expect(typedUpdate.cameraPosition.target.longitude, update.cameraPosition.target.longitude); }); test('moveCamera calls through with expected newLatLng', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLng(latLng); @@ -1312,8 +1101,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; update as CameraUpdateNewLatLng; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1321,9 +1109,7 @@ void main() { test('moveCamera calls through with expected newLatLngBounds', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final latLng = LatLngBounds( northeast: const LatLng(10.0, 20.0), @@ -1334,33 +1120,18 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; update as CameraUpdateNewLatLngBounds; - expect( - typedUpdate.bounds.northeast.latitude, - update.bounds.northeast.latitude, - ); - expect( - typedUpdate.bounds.northeast.longitude, - update.bounds.northeast.longitude, - ); - expect( - typedUpdate.bounds.southwest.latitude, - update.bounds.southwest.latitude, - ); - expect( - typedUpdate.bounds.southwest.longitude, - update.bounds.southwest.longitude, - ); + expect(typedUpdate.bounds.northeast.latitude, update.bounds.northeast.latitude); + expect(typedUpdate.bounds.northeast.longitude, update.bounds.northeast.longitude); + expect(typedUpdate.bounds.southwest.latitude, update.bounds.southwest.latitude); + expect(typedUpdate.bounds.southwest.longitude, update.bounds.southwest.longitude); expect(typedUpdate.padding, update.padding); }); test('moveCamera calls through with expected newLatLngZoom', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLngZoom(latLng, 2.0); @@ -1368,8 +1139,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; update as CameraUpdateNewLatLngZoom; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1378,9 +1148,7 @@ void main() { test('moveCamera calls through with expected zoomBy', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const focus = Offset(10.0, 20.0); final CameraUpdate update = CameraUpdate.zoomBy(2.0, focus); @@ -1397,9 +1165,7 @@ void main() { test('moveCamera calls through with expected zoomTo', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomTo(2.0); await maps.moveCamera(update, mapId: mapId); @@ -1413,9 +1179,7 @@ void main() { test('moveCamera calls through with expected zoomIn', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomIn(); await maps.moveCamera(update, mapId: mapId); @@ -1428,9 +1192,7 @@ void main() { test('moveCamera calls through with expected zoomOut', () async { const mapId = 1; - final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterAndroid maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomOut(); await maps.moveCamera(update, mapId: mapId); @@ -1443,15 +1205,11 @@ void main() { test('MapBitmapScaling to PlatformMapBitmapScaling', () { expect( - GoogleMapsFlutterAndroid.platformMapBitmapScalingFromScaling( - MapBitmapScaling.auto, - ), + GoogleMapsFlutterAndroid.platformMapBitmapScalingFromScaling(MapBitmapScaling.auto), PlatformMapBitmapScaling.auto, ); expect( - GoogleMapsFlutterAndroid.platformMapBitmapScalingFromScaling( - MapBitmapScaling.none, - ), + GoogleMapsFlutterAndroid.platformMapBitmapScalingFromScaling(MapBitmapScaling.none), PlatformMapBitmapScaling.none, ); }); @@ -1486,12 +1244,7 @@ void main() { test('AssetMapBitmap bitmap to PlatformBitmap', () { const assetName = 'fake_asset_name'; - final bitmap = AssetMapBitmap( - assetName, - imagePixelRatio: 2.0, - width: 100.0, - height: 200.0, - ); + final bitmap = AssetMapBitmap(assetName, imagePixelRatio: 2.0, width: 100.0, height: 200.0); final PlatformBitmap platformBitmap = GoogleMapsFlutterAndroid.platformBitmapFromBitmapDescriptor(bitmap); expect(platformBitmap.bitmap, isA()); @@ -1519,16 +1272,12 @@ void main() { const BitmapDescriptor bitmap = BitmapDescriptor.defaultMarker; const customCap = CustomCap(bitmap, refWidth: 15.0); - final PlatformCap platformCap = GoogleMapsFlutterAndroid.platformCapFromCap( - customCap, - ); + final PlatformCap platformCap = GoogleMapsFlutterAndroid.platformCapFromCap(customCap); expect(platformCap.type, PlatformCapType.customCap); expect(customCap.refWidth, 15.0); }); - testWidgets('Use PlatformViewLink when using surface view', ( - WidgetTester tester, - ) async { + testWidgets('Use PlatformViewLink when using surface view', (WidgetTester tester) async { final maps = GoogleMapsFlutterAndroid(); maps.useAndroidViewSurface = true; @@ -1563,31 +1312,28 @@ void main() { const mapId = '000000000000000'; // Dummy map ID. final passedMapIdCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) async { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null) { - final String? passedMapId = - creationParams.mapConfiguration.mapId; - if (passedMapId != null) { - passedMapIdCompleter.complete(passedMapId); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) async { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null) { + final String? passedMapId = creationParams.mapConfiguration.mapId; + if (passedMapId != null) { + passedMapIdCompleter.complete(passedMapId); } } } - return 0; - }); + } + return 0; + }, + ); final maps = GoogleMapsFlutterAndroid(); @@ -1619,18 +1365,14 @@ void main() { initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), - mapConfiguration: const MapConfiguration( - markerType: MarkerType.advancedMarker, - ), + mapConfiguration: const MapConfiguration(markerType: MarkerType.advancedMarker), ); expect(widget, isA()); final dynamic creationParams = (widget as AndroidView).creationParams; expect(creationParams, isA()); expect( - (creationParams as PlatformMapViewCreationParams) - .mapConfiguration - .markerType, + (creationParams as PlatformMapViewCreationParams).mapConfiguration.markerType, PlatformMarkerType.advancedMarker, ); @@ -1667,9 +1409,7 @@ void main() { final dynamic creationParams = (widget as AndroidView).creationParams; expect(creationParams, isA()); expect( - (creationParams as PlatformMapViewCreationParams) - .mapConfiguration - .markerType, + (creationParams as PlatformMapViewCreationParams).mapConfiguration.markerType, PlatformMarkerType.marker, ); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.mocks.dart index e0f050017114..85ab33b67835 100644 --- a/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_android/test/google_maps_flutter_android_test.mocks.dart @@ -29,14 +29,12 @@ class _FakePlatformPoint_0 extends _i1.SmartFake implements _i2.PlatformPoint { : super(parent, parentInvocation); } -class _FakePlatformLatLng_1 extends _i1.SmartFake - implements _i2.PlatformLatLng { +class _FakePlatformLatLng_1 extends _i1.SmartFake implements _i2.PlatformLatLng { _FakePlatformLatLng_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePlatformLatLngBounds_2 extends _i1.SmartFake - implements _i2.PlatformLatLngBounds { +class _FakePlatformLatLngBounds_2 extends _i1.SmartFake implements _i2.PlatformLatLngBounds { _FakePlatformLatLngBounds_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -46,363 +44,262 @@ class _FakePlatformLatLngBounds_2 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockMapsApi extends _i1.Mock implements _i2.MapsApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future waitForMap() => - (super.noSuchMethod( - Invocation.method(#waitForMap, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future waitForMap() => (super.noSuchMethod( + Invocation.method(#waitForMap, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future updateMapConfiguration( - _i2.PlatformMapConfiguration? configuration, - ) => + _i4.Future updateMapConfiguration(_i2.PlatformMapConfiguration? configuration) => (super.noSuchMethod( - Invocation.method(#updateMapConfiguration, [configuration]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#updateMapConfiguration, [configuration]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateCircles( List<_i2.PlatformCircle>? toAdd, List<_i2.PlatformCircle>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateHeatmaps( List<_i2.PlatformHeatmap>? toAdd, List<_i2.PlatformHeatmap>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateClusterManagers( List<_i2.PlatformClusterManager>? toAdd, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateMarkers( List<_i2.PlatformMarker>? toAdd, List<_i2.PlatformMarker>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolygons( List<_i2.PlatformPolygon>? toAdd, List<_i2.PlatformPolygon>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolylines( List<_i2.PlatformPolyline>? toAdd, List<_i2.PlatformPolyline>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateTileOverlays( List<_i2.PlatformTileOverlay>? toAdd, List<_i2.PlatformTileOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateTileOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateTileOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateGroundOverlays( List<_i2.PlatformGroundOverlay>? toAdd, List<_i2.PlatformGroundOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateGroundOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateGroundOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformPoint> getScreenCoordinate( - _i2.PlatformLatLng? latLng, - ) => + _i4.Future<_i2.PlatformPoint> getScreenCoordinate(_i2.PlatformLatLng? latLng) => (super.noSuchMethod( - Invocation.method(#getScreenCoordinate, [latLng]), - returnValue: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - ) - as _i4.Future<_i2.PlatformPoint>); + Invocation.method(#getScreenCoordinate, [latLng]), + returnValue: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + ) as _i4.Future<_i2.PlatformPoint>); @override - _i4.Future<_i2.PlatformLatLng> getLatLng( - _i2.PlatformPoint? screenCoordinate, - ) => + _i4.Future<_i2.PlatformLatLng> getLatLng(_i2.PlatformPoint? screenCoordinate) => (super.noSuchMethod( - Invocation.method(#getLatLng, [screenCoordinate]), - returnValue: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLng>); + Invocation.method(#getLatLng, [screenCoordinate]), + returnValue: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + ) as _i4.Future<_i2.PlatformLatLng>); @override - _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => - (super.noSuchMethod( - Invocation.method(#getVisibleRegion, []), - returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLngBounds>); + _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => (super.noSuchMethod( + Invocation.method(#getVisibleRegion, []), + returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + ) as _i4.Future<_i2.PlatformLatLngBounds>); @override - _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => - (super.noSuchMethod( - Invocation.method(#moveCamera, [cameraUpdate]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => (super.noSuchMethod( + Invocation.method(#moveCamera, [cameraUpdate]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future animateCamera( _i2.PlatformCameraUpdate? cameraUpdate, int? durationMilliseconds, - ) => - (super.noSuchMethod( - Invocation.method(#animateCamera, [ - cameraUpdate, - durationMilliseconds, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#animateCamera, [cameraUpdate, durationMilliseconds]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getZoomLevel() => (super.noSuchMethod( + Invocation.method(#getZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future showInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#showInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future showInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#showInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future hideInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#hideInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future hideInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#hideInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future isInfoWindowShown(String? markerId) => - (super.noSuchMethod( - Invocation.method(#isInfoWindowShown, [markerId]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isInfoWindowShown(String? markerId) => (super.noSuchMethod( + Invocation.method(#isInfoWindowShown, [markerId]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future setStyle(String? style) => - (super.noSuchMethod( - Invocation.method(#setStyle, [style]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future setStyle(String? style) => (super.noSuchMethod( + Invocation.method(#setStyle, [style]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future didLastStyleSucceed() => - (super.noSuchMethod( - Invocation.method(#didLastStyleSucceed, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future didLastStyleSucceed() => (super.noSuchMethod( + Invocation.method(#didLastStyleSucceed, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future isAdvancedMarkersAvailable() => - (super.noSuchMethod( - Invocation.method(#isAdvancedMarkersAvailable, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isAdvancedMarkersAvailable() => (super.noSuchMethod( + Invocation.method(#isAdvancedMarkersAvailable, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future clearTileCache(String? tileOverlayId) => - (super.noSuchMethod( - Invocation.method(#clearTileCache, [tileOverlayId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future clearTileCache(String? tileOverlayId) => (super.noSuchMethod( + Invocation.method(#clearTileCache, [tileOverlayId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i5.Uint8List> takeSnapshot() => - (super.noSuchMethod( - Invocation.method(#takeSnapshot, []), - returnValue: _i4.Future<_i5.Uint8List>.value(_i5.Uint8List(0)), - returnValueForMissingStub: _i4.Future<_i5.Uint8List>.value( - _i5.Uint8List(0), - ), - ) - as _i4.Future<_i5.Uint8List>); + _i4.Future<_i5.Uint8List> takeSnapshot() => (super.noSuchMethod( + Invocation.method(#takeSnapshot, []), + returnValue: _i4.Future<_i5.Uint8List>.value(_i5.Uint8List(0)), + returnValueForMissingStub: _i4.Future<_i5.Uint8List>.value(_i5.Uint8List(0)), + ) as _i4.Future<_i5.Uint8List>); } /// A class which mocks [MapsInitializerApi]. /// /// See the documentation for Mockito's code generation for more information. -class MockMapsInitializerApi extends _i1.Mock - implements _i2.MapsInitializerApi { +class MockMapsInitializerApi extends _i1.Mock implements _i2.MapsInitializerApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override _i4.Future<_i2.PlatformRendererType> initializeWithPreferredRenderer( _i2.PlatformRendererType? type, - ) => - (super.noSuchMethod( - Invocation.method(#initializeWithPreferredRenderer, [type]), - returnValue: _i4.Future<_i2.PlatformRendererType>.value( - _i2.PlatformRendererType.legacy, - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformRendererType>.value( - _i2.PlatformRendererType.legacy, - ), - ) - as _i4.Future<_i2.PlatformRendererType>); + ) => (super.noSuchMethod( + Invocation.method(#initializeWithPreferredRenderer, [type]), + returnValue: _i4.Future<_i2.PlatformRendererType>.value(_i2.PlatformRendererType.legacy), + returnValueForMissingStub: _i4.Future<_i2.PlatformRendererType>.value( + _i2.PlatformRendererType.legacy, + ), + ) as _i4.Future<_i2.PlatformRendererType>); @override - _i4.Future warmup() => - (super.noSuchMethod( - Invocation.method(#warmup, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future warmup() => (super.noSuchMethod( + Invocation.method(#warmup, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/integration_test/google_maps_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/integration_test/google_maps_test.dart index f1c15e56e975..86260596009a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/integration_test/google_maps_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/integration_test/google_maps_test.dart @@ -41,8 +41,9 @@ final LatLngBounds _testCameraBounds = LatLngBounds( northeast: const LatLng(50, -65), southwest: const LatLng(28.5, -123), ); -final ValueVariant _cameraUpdateTypeVariants = - ValueVariant(CameraUpdateType.values.toSet()); +final ValueVariant _cameraUpdateTypeVariants = ValueVariant( + CameraUpdateType.values.toSet(), +); void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -66,8 +67,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool compassEnabled = await inspector.isCompassEnabled(mapId: mapId); expect(compassEnabled, false); @@ -106,11 +106,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled(mapId: mapId); // This is only supported on Android, so should always return false. expect(mapToolbarEnabled, false); }); @@ -136,14 +133,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final ExampleGoogleMapController controller = await controllerCompleter.future; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; - MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( - mapId: controller.mapId, - ); + MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels(mapId: controller.mapId); expect(zoomLevel, equals(initialZoomLevel)); await tester.pumpWidget( @@ -183,11 +176,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled(mapId: mapId); expect(zoomGesturesEnabled, false); await tester.pumpWidget( @@ -225,11 +215,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); /// Zoom Controls functionality is not available on iOS at the moment. expect(zoomControlsEnabled, false); @@ -254,11 +241,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, false); await tester.pumpWidget( @@ -274,9 +258,7 @@ void main() { ), ); - rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, true); }); @@ -299,11 +281,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled(mapId: mapId); expect(tiltGesturesEnabled, false); await tester.pumpWidget( @@ -342,11 +321,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, false); await tester.pumpWidget( @@ -362,9 +338,7 @@ void main() { ), ); - scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, true); }); @@ -387,8 +361,7 @@ void main() { ), ), ); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; await tester.pumpAndSettle(); @@ -397,8 +370,9 @@ void main() { // https://github.com/flutter/flutter/issues/54758 await Future.delayed(const Duration(seconds: 1)); - final ScreenCoordinate coordinate = await mapController - .getScreenCoordinate(_kInitialCameraPosition.target); + final ScreenCoordinate coordinate = await mapController.getScreenCoordinate( + _kInitialCameraPosition.target, + ); final Rect rect = tester.getRect(find.byKey(key)); expect(coordinate.x, (rect.center.dx - rect.topLeft.dx).round()); expect(coordinate.y, (rect.center.dy - rect.topLeft.dy).round()); @@ -434,11 +408,9 @@ void main() { ); await tester.pumpAndSettle(); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; - final LatLngBounds firstVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds firstVisibleRegion = await mapController.getVisibleRegion(); expect(firstVisibleRegion, isNotNull); expect(firstVisibleRegion.southwest, isNotNull); @@ -464,21 +436,15 @@ void main() { expect(firstVisibleRegion.contains(northEast), isFalse); expect(firstVisibleRegion.contains(southWest), isFalse); - final latLngBounds = LatLngBounds( - southwest: southWest, - northeast: northEast, - ); + final latLngBounds = LatLngBounds(southwest: southWest, northeast: northEast); // TODO(iskakaushik): non-zero padding is needed for some device configurations // https://github.com/flutter/flutter/issues/30575 const double padding = 0; - await mapController.moveCamera( - CameraUpdate.newLatLngBounds(latLngBounds, padding), - ); + await mapController.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController.getVisibleRegion(); expect(secondVisibleRegion, isNotNull); expect(secondVisibleRegion.southwest, isNotNull); @@ -511,8 +477,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool isTrafficEnabled = await inspector.isTrafficEnabled(mapId: mapId); expect(isTrafficEnabled, true); @@ -551,11 +516,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool isBuildingsEnabled = await inspector.areBuildingsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool isBuildingsEnabled = await inspector.areBuildingsEnabled(mapId: mapId); expect(isBuildingsEnabled, true); }); @@ -577,11 +539,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); await tester.pumpWidget( @@ -598,15 +557,11 @@ void main() { ), ); - myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value false', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value false', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -625,16 +580,12 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value true', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value true', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -652,10 +603,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); }); @@ -676,19 +625,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - const mapStyle = - '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - mapStyle, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + const mapStyle = '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; + await GoogleMapsFlutterPlatform.instance.setMapStyle(mapStyle, mapId: controller.mapId); }); - testWidgets('testSetMapStyle invalid Json String', ( - WidgetTester tester, - ) async { + testWidgets('testSetMapStyle invalid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -705,8 +647,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; try { await GoogleMapsFlutterPlatform.instance.setMapStyle( @@ -737,12 +678,8 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - null, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + await GoogleMapsFlutterPlatform.instance.setMapStyle(null, mapId: controller.mapId); }); testWidgets('testGetLatLng', (WidgetTester tester) async { @@ -762,8 +699,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -772,13 +708,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng topLeft = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); + final LatLng topLeft = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); expect(topLeft, northWest); }); @@ -802,8 +733,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -841,8 +771,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -851,13 +780,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); - final ScreenCoordinate topLeft = await controller.getScreenCoordinate( - northWest, - ); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); + final ScreenCoordinate topLeft = await controller.getScreenCoordinate(northWest); expect(topLeft, const ScreenCoordinate(x: 0, y: 0)); }, // TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825 @@ -880,8 +804,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpWidget( Directionality( @@ -917,9 +840,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController googleMapController) { controllerCompleter.complete(googleMapController); @@ -928,12 +849,9 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, false); await controller.showMarkerInfoWindow(marker.markerId); @@ -945,9 +863,7 @@ void main() { expect(iwVisibleStatus, false); }); - testWidgets('updating a marker does not hide its info window', ( - WidgetTester tester, - ) async { + testWidgets('updating a marker does not hide its info window', (WidgetTester tester) async { final Key key = GlobalKey(); const marker = Marker( markerId: MarkerId('marker'), @@ -955,9 +871,7 @@ void main() { ); var markers = {marker}; - const clusterManager = ClusterManager( - clusterManagerId: ClusterManagerId('cluster_manager'), - ); + const clusterManager = ClusterManager(clusterManagerId: ClusterManagerId('cluster_manager')); final clusterManagers = {clusterManager}; final controllerCompleter = Completer(); @@ -967,9 +881,7 @@ void main() { textDirection: TextDirection.ltr, child: ExampleGoogleMap( key: key, - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, clusterManagers: clusterManagers, onMapCreated: (ExampleGoogleMapController googleMapController) { @@ -979,13 +891,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await controller.showMarkerInfoWindow(marker.markerId); - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, true); // Update marker and ensure the info window remains visible when added to a @@ -1031,8 +940,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final Uint8List? bytes = await controller.takeSnapshot(); expect(bytes?.isNotEmpty, true); }, @@ -1072,8 +980,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( tileOverlay1.mapsId, @@ -1086,18 +993,12 @@ void main() { expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.2, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); - expect( - tileOverlayInfo2.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }); @@ -1132,8 +1033,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final tileOverlay1New = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), @@ -1171,10 +1071,7 @@ void main() { expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); @@ -1205,8 +1102,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1249,10 +1145,7 @@ void main() { final marker = Marker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1260,8 +1153,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1278,8 +1170,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1296,8 +1187,7 @@ void main() { final MarkerId markerIdToMove = markers.entries .firstWhere( (MapEntry entry) => - entry.value.clusterManagerId == - clusterManagers.first.clusterManagerId, + entry.value.clusterManagerId == clusterManagers.first.clusterManagerId, ) .key; markers[markerIdToMove] = _copyMarkerWithClusterManagerId( @@ -1385,10 +1275,7 @@ void main() { final marker = AdvancedMarker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1396,8 +1283,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1415,8 +1301,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1431,10 +1316,7 @@ void main() { // Remove markers from clusterManagers and test that clusterManagers are empty. for (final MapEntry entry in markers.entries) { - markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId( - entry.value, - null, - ); + markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId(entry.value, null); } await tester.pumpWidget( Directionality( @@ -1490,15 +1372,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNotNull); }); - testWidgets('getStyleError returns null for a valid style', ( - WidgetTester tester, - ) async { + testWidgets('getStyleError returns null for a valid style', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -1517,8 +1396,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNull); }); @@ -1534,9 +1412,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1546,25 +1422,18 @@ void main() { }); testWidgets('markerWithAssetMapBitmapCreate', (WidgetTester tester) async { - final imageConfiguration = ImageConfiguration( - devicePixelRatio: tester.view.devicePixelRatio, - ); + final imageConfiguration = ImageConfiguration(devicePixelRatio: tester.view.devicePixelRatio); final markers = { Marker( markerId: const MarkerId('1'), - icon: await AssetMapBitmap.create( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await AssetMapBitmap.create(imageConfiguration, 'assets/red_square.png'), ), }; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1578,10 +1447,7 @@ void main() { final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; @@ -1589,9 +1455,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1602,19 +1466,13 @@ void main() { testWidgets('markerWithLegacyAsset', (WidgetTester tester) async { //tester.view.devicePixelRatio = 2.0; - const imageConfiguration = ImageConfiguration( - devicePixelRatio: 2.0, - size: Size(100, 100), - ); + const imageConfiguration = ImageConfiguration(devicePixelRatio: 2.0, size: Size(100, 100)); final markers = { Marker( markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. // ignore: deprecated_member_use - icon: await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await BitmapDescriptor.fromAssetImage(imageConfiguration, 'assets/red_square.png'), ), }; final controllerCompleter = Completer(); @@ -1622,9 +1480,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1648,9 +1504,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1690,19 +1544,13 @@ void main() { ), ); - void expectGroundOverlayEquals( - GroundOverlay source, - GroundOverlay response, - ) { + void expectGroundOverlayEquals(GroundOverlay source, GroundOverlay response) { expect(response.groundOverlayId, source.groundOverlayId); expect( response.transparency, moreOrLessEquals(source.transparency, epsilon: _floatTolerance), ); - expect( - response.bearing, - moreOrLessEquals(source.bearing, epsilon: _floatTolerance), - ); + expect(response.bearing, moreOrLessEquals(source.bearing, epsilon: _floatTolerance)); // Only test bounds if it was given in the original object if (source.bounds != null) { @@ -1717,14 +1565,8 @@ void main() { expect(response.clickable, source.clickable); expect(response.zIndex, source.zIndex); expect(response.zoomLevel, source.zoomLevel); - expect( - response.anchor?.dx, - moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance), - ); - expect( - response.anchor?.dy, - moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance), - ); + expect(response.anchor?.dx, moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance)); + expect(response.anchor?.dy, moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance)); } testWidgets('set ground overlays correctly', (WidgetTester tester) async { @@ -1754,38 +1596,29 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayBoundsInfo2 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPositionInfo1 = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1, - groundOverlayBoundsInfo1, - ); - expectGroundOverlayEquals( - groundOverlayBounds2, - groundOverlayBoundsInfo2, - ); - expectGroundOverlayEquals( - groundOverlayPosition1, - groundOverlayPositionInfo1, - ); + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds2.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPositionInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1, groundOverlayBoundsInfo1); + expectGroundOverlayEquals(groundOverlayBounds2, groundOverlayBoundsInfo2); + expectGroundOverlayEquals(groundOverlayPosition1, groundOverlayPositionInfo1); } }); - testWidgets('update ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('update ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1795,10 +1628,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1807,26 +1637,23 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - - final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); - - final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + + final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); + + final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); await tester.pumpWidget( Directionality( @@ -1834,10 +1661,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1New, - groundOverlayPosition1New, - }, + groundOverlays: {groundOverlayBounds1New, groundOverlayPosition1New}, onMapCreated: (ExampleGoogleMapController controller) { fail('update: OnMapCreated should get called only once.'); }, @@ -1848,28 +1672,21 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPosition1Info = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1New, - groundOverlayBounds1Info, - ); - expectGroundOverlayEquals( - groundOverlayPosition1New, - groundOverlayPosition1Info, - ); + final GroundOverlay groundOverlayBounds1Info = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPosition1Info = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1New, groundOverlayBounds1Info); + expectGroundOverlayEquals(groundOverlayPosition1New, groundOverlayPosition1Info); } }); - testWidgets('remove ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('remove ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1879,10 +1696,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1891,8 +1705,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1910,10 +1723,14 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay? groundOverlayBounds1Info = await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId); - final GroundOverlay? groundOverlayPositionInfo = await inspector - .getGroundOverlayInfo(groundOverlayPosition1.mapsId, mapId: mapId); + final GroundOverlay? groundOverlayBounds1Info = await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ); + final GroundOverlay? groundOverlayPositionInfo = await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ); expect(groundOverlayBounds1Info, isNull); expect(groundOverlayPositionInfo, isNull); @@ -1926,8 +1743,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -1939,8 +1755,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { cameraIdleCompleter.complete(); } }, @@ -1951,8 +1766,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -1972,8 +1786,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -1988,8 +1803,9 @@ void main() { await cameraIdleCompleter.future; // After onCameraIdle event, the camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2019,8 +1835,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -2044,8 +1859,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { stopwatch.stop(); cameraIdleCompleter.complete(); } @@ -2057,8 +1871,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -2090,15 +1903,10 @@ void main() { // For short animation duration, check that the animation is completed // faster than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - lessThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, lessThan(animationDurationMiddlePoint)); // Reset camera to initial position before testing long duration. - await controller.moveCamera( - CameraUpdate.newCameraPosition(_kInitialCameraPosition), - ); + await controller.moveCamera(CameraUpdate.newCameraPosition(_kInitialCameraPosition)); await tester.pumpAndSettle(); // Create completer for camera idle event. @@ -2121,8 +1929,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -2138,14 +1947,12 @@ void main() { // For longer animation duration, check that the animation is completed // slower than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - greaterThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, greaterThan(animationDurationMiddlePoint)); // Camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2179,9 +1986,7 @@ void main() { Directionality( textDirection: ui.TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 20.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 20.0)), markers: markers, markerType: MarkerType.advancedMarker, onMapCreated: (ExampleGoogleMapController controller) => @@ -2212,31 +2017,20 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, @@ -2286,23 +2080,15 @@ AdvancedMarker _copyAdvancedMarkerWithClusterManagerId( CameraUpdate _getCameraUpdateForType(CameraUpdateType type) { return switch (type) { - CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition( - _kTestCameraPosition, - ), + CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition(_kTestCameraPosition), CameraUpdateType.newLatLng => CameraUpdate.newLatLng(_kTestMapCenter), - CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds( - _testCameraBounds, - 0, - ), + CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds(_testCameraBounds, 0), CameraUpdateType.newLatLngZoom => CameraUpdate.newLatLngZoom( _kTestMapCenter, _kTestCameraZoomLevel, ), CameraUpdateType.scrollBy => CameraUpdate.scrollBy(10, 10), - CameraUpdateType.zoomBy => CameraUpdate.zoomBy( - _kTestZoomByAmount, - const Offset(1, 1), - ), + CameraUpdateType.zoomBy => CameraUpdate.zoomBy(_kTestZoomByAmount, const Offset(1, 1)), CameraUpdateType.zoomTo => CameraUpdate.zoomTo(_kTestCameraZoomLevel), CameraUpdateType.zoomIn => CameraUpdate.zoomIn(), CameraUpdateType.zoomOut => CameraUpdate.zoomOut(), @@ -2322,29 +2108,16 @@ Future _checkCameraUpdateByType( switch (type) { case CameraUpdateType.newCameraPosition: - expect( - currentPosition.bearing, - wrapMatcher(equals(_kTestCameraPosition.bearing)), - ); - expect( - currentPosition.zoom, - wrapMatcher(equals(_kTestCameraPosition.zoom)), - ); - expect( - currentPosition.tilt, - wrapMatcher(equals(_kTestCameraPosition.tilt)), - ); + expect(currentPosition.bearing, wrapMatcher(equals(_kTestCameraPosition.bearing))); + expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraPosition.zoom))); + expect(currentPosition.tilt, wrapMatcher(equals(_kTestCameraPosition.tilt))); expect( currentPosition.target.latitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.latitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.latitude, latLngThreshold)), ); expect( currentPosition.target.longitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLng: expect( @@ -2359,15 +2132,11 @@ Future _checkCameraUpdateByType( final LatLngBounds bounds = await controller.getVisibleRegion(); expect( bounds.northeast.longitude, - wrapMatcher( - closeTo(_testCameraBounds.northeast.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.northeast.longitude, latLngThreshold)), ); expect( bounds.southwest.longitude, - wrapMatcher( - closeTo(_testCameraBounds.southwest.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.southwest.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLngZoom: expect( @@ -2382,20 +2151,11 @@ Future _checkCameraUpdateByType( case CameraUpdateType.scrollBy: // For scrollBy, just check that the location has changed. if (oldPosition != null) { - expect( - currentPosition.target.latitude, - isNot(equals(oldPosition.target.latitude)), - ); - expect( - currentPosition.target.longitude, - isNot(equals(oldPosition.target.longitude)), - ); + expect(currentPosition.target.latitude, isNot(equals(oldPosition.target.latitude))); + expect(currentPosition.target.longitude, isNot(equals(oldPosition.target.longitude))); } case CameraUpdateType.zoomBy: - expect( - currentPosition.zoom, - wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount)), - ); + expect(currentPosition.zoom, wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount))); case CameraUpdateType.zoomTo: expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraZoomLevel))); case CameraUpdateType.zoomIn: diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_marker_icons.dart index 5069f3f900af..ff45dd833cef 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_marker_icons.dart @@ -33,8 +33,7 @@ class _AdvancedMarkerIconsBody extends StatefulWidget { final String? mapId; @override - State<_AdvancedMarkerIconsBody> createState() => - _AdvancedMarkerIconsBodyState(); + State<_AdvancedMarkerIconsBody> createState() => _AdvancedMarkerIconsBodyState(); } class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { @@ -51,10 +50,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: (ExampleGoogleMapController controller) { setState(() { @@ -73,29 +69,22 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { const ImageConfiguration(size: Size(12, 12)), 'assets/red_square.png', ); - final AssetMapBitmap largeAsset = - await BitmapDescriptor.asset( - const ImageConfiguration(size: Size(36, 36)), - 'assets/red_square.png', - ); + final AssetMapBitmap largeAsset = await BitmapDescriptor.asset( + const ImageConfiguration(size: Size(36, 36)), + 'assets/red_square.png', + ); setState(() { _markers.addAll([ // Default icon AdvancedMarker( markerId: const MarkerId('1'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude + 1), ), // Custom pin colors AdvancedMarker( markerId: const MarkerId('2'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.black, @@ -105,26 +94,17 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Pin with text AdvancedMarker( markerId: const MarkerId('3'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude + 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.blue, backgroundColor: Colors.white, - glyph: const TextGlyph( - text: 'Hi!', - textColor: Colors.blue, - ), + glyph: const TextGlyph(text: 'Hi!', textColor: Colors.blue), ), ), // Pin with bitmap AdvancedMarker( markerId: const MarkerId('4'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.white, @@ -134,10 +114,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Custom marker icon AdvancedMarker( markerId: const MarkerId('5'), - position: LatLng( - _kMapCenter.latitude, - _kMapCenter.longitude, - ), + position: LatLng(_kMapCenter.latitude, _kMapCenter.longitude), icon: largeAsset, ), ]); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_markers_clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_markers_clustering.dart index 1787e9077a50..985566ee454f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_markers_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/advanced_markers_clustering.dart @@ -16,10 +16,7 @@ import 'page.dart'; class AdvancedMarkersClusteringPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkersClusteringPage({super.key, required this.mapId}) - : super( - const Icon(Icons.place_outlined), - 'Manage clusters of advanced markers', - ); + : super(const Icon(Icons.place_outlined), 'Manage clusters of advanced markers'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -78,8 +75,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -107,17 +103,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; }); } @@ -159,14 +149,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -210,9 +197,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/animate_camera.dart index 001006fb54be..d278e2c5b3b6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/animate_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class AnimateCameraPage extends GoogleMapExampleAppPage { - const AnimateCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control, animated'); + const AnimateCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control, animated'); @override Widget build(BuildContext context) { @@ -58,9 +57,7 @@ class AnimateCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -88,9 +85,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), duration: _cameraUpdateAnimationDuration, ); }, @@ -114,10 +109,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), duration: _cameraUpdateAnimationDuration, ); }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/clustering.dart index 18e9af8c1be8..e7ea5e7ddefc 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/clustering.dart @@ -13,8 +13,7 @@ import 'page.dart'; /// Page for demonstrating marker clustering support. class ClusteringPage extends GoogleMapExampleAppPage { /// Default Constructor. - const ClusteringPage({super.key}) - : super(const Icon(Icons.place), 'Manage clustering'); + const ClusteringPage({super.key}) : super(const Icon(Icons.place), 'Manage clustering'); @override Widget build(BuildContext context) { @@ -61,8 +60,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -95,10 +93,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = _copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = _copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -134,8 +129,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -144,14 +138,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -190,9 +181,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); @@ -239,8 +228,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { TextButton( onPressed: clusterManagers.isEmpty ? null - : () => - _removeClusterManager(clusterManagers.values.last), + : () => _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -248,8 +236,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { Wrap( alignment: WrapAlignment.spaceEvenly, children: [ - for (final MapEntry - clusterEntry + for (final MapEntry clusterEntry in clusterManagers.entries) TextButton( onPressed: () => _addMarkersToCluster(clusterEntry.value), @@ -272,9 +259,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { child: const Text('Remove selected marker'), ), TextButton( - onPressed: markers.isEmpty - ? null - : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty ? null : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/collision_behavior.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/collision_behavior.dart index a6a8ef8aec70..f93d850a6836 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/collision_behavior.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/collision_behavior.dart @@ -15,10 +15,7 @@ import 'place_marker.dart'; class AdvancedMarkerCollisionBehaviorPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkerCollisionBehaviorPage({super.key, required this.mapId}) - : super( - const Icon(Icons.not_listed_location), - 'Advanced marker collision behavior', - ); + : super(const Icon(Icons.not_listed_location), 'Advanced marker collision behavior'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -35,12 +32,10 @@ class _CollisionBehaviorPageBody extends StatefulWidget { final String? mapId; @override - State<_CollisionBehaviorPageBody> createState() => - _CollisionBehaviorPageBodyState(); + State<_CollisionBehaviorPageBody> createState() => _CollisionBehaviorPageBodyState(); } -class _CollisionBehaviorPageBodyState - extends State<_CollisionBehaviorPageBody> { +class _CollisionBehaviorPageBodyState extends State<_CollisionBehaviorPageBody> { static const LatLng center = LatLng(-33.86711, 151.1947171); static const double zoomOutLevel = 9; static const double zoomInLevel = 12; @@ -78,10 +73,7 @@ class _CollisionBehaviorPageBodyState child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: center, - zoom: zoomInLevel, - ), + initialCameraPosition: const CameraPosition(target: center, zoom: zoomInLevel), markers: Set.of(markers), tiltGesturesEnabled: false, zoomGesturesEnabled: false, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/custom_marker_icon.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/custom_marker_icon.dart index 548146c6206c..3391ba1bcba2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/custom_marker_icon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/custom_marker_icon.dart @@ -20,9 +20,7 @@ Future createCustomMarkerIconImage({required Size size}) async { size.height.floor(), ); - final ByteData? bytes = await image.toByteData( - format: ui.ImageByteFormat.png, - ); + final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); return bytes!; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/example_google_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/example_google_map.dart index 2b8a8243d381..e18943a3345f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/example_google_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/example_google_map.dart @@ -47,10 +47,7 @@ class ExampleGoogleMapController { if (_googleMapState.widget.onCameraMove != null) { GoogleMapsFlutterPlatform.instance .onCameraMove(mapId: mapId) - .listen( - (CameraMoveEvent e) => - _googleMapState.widget.onCameraMove!(e.value), - ); + .listen((CameraMoveEvent e) => _googleMapState.widget.onCameraMove!(e.value)); } if (_googleMapState.widget.onCameraIdle != null) { GoogleMapsFlutterPlatform.instance @@ -62,27 +59,16 @@ class ExampleGoogleMapController { .listen((MarkerTapEvent e) => _googleMapState.onMarkerTap(e.value)); GoogleMapsFlutterPlatform.instance .onMarkerDragStart(mapId: mapId) - .listen( - (MarkerDragStartEvent e) => - _googleMapState.onMarkerDragStart(e.value, e.position), - ); + .listen((MarkerDragStartEvent e) => _googleMapState.onMarkerDragStart(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDrag(mapId: mapId) - .listen( - (MarkerDragEvent e) => - _googleMapState.onMarkerDrag(e.value, e.position), - ); + .listen((MarkerDragEvent e) => _googleMapState.onMarkerDrag(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDragEnd(mapId: mapId) - .listen( - (MarkerDragEndEvent e) => - _googleMapState.onMarkerDragEnd(e.value, e.position), - ); + .listen((MarkerDragEndEvent e) => _googleMapState.onMarkerDragEnd(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onInfoWindowTap(mapId: mapId) - .listen( - (InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value), - ); + .listen((InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value)); GoogleMapsFlutterPlatform.instance .onPolylineTap(mapId: mapId) .listen((PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value)); @@ -94,18 +80,13 @@ class ExampleGoogleMapController { .listen((CircleTapEvent e) => _googleMapState.onCircleTap(e.value)); GoogleMapsFlutterPlatform.instance .onGroundOverlayTap(mapId: mapId) - .listen( - (GroundOverlayTapEvent e) => - _googleMapState.onGroundOverlayTap(e.value), - ); + .listen((GroundOverlayTapEvent e) => _googleMapState.onGroundOverlayTap(e.value)); GoogleMapsFlutterPlatform.instance .onTap(mapId: mapId) .listen((MapTapEvent e) => _googleMapState.onTap(e.position)); GoogleMapsFlutterPlatform.instance .onLongPress(mapId: mapId) - .listen( - (MapLongPressEvent e) => _googleMapState.onLongPress(e.position), - ); + .listen((MapLongPressEvent e) => _googleMapState.onLongPress(e.position)); GoogleMapsFlutterPlatform.instance .onClusterTap(mapId: mapId) .listen((ClusterTapEvent e) => _googleMapState.onClusterTap(e.value)); @@ -113,24 +94,16 @@ class ExampleGoogleMapController { /// Updates configuration options of the map user interface. Future _updateMapConfiguration(MapConfiguration update) { - return GoogleMapsFlutterPlatform.instance.updateMapConfiguration( - update, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMapConfiguration(update, mapId: mapId); } /// Updates marker configuration. Future _updateMarkers(MarkerUpdates markerUpdates) { - return GoogleMapsFlutterPlatform.instance.updateMarkers( - markerUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMarkers(markerUpdates, mapId: mapId); } /// Updates cluster manager configuration. - Future _updateClusterManagers( - ClusterManagerUpdates clusterManagerUpdates, - ) { + Future _updateClusterManagers(ClusterManagerUpdates clusterManagerUpdates) { return GoogleMapsFlutterPlatform.instance.updateClusterManagers( clusterManagerUpdates, mapId: mapId, @@ -138,9 +111,7 @@ class ExampleGoogleMapController { } /// Updates ground overlay configuration. - Future _updateGroundOverlays( - GroundOverlayUpdates groundOverlayUpdates, - ) { + Future _updateGroundOverlays(GroundOverlayUpdates groundOverlayUpdates) { return GoogleMapsFlutterPlatform.instance.updateGroundOverlays( groundOverlayUpdates, mapId: mapId, @@ -149,26 +120,17 @@ class ExampleGoogleMapController { /// Updates polygon configuration. Future _updatePolygons(PolygonUpdates polygonUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolygons( - polygonUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolygons(polygonUpdates, mapId: mapId); } /// Updates polyline configuration. Future _updatePolylines(PolylineUpdates polylineUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolylines( - polylineUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolylines(polylineUpdates, mapId: mapId); } /// Updates circle configuration. Future _updateCircles(CircleUpdates circleUpdates) { - return GoogleMapsFlutterPlatform.instance.updateCircles( - circleUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateCircles(circleUpdates, mapId: mapId); } /// Updates tile overlays configuration. @@ -182,10 +144,7 @@ class ExampleGoogleMapController { /// Clears the tile cache so that all tiles will be requested again from the /// [TileProvider]. Future clearTileCache(TileOverlayId tileOverlayId) async { - return GoogleMapsFlutterPlatform.instance.clearTileCache( - tileOverlayId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.clearTileCache(tileOverlayId, mapId: mapId); } /// Starts an animated change of the map camera position. @@ -199,10 +158,7 @@ class ExampleGoogleMapController { /// Changes the map camera position. Future moveCamera(CameraUpdate cameraUpdate) { - return GoogleMapsFlutterPlatform.instance.moveCamera( - cameraUpdate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.moveCamera(cameraUpdate, mapId: mapId); } /// Return [LatLngBounds] defining the region that is visible in a map. @@ -212,42 +168,27 @@ class ExampleGoogleMapController { /// Return [ScreenCoordinate] of the [LatLng] in the current map view. Future getScreenCoordinate(LatLng latLng) { - return GoogleMapsFlutterPlatform.instance.getScreenCoordinate( - latLng, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getScreenCoordinate(latLng, mapId: mapId); } /// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view. Future getLatLng(ScreenCoordinate screenCoordinate) { - return GoogleMapsFlutterPlatform.instance.getLatLng( - screenCoordinate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getLatLng(screenCoordinate, mapId: mapId); } /// Programmatically show the Info Window for a [Marker]. Future showMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow(markerId, mapId: mapId); } /// Programmatically hide the Info Window for a [Marker]. Future hideMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow(markerId, mapId: mapId); } /// Returns `true` when the [InfoWindow] is showing, `false` otherwise. Future isMarkerInfoWindowShown(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown(markerId, mapId: mapId); } /// Returns the current zoom level of the map @@ -267,9 +208,7 @@ class ExampleGoogleMapController { /// Returns true if [AdvancedMarker]s can be used with this map. Future isAdvancedMarkersAvailable() { - return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable( - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: mapId); } /// Disposes of the platform resources @@ -446,17 +385,14 @@ class ExampleGoogleMap extends StatefulWidget { class _ExampleGoogleMapState extends State { final int _mapId = _nextMapCreationId++; - final Completer _controller = - Completer(); + final Completer _controller = Completer(); Map _markers = {}; Map _polygons = {}; Map _polylines = {}; Map _circles = {}; - Map _clusterManagers = - {}; - Map _groundOverlays = - {}; + Map _clusterManagers = {}; + Map _groundOverlays = {}; late MapConfiguration _mapConfiguration; @override @@ -466,9 +402,7 @@ class _ExampleGoogleMapState extends State { onPlatformViewCreated, widgetConfiguration: MapWidgetConfiguration( textDirection: - widget.layoutDirection ?? - Directionality.maybeOf(context) ?? - TextDirection.ltr, + widget.layoutDirection ?? Directionality.maybeOf(context) ?? TextDirection.ltr, initialCameraPosition: widget.initialCameraPosition, gestureRecognizers: widget.gestureRecognizers, ), @@ -498,9 +432,7 @@ class _ExampleGoogleMapState extends State { @override void dispose() { - _controller.future.then( - (ExampleGoogleMapController controller) => controller.dispose(), - ); + _controller.future.then((ExampleGoogleMapController controller) => controller.dispose()); super.dispose(); } @@ -531,9 +463,7 @@ class _ExampleGoogleMapState extends State { Future _updateMarkers() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateMarkers( - MarkerUpdates.from(_markers.values.toSet(), widget.markers), - ), + controller._updateMarkers(MarkerUpdates.from(_markers.values.toSet(), widget.markers)), ); _markers = keyByMarkerId(widget.markers); } @@ -542,10 +472,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateClusterManagers( - ClusterManagerUpdates.from( - _clusterManagers.values.toSet(), - widget.clusterManagers, - ), + ClusterManagerUpdates.from(_clusterManagers.values.toSet(), widget.clusterManagers), ), ); _clusterManagers = keyByClusterManagerId(widget.clusterManagers); @@ -555,10 +482,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateGroundOverlays( - GroundOverlayUpdates.from( - _groundOverlays.values.toSet(), - widget.groundOverlays, - ), + GroundOverlayUpdates.from(_groundOverlays.values.toSet(), widget.groundOverlays), ), ); _groundOverlays = keyByGroundOverlayId(widget.groundOverlays); @@ -567,9 +491,7 @@ class _ExampleGoogleMapState extends State { Future _updatePolygons() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updatePolygons( - PolygonUpdates.from(_polygons.values.toSet(), widget.polygons), - ), + controller._updatePolygons(PolygonUpdates.from(_polygons.values.toSet(), widget.polygons)), ); _polygons = keyByPolygonId(widget.polygons); } @@ -587,9 +509,7 @@ class _ExampleGoogleMapState extends State { Future _updateCircles() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateCircles( - CircleUpdates.from(_circles.values.toSet(), widget.circles), - ), + controller._updateCircles(CircleUpdates.from(_circles.values.toSet(), widget.circles)), ); _circles = keyByCircleId(widget.circles); } @@ -600,12 +520,11 @@ class _ExampleGoogleMapState extends State { } Future onPlatformViewCreated(int id) async { - final ExampleGoogleMapController controller = - await ExampleGoogleMapController._init( - id, - widget.initialCameraPosition, - this, - ); + final ExampleGoogleMapController controller = await ExampleGoogleMapController._init( + id, + widget.initialCameraPosition, + this, + ); _controller.complete(controller); unawaited(_updateTileOverlays()); widget.onMapCreated?.call(controller); @@ -656,8 +575,7 @@ class _ExampleGoogleMapState extends State { } void onClusterTap(Cluster cluster) { - final ClusterManager? clusterManager = - _clusterManagers[cluster.clusterManagerId]; + final ClusterManager? clusterManager = _clusterManagers[cluster.clusterManagerId]; clusterManager?.onClusterTap?.call(cluster); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/ground_overlay.dart index 00a7d8126539..878f5c9200a2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/ground_overlay.dart @@ -13,8 +13,7 @@ import 'page.dart'; enum _GroundOverlayPlacing { position, bounds } class GroundOverlayPage extends GoogleMapExampleAppPage { - const GroundOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Ground overlay'); + const GroundOverlayPage({super.key}) : super(const Icon(Icons.map), 'Ground overlay'); @override Widget build(BuildContext context) { @@ -132,9 +131,7 @@ class GroundOverlayBodyState extends State { // Adjusts the bearing by 10 degrees, wrapping around at 360 degrees. // 10 is the increment, 350 degrees of the full circle -10. _groundOverlay = _groundOverlay!.copyWith( - bearingParam: _groundOverlay!.bearing >= 350 - ? 0 - : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, ); }); } @@ -143,9 +140,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { final transparency = _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; - _groundOverlay = _groundOverlay!.copyWith( - transparencyParam: transparency, - ); + _groundOverlay = _groundOverlay!.copyWith(transparencyParam: transparency); }); } @@ -167,8 +162,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.bounds); setState(() { - _currentGroundOverlayBounds = - _currentGroundOverlayBounds == _groundOverlayBounds1 + _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 ? _groundOverlayBounds2 : _groundOverlayBounds1; }); @@ -181,9 +175,7 @@ class GroundOverlayBodyState extends State { void _toggleVisible() { assert(_groundOverlay != null); setState(() { - _groundOverlay = _groundOverlay!.copyWith( - visibleParam: !_groundOverlay!.visible, - ); + _groundOverlay = _groundOverlay!.copyWith(visibleParam: !_groundOverlay!.visible); }); } @@ -223,9 +215,7 @@ class GroundOverlayBodyState extends State { @override Widget build(BuildContext context) { - final overlays = { - if (_groundOverlay != null) _groundOverlay!, - }; + final overlays = {if (_groundOverlay != null) _groundOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -233,10 +223,7 @@ class GroundOverlayBodyState extends State { children: [ Expanded( child: ExampleGoogleMap( - initialCameraPosition: CameraPosition( - target: _mapCenter, - zoom: 14.0, - ), + initialCameraPosition: CameraPosition(target: _mapCenter, zoom: 14.0), groundOverlays: overlays, onMapCreated: _onMapCreated, ), @@ -258,9 +245,7 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeTransparency(), + onPressed: _groundOverlay == null ? null : () => _changeTransparency(), child: const Text('change transparency'), ), TextButton( @@ -282,23 +267,17 @@ class GroundOverlayBodyState extends State { TextButton( onPressed: _groundOverlay == null ? null : () => _changeType(), child: Text( - _placingType == _GroundOverlayPlacing.position - ? 'use bounds' - : 'use position', + _placingType == _GroundOverlayPlacing.position ? 'use bounds' : 'use position', ), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changePosition(), child: const Text('change position'), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.bounds || _groundOverlay == null ? null : () => _changeBounds(), child: const Text('change bounds'), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_click.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_click.dart index a786197d5205..49ecd2656bab 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_click.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_click.dart @@ -58,42 +58,25 @@ class _MapClickBodyState extends State<_MapClickBody> { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; if (mapController != null) { final lastTap = 'Tap:\n${_lastTap ?? ""}\n'; final lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; + columnChildren.add(Center(child: Text(lastTap, textAlign: TextAlign.center))); columnChildren.add( - Center(child: Text(lastTap, textAlign: TextAlign.center)), - ); - columnChildren.add( - Center( - child: Text( - _lastTap != null ? 'Tapped' : '', - textAlign: TextAlign.center, - ), - ), - ); - columnChildren.add( - Center(child: Text(lastLongPress, textAlign: TextAlign.center)), + Center(child: Text(_lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center)), ); + columnChildren.add(Center(child: Text(lastLongPress, textAlign: TextAlign.center))); columnChildren.add( Center( - child: Text( - _lastLongPress != null ? 'Long pressed' : '', - textAlign: TextAlign.center, - ), + child: Text(_lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } Future onMapCreated(ExampleGoogleMapController controller) async { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_coordinates.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_coordinates.dart index 646301db99ae..51a68e8d5cf4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_coordinates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_coordinates.dart @@ -16,8 +16,7 @@ const CameraPosition _kInitialPosition = CameraPosition( ); class MapCoordinatesPage extends GoogleMapExampleAppPage { - const MapCoordinatesPage({super.key}) - : super(const Icon(Icons.map), 'Map coordinates'); + const MapCoordinatesPage({super.key}) : super(const Icon(Icons.map), 'Map coordinates'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { final googleMap = ExampleGoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, - onCameraIdle: - _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 + onCameraIdle: _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 ); return NotificationListener( @@ -61,13 +59,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { children: [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox( - width: 300.0, - height: 200.0, - child: googleMap, - ), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), // Add a block at the bottom of this list to allow validation that the visible region of the map // does not change when scrolled under the safe view on iOS. diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_map_id.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_map_id.dart index 94a01eb03368..89ba5c25396f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_map_id.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_map_id.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { - const MapIdPage({super.key}) - : super(const Icon(Icons.map), 'Cloud-based maps styling'); + const MapIdPage({super.key}) : super(const Icon(Icons.map), 'Cloud-based maps styling'); @override Widget build(BuildContext context) { @@ -49,10 +48,7 @@ class MapIdBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), key: _key, mapId: _mapId, ); @@ -60,9 +56,7 @@ class MapIdBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), Padding( padding: const EdgeInsets.all(10.0), @@ -80,10 +74,7 @@ class MapIdBodyState extends State { ), ]; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_ui.dart index 258c88170924..d7e7ff773a64 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/map_ui.dart @@ -84,9 +84,7 @@ class MapUiBodyState extends State { Widget _latLngBoundsToggler() { return TextButton( child: Text( - _cameraTargetBounds.bounds == null - ? 'bound camera target' - : 'release camera target', + _cameraTargetBounds.bounds == null ? 'bound camera target' : 'release camera target', ), onPressed: () { setState(() { @@ -100,9 +98,7 @@ class MapUiBodyState extends State { Widget _zoomBoundsToggler() { return TextButton( - child: Text( - _minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom', - ), + child: Text(_minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom'), onPressed: () { setState(() { _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null @@ -114,8 +110,7 @@ class MapUiBodyState extends State { } Widget _mapTypeCycler() { - final MapType nextType = - MapType.values[(_mapType.index + 1) % MapType.values.length]; + final MapType nextType = MapType.values[(_mapType.index + 1) % MapType.values.length]; return TextButton( child: Text('change map type to $nextType'), onPressed: () { @@ -172,9 +167,7 @@ class MapUiBodyState extends State { Widget _zoomControlsToggler() { return TextButton( - child: Text( - '${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls', - ), + child: Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'), onPressed: () { setState(() { _zoomControlsEnabled = !_zoomControlsEnabled; @@ -196,9 +189,7 @@ class MapUiBodyState extends State { Widget _myLocationToggler() { return TextButton( - child: Text( - '${_myLocationEnabled ? 'disable' : 'enable'} my location marker', - ), + child: Text('${_myLocationEnabled ? 'disable' : 'enable'} my location marker'), onPressed: () { setState(() { _myLocationEnabled = !_myLocationEnabled; @@ -209,9 +200,7 @@ class MapUiBodyState extends State { Widget _myLocationButtonToggler() { return TextButton( - child: Text( - '${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button', - ), + child: Text('${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'), onPressed: () { setState(() { _myLocationButtonEnabled = !_myLocationButtonEnabled; @@ -240,9 +229,7 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = _nightMode - ? await _getFileData('assets/night_mode.json') - : ''; + final String style = _nightMode ? await _getFileData('assets/night_mode.json') : ''; setState(() { _mapStyle = style; }); @@ -275,9 +262,7 @@ class MapUiBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; @@ -313,10 +298,7 @@ class MapUiBodyState extends State { ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _updateCameraPosition(CameraPosition position) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/marker_icons.dart index d4ac8d6ac597..84d13ac32e89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/marker_icons.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MarkerIconsPage extends GoogleMapExampleAppPage { - const MarkerIconsPage({super.key}) - : super(const Icon(Icons.image), 'Marker icons'); + const MarkerIconsPage({super.key}) : super(const Icon(Icons.image), 'Marker icons'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { AssetMapBitmap? _markerIconAsset; BytesMapBitmap? _markerIconBytes; final int _markersAmountPerType = 15; - bool get _customSizeEnabled => - _currentSizeOption != _MarkerSizeOption.original; + bool get _customSizeEnabled => _currentSizeOption != _MarkerSizeOption.original; @override Widget build(BuildContext context) { @@ -64,10 +62,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { width: 350.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: _onMapCreated, ), @@ -75,11 +70,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ), TextButton( onPressed: () => _toggleScaling(context), - child: Text( - _scalingEnabled - ? 'Disable auto scaling' - : 'Enable auto scaling', - ), + child: Text(_scalingEnabled ? 'Disable auto scaling' : 'Enable auto scaling'), ), if (_scalingEnabled) ...[ Container( @@ -91,10 +82,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'Reference box with size of ${referenceSize.width} x ${referenceSize.height} in logical pixels.', ), const SizedBox(height: 10), - Image.asset( - 'assets/red_square.png', - scale: _mipMapsEnabled ? null : 1.0, - ), + Image.asset('assets/red_square.png', scale: _mipMapsEnabled ? null : 1.0), const Text('Asset image rendered with flutter'), const SizedBox(height: 10), Row( @@ -112,9 +100,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { }); } }, - items: _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { + items: _MarkerSizeOption.values.map((_MarkerSizeOption option) { return DropdownMenuItem<_MarkerSizeOption>( value: option, child: Text(_getMarkerSizeOptionName(option)), @@ -126,9 +112,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ], TextButton( onPressed: () => _toggleMipMaps(context), - child: Text( - _mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps', - ), + child: Text(_mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps'), ), ], ), @@ -179,15 +163,9 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { if (width != null && height != null) { return Size(width, height); } else if (width != null) { - return Size( - width, - width * _markerAssetImageSize.height / _markerAssetImageSize.width, - ); + return Size(width, width * _markerAssetImageSize.height / _markerAssetImageSize.width); } else if (height != null) { - return Size( - height * _markerAssetImageSize.width / _markerAssetImageSize.height, - height, - ); + return Size(height * _markerAssetImageSize.width / _markerAssetImageSize.height, height); } else { return _markerAssetImageSize; } @@ -210,10 +188,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createAssetMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude - 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude - 1); return Marker( markerId: MarkerId('marker_asset_$index'), @@ -223,10 +198,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createBytesMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude + 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude + 1); return Marker( markerId: MarkerId('marker_bytes_$index'), @@ -252,26 +224,20 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { - final ImageConfiguration imageConfiguration = - createLocalImageConfiguration(context); + final ImageConfiguration imageConfiguration = createLocalImageConfiguration(context); assetMapBitmap = await AssetMapBitmap.create( imageConfiguration, 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -281,9 +247,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } @@ -291,9 +255,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Future _updateMarkerBytesImage(BuildContext context) async { - final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf( - context, - ); + final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context); final Size bitmapLogicalSize = _getMarkerReferenceSize(); final double? imagePixelRatio = _scalingEnabled ? devicePixelRatio : null; @@ -307,10 +269,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); @@ -319,9 +278,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/move_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/move_camera.dart index 5fc48e659246..28ce96f2b55f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/move_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/move_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MoveCameraPage extends GoogleMapExampleAppPage { - const MoveCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control'); + const MoveCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control'); @override Widget build(BuildContext context) { @@ -46,9 +45,7 @@ class MoveCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -75,9 +72,7 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -99,19 +94,14 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.moveCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), @@ -121,9 +111,7 @@ class MoveCameraState extends State { children: [ TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0)), - ); + mapController?.moveCamera(CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0))); }, child: const Text('zoomBy with focus'), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/padding.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/padding.dart index a0f4f8521c8e..82136d27cd8c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/padding.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/padding.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PaddingPage extends GoogleMapExampleAppPage { - const PaddingPage({super.key}) - : super(const Icon(Icons.map), 'Add padding to the map'); + const PaddingPage({super.key}) : super(const Icon(Icons.map), 'Add padding to the map'); @override Widget build(BuildContext context) { @@ -38,19 +37,14 @@ class MarkerIconsBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), padding: _padding, ); final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), const Padding( padding: EdgeInsets.only(top: 20), @@ -65,10 +59,7 @@ class MarkerIconsBodyState extends State { columnChildren.addAll([_paddingInput(), _buttons()]); - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _onMapCreated(ExampleGoogleMapController controllerParam) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_advanced_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_advanced_marker.dart index 08a886c11041..61c0898fed88 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_advanced_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_advanced_marker.dart @@ -53,18 +53,18 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { this.controller = controller; }); - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; }); + }); + }); } void _onMarkerTapped(MarkerId markerId) { @@ -73,17 +73,11 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; markerPosition = null; @@ -108,10 +102,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -177,16 +168,10 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { void _changePosition(MarkerId markerId) { final AdvancedMarker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -239,9 +224,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -249,9 +232,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -266,9 +247,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -289,9 +268,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { /// Performs customizations of the [marker] to mark it as selected or not. AdvancedMarker copyWithSelectedState(AdvancedMarker marker, bool isSelected) { - return marker.copyWith( - iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected), - ); + return marker.copyWith(iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected)); } @override @@ -308,8 +285,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, @@ -340,9 +316,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -351,70 +325,49 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( onPressed: selectedId == null ? null - : () => - _setMarkerIcon(selectedId, _getMarkerIcon(context)), + : () => _setMarkerIcon(selectedId, _getMarkerIcon(context)), child: const Text('set glyph text'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_circle.dart index 3c0335bfd18b..6bd22df33ef2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_circle.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { - const PlaceCirclePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place circle'); + const PlaceCirclePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place circle'); @override Widget build(BuildContext context) { @@ -38,12 +37,7 @@ class PlaceCircleBodyState extends State { // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling circle stroke width int widthsIndex = 0; @@ -133,9 +127,7 @@ class PlaceCircleBodyState extends State { void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { - circles[circleId] = circle.copyWith( - strokeWidthParam: widths[++widthsIndex % widths.length], - ); + circles[circleId] = circle.copyWith(strokeWidthParam: widths[++widthsIndex % widths.length]); }); } @@ -171,15 +163,11 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_marker.dart index 77ba3787d8e7..43f16a23979a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_marker.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceMarkerPage extends GoogleMapExampleAppPage { - const PlaceMarkerPage({super.key}) - : super(const Icon(Icons.place), 'Place marker'); + const PlaceMarkerPage({super.key}) : super(const Icon(Icons.place), 'Place marker'); @override Widget build(BuildContext context) { @@ -61,10 +60,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -170,16 +166,10 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { void _changePosition(MarkerId markerId) { final Marker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -232,9 +222,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -242,9 +230,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -259,9 +245,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -311,9 +295,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -322,63 +304,43 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( @@ -430,12 +392,10 @@ class AdvancedMarkersCapabilityStatus extends StatefulWidget { final ExampleGoogleMapController? controller; @override - State createState() => - _AdvancedMarkersCapabilityStatusState(); + State createState() => _AdvancedMarkersCapabilityStatusState(); } -class _AdvancedMarkersCapabilityStatusState - extends State { +class _AdvancedMarkersCapabilityStatusState extends State { /// Whether map supports advanced markers. bool? _isAdvancedMarkersAvailable; @@ -456,21 +416,19 @@ class _AdvancedMarkersCapabilityStatusState void _checkCapabilityIfNeeded() { final ExampleGoogleMapController? controller = widget.controller; - if (controller != null && - _isAdvancedMarkersAvailable == null && - !_isFetching) { + if (controller != null && _isAdvancedMarkersAvailable == null && !_isFetching) { _isFetching = true; - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - _isFetching = false; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; + _isFetching = false; + }); + }); } } @@ -481,8 +439,7 @@ class _AdvancedMarkersCapabilityStatusState child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polygon.dart index 70ad42c93724..d7c518cdf48d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polygon.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolygonPage extends GoogleMapExampleAppPage { - const PlacePolygonPage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polygon'); + const PlacePolygonPage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polygon'); @override Widget build(BuildContext context) { @@ -39,12 +38,7 @@ class PlacePolygonBodyState extends State { // Values when toggling polygon color int strokeColorsIndex = 0; int fillColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polygon width int widthsIndex = 0; @@ -149,9 +143,7 @@ class PlacePolygonBodyState extends State { void _addHoles(PolygonId polygonId) { final Polygon polygon = polygons[polygonId]!; setState(() { - polygons[polygonId] = polygon.copyWith( - holesParam: _createHoles(polygonId), - ); + polygons[polygonId] = polygon.copyWith(holesParam: _createHoles(polygonId)); }); } @@ -194,15 +186,11 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -232,9 +220,7 @@ class PlacePolygonBodyState extends State { child: const Text('remove holes'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polyline.dart index 8703ffcbd68f..a60d106bbe0b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/place_polyline.dart @@ -12,8 +12,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolylinePage extends GoogleMapExampleAppPage { - const PlacePolylinePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polyline'); + const PlacePolylinePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polyline'); @override Widget build(BuildContext context) { @@ -38,23 +37,14 @@ class PlacePolylineBodyState extends State { // Values when toggling polyline color int colorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polyline width int widthsIndex = 0; List widths = [10, 20, 5]; int jointTypesIndex = 0; - List jointTypes = [ - JointType.mitered, - JointType.bevel, - JointType.round, - ]; + List jointTypes = [JointType.mitered, JointType.bevel, JointType.round]; // Values when toggling polyline end cap type int endCapsIndex = 0; @@ -133,36 +123,28 @@ class PlacePolylineBodyState extends State { void _toggleGeodesic(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - geodesicParam: !polyline.geodesic, - ); + polylines[polylineId] = polyline.copyWith(geodesicParam: !polyline.geodesic); }); } void _toggleVisible(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - visibleParam: !polyline.visible, - ); + polylines[polylineId] = polyline.copyWith(visibleParam: !polyline.visible); }); } void _changeColor(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - colorParam: colors[++colorsIndex % colors.length], - ); + polylines[polylineId] = polyline.copyWith(colorParam: colors[++colorsIndex % colors.length]); }); } void _changeWidth(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - widthParam: widths[++widthsIndex % widths.length], - ); + polylines[polylineId] = polyline.copyWith(widthParam: widths[++widthsIndex % widths.length]); }); } @@ -237,15 +219,11 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -259,15 +237,11 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) ? null : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( @@ -289,9 +263,7 @@ class PlacePolylineBodyState extends State { child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) ? null : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/scrolling_map.dart index e5a8ec2ce5a6..443544402c31 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/scrolling_map.dart @@ -15,8 +15,7 @@ import 'page.dart'; const LatLng _center = LatLng(32.080664, 34.9563837); class ScrollingMapPage extends GoogleMapExampleAppPage { - const ScrollingMapPage({super.key}) - : super(const Icon(Icons.map), 'Scrolling map'); + const ScrollingMapPage({super.key}) : super(const Icon(Icons.map), 'Scrolling map'); @override Widget build(BuildContext context) { @@ -45,15 +44,10 @@ class ScrollingMapBody extends StatelessWidget { width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), gestureRecognizers: // >{ - Factory( - () => EagerGestureRecognizer(), - ), + Factory(() => EagerGestureRecognizer()), }, ), ), @@ -70,19 +64,14 @@ class ScrollingMapBody extends StatelessWidget { const Text("This map doesn't consume the vertical drags."), const Padding( padding: EdgeInsets.only(bottom: 12.0), - child: Text( - 'It still gets other gestures (e.g scale or tap).', - ), + child: Text('It still gets other gestures (e.g scale or tap).'), ), Center( child: SizedBox( width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), markers: { Marker( markerId: const MarkerId('test_marker_id'), @@ -93,12 +82,9 @@ class ScrollingMapBody extends StatelessWidget { ), ), }, - gestureRecognizers: - >{ - Factory( - () => ScaleGestureRecognizer(), - ), - }, + gestureRecognizers: >{ + Factory(() => ScaleGestureRecognizer()), + }, ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/snapshot.dart index 6f1624234ec4..906b3de2ecff 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/snapshot.dart @@ -53,8 +53,7 @@ class _SnapshotBodyState extends State<_SnapshotBody> { TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = await _mapController - ?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/tile_overlay.dart index cefa70eb34d5..3f3a26b6ab89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/lib/tile_overlay.dart @@ -14,8 +14,7 @@ import 'example_google_map.dart'; import 'page.dart'; class TileOverlayPage extends GoogleMapExampleAppPage { - const TileOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Tile overlay'); + const TileOverlayPage({super.key}) : super(const Icon(Icons.map), 'Tile overlay'); @override Widget build(BuildContext context) { @@ -90,18 +89,9 @@ class TileOverlayBodyState extends State { ), ), ), - TextButton( - onPressed: _addTileOverlay, - child: const Text('Add tile overlay'), - ), - TextButton( - onPressed: _removeTileOverlay, - child: const Text('Remove tile overlay'), - ), - TextButton( - onPressed: _clearTileCache, - child: const Text('Clear tile cache'), - ), + TextButton(onPressed: _addTileOverlay, child: const Text('Add tile overlay')), + TextButton(onPressed: _removeTileOverlay, child: const Text('Remove tile overlay')), + TextButton(onPressed: _clearTileCache, child: const Text('Clear tile cache')), ], ); } @@ -125,22 +115,14 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/test/example_google_map_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/test/example_google_map_test.dart index 261fc473e8bb..6aa25acb4b63 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/test/example_google_map_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/test/example_google_map_test.dart @@ -107,17 +107,12 @@ void main() { const p1 = Polygon(polygonId: PolygonId('polygon_1')); const p2 = Polygon(polygonId: PolygonId('polygon_2')); const p3 = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1); - const p3updated = Polygon( - polygonId: PolygonId('polygon_3'), - strokeWidth: 2, - ); + const p3updated = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polygons: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polygons: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -149,9 +144,7 @@ void main() { // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polylines: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polylines: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -163,9 +156,7 @@ void main() { expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[1].polylinesToAdd, {p3}); - expect(map.polylineUpdates[1].polylineIdsToRemove, { - p2.polylineId, - }); + expect(map.polylineUpdates[1].polylineIdsToRemove, {p2.polylineId}); expect(map.polylineUpdates[2].polylinesToChange, {p3updated}); expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/test/fake_google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter_ios/example/test/fake_google_maps_flutter_platform.dart index 899a7709c548..3e8beefc78c4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/example/test/fake_google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/example/test/fake_google_maps_flutter_platform.dart @@ -17,8 +17,7 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { List createdIds = []; /// A map of creation IDs to fake map instances. - Map mapInstances = - {}; + Map mapInstances = {}; PlatformMapStateRecorder get lastCreatedMap => mapInstances[createdIds.last]!; @@ -41,46 +40,31 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { Future init(int mapId) async {} @override - Future updateMapConfiguration( - MapConfiguration update, { - required int mapId, - }) async { + Future updateMapConfiguration(MapConfiguration update, {required int mapId}) async { mapInstances[mapId]?.mapConfiguration = update; await _fakeDelay(); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { mapInstances[mapId]?.markerUpdates.add(markerUpdates); await _fakeDelay(); } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { mapInstances[mapId]?.polygonUpdates.add(polygonUpdates); await _fakeDelay(); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { mapInstances[mapId]?.polylineUpdates.add(polylineUpdates); await _fakeDelay(); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { mapInstances[mapId]?.circleUpdates.add(circleUpdates); await _fakeDelay(); } @@ -113,16 +97,10 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async {} + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async {} @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future animateCameraWithConfiguration( @@ -132,55 +110,34 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { }) async {} @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future setMapStyle(String? mapStyle, {required int mapId}) async {} @override Future getVisibleRegion({required int mapId}) async { - return LatLngBounds( - southwest: const LatLng(0, 0), - northeast: const LatLng(0, 0), - ); + return LatLngBounds(southwest: const LatLng(0, 0), northeast: const LatLng(0, 0)); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return const ScreenCoordinate(x: 0, y: 0); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return const LatLng(0, 0); } @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return false; } @@ -312,24 +269,14 @@ class PlatformMapStateRecorder { this.mapConfiguration = const MapConfiguration(), }) { clusterManagerUpdates.add( - ClusterManagerUpdates.from( - const {}, - mapObjects.clusterManagers, - ), + ClusterManagerUpdates.from(const {}, mapObjects.clusterManagers), ); groundOverlayUpdates.add( - GroundOverlayUpdates.from( - const {}, - mapObjects.groundOverlays, - ), + GroundOverlayUpdates.from(const {}, mapObjects.groundOverlays), ); markerUpdates.add(MarkerUpdates.from(const {}, mapObjects.markers)); - polygonUpdates.add( - PolygonUpdates.from(const {}, mapObjects.polygons), - ); - polylineUpdates.add( - PolylineUpdates.from(const {}, mapObjects.polylines), - ); + polygonUpdates.add(PolygonUpdates.from(const {}, mapObjects.polygons)); + polylineUpdates.add(PolylineUpdates.from(const {}, mapObjects.polylines)); circleUpdates.add(CircleUpdates.from(const {}, mapObjects.circles)); tileOverlaySets.add(mapObjects.tileOverlays); } @@ -343,8 +290,6 @@ class PlatformMapStateRecorder { final List polylineUpdates = []; final List circleUpdates = []; final List> tileOverlaySets = >[]; - final List clusterManagerUpdates = - []; - final List groundOverlayUpdates = - []; + final List clusterManagerUpdates = []; + final List groundOverlayUpdates = []; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart index a0057b9fdc54..a0d3b46c6cbb 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_map_inspector_ios.dart @@ -14,9 +14,8 @@ import 'messages.g.dart'; class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { /// Creates an inspector API instance for a given map ID from /// [inspectorProvider]. - GoogleMapsInspectorIOS( - MapsInspectorApi? Function(int mapId) inspectorProvider, - ) : _inspectorProvider = inspectorProvider; + GoogleMapsInspectorIOS(MapsInspectorApi? Function(int mapId) inspectorProvider) + : _inspectorProvider = inspectorProvider; final MapsInspectorApi? Function(int mapId) _inspectorProvider; @@ -53,17 +52,12 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { @override Future getMinMaxZoomLevels({required int mapId}) async { - final PlatformZoomRange zoomLevels = await _inspectorProvider( - mapId, - )!.getZoomRange(); + final PlatformZoomRange zoomLevels = await _inspectorProvider(mapId)!.getZoomRange(); return MinMaxZoomPreference(zoomLevels.min, zoomLevels.max); } @override - Future getTileOverlayInfo( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) async { final PlatformTileLayer? tileInfo = await _inspectorProvider( mapId, )!.getTileOverlayInfo(tileOverlayId.value); @@ -83,10 +77,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { bool supportsGettingHeatmapInfo() => true; @override - Future getHeatmapInfo( - HeatmapId heatmapId, { - required int mapId, - }) async { + Future getHeatmapInfo(HeatmapId heatmapId, {required int mapId}) async { final PlatformHeatmap? heatmapInfo = await _inspectorProvider( mapId, )!.getHeatmapInfo(heatmapId.value); @@ -140,24 +131,15 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { transparency: groundOverlayInfo.transparency, visible: groundOverlayInfo.visible, clickable: groundOverlayInfo.clickable, - anchor: Offset( - groundOverlayInfo.anchor!.x, - groundOverlayInfo.anchor!.y, - ), + anchor: Offset(groundOverlayInfo.anchor!.x, groundOverlayInfo.anchor!.y), zoomLevel: groundOverlayInfo.zoomLevel, ); } else if (bounds != null) { return GroundOverlay.fromBounds( groundOverlayId: groundOverlayId, bounds: LatLngBounds( - southwest: LatLng( - bounds.southwest.latitude, - bounds.southwest.longitude, - ), - northeast: LatLng( - bounds.northeast.latitude, - bounds.northeast.longitude, - ), + southwest: LatLng(bounds.southwest.latitude, bounds.southwest.longitude), + northeast: LatLng(bounds.northeast.latitude, bounds.northeast.longitude), ), image: dummyImage, zIndex: groundOverlayInfo.zIndex, @@ -202,13 +184,8 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { required int mapId, required ClusterManagerId clusterManagerId, }) async { - return (await _inspectorProvider( - mapId, - )!.getClusters(clusterManagerId.value)) - .map( - (PlatformCluster cluster) => - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ) + return (await _inspectorProvider(mapId)!.getClusters(clusterManagerId.value)) + .map((PlatformCluster cluster) => GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)) .toList(); } @@ -221,19 +198,14 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { mapId, )!.getCameraPosition(); return CameraPosition( - target: LatLng( - cameraPosition.target.latitude, - cameraPosition.target.longitude, - ), + target: LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude), bearing: cameraPosition.bearing, tilt: cameraPosition.tilt, zoom: cameraPosition.zoom, ); } - static HeatmapGradient? _deserializeHeatmapGradient( - PlatformHeatmapGradient? gradient, - ) { + static HeatmapGradient? _deserializeHeatmapGradient(PlatformHeatmapGradient? gradient) { if (gradient == null) { return null; } @@ -243,12 +215,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { _mapEnumerated( gradient.colors, (PlatformColor color, int i) => HeatmapGradientColor( - Color.from( - red: color.red, - green: color.green, - blue: color.blue, - alpha: color.alpha, - ), + Color.from(red: color.red, green: color.green, blue: color.blue, alpha: color.alpha), gradient.startPoints[i], ), ).toList(), @@ -256,9 +223,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { ); } - static WeightedLatLng _deserializeWeightedLatLng( - PlatformWeightedLatLng weightedLatLng, - ) { + static WeightedLatLng _deserializeWeightedLatLng(PlatformWeightedLatLng weightedLatLng) { return WeightedLatLng( LatLng(weightedLatLng.point.latitude, weightedLatLng.point.longitude), weight: weightedLatLng.weight, @@ -266,10 +231,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { } } -Iterable _mapEnumerated( - Iterable iterable, - E Function(T, int) fn, -) sync* { +Iterable _mapEnumerated(Iterable iterable, E Function(T, int) fn) sync* { var index = 0; for (final item in iterable) { yield fn(item, index++); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart index c1709a97ad52..c0c8db027c8d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/google_maps_flutter_ios.dart @@ -43,9 +43,8 @@ class UnknownMapIDError extends Error { /// An implementation of [GoogleMapsFlutterPlatform] for iOS. class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Creates a new Android maps implementation instance. - GoogleMapsFlutterIOS({ - @visibleForTesting MapsApi Function(int mapId)? apiProvider, - }) : _apiProvider = apiProvider ?? _productionApiProvider; + GoogleMapsFlutterIOS({@visibleForTesting MapsApi Function(int mapId)? apiProvider}) + : _apiProvider = apiProvider ?? _productionApiProvider; /// Registers the iOS implementation of GoogleMapsFlutterPlatform. static void registerWith() { @@ -59,8 +58,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// The per-map handlers for callbacks from the host side. @visibleForTesting - final Map hostMapHandlers = - {}; + final Map hostMapHandlers = {}; /// Accesses the MapsApi associated to the passed mapId. MapsApi _hostApi(int mapId) { @@ -84,8 +82,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { mapId, _mapEventStreamController, tileOverlayProvider: (TileOverlayId tileOverlayId) { - final Map? tileOverlaysForMap = - _tileOverlays[mapId]; + final Map? tileOverlaysForMap = _tileOverlays[mapId]; return tileOverlaysForMap?[tileOverlayId]; }, ); @@ -127,9 +124,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { StreamController>.broadcast(); // Returns a filtered view of the events in the _controller, by mapId. - Stream> _events(int mapId) => _mapEventStreamController - .stream - .where((MapEvent event) => event.mapId == mapId); + Stream> _events(int mapId) => + _mapEventStreamController.stream.where((MapEvent event) => event.mapId == mapId); @override Stream onCameraMoveStarted({required int mapId}) { @@ -207,30 +203,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateMapConfiguration( - MapConfiguration configuration, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromMapConfiguration(configuration), - ); + Future updateMapConfiguration(MapConfiguration configuration, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromMapConfiguration(configuration)); } @override - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromOptionsJson(optionsUpdate), - ); + Future updateMapOptions(Map optionsUpdate, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromOptionsJson(optionsUpdate)); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) { return _hostApi(mapId).updateMarkers( markerUpdates.markersToAdd.map(_platformMarkerFromMarker).toList(), markerUpdates.markersToChange.map(_platformMarkerFromMarker).toList(), @@ -239,42 +226,25 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) { return _hostApi(mapId).updatePolygons( polygonUpdates.polygonsToAdd.map(_platformPolygonFromPolygon).toList(), polygonUpdates.polygonsToChange.map(_platformPolygonFromPolygon).toList(), - polygonUpdates.polygonIdsToRemove - .map((PolygonId id) => id.value) - .toList(), + polygonUpdates.polygonIdsToRemove.map((PolygonId id) => id.value).toList(), ); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) { return _hostApi(mapId).updatePolylines( - polylineUpdates.polylinesToAdd - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylinesToChange - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylineIdsToRemove - .map((PolylineId id) => id.value) - .toList(), + polylineUpdates.polylinesToAdd.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylinesToChange.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylineIdsToRemove.map((PolylineId id) => id.value).toList(), ); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) { return _hostApi(mapId).updateCircles( circleUpdates.circlesToAdd.map(_platformCircleFromCircle).toList(), circleUpdates.circlesToChange.map(_platformCircleFromCircle).toList(), @@ -283,41 +253,26 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) { return _hostApi(mapId).updateHeatmaps( heatmapUpdates.heatmapsToAdd.map(_platformHeatmapFromHeatmap).toList(), heatmapUpdates.heatmapsToChange.map(_platformHeatmapFromHeatmap).toList(), - heatmapUpdates.heatmapIdsToRemove - .map((HeatmapId id) => id.value) - .toList(), + heatmapUpdates.heatmapIdsToRemove.map((HeatmapId id) => id.value).toList(), ); } @override - Future updateTileOverlays({ - required Set newTileOverlays, - required int mapId, - }) { - final Map? currentTileOverlays = - _tileOverlays[mapId]; + Future updateTileOverlays({required Set newTileOverlays, required int mapId}) { + final Map? currentTileOverlays = _tileOverlays[mapId]; final Set previousSet = currentTileOverlays != null ? currentTileOverlays.values.toSet() : {}; final updates = _TileOverlayUpdates.from(previousSet, newTileOverlays); _tileOverlays[mapId] = keyTileOverlayId(newTileOverlays); return _hostApi(mapId).updateTileOverlays( - updates.tileOverlaysToAdd - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlaysToChange - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlayIdsToRemove - .map((TileOverlayId id) => id.value) - .toList(), + updates.tileOverlaysToAdd.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlaysToChange.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlayIdsToRemove.map((TileOverlayId id) => id.value).toList(), ); } @@ -356,17 +311,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { groundOverlayUpdates.groundOverlaysToChange .map(_platformGroundOverlayFromGroundOverlay) .toList(), - groundOverlayUpdates.groundOverlayIdsToRemove - .map((GroundOverlayId id) => id.value) - .toList(), + groundOverlayUpdates.groundOverlayIdsToRemove.map((GroundOverlayId id) => id.value).toList(), ); } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) { return _hostApi(mapId).clearTileCache(tileOverlayId.value); } @@ -393,16 +343,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) { - return _hostApi( - mapId, - ).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); + return _hostApi(mapId).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); } @override Future setMapStyle(String? mapStyle, {required int mapId}) async { - final String? errorDescription = await _hostApi( - mapId, - ).setStyle(mapStyle ?? ''); + final String? errorDescription = await _hostApi(mapId).setStyle(mapStyle ?? ''); if (errorDescription != null) { throw MapStyleException(errorDescription); } @@ -410,32 +356,20 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future getVisibleRegion({required int mapId}) async { - return _latLngBoundsFromPlatformLatLngBounds( - await _hostApi(mapId).getVisibleRegion(), - ); + return _latLngBoundsFromPlatformLatLngBounds(await _hostApi(mapId).getVisibleRegion()); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return _screenCoordinateFromPlatformPoint( - await _hostApi( - mapId, - ).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), + await _hostApi(mapId).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), ); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return _latLngFromPlatformLatLng( - await _hostApi( - mapId, - ).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), + await _hostApi(mapId).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), ); } @@ -450,10 +384,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) { return _hostApi(mapId).isInfoWindowShown(markerId.value); } @@ -497,21 +428,11 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { widgetConfiguration.initialCameraPosition, ), mapConfiguration: mapConfiguration, - initialMarkers: mapObjects.markers - .map(_platformMarkerFromMarker) - .toList(), - initialPolygons: mapObjects.polygons - .map(_platformPolygonFromPolygon) - .toList(), - initialPolylines: mapObjects.polylines - .map(_platformPolylineFromPolyline) - .toList(), - initialCircles: mapObjects.circles - .map(_platformCircleFromCircle) - .toList(), - initialHeatmaps: mapObjects.heatmaps - .map(_platformHeatmapFromHeatmap) - .toList(), + initialMarkers: mapObjects.markers.map(_platformMarkerFromMarker).toList(), + initialPolygons: mapObjects.polygons.map(_platformPolygonFromPolygon).toList(), + initialPolylines: mapObjects.polylines.map(_platformPolylineFromPolyline).toList(), + initialCircles: mapObjects.circles.map(_platformCircleFromCircle).toList(), + initialHeatmaps: mapObjects.heatmaps.map(_platformHeatmapFromHeatmap).toList(), initialTileOverlays: mapObjects.tileOverlays .map(_platformTileOverlayFromTileOverlay) .toList(), @@ -545,9 +466,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { onPlatformViewCreated, widgetConfiguration: widgetConfiguration, mapObjects: mapObjects, - mapConfiguration: _platformMapConfigurationFromMapConfiguration( - mapConfiguration, - ), + mapConfiguration: _platformMapConfigurationFromMapConfiguration(mapConfiguration), ); } @@ -629,19 +548,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static ScreenCoordinate _screenCoordinateFromPlatformPoint( - PlatformPoint point, - ) { + static ScreenCoordinate _screenCoordinateFromPlatformPoint(PlatformPoint point) { return ScreenCoordinate(x: point.x.round(), y: point.y.round()); } - static PlatformPoint _platformPointFromScreenCoordinate( - ScreenCoordinate coordinate, - ) { - return PlatformPoint( - x: coordinate.x.toDouble(), - y: coordinate.y.toDouble(), - ); + static PlatformPoint _platformPointFromScreenCoordinate(ScreenCoordinate coordinate) { + return PlatformPoint(x: coordinate.x.toDouble(), y: coordinate.y.toDouble()); } static PlatformPoint _platformPointFromOffset(Offset offset) { @@ -670,9 +582,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { final HeatmapGradient? gradient = heatmap.gradient; return PlatformHeatmap( heatmapId: heatmap.heatmapId.value, - data: heatmap.data - .map(_platformWeightedLatLngFromWeightedLatLng) - .toList(), + data: heatmap.data.map(_platformWeightedLatLngFromWeightedLatLng).toList(), gradient: _platformHeatmapGradientFromHeatmapGradient(gradient), opacity: heatmap.opacity, radius: heatmap.radius.radius, @@ -691,16 +601,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { colors: gradient.colors .map((HeatmapGradientColor c) => _platformColorFromColor(c.color)) .toList(), - startPoints: gradient.colors - .map((HeatmapGradientColor c) => c.startPoint) - .toList(), + startPoints: gradient.colors.map((HeatmapGradientColor c) => c.startPoint).toList(), colorMapSize: gradient.colorMapSize, ); } - static PlatformInfoWindow _platformInfoWindowFromInfoWindow( - InfoWindow window, - ) { + static PlatformInfoWindow _platformInfoWindowFromInfoWindow(InfoWindow window) { return PlatformInfoWindow( title: window.title, snippet: window.snippet, @@ -724,9 +630,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { markerId: marker.markerId.value, clusterManagerId: marker.clusterManagerId?.value, collisionBehavior: marker is AdvancedMarker - ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( - marker.collisionBehavior, - ) + ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior(marker.collisionBehavior) : null, ); } @@ -736,9 +640,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ) { return PlatformGroundOverlay( groundOverlayId: groundOverlay.groundOverlayId.value, - anchor: groundOverlay.anchor != null - ? _platformPointFromOffset(groundOverlay.anchor!) - : null, + anchor: groundOverlay.anchor != null ? _platformPointFromOffset(groundOverlay.anchor!) : null, image: platformBitmapFromBitmapDescriptor(groundOverlay.image), position: groundOverlay.position != null ? _platformLatLngFromLatLng(groundOverlay.position!) @@ -754,12 +656,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolygon _platformPolygonFromPolygon(Polygon polygon) { - final List points = polygon.points - .map(_platformLatLngFromLatLng) - .toList(); - final List> holes = polygon.holes.map(( - List hole, - ) { + final List points = polygon.points.map(_platformLatLngFromLatLng).toList(); + final List> holes = polygon.holes.map((List hole) { return hole.map(_platformLatLngFromLatLng).toList(); }).toList(); return PlatformPolygon( @@ -777,9 +675,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolyline _platformPolylineFromPolyline(Polyline polyline) { - final List points = polyline.points - .map(_platformLatLngFromLatLng) - .toList(); + final List points = polyline.points.map(_platformLatLngFromLatLng).toList(); final List pattern = polyline.patterns .map(platformPatternItemFromPatternItem) .toList(); @@ -797,9 +693,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static PlatformTileOverlay _platformTileOverlayFromTileOverlay( - TileOverlay tileOverlay, - ) { + static PlatformTileOverlay _platformTileOverlayFromTileOverlay(TileOverlay tileOverlay) { return PlatformTileOverlay( tileOverlayId: tileOverlay.tileOverlayId.value, fadeIn: tileOverlay.fadeIn, @@ -813,22 +707,16 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { static PlatformClusterManager _platformClusterManagerFromClusterManager( ClusterManager clusterManager, ) { - return PlatformClusterManager( - identifier: clusterManager.clusterManagerId.value, - ); + return PlatformClusterManager(identifier: clusterManager.clusterManagerId.value); } - static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate( - CameraUpdate update, - ) { + static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate(CameraUpdate update) { switch (update.updateType) { case CameraUpdateType.newCameraPosition: update as CameraUpdateNewCameraPosition; return PlatformCameraUpdate( cameraUpdate: PlatformCameraUpdateNewCameraPosition( - cameraPosition: _platformCameraPositionFromCameraPosition( - update.cameraPosition, - ), + cameraPosition: _platformCameraPositionFromCameraPosition(update.cameraPosition), ), ); case CameraUpdateType.newLatLng: @@ -856,9 +744,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomTo: update as CameraUpdateZoomTo; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom)); case CameraUpdateType.zoomBy: update as CameraUpdateZoomBy; final Offset? focus = update.focus; @@ -870,30 +756,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomIn: update as CameraUpdateZoomIn; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: false), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: false)); case CameraUpdateType.zoomOut: update as CameraUpdateZoomOut; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: true), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: true)); case CameraUpdateType.scrollBy: update as CameraUpdateScrollBy; return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateScrollBy( - dx: update.dx, - dy: update.dy, - ), + cameraUpdate: PlatformCameraUpdateScrollBy(dx: update.dx, dy: update.dy), ); } } /// Converts [MapBitmapScaling] from platform interface to [PlatformMapBitmapScaling] Pigeon. @visibleForTesting - static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling( - MapBitmapScaling scaling, - ) { + static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling(MapBitmapScaling scaling) { switch (scaling) { case MapBitmapScaling.auto: return PlatformMapBitmapScaling.auto; @@ -913,8 +790,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [MarkersCollisionBehavior] from platform interface to /// [PlatformMarkerCollisionBehavior] Pigeon. @visibleForTesting - static PlatformMarkerCollisionBehavior - platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( + static PlatformMarkerCollisionBehavior platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( MarkerCollisionBehavior collisionBehavior, ) { switch (collisionBehavior) { @@ -937,14 +813,10 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [BitmapDescriptor] from platform interface to [PlatformBitmap] pigeon. @visibleForTesting - static PlatformBitmap platformBitmapFromBitmapDescriptor( - BitmapDescriptor bitmap, - ) { + static PlatformBitmap platformBitmapFromBitmapDescriptor(BitmapDescriptor bitmap) { switch (bitmap) { case final DefaultMarker marker: - return PlatformBitmap( - bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble()), - ); + return PlatformBitmap(bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble())); // Clients may still use this deprecated format, so it must be supported. // ignore: deprecated_member_use case final BytesBitmap bytes: @@ -974,9 +846,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapAssetMap( assetName: asset.assetName, - bitmapScaling: platformMapBitmapScalingFromScaling( - asset.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(asset.bitmapScaling), imagePixelRatio: asset.imagePixelRatio, width: asset.width, height: asset.height, @@ -986,9 +856,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapBytesMap( byteData: bytes.byteData, - bitmapScaling: platformMapBitmapScalingFromScaling( - bytes.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(bytes.bitmapScaling), imagePixelRatio: bytes.imagePixelRatio, width: bytes.width, height: bytes.height, @@ -1026,9 +894,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { bitmap: PlatformBitmapPinConfig( backgroundColor: backgroundColor, borderColor: borderColor, - glyphBitmap: platformBitmapFromBitmapDescriptor( - bitmapGlyph.bitmap, - ), + glyphBitmap: platformBitmapFromBitmapDescriptor(bitmapGlyph.bitmap), ), ); case null: @@ -1050,10 +916,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { 'Glyph type "${pinConfig.glyph.runtimeType}" has not been implemented', ); default: - throw ArgumentError( - 'Unrecognized type of bitmap ${bitmap.runtimeType}', - 'bitmap', - ); + throw ArgumentError('Unrecognized type of bitmap ${bitmap.runtimeType}', 'bitmap'); } } } @@ -1063,11 +926,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { class HostMapMessageHandler implements MapsCallbackApi { /// Creates a new handler that listens for events from map [mapId], and /// broadcasts them to [streamController]. - HostMapMessageHandler( - this.mapId, - this.streamController, { - required this.tileOverlayProvider, - }) { + HostMapMessageHandler(this.mapId, this.streamController, {required this.tileOverlayProvider}) { MapsCallbackApi.setUp(this, messageChannelSuffix: mapId.toString()); } @@ -1092,17 +951,11 @@ class HostMapMessageHandler implements MapsCallbackApi { PlatformPoint location, int zoom, ) async { - final TileOverlay? tileOverlay = tileOverlayProvider( - TileOverlayId(tileOverlayId), - ); + final TileOverlay? tileOverlay = tileOverlayProvider(TileOverlayId(tileOverlayId)); final TileProvider? tileProvider = tileOverlay?.tileProvider; final Tile tile = tileProvider == null ? TileProvider.noTile - : await tileProvider.getTile( - location.x.round(), - location.y.round(), - zoom, - ); + : await tileProvider.getTile(location.x.round(), location.y.round(), zoom); return _platformTileFromTile(tile); } @@ -1139,10 +992,7 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onClusterTap(PlatformCluster cluster) { streamController.add( - ClusterTapEvent( - mapId, - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ), + ClusterTapEvent(mapId, GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)), ); } @@ -1153,41 +1003,27 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onLongPress(PlatformLatLng position) { - streamController.add( - MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position))); } @override void onMarkerDrag(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragStart(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragStartEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragStartEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragEnd(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEndEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEndEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @@ -1208,35 +1044,24 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onGroundOverlayTap(String groundOverlayId) { - streamController.add( - GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId)), - ); + streamController.add(GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId))); } @override void onTap(PlatformLatLng position) { - streamController.add( - MapTapEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapTapEvent(mapId, _latLngFromPlatformLatLng(position))); } } PlatformColor _platformColorFromColor(Color color) { - return PlatformColor( - red: color.r, - green: color.g, - blue: color.b, - alpha: color.a, - ); + return PlatformColor(red: color.r, green: color.g, blue: color.b, alpha: color.a); } LatLng _latLngFromPlatformLatLng(PlatformLatLng latLng) { return LatLng(latLng.latitude, latLng.longitude); } -LatLngBounds _latLngBoundsFromPlatformLatLngBounds( - PlatformLatLngBounds bounds, -) { +LatLngBounds _latLngBoundsFromPlatformLatLngBounds(PlatformLatLngBounds bounds) { return LatLngBounds( southwest: _latLngFromPlatformLatLng(bounds.southwest), northeast: _latLngFromPlatformLatLng(bounds.northeast), @@ -1247,9 +1072,7 @@ PlatformLatLng _platformLatLngFromLatLng(LatLng latLng) { return PlatformLatLng(latitude: latLng.latitude, longitude: latLng.longitude); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( - LatLngBounds? bounds, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds(LatLngBounds? bounds) { if (bounds == null) { return null; } @@ -1259,9 +1082,7 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( ); } -PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng( - WeightedLatLng weightedLatLng, -) { +PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng(WeightedLatLng weightedLatLng) { return PlatformWeightedLatLng( point: _platformLatLngFromLatLng(weightedLatLng.point), weight: weightedLatLng.weight, @@ -1273,9 +1094,7 @@ PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBounds( ) { return bounds == null ? null - : PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds), - ); + : PlatformCameraTargetBounds(bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds)); } PlatformTile _platformTileFromTile(Tile tile) { @@ -1306,12 +1125,8 @@ PlatformMapType? _platformMapTypeFromMapType(MapType? type) { return PlatformMapType.normal; } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference( - MinMaxZoomPreference? zoomPref, -) { - return zoomPref == null - ? null - : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference(MinMaxZoomPreference? zoomPref) { + return zoomPref == null ? null : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); } PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { @@ -1325,18 +1140,14 @@ PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { ); } -PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( - MapConfiguration config, -) { +PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration(MapConfiguration config) { return PlatformMapConfiguration( compassEnabled: config.compassEnabled, cameraTargetBounds: _platformCameraTargetBoundsFromCameraTargetBounds( config.cameraTargetBounds, ), mapType: _platformMapTypeFromMapType(config.mapType), - minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference( - config.minMaxZoomPreference, - ), + minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference(config.minMaxZoomPreference), rotateGesturesEnabled: config.rotateGesturesEnabled, scrollGesturesEnabled: config.scrollGesturesEnabled, tiltGesturesEnabled: config.tiltGesturesEnabled, @@ -1348,9 +1159,7 @@ PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( indoorViewEnabled: config.indoorViewEnabled, trafficEnabled: config.trafficEnabled, buildingsEnabled: config.buildingsEnabled, - markerType: _platformMarkerTypeFromMarkerType( - config.markerType ?? MarkerType.marker, - ), + markerType: _platformMarkerTypeFromMarkerType(config.markerType ?? MarkerType.marker), mapId: config.mapId, style: config.style, ); @@ -1374,14 +1183,11 @@ PlatformMarkerType _platformMarkerTypeFromMarkerType(MarkerType markerType) { } // For supporting the deprecated updateMapOptions API. -PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( - Map options, -) { +PlatformMapConfiguration _platformMapConfigurationFromOptionsJson(Map options) { // All of these hard-coded values and structures come from // google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart // to support this legacy API that relied on cross-package magic strings. - final List? padding = (options['padding'] as List?) - ?.cast(); + final List? padding = (options['padding'] as List?)?.cast(); final mapType = options['mapType'] as int?; return PlatformMapConfiguration( compassEnabled: options['compassEnabled'] as bool?, @@ -1416,9 +1222,7 @@ PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( ); } -PlatformCameraPosition _platformCameraPositionFromCameraPosition( - CameraPosition position, -) { +PlatformCameraPosition _platformCameraPositionFromCameraPosition(CameraPosition position) { return PlatformCameraPosition( bearing: position.bearing, target: _platformLatLngFromLatLng(position.target), @@ -1446,9 +1250,7 @@ PlatformLatLng _platformLatLngFromLatLngJson(Object latLngJson) { return PlatformLatLng(latitude: list[0], longitude: list[1]); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( - Object? boundsJson, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson(Object? boundsJson) { if (boundsJson == null) { return null; } @@ -1460,28 +1262,24 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( ); } -PlatformCameraTargetBounds? -_platformCameraTargetBoundsFromCameraTargetBoundsJson(Object? targetJson) { +PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBoundsJson( + Object? targetJson, +) { if (targetJson == null) { return null; } // See `CameraTargetBounds.toJson`. return PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBoundsJson( - (targetJson as List)[0], - ), + bounds: _platformLatLngBoundsFromLatLngBoundsJson((targetJson as List)[0]), ); } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson( - Object? zoomPrefsJson, -) { +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson(Object? zoomPrefsJson) { if (zoomPrefsJson == null) { return null; } // See `MinMaxZoomPreference.toJson`. - final List minMaxZoom = (zoomPrefsJson as List) - .cast(); + final List minMaxZoom = (zoomPrefsJson as List).cast(); return PlatformZoomRange(min: minMaxZoom[0], max: minMaxZoom[1]); } @@ -1514,16 +1312,10 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { return PlatformPatternItem(type: PlatformPatternItemType.dot); case PatternItemType.dash: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.dash, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.dash, length: length); case PatternItemType.gap: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.gap, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.gap, length: length); } // The enum comes from a different package, which could get a new value at @@ -1540,15 +1332,13 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { // interface, and remove this copy. class _TileOverlayUpdates extends MapsObjectUpdates { /// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s. - _TileOverlayUpdates.from(super.previous, super.current) - : super.from(objectName: 'tileOverlay'); + _TileOverlayUpdates.from(super.previous, super.current) : super.from(objectName: 'tileOverlay'); /// Set of TileOverlays to be added in this update. Set get tileOverlaysToAdd => objectsToAdd; /// Set of TileOverlayIds to be removed in this update. - Set get tileOverlayIdsToRemove => - objectIdsToRemove.cast(); + Set get tileOverlayIdsToRemove => objectIdsToRemove.cast(); /// Set of TileOverlays to be changed in this update. Set get tileOverlaysToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart index 87fd64fcb0bc..be134f058b12 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/lib/src/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -187,8 +181,7 @@ class PlatformCameraUpdateNewCameraPosition { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewCameraPosition || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewCameraPosition || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -224,8 +217,7 @@ class PlatformCameraUpdateNewLatLng { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLng || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLng || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -241,10 +233,7 @@ class PlatformCameraUpdateNewLatLng { /// Pigeon equivalent of NewLatLngBounds class PlatformCameraUpdateNewLatLngBounds { - PlatformCameraUpdateNewLatLngBounds({ - required this.bounds, - required this.padding, - }); + PlatformCameraUpdateNewLatLngBounds({required this.bounds, required this.padding}); PlatformLatLngBounds bounds; @@ -269,8 +258,7 @@ class PlatformCameraUpdateNewLatLngBounds { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -311,8 +299,7 @@ class PlatformCameraUpdateNewLatLngZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -344,17 +331,13 @@ class PlatformCameraUpdateScrollBy { static PlatformCameraUpdateScrollBy decode(Object result) { result as List; - return PlatformCameraUpdateScrollBy( - dx: result[0]! as double, - dy: result[1]! as double, - ); + return PlatformCameraUpdateScrollBy(dx: result[0]! as double, dy: result[1]! as double); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateScrollBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateScrollBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -395,8 +378,7 @@ class PlatformCameraUpdateZoomBy { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -432,8 +414,7 @@ class PlatformCameraUpdateZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -469,8 +450,7 @@ class PlatformCameraUpdateZoomTo { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomTo || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomTo || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1255,14 +1235,7 @@ class PlatformTileOverlay { int tileSize; List _toList() { - return [ - tileOverlayId, - fadeIn, - transparency, - zIndex, - visible, - tileSize, - ]; + return [tileOverlayId, fadeIn, transparency, zIndex, visible, tileSize]; } Object encode() { @@ -1368,10 +1341,7 @@ class PlatformLatLng { static PlatformLatLng decode(Object result) { result as List; - return PlatformLatLng( - latitude: result[0]! as double, - longitude: result[1]! as double, - ); + return PlatformLatLng(latitude: result[0]! as double, longitude: result[1]! as double); } @override @@ -1451,16 +1421,13 @@ class PlatformCameraTargetBounds { static PlatformCameraTargetBounds decode(Object result) { result as List; - return PlatformCameraTargetBounds( - bounds: result[0] as PlatformLatLngBounds?, - ); + return PlatformCameraTargetBounds(bounds: result[0] as PlatformLatLngBounds?); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraTargetBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraTargetBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1630,20 +1597,16 @@ class PlatformMapViewCreationParams { initialPolygons: (result[4] as List?)!.cast(), initialPolylines: (result[5] as List?)!.cast(), initialHeatmaps: (result[6] as List?)!.cast(), - initialTileOverlays: (result[7] as List?)! - .cast(), - initialClusterManagers: (result[8] as List?)! - .cast(), - initialGroundOverlays: (result[9] as List?)! - .cast(), + initialTileOverlays: (result[7] as List?)!.cast(), + initialClusterManagers: (result[8] as List?)!.cast(), + initialGroundOverlays: (result[9] as List?)!.cast(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapViewCreationParams || - other.runtimeType != runtimeType) { + if (other is! PlatformMapViewCreationParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1770,8 +1733,7 @@ class PlatformMapConfiguration { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapConfiguration || - other.runtimeType != runtimeType) { + if (other is! PlatformMapConfiguration || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1841,10 +1803,7 @@ class PlatformSize { static PlatformSize decode(Object result) { result as List; - return PlatformSize( - width: result[0]! as double, - height: result[1]! as double, - ); + return PlatformSize(width: result[0]! as double, height: result[1]! as double); } @override @@ -1866,12 +1825,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); double red; @@ -1986,10 +1940,7 @@ class PlatformZoomRange { static PlatformZoomRange decode(Object result) { result as List; - return PlatformZoomRange( - min: result[0] as double?, - max: result[1] as double?, - ); + return PlatformZoomRange(min: result[0] as double?, max: result[1] as double?); } @override @@ -2076,8 +2027,7 @@ class PlatformBitmapDefaultMarker { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapDefaultMarker || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapDefaultMarker || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2109,10 +2059,7 @@ class PlatformBitmapBytes { static PlatformBitmapBytes decode(Object result) { result as List; - return PlatformBitmapBytes( - byteData: result[0]! as Uint8List, - size: result[1] as PlatformSize?, - ); + return PlatformBitmapBytes(byteData: result[0]! as Uint8List, size: result[1] as PlatformSize?); } @override @@ -2150,10 +2097,7 @@ class PlatformBitmapAsset { static PlatformBitmapAsset decode(Object result) { result as List; - return PlatformBitmapAsset( - name: result[0]! as String, - pkg: result[1] as String?, - ); + return PlatformBitmapAsset(name: result[0]! as String, pkg: result[1] as String?); } @override @@ -2175,11 +2119,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); String name; @@ -2207,8 +2147,7 @@ class PlatformBitmapAssetImage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapAssetImage || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapAssetImage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2568,9 +2507,7 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PlatformMapType.values[value]; case 130: final value = readValue(buffer) as int?; - return value == null - ? null - : PlatformMarkerCollisionBehavior.values[value]; + return value == null ? null : PlatformMarkerCollisionBehavior.values[value]; case 131: final value = readValue(buffer) as int?; return value == null ? null : PlatformJointType.values[value]; @@ -2721,9 +2658,7 @@ class MapsApi { /// /// Only non-null configuration values will result in updates; options with /// null values will remain unchanged. - Future updateMapConfiguration( - PlatformMapConfiguration configuration, - ) async { + Future updateMapConfiguration(PlatformMapConfiguration configuration) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.updateMapConfiguration$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2731,9 +2666,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [configuration], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([configuration]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2761,9 +2694,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2791,9 +2726,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2820,9 +2757,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2850,9 +2788,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2880,9 +2820,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2910,9 +2852,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2940,9 +2884,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2970,9 +2916,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2996,9 +2944,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [latLng], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([latLng]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3027,9 +2973,9 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [screenCoordinate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + screenCoordinate, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3088,9 +3034,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraUpdate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3107,10 +3051,7 @@ class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. - Future animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ) async { + Future animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.animateCamera$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3118,9 +3059,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate, durationMilliseconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraUpdate, + durationMilliseconds, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3173,9 +3115,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3199,9 +3139,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3226,9 +3164,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3261,9 +3197,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [style], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([style]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3315,9 +3249,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3436,20 +3368,14 @@ abstract class MapsCallbackApi { void onGroundOverlayTap(String groundOverlayId); /// Called to get data for a map tile. - Future getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + Future getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); static void setUp( MapsCallbackApi? api, { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMoveStarted$messageChannelSuffix', @@ -3488,8 +3414,7 @@ abstract class MapsCallbackApi { 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null.', ); final List args = (message as List?)!; - final PlatformCameraPosition? arg_cameraPosition = - (args[0] as PlatformCameraPosition?); + final PlatformCameraPosition? arg_cameraPosition = (args[0] as PlatformCameraPosition?); assert( arg_cameraPosition != null, 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null, expected non-null PlatformCameraPosition.', @@ -3998,13 +3923,11 @@ class MapsPlatformViewApi { /// Constructor for [MapsPlatformViewApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsPlatformViewApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsPlatformViewApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4019,9 +3942,7 @@ class MapsPlatformViewApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [type], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([type]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4042,13 +3963,11 @@ class MapsInspectorApi { /// Constructor for [MapsInspectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsInspectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsInspectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4287,9 +4206,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4304,9 +4221,7 @@ class MapsInspectorApi { } } - Future getGroundOverlayInfo( - String groundOverlayId, - ) async { + Future getGroundOverlayInfo(String groundOverlayId) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsInspectorApi.getGroundOverlayInfo$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4314,9 +4229,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [groundOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([groundOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4339,9 +4252,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [heatmapId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([heatmapId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4392,9 +4303,9 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [clusterManagerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + clusterManagerId, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4410,8 +4321,7 @@ class MapsInspectorApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/pigeons/messages.dart b/packages/google_maps_flutter/google_maps_flutter_ios/pigeons/messages.dart index 66e475c54232..a04e857d05fc 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/pigeons/messages.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/pigeons/messages.dart @@ -510,12 +510,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); final double red; final double green; @@ -587,11 +582,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); final String name; final double scale; final PlatformSize? size; @@ -685,10 +676,7 @@ abstract class MapsApi { /// Updates the set of custer managers for clusters on the map. @ObjCSelector('updateClusterManagersByAdding:removing:') - void updateClusterManagers( - List toAdd, - List idsToRemove, - ); + void updateClusterManagers(List toAdd, List idsToRemove); /// Updates the set of markers on the map. @ObjCSelector('updateMarkersByAdding:changing:removing:') @@ -750,10 +738,7 @@ abstract class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. @ObjCSelector('animateCameraWithUpdate:duration:') - void animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ); + void animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds); /// Gets the current map zoom level. @ObjCSelector('currentZoomLevel') @@ -866,11 +851,7 @@ abstract class MapsCallbackApi { /// Called to get data for a map tile. @async @ObjCSelector('tileWithOverlayIdentifier:location:zoom:') - PlatformTile getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + PlatformTile getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); } /// Dummy interface to force generation of the platform view creation params, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.dart index 486884bc81d1..c2fa99cac0dd 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.dart @@ -43,28 +43,18 @@ void main() { test('getScreenCoordinate converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const latLng = LatLng(10, 20); const expectedCoord = ScreenCoordinate(x: 30, y: 40); when(api.getScreenCoordinate(any)).thenAnswer( - (_) async => PlatformPoint( - x: expectedCoord.x.toDouble(), - y: expectedCoord.y.toDouble(), - ), + (_) async => PlatformPoint(x: expectedCoord.x.toDouble(), y: expectedCoord.y.toDouble()), ); - final ScreenCoordinate coord = await maps.getScreenCoordinate( - latLng, - mapId: mapId, - ); + final ScreenCoordinate coord = await maps.getScreenCoordinate(latLng, mapId: mapId); expect(coord, expectedCoord); - final VerificationResult verification = verify( - api.getScreenCoordinate(captureAny), - ); + final VerificationResult verification = verify(api.getScreenCoordinate(captureAny)); final passedLatLng = verification.captured[0] as PlatformLatLng; expect(passedLatLng.latitude, latLng.latitude); expect(passedLatLng.longitude, latLng.longitude); @@ -72,18 +62,14 @@ void main() { test('getLatLng converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const expectedLatLng = LatLng(10, 20); const coord = ScreenCoordinate(x: 30, y: 40); when(api.getLatLng(any)).thenAnswer( - (_) async => PlatformLatLng( - latitude: expectedLatLng.latitude, - longitude: expectedLatLng.longitude, - ), + (_) async => + PlatformLatLng(latitude: expectedLatLng.latitude, longitude: expectedLatLng.longitude), ); final LatLng latLng = await maps.getLatLng(coord, mapId: mapId); @@ -96,9 +82,7 @@ void main() { test('getVisibleRegion converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. final expectedBounds = LatLngBounds( @@ -124,9 +108,7 @@ void main() { test('moveCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.moveCamera(update, mapId: mapId); @@ -141,16 +123,12 @@ void main() { test('animateCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.animateCamera(update, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -161,24 +139,14 @@ void main() { test('animateCameraWithConfiguration calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); - const configuration = CameraUpdateAnimationConfiguration( - duration: Duration(seconds: 1), - ); + const configuration = CameraUpdateAnimationConfiguration(duration: Duration(seconds: 1)); expect(configuration.duration?.inSeconds, 1); - await maps.animateCameraWithConfiguration( - update, - configuration, - mapId: mapId, - ); + await maps.animateCameraWithConfiguration(update, configuration, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -191,9 +159,7 @@ void main() { test('getZoomLevel passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const expectedZoom = 4.2; when(api.getZoomLevel()).thenAnswer((_) async => expectedZoom); @@ -204,9 +170,7 @@ void main() { test('showInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.showMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -216,9 +180,7 @@ void main() { test('hideInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.hideMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -228,27 +190,17 @@ void main() { test('isInfoWindowShown calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; when(api.isInfoWindowShown(markedId)).thenAnswer((_) async => true); - expect( - await maps.isMarkerInfoWindowShown( - const MarkerId(markedId), - mapId: mapId, - ), - true, - ); + expect(await maps.isMarkerInfoWindowShown(const MarkerId(markedId), mapId: mapId), true); }); test('takeSnapshot calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final fakeSnapshot = Uint8List(10); when(api.takeSnapshot()).thenAnswer((_) async => fakeSnapshot); @@ -258,9 +210,7 @@ void main() { test('clearTileCache calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const tileOverlayId = 'overlay'; await maps.clearTileCache(const TileOverlayId(tileOverlayId), mapId: mapId); @@ -270,16 +220,11 @@ void main() { test('updateMapConfiguration passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = MapConfiguration( compassEnabled: true, @@ -288,9 +233,7 @@ void main() { ); await maps.updateMapConfiguration(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -319,16 +262,11 @@ void main() { test('updateMapOptions passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = { 'compassEnabled': true, @@ -337,9 +275,7 @@ void main() { }; await maps.updateMapOptions(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -368,19 +304,14 @@ void main() { test('updateCircles passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Circle(circleId: CircleId('1')); const object2old = Circle(circleId: CircleId('2')); final Circle object2new = object2old.copyWith(radiusParam: 42); const object3 = Circle(circleId: CircleId('3')); await maps.updateCircles( - CircleUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + CircleUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -427,17 +358,12 @@ void main() { test('updateClusterManagers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = ClusterManager(clusterManagerId: ClusterManagerId('1')); const object3 = ClusterManager(clusterManagerId: ClusterManagerId('3')); await maps.updateClusterManagers( - ClusterManagerUpdates.from( - {object1}, - {object3}, - ), + ClusterManagerUpdates.from({object1}, {object3}), mapId: mapId, ); @@ -458,19 +384,14 @@ void main() { test('updateMarkers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Marker(markerId: MarkerId('1')); const object2old = Marker(markerId: MarkerId('2')); final Marker object2new = object2old.copyWith(rotationParam: 42); const object3 = Marker(markerId: MarkerId('3')); await maps.updateMarkers( - MarkerUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + MarkerUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -495,9 +416,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -523,9 +442,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -543,21 +460,17 @@ void main() { test('updateMarkers passes expected arguments (AdvancedMarkers)', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final object1 = AdvancedMarker(markerId: const MarkerId('1')); final object2old = AdvancedMarker(markerId: const MarkerId('2')); final AdvancedMarker object2new = object2old.copyWith( rotationParam: 42, - collisionBehaviorParam: - advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, + collisionBehaviorParam: advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, ); final object3 = AdvancedMarker( markerId: const MarkerId('3'), - collisionBehavior: - advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, + collisionBehavior: advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, ); await maps.updateMarkers( MarkerUpdates.from( @@ -588,9 +501,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -622,9 +533,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -648,19 +557,14 @@ void main() { test('updatePolygons passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polygon(polygonId: PolygonId('1')); const object2old = Polygon(polygonId: PolygonId('2')); final Polygon object2new = object2old.copyWith(strokeWidthParam: 42); const object3 = Polygon(polygonId: PolygonId('3')); await maps.updatePolygons( - PolygonUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolygonUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -707,9 +611,7 @@ void main() { test('updatePolylines passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polyline(polylineId: PolylineId('1')); const object2old = Polyline(polylineId: PolylineId('2')); @@ -718,20 +620,14 @@ void main() { startCapParam: Cap.squareCap, endCapParam: Cap.buttCap, ); - final Cap customCap = Cap.customCapFromBitmap( - BitmapDescriptor.defaultMarker, - refWidth: 15, - ); + final Cap customCap = Cap.customCapFromBitmap(BitmapDescriptor.defaultMarker, refWidth: 15); final object3 = Polyline( polylineId: const PolylineId('3'), startCap: customCap, endCap: Cap.roundCap, ); await maps.updatePolylines( - PolylineUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolylineUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -746,10 +642,7 @@ void main() { expect(actual.consumesTapEvents, expected.consumeTapEvents); _expectColorsEqual(actual.color, expected.color); expect(actual.geodesic, expected.geodesic); - expect( - actual.jointType, - platformJointTypeFromJointType(expected.jointType), - ); + expect(actual.jointType, platformJointTypeFromJointType(expected.jointType)); expect(actual.visible, expected.visible); expect(actual.width, expected.width); expect(actual.zIndex, expected.zIndex); @@ -759,8 +652,7 @@ void main() { expect(point?.longitude, actual.points[i].longitude); } expect(actual.patterns.length, expected.patterns.length); - for (final (int i, PlatformPatternItem? pattern) - in actual.patterns.indexed) { + for (final (int i, PlatformPatternItem? pattern) in actual.patterns.indexed) { expect( pattern?.encode(), platformPatternItemFromPatternItem(expected.patterns[i]).encode(), @@ -781,9 +673,7 @@ void main() { test('updateTileOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = TileOverlay(tileOverlayId: TileOverlayId('1')); const object2old = TileOverlay(tileOverlayId: TileOverlayId('2')); @@ -830,9 +720,7 @@ void main() { test('updateGroundOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final image = AssetMapBitmap( 'assets/red_square.png', @@ -842,18 +730,12 @@ void main() { final object1 = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('1'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final object2old = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('2'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final GroundOverlay object2new = object2old.copyWith( @@ -895,22 +777,10 @@ void main() { expect(firstChanged.anchor?.x, object2new.anchor?.dx); expect(firstChanged.anchor?.y, object2new.anchor?.dy); expect(firstChanged.bearing, object2new.bearing); - expect( - firstChanged.bounds?.northeast.latitude, - object2new.bounds?.northeast.latitude, - ); - expect( - firstChanged.bounds?.northeast.longitude, - object2new.bounds?.northeast.longitude, - ); - expect( - firstChanged.bounds?.southwest.latitude, - object2new.bounds?.southwest.latitude, - ); - expect( - firstChanged.bounds?.southwest.longitude, - object2new.bounds?.southwest.longitude, - ); + expect(firstChanged.bounds?.northeast.latitude, object2new.bounds?.northeast.latitude); + expect(firstChanged.bounds?.northeast.longitude, object2new.bounds?.northeast.longitude); + expect(firstChanged.bounds?.southwest.latitude, object2new.bounds?.southwest.latitude); + expect(firstChanged.bounds?.southwest.longitude, object2new.bounds?.southwest.longitude); expect(firstChanged.visible, object2new.visible); expect(firstChanged.clickable, object2new.clickable); expect(firstChanged.zIndex, object2new.zIndex); @@ -932,22 +802,10 @@ void main() { expect(firstAdded.anchor?.x, object3.anchor?.dx); expect(firstAdded.anchor?.y, object3.anchor?.dy); expect(firstAdded.bearing, object3.bearing); - expect( - firstAdded.bounds?.northeast.latitude, - object3.bounds?.northeast.latitude, - ); - expect( - firstAdded.bounds?.northeast.longitude, - object3.bounds?.northeast.longitude, - ); - expect( - firstAdded.bounds?.southwest.latitude, - object3.bounds?.southwest.latitude, - ); - expect( - firstAdded.bounds?.southwest.longitude, - object3.bounds?.southwest.longitude, - ); + expect(firstAdded.bounds?.northeast.latitude, object3.bounds?.northeast.latitude); + expect(firstAdded.bounds?.northeast.longitude, object3.bounds?.northeast.longitude); + expect(firstAdded.bounds?.southwest.latitude, object3.bounds?.southwest.latitude); + expect(firstAdded.bounds?.southwest.longitude, object3.bounds?.southwest.longitude); expect(firstAdded.visible, object3.visible); expect(firstAdded.clickable, object3.clickable); expect(firstAdded.zIndex, object3.zIndex); @@ -957,48 +815,39 @@ void main() { expect(firstAdded.transparency, object3.transparency); expect( firstAdded.image.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.image, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.image).bitmap.runtimeType, ); } }); - test( - 'updateGroundOverlays throws assertion error on unsupported ground overlays', - () async { - const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + test('updateGroundOverlays throws assertion error on unsupported ground overlays', () async { + const mapId = 1; + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); - final image = AssetMapBitmap( - 'assets/red_square.png', - imagePixelRatio: 1.0, - bitmapScaling: MapBitmapScaling.none, - ); + final image = AssetMapBitmap( + 'assets/red_square.png', + imagePixelRatio: 1.0, + bitmapScaling: MapBitmapScaling.none, + ); - final object3 = GroundOverlay.fromPosition( - groundOverlayId: const GroundOverlayId('1'), - position: const LatLng(10, 20), - // Assert should be thrown because zoomLevel is not set for position-based - // ground overlay on iOS. - // ignore: avoid_redundant_argument_values - zoomLevel: null, - image: image, - ); + final object3 = GroundOverlay.fromPosition( + groundOverlayId: const GroundOverlayId('1'), + position: const LatLng(10, 20), + // Assert should be thrown because zoomLevel is not set for position-based + // ground overlay on iOS. + // ignore: avoid_redundant_argument_values + zoomLevel: null, + image: image, + ); - expect( - () async => maps.updateGroundOverlays( - GroundOverlayUpdates.from(const {}, { - object3, - }), - mapId: mapId, - ), - throwsAssertionError, - ); - }, - ); + expect( + () async => maps.updateGroundOverlays( + GroundOverlayUpdates.from(const {}, {object3}), + mapId: mapId, + ), + throwsAssertionError, + ); + }); test('markers send drag event to correct streams', () async { const mapId = 1; @@ -1008,19 +857,13 @@ void main() { final fakePosition = PlatformLatLng(latitude: 1.0, longitude: 1.0); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final markerDragStartStream = StreamQueue( maps.onMarkerDragStart(mapId: mapId), ); - final markerDragStream = StreamQueue( - maps.onMarkerDrag(mapId: mapId), - ); - final markerDragEndStream = StreamQueue( - maps.onMarkerDragEnd(mapId: mapId), - ); + final markerDragStream = StreamQueue(maps.onMarkerDrag(mapId: mapId)); + final markerDragEndStream = StreamQueue(maps.onMarkerDragEnd(mapId: mapId)); // Simulate messages from the native side. callbackHandler.onMarkerDragStart(dragStartId, fakePosition); @@ -1037,9 +880,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onMarkerTap(mapId: mapId)); @@ -1054,9 +895,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onCircleTap(mapId: mapId)); @@ -1083,13 +922,9 @@ void main() { ); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onClusterTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onClusterTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onClusterTap(cluster); @@ -1099,15 +934,9 @@ void main() { expect(eventValue.position.latitude, fakePosition.latitude); expect(eventValue.position.longitude, fakePosition.longitude); expect(eventValue.bounds.southwest.latitude, fakeBounds.southwest.latitude); - expect( - eventValue.bounds.southwest.longitude, - fakeBounds.southwest.longitude, - ); + expect(eventValue.bounds.southwest.longitude, fakeBounds.southwest.longitude); expect(eventValue.bounds.northeast.latitude, fakeBounds.northeast.latitude); - expect( - eventValue.bounds.northeast.longitude, - fakeBounds.northeast.longitude, - ); + expect(eventValue.bounds.northeast.longitude, fakeBounds.northeast.longitude); expect(eventValue.markerIds.length, markerIds.length); expect(eventValue.markerIds.first.value, markerIds.first); }); @@ -1117,13 +946,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolygonTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolygonTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolygonTap(objectId); @@ -1136,13 +961,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolylineTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolylineTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolylineTap(objectId); @@ -1155,13 +976,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onGroundOverlayTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onGroundOverlayTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onGroundOverlayTap(objectId); @@ -1171,9 +988,7 @@ void main() { test('moveCamera calls through with expected newCameraPosition', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); const position = CameraPosition(target: latLng); @@ -1182,24 +997,15 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; update as CameraUpdateNewCameraPosition; - expect( - typedUpdate.cameraPosition.target.latitude, - update.cameraPosition.target.latitude, - ); - expect( - typedUpdate.cameraPosition.target.longitude, - update.cameraPosition.target.longitude, - ); + expect(typedUpdate.cameraPosition.target.latitude, update.cameraPosition.target.latitude); + expect(typedUpdate.cameraPosition.target.longitude, update.cameraPosition.target.longitude); }); test('moveCamera calls through with expected newLatLng', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLng(latLng); @@ -1207,8 +1013,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; update as CameraUpdateNewLatLng; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1216,9 +1021,7 @@ void main() { test('moveCamera calls through with expected newLatLngBounds', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final latLng = LatLngBounds( northeast: const LatLng(10.0, 20.0), @@ -1229,33 +1032,18 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; update as CameraUpdateNewLatLngBounds; - expect( - typedUpdate.bounds.northeast.latitude, - update.bounds.northeast.latitude, - ); - expect( - typedUpdate.bounds.northeast.longitude, - update.bounds.northeast.longitude, - ); - expect( - typedUpdate.bounds.southwest.latitude, - update.bounds.southwest.latitude, - ); - expect( - typedUpdate.bounds.southwest.longitude, - update.bounds.southwest.longitude, - ); + expect(typedUpdate.bounds.northeast.latitude, update.bounds.northeast.latitude); + expect(typedUpdate.bounds.northeast.longitude, update.bounds.northeast.longitude); + expect(typedUpdate.bounds.southwest.latitude, update.bounds.southwest.latitude); + expect(typedUpdate.bounds.southwest.longitude, update.bounds.southwest.longitude); expect(typedUpdate.padding, update.padding); }); test('moveCamera calls through with expected newLatLngZoom', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLngZoom(latLng, 2.0); @@ -1263,8 +1051,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; update as CameraUpdateNewLatLngZoom; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1273,9 +1060,7 @@ void main() { test('moveCamera calls through with expected zoomBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const focus = Offset(10.0, 20.0); final CameraUpdate update = CameraUpdate.zoomBy(2.0, focus); @@ -1292,9 +1077,7 @@ void main() { test('moveCamera calls through with expected zoomTo', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomTo(2.0); await maps.moveCamera(update, mapId: mapId); @@ -1308,9 +1091,7 @@ void main() { test('moveCamera calls through with expected zoomIn', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomIn(); await maps.moveCamera(update, mapId: mapId); @@ -1323,9 +1104,7 @@ void main() { test('moveCamera calls through with expected zoomOut', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomOut(); await maps.moveCamera(update, mapId: mapId); @@ -1338,23 +1117,20 @@ void main() { test('MapBitmapScaling to PlatformMapBitmapScaling', () { expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.auto, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.auto), PlatformMapBitmapScaling.auto, ); expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.none, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.none), PlatformMapBitmapScaling.none, ); }); test('DefaultMarker bitmap to PlatformBitmap', () { final BitmapDescriptor bitmap = BitmapDescriptor.defaultMarkerWithHue(10.0); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapDefaultMarker; expect(typedBitmap.hue, 10.0); @@ -1368,8 +1144,9 @@ void main() { width: 100.0, height: 200.0, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapBytesMap; expect(typedBitmap.byteData, data); @@ -1381,14 +1158,10 @@ void main() { test('AssetMapBitmap bitmap to PlatformBitmap', () { const assetName = 'fake_asset_name'; - final bitmap = AssetMapBitmap( - assetName, - imagePixelRatio: 2.0, - width: 100.0, - height: 200.0, + final bitmap = AssetMapBitmap(assetName, imagePixelRatio: 2.0, width: 100.0, height: 200.0); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapAssetMap; expect(typedBitmap.assetName, assetName); @@ -1402,31 +1175,28 @@ void main() { const cloudMapId = '000000000000000'; // Dummy map ID. final passedCloudMapIdCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null) { - final String? passedMapId = - creationParams.mapConfiguration.mapId; - if (passedMapId != null) { - passedCloudMapIdCompleter.complete(passedMapId); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null) { + final String? passedMapId = creationParams.mapConfiguration.mapId; + if (passedMapId != null) { + passedCloudMapIdCompleter.complete(passedMapId); } } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1437,10 +1207,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: const MapConfiguration(mapId: cloudMapId), @@ -1462,30 +1229,25 @@ void main() { ) async { final passedMarkerTypeCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null && - !passedMarkerTypeCompleter.isCompleted) { - passedMarkerTypeCompleter.complete( - creationParams.mapConfiguration.markerType, - ); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null && !passedMarkerTypeCompleter.isCompleted) { + passedMarkerTypeCompleter.complete(creationParams.mapConfiguration.markerType); } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1496,10 +1258,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: MapConfiguration(markerType: markerType), @@ -1513,11 +1272,10 @@ void main() { testWidgets('passes advancedMarker when MarkerType.advancedMarker is set', ( WidgetTester tester, ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams( - tester, - MarkerType.advancedMarker, - ); + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.advancedMarker, + ); expect( passedMarkerType, @@ -1527,31 +1285,29 @@ void main() { ); }); - testWidgets('passes marker when MarkerType.marker is set', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, MarkerType.marker); + testWidgets('passes marker when MarkerType.marker is set', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.marker, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should pass marker on PlatformView creation when MarkerType.marker is set', + reason: 'Should pass marker on PlatformView creation when MarkerType.marker is set', ); }); - testWidgets('passes marker when markerType is null', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, null); + testWidgets('passes marker when markerType is null', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + null, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should default to marker on PlatformView creation when markerType is null', + reason: 'Should default to marker on PlatformView creation when markerType is null', ); }); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.mocks.dart index e4ff2b78e188..a386c6d1e16e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/test/google_maps_flutter_ios_test.mocks.dart @@ -29,14 +29,12 @@ class _FakePlatformPoint_0 extends _i1.SmartFake implements _i2.PlatformPoint { : super(parent, parentInvocation); } -class _FakePlatformLatLng_1 extends _i1.SmartFake - implements _i2.PlatformLatLng { +class _FakePlatformLatLng_1 extends _i1.SmartFake implements _i2.PlatformLatLng { _FakePlatformLatLng_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePlatformLatLngBounds_2 extends _i1.SmartFake - implements _i2.PlatformLatLngBounds { +class _FakePlatformLatLngBounds_2 extends _i1.SmartFake implements _i2.PlatformLatLngBounds { _FakePlatformLatLngBounds_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -46,315 +44,229 @@ class _FakePlatformLatLngBounds_2 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockMapsApi extends _i1.Mock implements _i2.MapsApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future waitForMap() => - (super.noSuchMethod( - Invocation.method(#waitForMap, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future waitForMap() => (super.noSuchMethod( + Invocation.method(#waitForMap, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future updateMapConfiguration( - _i2.PlatformMapConfiguration? configuration, - ) => + _i4.Future updateMapConfiguration(_i2.PlatformMapConfiguration? configuration) => (super.noSuchMethod( - Invocation.method(#updateMapConfiguration, [configuration]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#updateMapConfiguration, [configuration]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateCircles( List<_i2.PlatformCircle>? toAdd, List<_i2.PlatformCircle>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateHeatmaps( List<_i2.PlatformHeatmap>? toAdd, List<_i2.PlatformHeatmap>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateClusterManagers( List<_i2.PlatformClusterManager>? toAdd, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateMarkers( List<_i2.PlatformMarker>? toAdd, List<_i2.PlatformMarker>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolygons( List<_i2.PlatformPolygon>? toAdd, List<_i2.PlatformPolygon>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolylines( List<_i2.PlatformPolyline>? toAdd, List<_i2.PlatformPolyline>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateTileOverlays( List<_i2.PlatformTileOverlay>? toAdd, List<_i2.PlatformTileOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateTileOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateTileOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateGroundOverlays( List<_i2.PlatformGroundOverlay>? toAdd, List<_i2.PlatformGroundOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateGroundOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateGroundOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformPoint> getScreenCoordinate( - _i2.PlatformLatLng? latLng, - ) => + _i4.Future<_i2.PlatformPoint> getScreenCoordinate(_i2.PlatformLatLng? latLng) => (super.noSuchMethod( - Invocation.method(#getScreenCoordinate, [latLng]), - returnValue: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - ) - as _i4.Future<_i2.PlatformPoint>); + Invocation.method(#getScreenCoordinate, [latLng]), + returnValue: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + ) as _i4.Future<_i2.PlatformPoint>); @override - _i4.Future<_i2.PlatformLatLng> getLatLng( - _i2.PlatformPoint? screenCoordinate, - ) => + _i4.Future<_i2.PlatformLatLng> getLatLng(_i2.PlatformPoint? screenCoordinate) => (super.noSuchMethod( - Invocation.method(#getLatLng, [screenCoordinate]), - returnValue: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLng>); + Invocation.method(#getLatLng, [screenCoordinate]), + returnValue: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + ) as _i4.Future<_i2.PlatformLatLng>); @override - _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => - (super.noSuchMethod( - Invocation.method(#getVisibleRegion, []), - returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLngBounds>); + _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => (super.noSuchMethod( + Invocation.method(#getVisibleRegion, []), + returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + ) as _i4.Future<_i2.PlatformLatLngBounds>); @override - _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => - (super.noSuchMethod( - Invocation.method(#moveCamera, [cameraUpdate]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => (super.noSuchMethod( + Invocation.method(#moveCamera, [cameraUpdate]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future animateCamera( _i2.PlatformCameraUpdate? cameraUpdate, int? durationMilliseconds, - ) => - (super.noSuchMethod( - Invocation.method(#animateCamera, [ - cameraUpdate, - durationMilliseconds, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#animateCamera, [cameraUpdate, durationMilliseconds]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getZoomLevel() => (super.noSuchMethod( + Invocation.method(#getZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future showInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#showInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future showInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#showInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future hideInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#hideInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future hideInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#hideInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future isInfoWindowShown(String? markerId) => - (super.noSuchMethod( - Invocation.method(#isInfoWindowShown, [markerId]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isInfoWindowShown(String? markerId) => (super.noSuchMethod( + Invocation.method(#isInfoWindowShown, [markerId]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future setStyle(String? style) => - (super.noSuchMethod( - Invocation.method(#setStyle, [style]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setStyle(String? style) => (super.noSuchMethod( + Invocation.method(#setStyle, [style]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getLastStyleError() => - (super.noSuchMethod( - Invocation.method(#getLastStyleError, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getLastStyleError() => (super.noSuchMethod( + Invocation.method(#getLastStyleError, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future clearTileCache(String? tileOverlayId) => - (super.noSuchMethod( - Invocation.method(#clearTileCache, [tileOverlayId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future clearTileCache(String? tileOverlayId) => (super.noSuchMethod( + Invocation.method(#clearTileCache, [tileOverlayId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i5.Uint8List?> takeSnapshot() => - (super.noSuchMethod( - Invocation.method(#takeSnapshot, []), - returnValue: _i4.Future<_i5.Uint8List?>.value(), - returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), - ) - as _i4.Future<_i5.Uint8List?>); + _i4.Future<_i5.Uint8List?> takeSnapshot() => (super.noSuchMethod( + Invocation.method(#takeSnapshot, []), + returnValue: _i4.Future<_i5.Uint8List?>.value(), + returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), + ) as _i4.Future<_i5.Uint8List?>); @override - _i4.Future isAdvancedMarkersAvailable() => - (super.noSuchMethod( - Invocation.method(#isAdvancedMarkersAvailable, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isAdvancedMarkersAvailable() => (super.noSuchMethod( + Invocation.method(#isAdvancedMarkersAvailable, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/tool/run_tests.dart b/packages/google_maps_flutter/google_maps_flutter_ios/tool/run_tests.dart index f49c29eaf7fe..af88ecc57b9c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/tool/run_tests.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/tool/run_tests.dart @@ -25,9 +25,7 @@ Future main(List args) async { exit(0); } - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); final sharedSourceRoot = Directory( p.join(packageRoot.parent.path, 'google_maps_flutter_ios_shared_code'), @@ -129,16 +127,11 @@ Future _validatePackageSharedCode( required bool log, }) async { var hasDiffs = false; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/tool/sync_shared_files.dart b/packages/google_maps_flutter/google_maps_flutter_ios/tool/sync_shared_files.dart index fbbd50d0a499..8711068a5604 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/tool/sync_shared_files.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/tool/sync_shared_files.dart @@ -18,23 +18,15 @@ import 'utils.dart'; const String _sharedSourceRootName = 'google_maps_flutter_ios_shared_code'; Future main(List args) async { - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); - final sharedSourceRoot = Directory( - p.join(packageRoot.parent.path, _sharedSourceRootName), - ); + final sharedSourceRoot = Directory(p.join(packageRoot.parent.path, _sharedSourceRootName)); _syncSharedFiles(packageRoot, packageName, sharedSourceRoot); _reportUnsharedFiles(packageRoot, packageName, sharedSourceRoot); } -void _syncSharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _syncSharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List otherImplementationPackages = sharedSourceRoot.parent .listSync() .whereType() @@ -49,16 +41,11 @@ void _syncSharedFiles( final copiedFiles = []; final missingFiles = []; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { @@ -88,10 +75,7 @@ void _syncSharedFiles( final String otherPackagePath = p.join( packageRoot.parent.path, otherPackageName, - packageRelativePathForSharedSourceRelativePath( - otherPackageName, - relativePath, - ), + packageRelativePathForSharedSourceRelativePath(otherPackageName, relativePath), ); _syncFile(packageFile, otherPackagePath, otherPackageName); } @@ -105,9 +89,7 @@ void _syncSharedFiles( } } if (missingFiles.isNotEmpty) { - print( - 'This package is missing the following files from the shared source:', - ); + print('This package is missing the following files from the shared source:'); for (final file in missingFiles) { print(' $file'); } @@ -123,11 +105,7 @@ void _syncSharedFiles( /// If the file needs special handling of package names that appear within the /// contents of the file, it will update the package name in the file to match /// the destination package name. -void _syncFile( - File source, - String destinationPath, - String destinationPackageName, -) { +void _syncFile(File source, String destinationPath, String destinationPackageName) { source.copySync(destinationPath); if ([ // The Pigeon definition file has output paths that must use the @@ -136,10 +114,7 @@ void _syncFile( // The mock needs to import the package. '.mocks.dart', ].any((pattern) => source.absolute.path.contains(pattern))) { - updatePackageNameInPathReferences( - File(destinationPath), - destinationPackageName, - ); + updatePackageNameInPathReferences(File(destinationPath), destinationPackageName); } // Native unit tests need to import the Swift package. if (source.absolute.path.contains('/RunnerTests/')) { @@ -147,11 +122,7 @@ void _syncFile( } } -void _reportUnsharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _reportUnsharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List unsharedFiles = unexpectedUnsharedSourceFiles( packageRoot, packageName, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/tool/utils.dart b/packages/google_maps_flutter/google_maps_flutter_ios/tool/utils.dart index c4b2b9b83433..fc75925d7304 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios/tool/utils.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios/tool/utils.dart @@ -21,10 +21,7 @@ List unexpectedUnsharedSourceFiles( .listSync(recursive: true) .whereType() // Only report code files. - .where( - (file) => - ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith), - ) + .where((file) => ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith)) // Flutter-generated files aren't expected to be shared. .where((file) => !file.path.contains('GeneratedPluginRegistrant')) // Ignore intermediate file directories. @@ -64,10 +61,7 @@ String packageRelativePathForSharedSourceRelativePath( String packageName, String sharedSourceRelativePath, ) { - return sharedSourceRelativePath.replaceAll( - '/google_maps_flutter_ios/', - '/$packageName/', - ); + return sharedSourceRelativePath.replaceAll('/google_maps_flutter_ios/', '/$packageName/'); } /// Returns the contents of the file with any differences caused only by the @@ -76,10 +70,7 @@ String normalizedFileContents(File file) { return file .readAsStringSync() // Ignore differences caused only by the package name. - .replaceAll( - RegExp(r'google_maps_flutter_ios_[\w\d]+'), - 'google_maps_flutter_ios', - ) + .replaceAll(RegExp(r'google_maps_flutter_ios_[\w\d]+'), 'google_maps_flutter_ios') // Package name diffs could change line wrapping, so collapse whitespace. .replaceAll(RegExp(r'[\s\n]+'), ' ') .trim(); @@ -106,10 +97,7 @@ void updatePackageNameInPathReferences(File file, String packageName) { /// package by name. void updatePackageNameInImports(File file, String packageName) { final String newContents = file.readAsStringSync().replaceAllMapped( - RegExp( - r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', - multiLine: true, - ), + RegExp(r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', multiLine: true), (match) => '${match.group(1)}import $packageName${match.group(2)}', ); file.writeAsStringSync(newContents); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/integration_test/google_maps_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/integration_test/google_maps_test.dart index f1c15e56e975..86260596009a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/integration_test/google_maps_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/integration_test/google_maps_test.dart @@ -41,8 +41,9 @@ final LatLngBounds _testCameraBounds = LatLngBounds( northeast: const LatLng(50, -65), southwest: const LatLng(28.5, -123), ); -final ValueVariant _cameraUpdateTypeVariants = - ValueVariant(CameraUpdateType.values.toSet()); +final ValueVariant _cameraUpdateTypeVariants = ValueVariant( + CameraUpdateType.values.toSet(), +); void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -66,8 +67,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool compassEnabled = await inspector.isCompassEnabled(mapId: mapId); expect(compassEnabled, false); @@ -106,11 +106,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled(mapId: mapId); // This is only supported on Android, so should always return false. expect(mapToolbarEnabled, false); }); @@ -136,14 +133,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final ExampleGoogleMapController controller = await controllerCompleter.future; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; - MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( - mapId: controller.mapId, - ); + MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels(mapId: controller.mapId); expect(zoomLevel, equals(initialZoomLevel)); await tester.pumpWidget( @@ -183,11 +176,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled(mapId: mapId); expect(zoomGesturesEnabled, false); await tester.pumpWidget( @@ -225,11 +215,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); /// Zoom Controls functionality is not available on iOS at the moment. expect(zoomControlsEnabled, false); @@ -254,11 +241,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, false); await tester.pumpWidget( @@ -274,9 +258,7 @@ void main() { ), ); - rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, true); }); @@ -299,11 +281,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled(mapId: mapId); expect(tiltGesturesEnabled, false); await tester.pumpWidget( @@ -342,11 +321,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, false); await tester.pumpWidget( @@ -362,9 +338,7 @@ void main() { ), ); - scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, true); }); @@ -387,8 +361,7 @@ void main() { ), ), ); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; await tester.pumpAndSettle(); @@ -397,8 +370,9 @@ void main() { // https://github.com/flutter/flutter/issues/54758 await Future.delayed(const Duration(seconds: 1)); - final ScreenCoordinate coordinate = await mapController - .getScreenCoordinate(_kInitialCameraPosition.target); + final ScreenCoordinate coordinate = await mapController.getScreenCoordinate( + _kInitialCameraPosition.target, + ); final Rect rect = tester.getRect(find.byKey(key)); expect(coordinate.x, (rect.center.dx - rect.topLeft.dx).round()); expect(coordinate.y, (rect.center.dy - rect.topLeft.dy).round()); @@ -434,11 +408,9 @@ void main() { ); await tester.pumpAndSettle(); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; - final LatLngBounds firstVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds firstVisibleRegion = await mapController.getVisibleRegion(); expect(firstVisibleRegion, isNotNull); expect(firstVisibleRegion.southwest, isNotNull); @@ -464,21 +436,15 @@ void main() { expect(firstVisibleRegion.contains(northEast), isFalse); expect(firstVisibleRegion.contains(southWest), isFalse); - final latLngBounds = LatLngBounds( - southwest: southWest, - northeast: northEast, - ); + final latLngBounds = LatLngBounds(southwest: southWest, northeast: northEast); // TODO(iskakaushik): non-zero padding is needed for some device configurations // https://github.com/flutter/flutter/issues/30575 const double padding = 0; - await mapController.moveCamera( - CameraUpdate.newLatLngBounds(latLngBounds, padding), - ); + await mapController.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController.getVisibleRegion(); expect(secondVisibleRegion, isNotNull); expect(secondVisibleRegion.southwest, isNotNull); @@ -511,8 +477,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool isTrafficEnabled = await inspector.isTrafficEnabled(mapId: mapId); expect(isTrafficEnabled, true); @@ -551,11 +516,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool isBuildingsEnabled = await inspector.areBuildingsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool isBuildingsEnabled = await inspector.areBuildingsEnabled(mapId: mapId); expect(isBuildingsEnabled, true); }); @@ -577,11 +539,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); await tester.pumpWidget( @@ -598,15 +557,11 @@ void main() { ), ); - myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value false', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value false', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -625,16 +580,12 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value true', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value true', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -652,10 +603,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); }); @@ -676,19 +625,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - const mapStyle = - '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - mapStyle, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + const mapStyle = '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; + await GoogleMapsFlutterPlatform.instance.setMapStyle(mapStyle, mapId: controller.mapId); }); - testWidgets('testSetMapStyle invalid Json String', ( - WidgetTester tester, - ) async { + testWidgets('testSetMapStyle invalid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -705,8 +647,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; try { await GoogleMapsFlutterPlatform.instance.setMapStyle( @@ -737,12 +678,8 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - null, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + await GoogleMapsFlutterPlatform.instance.setMapStyle(null, mapId: controller.mapId); }); testWidgets('testGetLatLng', (WidgetTester tester) async { @@ -762,8 +699,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -772,13 +708,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng topLeft = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); + final LatLng topLeft = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); expect(topLeft, northWest); }); @@ -802,8 +733,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -841,8 +771,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -851,13 +780,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); - final ScreenCoordinate topLeft = await controller.getScreenCoordinate( - northWest, - ); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); + final ScreenCoordinate topLeft = await controller.getScreenCoordinate(northWest); expect(topLeft, const ScreenCoordinate(x: 0, y: 0)); }, // TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825 @@ -880,8 +804,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpWidget( Directionality( @@ -917,9 +840,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController googleMapController) { controllerCompleter.complete(googleMapController); @@ -928,12 +849,9 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, false); await controller.showMarkerInfoWindow(marker.markerId); @@ -945,9 +863,7 @@ void main() { expect(iwVisibleStatus, false); }); - testWidgets('updating a marker does not hide its info window', ( - WidgetTester tester, - ) async { + testWidgets('updating a marker does not hide its info window', (WidgetTester tester) async { final Key key = GlobalKey(); const marker = Marker( markerId: MarkerId('marker'), @@ -955,9 +871,7 @@ void main() { ); var markers = {marker}; - const clusterManager = ClusterManager( - clusterManagerId: ClusterManagerId('cluster_manager'), - ); + const clusterManager = ClusterManager(clusterManagerId: ClusterManagerId('cluster_manager')); final clusterManagers = {clusterManager}; final controllerCompleter = Completer(); @@ -967,9 +881,7 @@ void main() { textDirection: TextDirection.ltr, child: ExampleGoogleMap( key: key, - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, clusterManagers: clusterManagers, onMapCreated: (ExampleGoogleMapController googleMapController) { @@ -979,13 +891,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await controller.showMarkerInfoWindow(marker.markerId); - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, true); // Update marker and ensure the info window remains visible when added to a @@ -1031,8 +940,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final Uint8List? bytes = await controller.takeSnapshot(); expect(bytes?.isNotEmpty, true); }, @@ -1072,8 +980,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( tileOverlay1.mapsId, @@ -1086,18 +993,12 @@ void main() { expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.2, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); - expect( - tileOverlayInfo2.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }); @@ -1132,8 +1033,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final tileOverlay1New = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), @@ -1171,10 +1071,7 @@ void main() { expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); @@ -1205,8 +1102,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1249,10 +1145,7 @@ void main() { final marker = Marker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1260,8 +1153,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1278,8 +1170,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1296,8 +1187,7 @@ void main() { final MarkerId markerIdToMove = markers.entries .firstWhere( (MapEntry entry) => - entry.value.clusterManagerId == - clusterManagers.first.clusterManagerId, + entry.value.clusterManagerId == clusterManagers.first.clusterManagerId, ) .key; markers[markerIdToMove] = _copyMarkerWithClusterManagerId( @@ -1385,10 +1275,7 @@ void main() { final marker = AdvancedMarker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1396,8 +1283,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1415,8 +1301,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1431,10 +1316,7 @@ void main() { // Remove markers from clusterManagers and test that clusterManagers are empty. for (final MapEntry entry in markers.entries) { - markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId( - entry.value, - null, - ); + markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId(entry.value, null); } await tester.pumpWidget( Directionality( @@ -1490,15 +1372,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNotNull); }); - testWidgets('getStyleError returns null for a valid style', ( - WidgetTester tester, - ) async { + testWidgets('getStyleError returns null for a valid style', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -1517,8 +1396,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNull); }); @@ -1534,9 +1412,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1546,25 +1422,18 @@ void main() { }); testWidgets('markerWithAssetMapBitmapCreate', (WidgetTester tester) async { - final imageConfiguration = ImageConfiguration( - devicePixelRatio: tester.view.devicePixelRatio, - ); + final imageConfiguration = ImageConfiguration(devicePixelRatio: tester.view.devicePixelRatio); final markers = { Marker( markerId: const MarkerId('1'), - icon: await AssetMapBitmap.create( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await AssetMapBitmap.create(imageConfiguration, 'assets/red_square.png'), ), }; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1578,10 +1447,7 @@ void main() { final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; @@ -1589,9 +1455,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1602,19 +1466,13 @@ void main() { testWidgets('markerWithLegacyAsset', (WidgetTester tester) async { //tester.view.devicePixelRatio = 2.0; - const imageConfiguration = ImageConfiguration( - devicePixelRatio: 2.0, - size: Size(100, 100), - ); + const imageConfiguration = ImageConfiguration(devicePixelRatio: 2.0, size: Size(100, 100)); final markers = { Marker( markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. // ignore: deprecated_member_use - icon: await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await BitmapDescriptor.fromAssetImage(imageConfiguration, 'assets/red_square.png'), ), }; final controllerCompleter = Completer(); @@ -1622,9 +1480,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1648,9 +1504,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1690,19 +1544,13 @@ void main() { ), ); - void expectGroundOverlayEquals( - GroundOverlay source, - GroundOverlay response, - ) { + void expectGroundOverlayEquals(GroundOverlay source, GroundOverlay response) { expect(response.groundOverlayId, source.groundOverlayId); expect( response.transparency, moreOrLessEquals(source.transparency, epsilon: _floatTolerance), ); - expect( - response.bearing, - moreOrLessEquals(source.bearing, epsilon: _floatTolerance), - ); + expect(response.bearing, moreOrLessEquals(source.bearing, epsilon: _floatTolerance)); // Only test bounds if it was given in the original object if (source.bounds != null) { @@ -1717,14 +1565,8 @@ void main() { expect(response.clickable, source.clickable); expect(response.zIndex, source.zIndex); expect(response.zoomLevel, source.zoomLevel); - expect( - response.anchor?.dx, - moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance), - ); - expect( - response.anchor?.dy, - moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance), - ); + expect(response.anchor?.dx, moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance)); + expect(response.anchor?.dy, moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance)); } testWidgets('set ground overlays correctly', (WidgetTester tester) async { @@ -1754,38 +1596,29 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayBoundsInfo2 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPositionInfo1 = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1, - groundOverlayBoundsInfo1, - ); - expectGroundOverlayEquals( - groundOverlayBounds2, - groundOverlayBoundsInfo2, - ); - expectGroundOverlayEquals( - groundOverlayPosition1, - groundOverlayPositionInfo1, - ); + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds2.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPositionInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1, groundOverlayBoundsInfo1); + expectGroundOverlayEquals(groundOverlayBounds2, groundOverlayBoundsInfo2); + expectGroundOverlayEquals(groundOverlayPosition1, groundOverlayPositionInfo1); } }); - testWidgets('update ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('update ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1795,10 +1628,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1807,26 +1637,23 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - - final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); - - final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + + final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); + + final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); await tester.pumpWidget( Directionality( @@ -1834,10 +1661,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1New, - groundOverlayPosition1New, - }, + groundOverlays: {groundOverlayBounds1New, groundOverlayPosition1New}, onMapCreated: (ExampleGoogleMapController controller) { fail('update: OnMapCreated should get called only once.'); }, @@ -1848,28 +1672,21 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPosition1Info = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1New, - groundOverlayBounds1Info, - ); - expectGroundOverlayEquals( - groundOverlayPosition1New, - groundOverlayPosition1Info, - ); + final GroundOverlay groundOverlayBounds1Info = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPosition1Info = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1New, groundOverlayBounds1Info); + expectGroundOverlayEquals(groundOverlayPosition1New, groundOverlayPosition1Info); } }); - testWidgets('remove ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('remove ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1879,10 +1696,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1891,8 +1705,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1910,10 +1723,14 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay? groundOverlayBounds1Info = await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId); - final GroundOverlay? groundOverlayPositionInfo = await inspector - .getGroundOverlayInfo(groundOverlayPosition1.mapsId, mapId: mapId); + final GroundOverlay? groundOverlayBounds1Info = await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ); + final GroundOverlay? groundOverlayPositionInfo = await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ); expect(groundOverlayBounds1Info, isNull); expect(groundOverlayPositionInfo, isNull); @@ -1926,8 +1743,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -1939,8 +1755,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { cameraIdleCompleter.complete(); } }, @@ -1951,8 +1766,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -1972,8 +1786,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -1988,8 +1803,9 @@ void main() { await cameraIdleCompleter.future; // After onCameraIdle event, the camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2019,8 +1835,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -2044,8 +1859,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { stopwatch.stop(); cameraIdleCompleter.complete(); } @@ -2057,8 +1871,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -2090,15 +1903,10 @@ void main() { // For short animation duration, check that the animation is completed // faster than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - lessThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, lessThan(animationDurationMiddlePoint)); // Reset camera to initial position before testing long duration. - await controller.moveCamera( - CameraUpdate.newCameraPosition(_kInitialCameraPosition), - ); + await controller.moveCamera(CameraUpdate.newCameraPosition(_kInitialCameraPosition)); await tester.pumpAndSettle(); // Create completer for camera idle event. @@ -2121,8 +1929,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -2138,14 +1947,12 @@ void main() { // For longer animation duration, check that the animation is completed // slower than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - greaterThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, greaterThan(animationDurationMiddlePoint)); // Camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2179,9 +1986,7 @@ void main() { Directionality( textDirection: ui.TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 20.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 20.0)), markers: markers, markerType: MarkerType.advancedMarker, onMapCreated: (ExampleGoogleMapController controller) => @@ -2212,31 +2017,20 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, @@ -2286,23 +2080,15 @@ AdvancedMarker _copyAdvancedMarkerWithClusterManagerId( CameraUpdate _getCameraUpdateForType(CameraUpdateType type) { return switch (type) { - CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition( - _kTestCameraPosition, - ), + CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition(_kTestCameraPosition), CameraUpdateType.newLatLng => CameraUpdate.newLatLng(_kTestMapCenter), - CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds( - _testCameraBounds, - 0, - ), + CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds(_testCameraBounds, 0), CameraUpdateType.newLatLngZoom => CameraUpdate.newLatLngZoom( _kTestMapCenter, _kTestCameraZoomLevel, ), CameraUpdateType.scrollBy => CameraUpdate.scrollBy(10, 10), - CameraUpdateType.zoomBy => CameraUpdate.zoomBy( - _kTestZoomByAmount, - const Offset(1, 1), - ), + CameraUpdateType.zoomBy => CameraUpdate.zoomBy(_kTestZoomByAmount, const Offset(1, 1)), CameraUpdateType.zoomTo => CameraUpdate.zoomTo(_kTestCameraZoomLevel), CameraUpdateType.zoomIn => CameraUpdate.zoomIn(), CameraUpdateType.zoomOut => CameraUpdate.zoomOut(), @@ -2322,29 +2108,16 @@ Future _checkCameraUpdateByType( switch (type) { case CameraUpdateType.newCameraPosition: - expect( - currentPosition.bearing, - wrapMatcher(equals(_kTestCameraPosition.bearing)), - ); - expect( - currentPosition.zoom, - wrapMatcher(equals(_kTestCameraPosition.zoom)), - ); - expect( - currentPosition.tilt, - wrapMatcher(equals(_kTestCameraPosition.tilt)), - ); + expect(currentPosition.bearing, wrapMatcher(equals(_kTestCameraPosition.bearing))); + expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraPosition.zoom))); + expect(currentPosition.tilt, wrapMatcher(equals(_kTestCameraPosition.tilt))); expect( currentPosition.target.latitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.latitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.latitude, latLngThreshold)), ); expect( currentPosition.target.longitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLng: expect( @@ -2359,15 +2132,11 @@ Future _checkCameraUpdateByType( final LatLngBounds bounds = await controller.getVisibleRegion(); expect( bounds.northeast.longitude, - wrapMatcher( - closeTo(_testCameraBounds.northeast.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.northeast.longitude, latLngThreshold)), ); expect( bounds.southwest.longitude, - wrapMatcher( - closeTo(_testCameraBounds.southwest.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.southwest.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLngZoom: expect( @@ -2382,20 +2151,11 @@ Future _checkCameraUpdateByType( case CameraUpdateType.scrollBy: // For scrollBy, just check that the location has changed. if (oldPosition != null) { - expect( - currentPosition.target.latitude, - isNot(equals(oldPosition.target.latitude)), - ); - expect( - currentPosition.target.longitude, - isNot(equals(oldPosition.target.longitude)), - ); + expect(currentPosition.target.latitude, isNot(equals(oldPosition.target.latitude))); + expect(currentPosition.target.longitude, isNot(equals(oldPosition.target.longitude))); } case CameraUpdateType.zoomBy: - expect( - currentPosition.zoom, - wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount)), - ); + expect(currentPosition.zoom, wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount))); case CameraUpdateType.zoomTo: expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraZoomLevel))); case CameraUpdateType.zoomIn: diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_marker_icons.dart index 5069f3f900af..ff45dd833cef 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_marker_icons.dart @@ -33,8 +33,7 @@ class _AdvancedMarkerIconsBody extends StatefulWidget { final String? mapId; @override - State<_AdvancedMarkerIconsBody> createState() => - _AdvancedMarkerIconsBodyState(); + State<_AdvancedMarkerIconsBody> createState() => _AdvancedMarkerIconsBodyState(); } class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { @@ -51,10 +50,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: (ExampleGoogleMapController controller) { setState(() { @@ -73,29 +69,22 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { const ImageConfiguration(size: Size(12, 12)), 'assets/red_square.png', ); - final AssetMapBitmap largeAsset = - await BitmapDescriptor.asset( - const ImageConfiguration(size: Size(36, 36)), - 'assets/red_square.png', - ); + final AssetMapBitmap largeAsset = await BitmapDescriptor.asset( + const ImageConfiguration(size: Size(36, 36)), + 'assets/red_square.png', + ); setState(() { _markers.addAll([ // Default icon AdvancedMarker( markerId: const MarkerId('1'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude + 1), ), // Custom pin colors AdvancedMarker( markerId: const MarkerId('2'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.black, @@ -105,26 +94,17 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Pin with text AdvancedMarker( markerId: const MarkerId('3'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude + 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.blue, backgroundColor: Colors.white, - glyph: const TextGlyph( - text: 'Hi!', - textColor: Colors.blue, - ), + glyph: const TextGlyph(text: 'Hi!', textColor: Colors.blue), ), ), // Pin with bitmap AdvancedMarker( markerId: const MarkerId('4'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.white, @@ -134,10 +114,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Custom marker icon AdvancedMarker( markerId: const MarkerId('5'), - position: LatLng( - _kMapCenter.latitude, - _kMapCenter.longitude, - ), + position: LatLng(_kMapCenter.latitude, _kMapCenter.longitude), icon: largeAsset, ), ]); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_markers_clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_markers_clustering.dart index 1787e9077a50..985566ee454f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_markers_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/advanced_markers_clustering.dart @@ -16,10 +16,7 @@ import 'page.dart'; class AdvancedMarkersClusteringPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkersClusteringPage({super.key, required this.mapId}) - : super( - const Icon(Icons.place_outlined), - 'Manage clusters of advanced markers', - ); + : super(const Icon(Icons.place_outlined), 'Manage clusters of advanced markers'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -78,8 +75,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -107,17 +103,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; }); } @@ -159,14 +149,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -210,9 +197,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/animate_camera.dart index 001006fb54be..d278e2c5b3b6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/animate_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class AnimateCameraPage extends GoogleMapExampleAppPage { - const AnimateCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control, animated'); + const AnimateCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control, animated'); @override Widget build(BuildContext context) { @@ -58,9 +57,7 @@ class AnimateCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -88,9 +85,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), duration: _cameraUpdateAnimationDuration, ); }, @@ -114,10 +109,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), duration: _cameraUpdateAnimationDuration, ); }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/clustering.dart index 18e9af8c1be8..e7ea5e7ddefc 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/clustering.dart @@ -13,8 +13,7 @@ import 'page.dart'; /// Page for demonstrating marker clustering support. class ClusteringPage extends GoogleMapExampleAppPage { /// Default Constructor. - const ClusteringPage({super.key}) - : super(const Icon(Icons.place), 'Manage clustering'); + const ClusteringPage({super.key}) : super(const Icon(Icons.place), 'Manage clustering'); @override Widget build(BuildContext context) { @@ -61,8 +60,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -95,10 +93,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = _copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = _copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -134,8 +129,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -144,14 +138,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -190,9 +181,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); @@ -239,8 +228,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { TextButton( onPressed: clusterManagers.isEmpty ? null - : () => - _removeClusterManager(clusterManagers.values.last), + : () => _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -248,8 +236,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { Wrap( alignment: WrapAlignment.spaceEvenly, children: [ - for (final MapEntry - clusterEntry + for (final MapEntry clusterEntry in clusterManagers.entries) TextButton( onPressed: () => _addMarkersToCluster(clusterEntry.value), @@ -272,9 +259,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { child: const Text('Remove selected marker'), ), TextButton( - onPressed: markers.isEmpty - ? null - : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty ? null : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/collision_behavior.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/collision_behavior.dart index a6a8ef8aec70..f93d850a6836 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/collision_behavior.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/collision_behavior.dart @@ -15,10 +15,7 @@ import 'place_marker.dart'; class AdvancedMarkerCollisionBehaviorPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkerCollisionBehaviorPage({super.key, required this.mapId}) - : super( - const Icon(Icons.not_listed_location), - 'Advanced marker collision behavior', - ); + : super(const Icon(Icons.not_listed_location), 'Advanced marker collision behavior'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -35,12 +32,10 @@ class _CollisionBehaviorPageBody extends StatefulWidget { final String? mapId; @override - State<_CollisionBehaviorPageBody> createState() => - _CollisionBehaviorPageBodyState(); + State<_CollisionBehaviorPageBody> createState() => _CollisionBehaviorPageBodyState(); } -class _CollisionBehaviorPageBodyState - extends State<_CollisionBehaviorPageBody> { +class _CollisionBehaviorPageBodyState extends State<_CollisionBehaviorPageBody> { static const LatLng center = LatLng(-33.86711, 151.1947171); static const double zoomOutLevel = 9; static const double zoomInLevel = 12; @@ -78,10 +73,7 @@ class _CollisionBehaviorPageBodyState child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: center, - zoom: zoomInLevel, - ), + initialCameraPosition: const CameraPosition(target: center, zoom: zoomInLevel), markers: Set.of(markers), tiltGesturesEnabled: false, zoomGesturesEnabled: false, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/custom_marker_icon.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/custom_marker_icon.dart index 548146c6206c..3391ba1bcba2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/custom_marker_icon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/custom_marker_icon.dart @@ -20,9 +20,7 @@ Future createCustomMarkerIconImage({required Size size}) async { size.height.floor(), ); - final ByteData? bytes = await image.toByteData( - format: ui.ImageByteFormat.png, - ); + final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); return bytes!; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/example_google_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/example_google_map.dart index 2b8a8243d381..e18943a3345f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/example_google_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/example_google_map.dart @@ -47,10 +47,7 @@ class ExampleGoogleMapController { if (_googleMapState.widget.onCameraMove != null) { GoogleMapsFlutterPlatform.instance .onCameraMove(mapId: mapId) - .listen( - (CameraMoveEvent e) => - _googleMapState.widget.onCameraMove!(e.value), - ); + .listen((CameraMoveEvent e) => _googleMapState.widget.onCameraMove!(e.value)); } if (_googleMapState.widget.onCameraIdle != null) { GoogleMapsFlutterPlatform.instance @@ -62,27 +59,16 @@ class ExampleGoogleMapController { .listen((MarkerTapEvent e) => _googleMapState.onMarkerTap(e.value)); GoogleMapsFlutterPlatform.instance .onMarkerDragStart(mapId: mapId) - .listen( - (MarkerDragStartEvent e) => - _googleMapState.onMarkerDragStart(e.value, e.position), - ); + .listen((MarkerDragStartEvent e) => _googleMapState.onMarkerDragStart(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDrag(mapId: mapId) - .listen( - (MarkerDragEvent e) => - _googleMapState.onMarkerDrag(e.value, e.position), - ); + .listen((MarkerDragEvent e) => _googleMapState.onMarkerDrag(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDragEnd(mapId: mapId) - .listen( - (MarkerDragEndEvent e) => - _googleMapState.onMarkerDragEnd(e.value, e.position), - ); + .listen((MarkerDragEndEvent e) => _googleMapState.onMarkerDragEnd(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onInfoWindowTap(mapId: mapId) - .listen( - (InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value), - ); + .listen((InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value)); GoogleMapsFlutterPlatform.instance .onPolylineTap(mapId: mapId) .listen((PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value)); @@ -94,18 +80,13 @@ class ExampleGoogleMapController { .listen((CircleTapEvent e) => _googleMapState.onCircleTap(e.value)); GoogleMapsFlutterPlatform.instance .onGroundOverlayTap(mapId: mapId) - .listen( - (GroundOverlayTapEvent e) => - _googleMapState.onGroundOverlayTap(e.value), - ); + .listen((GroundOverlayTapEvent e) => _googleMapState.onGroundOverlayTap(e.value)); GoogleMapsFlutterPlatform.instance .onTap(mapId: mapId) .listen((MapTapEvent e) => _googleMapState.onTap(e.position)); GoogleMapsFlutterPlatform.instance .onLongPress(mapId: mapId) - .listen( - (MapLongPressEvent e) => _googleMapState.onLongPress(e.position), - ); + .listen((MapLongPressEvent e) => _googleMapState.onLongPress(e.position)); GoogleMapsFlutterPlatform.instance .onClusterTap(mapId: mapId) .listen((ClusterTapEvent e) => _googleMapState.onClusterTap(e.value)); @@ -113,24 +94,16 @@ class ExampleGoogleMapController { /// Updates configuration options of the map user interface. Future _updateMapConfiguration(MapConfiguration update) { - return GoogleMapsFlutterPlatform.instance.updateMapConfiguration( - update, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMapConfiguration(update, mapId: mapId); } /// Updates marker configuration. Future _updateMarkers(MarkerUpdates markerUpdates) { - return GoogleMapsFlutterPlatform.instance.updateMarkers( - markerUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMarkers(markerUpdates, mapId: mapId); } /// Updates cluster manager configuration. - Future _updateClusterManagers( - ClusterManagerUpdates clusterManagerUpdates, - ) { + Future _updateClusterManagers(ClusterManagerUpdates clusterManagerUpdates) { return GoogleMapsFlutterPlatform.instance.updateClusterManagers( clusterManagerUpdates, mapId: mapId, @@ -138,9 +111,7 @@ class ExampleGoogleMapController { } /// Updates ground overlay configuration. - Future _updateGroundOverlays( - GroundOverlayUpdates groundOverlayUpdates, - ) { + Future _updateGroundOverlays(GroundOverlayUpdates groundOverlayUpdates) { return GoogleMapsFlutterPlatform.instance.updateGroundOverlays( groundOverlayUpdates, mapId: mapId, @@ -149,26 +120,17 @@ class ExampleGoogleMapController { /// Updates polygon configuration. Future _updatePolygons(PolygonUpdates polygonUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolygons( - polygonUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolygons(polygonUpdates, mapId: mapId); } /// Updates polyline configuration. Future _updatePolylines(PolylineUpdates polylineUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolylines( - polylineUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolylines(polylineUpdates, mapId: mapId); } /// Updates circle configuration. Future _updateCircles(CircleUpdates circleUpdates) { - return GoogleMapsFlutterPlatform.instance.updateCircles( - circleUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateCircles(circleUpdates, mapId: mapId); } /// Updates tile overlays configuration. @@ -182,10 +144,7 @@ class ExampleGoogleMapController { /// Clears the tile cache so that all tiles will be requested again from the /// [TileProvider]. Future clearTileCache(TileOverlayId tileOverlayId) async { - return GoogleMapsFlutterPlatform.instance.clearTileCache( - tileOverlayId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.clearTileCache(tileOverlayId, mapId: mapId); } /// Starts an animated change of the map camera position. @@ -199,10 +158,7 @@ class ExampleGoogleMapController { /// Changes the map camera position. Future moveCamera(CameraUpdate cameraUpdate) { - return GoogleMapsFlutterPlatform.instance.moveCamera( - cameraUpdate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.moveCamera(cameraUpdate, mapId: mapId); } /// Return [LatLngBounds] defining the region that is visible in a map. @@ -212,42 +168,27 @@ class ExampleGoogleMapController { /// Return [ScreenCoordinate] of the [LatLng] in the current map view. Future getScreenCoordinate(LatLng latLng) { - return GoogleMapsFlutterPlatform.instance.getScreenCoordinate( - latLng, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getScreenCoordinate(latLng, mapId: mapId); } /// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view. Future getLatLng(ScreenCoordinate screenCoordinate) { - return GoogleMapsFlutterPlatform.instance.getLatLng( - screenCoordinate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getLatLng(screenCoordinate, mapId: mapId); } /// Programmatically show the Info Window for a [Marker]. Future showMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow(markerId, mapId: mapId); } /// Programmatically hide the Info Window for a [Marker]. Future hideMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow(markerId, mapId: mapId); } /// Returns `true` when the [InfoWindow] is showing, `false` otherwise. Future isMarkerInfoWindowShown(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown(markerId, mapId: mapId); } /// Returns the current zoom level of the map @@ -267,9 +208,7 @@ class ExampleGoogleMapController { /// Returns true if [AdvancedMarker]s can be used with this map. Future isAdvancedMarkersAvailable() { - return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable( - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: mapId); } /// Disposes of the platform resources @@ -446,17 +385,14 @@ class ExampleGoogleMap extends StatefulWidget { class _ExampleGoogleMapState extends State { final int _mapId = _nextMapCreationId++; - final Completer _controller = - Completer(); + final Completer _controller = Completer(); Map _markers = {}; Map _polygons = {}; Map _polylines = {}; Map _circles = {}; - Map _clusterManagers = - {}; - Map _groundOverlays = - {}; + Map _clusterManagers = {}; + Map _groundOverlays = {}; late MapConfiguration _mapConfiguration; @override @@ -466,9 +402,7 @@ class _ExampleGoogleMapState extends State { onPlatformViewCreated, widgetConfiguration: MapWidgetConfiguration( textDirection: - widget.layoutDirection ?? - Directionality.maybeOf(context) ?? - TextDirection.ltr, + widget.layoutDirection ?? Directionality.maybeOf(context) ?? TextDirection.ltr, initialCameraPosition: widget.initialCameraPosition, gestureRecognizers: widget.gestureRecognizers, ), @@ -498,9 +432,7 @@ class _ExampleGoogleMapState extends State { @override void dispose() { - _controller.future.then( - (ExampleGoogleMapController controller) => controller.dispose(), - ); + _controller.future.then((ExampleGoogleMapController controller) => controller.dispose()); super.dispose(); } @@ -531,9 +463,7 @@ class _ExampleGoogleMapState extends State { Future _updateMarkers() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateMarkers( - MarkerUpdates.from(_markers.values.toSet(), widget.markers), - ), + controller._updateMarkers(MarkerUpdates.from(_markers.values.toSet(), widget.markers)), ); _markers = keyByMarkerId(widget.markers); } @@ -542,10 +472,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateClusterManagers( - ClusterManagerUpdates.from( - _clusterManagers.values.toSet(), - widget.clusterManagers, - ), + ClusterManagerUpdates.from(_clusterManagers.values.toSet(), widget.clusterManagers), ), ); _clusterManagers = keyByClusterManagerId(widget.clusterManagers); @@ -555,10 +482,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateGroundOverlays( - GroundOverlayUpdates.from( - _groundOverlays.values.toSet(), - widget.groundOverlays, - ), + GroundOverlayUpdates.from(_groundOverlays.values.toSet(), widget.groundOverlays), ), ); _groundOverlays = keyByGroundOverlayId(widget.groundOverlays); @@ -567,9 +491,7 @@ class _ExampleGoogleMapState extends State { Future _updatePolygons() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updatePolygons( - PolygonUpdates.from(_polygons.values.toSet(), widget.polygons), - ), + controller._updatePolygons(PolygonUpdates.from(_polygons.values.toSet(), widget.polygons)), ); _polygons = keyByPolygonId(widget.polygons); } @@ -587,9 +509,7 @@ class _ExampleGoogleMapState extends State { Future _updateCircles() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateCircles( - CircleUpdates.from(_circles.values.toSet(), widget.circles), - ), + controller._updateCircles(CircleUpdates.from(_circles.values.toSet(), widget.circles)), ); _circles = keyByCircleId(widget.circles); } @@ -600,12 +520,11 @@ class _ExampleGoogleMapState extends State { } Future onPlatformViewCreated(int id) async { - final ExampleGoogleMapController controller = - await ExampleGoogleMapController._init( - id, - widget.initialCameraPosition, - this, - ); + final ExampleGoogleMapController controller = await ExampleGoogleMapController._init( + id, + widget.initialCameraPosition, + this, + ); _controller.complete(controller); unawaited(_updateTileOverlays()); widget.onMapCreated?.call(controller); @@ -656,8 +575,7 @@ class _ExampleGoogleMapState extends State { } void onClusterTap(Cluster cluster) { - final ClusterManager? clusterManager = - _clusterManagers[cluster.clusterManagerId]; + final ClusterManager? clusterManager = _clusterManagers[cluster.clusterManagerId]; clusterManager?.onClusterTap?.call(cluster); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/ground_overlay.dart index 00a7d8126539..878f5c9200a2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/ground_overlay.dart @@ -13,8 +13,7 @@ import 'page.dart'; enum _GroundOverlayPlacing { position, bounds } class GroundOverlayPage extends GoogleMapExampleAppPage { - const GroundOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Ground overlay'); + const GroundOverlayPage({super.key}) : super(const Icon(Icons.map), 'Ground overlay'); @override Widget build(BuildContext context) { @@ -132,9 +131,7 @@ class GroundOverlayBodyState extends State { // Adjusts the bearing by 10 degrees, wrapping around at 360 degrees. // 10 is the increment, 350 degrees of the full circle -10. _groundOverlay = _groundOverlay!.copyWith( - bearingParam: _groundOverlay!.bearing >= 350 - ? 0 - : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, ); }); } @@ -143,9 +140,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { final transparency = _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; - _groundOverlay = _groundOverlay!.copyWith( - transparencyParam: transparency, - ); + _groundOverlay = _groundOverlay!.copyWith(transparencyParam: transparency); }); } @@ -167,8 +162,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.bounds); setState(() { - _currentGroundOverlayBounds = - _currentGroundOverlayBounds == _groundOverlayBounds1 + _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 ? _groundOverlayBounds2 : _groundOverlayBounds1; }); @@ -181,9 +175,7 @@ class GroundOverlayBodyState extends State { void _toggleVisible() { assert(_groundOverlay != null); setState(() { - _groundOverlay = _groundOverlay!.copyWith( - visibleParam: !_groundOverlay!.visible, - ); + _groundOverlay = _groundOverlay!.copyWith(visibleParam: !_groundOverlay!.visible); }); } @@ -223,9 +215,7 @@ class GroundOverlayBodyState extends State { @override Widget build(BuildContext context) { - final overlays = { - if (_groundOverlay != null) _groundOverlay!, - }; + final overlays = {if (_groundOverlay != null) _groundOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -233,10 +223,7 @@ class GroundOverlayBodyState extends State { children: [ Expanded( child: ExampleGoogleMap( - initialCameraPosition: CameraPosition( - target: _mapCenter, - zoom: 14.0, - ), + initialCameraPosition: CameraPosition(target: _mapCenter, zoom: 14.0), groundOverlays: overlays, onMapCreated: _onMapCreated, ), @@ -258,9 +245,7 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeTransparency(), + onPressed: _groundOverlay == null ? null : () => _changeTransparency(), child: const Text('change transparency'), ), TextButton( @@ -282,23 +267,17 @@ class GroundOverlayBodyState extends State { TextButton( onPressed: _groundOverlay == null ? null : () => _changeType(), child: Text( - _placingType == _GroundOverlayPlacing.position - ? 'use bounds' - : 'use position', + _placingType == _GroundOverlayPlacing.position ? 'use bounds' : 'use position', ), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changePosition(), child: const Text('change position'), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.bounds || _groundOverlay == null ? null : () => _changeBounds(), child: const Text('change bounds'), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_click.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_click.dart index a786197d5205..49ecd2656bab 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_click.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_click.dart @@ -58,42 +58,25 @@ class _MapClickBodyState extends State<_MapClickBody> { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; if (mapController != null) { final lastTap = 'Tap:\n${_lastTap ?? ""}\n'; final lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; + columnChildren.add(Center(child: Text(lastTap, textAlign: TextAlign.center))); columnChildren.add( - Center(child: Text(lastTap, textAlign: TextAlign.center)), - ); - columnChildren.add( - Center( - child: Text( - _lastTap != null ? 'Tapped' : '', - textAlign: TextAlign.center, - ), - ), - ); - columnChildren.add( - Center(child: Text(lastLongPress, textAlign: TextAlign.center)), + Center(child: Text(_lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center)), ); + columnChildren.add(Center(child: Text(lastLongPress, textAlign: TextAlign.center))); columnChildren.add( Center( - child: Text( - _lastLongPress != null ? 'Long pressed' : '', - textAlign: TextAlign.center, - ), + child: Text(_lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } Future onMapCreated(ExampleGoogleMapController controller) async { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_coordinates.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_coordinates.dart index 646301db99ae..51a68e8d5cf4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_coordinates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_coordinates.dart @@ -16,8 +16,7 @@ const CameraPosition _kInitialPosition = CameraPosition( ); class MapCoordinatesPage extends GoogleMapExampleAppPage { - const MapCoordinatesPage({super.key}) - : super(const Icon(Icons.map), 'Map coordinates'); + const MapCoordinatesPage({super.key}) : super(const Icon(Icons.map), 'Map coordinates'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { final googleMap = ExampleGoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, - onCameraIdle: - _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 + onCameraIdle: _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 ); return NotificationListener( @@ -61,13 +59,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { children: [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox( - width: 300.0, - height: 200.0, - child: googleMap, - ), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), // Add a block at the bottom of this list to allow validation that the visible region of the map // does not change when scrolled under the safe view on iOS. diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_map_id.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_map_id.dart index 94a01eb03368..89ba5c25396f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_map_id.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_map_id.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { - const MapIdPage({super.key}) - : super(const Icon(Icons.map), 'Cloud-based maps styling'); + const MapIdPage({super.key}) : super(const Icon(Icons.map), 'Cloud-based maps styling'); @override Widget build(BuildContext context) { @@ -49,10 +48,7 @@ class MapIdBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), key: _key, mapId: _mapId, ); @@ -60,9 +56,7 @@ class MapIdBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), Padding( padding: const EdgeInsets.all(10.0), @@ -80,10 +74,7 @@ class MapIdBodyState extends State { ), ]; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_ui.dart index 258c88170924..d7e7ff773a64 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/map_ui.dart @@ -84,9 +84,7 @@ class MapUiBodyState extends State { Widget _latLngBoundsToggler() { return TextButton( child: Text( - _cameraTargetBounds.bounds == null - ? 'bound camera target' - : 'release camera target', + _cameraTargetBounds.bounds == null ? 'bound camera target' : 'release camera target', ), onPressed: () { setState(() { @@ -100,9 +98,7 @@ class MapUiBodyState extends State { Widget _zoomBoundsToggler() { return TextButton( - child: Text( - _minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom', - ), + child: Text(_minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom'), onPressed: () { setState(() { _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null @@ -114,8 +110,7 @@ class MapUiBodyState extends State { } Widget _mapTypeCycler() { - final MapType nextType = - MapType.values[(_mapType.index + 1) % MapType.values.length]; + final MapType nextType = MapType.values[(_mapType.index + 1) % MapType.values.length]; return TextButton( child: Text('change map type to $nextType'), onPressed: () { @@ -172,9 +167,7 @@ class MapUiBodyState extends State { Widget _zoomControlsToggler() { return TextButton( - child: Text( - '${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls', - ), + child: Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'), onPressed: () { setState(() { _zoomControlsEnabled = !_zoomControlsEnabled; @@ -196,9 +189,7 @@ class MapUiBodyState extends State { Widget _myLocationToggler() { return TextButton( - child: Text( - '${_myLocationEnabled ? 'disable' : 'enable'} my location marker', - ), + child: Text('${_myLocationEnabled ? 'disable' : 'enable'} my location marker'), onPressed: () { setState(() { _myLocationEnabled = !_myLocationEnabled; @@ -209,9 +200,7 @@ class MapUiBodyState extends State { Widget _myLocationButtonToggler() { return TextButton( - child: Text( - '${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button', - ), + child: Text('${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'), onPressed: () { setState(() { _myLocationButtonEnabled = !_myLocationButtonEnabled; @@ -240,9 +229,7 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = _nightMode - ? await _getFileData('assets/night_mode.json') - : ''; + final String style = _nightMode ? await _getFileData('assets/night_mode.json') : ''; setState(() { _mapStyle = style; }); @@ -275,9 +262,7 @@ class MapUiBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; @@ -313,10 +298,7 @@ class MapUiBodyState extends State { ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _updateCameraPosition(CameraPosition position) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/marker_icons.dart index d4ac8d6ac597..84d13ac32e89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/marker_icons.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MarkerIconsPage extends GoogleMapExampleAppPage { - const MarkerIconsPage({super.key}) - : super(const Icon(Icons.image), 'Marker icons'); + const MarkerIconsPage({super.key}) : super(const Icon(Icons.image), 'Marker icons'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { AssetMapBitmap? _markerIconAsset; BytesMapBitmap? _markerIconBytes; final int _markersAmountPerType = 15; - bool get _customSizeEnabled => - _currentSizeOption != _MarkerSizeOption.original; + bool get _customSizeEnabled => _currentSizeOption != _MarkerSizeOption.original; @override Widget build(BuildContext context) { @@ -64,10 +62,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { width: 350.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: _onMapCreated, ), @@ -75,11 +70,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ), TextButton( onPressed: () => _toggleScaling(context), - child: Text( - _scalingEnabled - ? 'Disable auto scaling' - : 'Enable auto scaling', - ), + child: Text(_scalingEnabled ? 'Disable auto scaling' : 'Enable auto scaling'), ), if (_scalingEnabled) ...[ Container( @@ -91,10 +82,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'Reference box with size of ${referenceSize.width} x ${referenceSize.height} in logical pixels.', ), const SizedBox(height: 10), - Image.asset( - 'assets/red_square.png', - scale: _mipMapsEnabled ? null : 1.0, - ), + Image.asset('assets/red_square.png', scale: _mipMapsEnabled ? null : 1.0), const Text('Asset image rendered with flutter'), const SizedBox(height: 10), Row( @@ -112,9 +100,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { }); } }, - items: _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { + items: _MarkerSizeOption.values.map((_MarkerSizeOption option) { return DropdownMenuItem<_MarkerSizeOption>( value: option, child: Text(_getMarkerSizeOptionName(option)), @@ -126,9 +112,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ], TextButton( onPressed: () => _toggleMipMaps(context), - child: Text( - _mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps', - ), + child: Text(_mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps'), ), ], ), @@ -179,15 +163,9 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { if (width != null && height != null) { return Size(width, height); } else if (width != null) { - return Size( - width, - width * _markerAssetImageSize.height / _markerAssetImageSize.width, - ); + return Size(width, width * _markerAssetImageSize.height / _markerAssetImageSize.width); } else if (height != null) { - return Size( - height * _markerAssetImageSize.width / _markerAssetImageSize.height, - height, - ); + return Size(height * _markerAssetImageSize.width / _markerAssetImageSize.height, height); } else { return _markerAssetImageSize; } @@ -210,10 +188,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createAssetMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude - 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude - 1); return Marker( markerId: MarkerId('marker_asset_$index'), @@ -223,10 +198,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createBytesMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude + 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude + 1); return Marker( markerId: MarkerId('marker_bytes_$index'), @@ -252,26 +224,20 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { - final ImageConfiguration imageConfiguration = - createLocalImageConfiguration(context); + final ImageConfiguration imageConfiguration = createLocalImageConfiguration(context); assetMapBitmap = await AssetMapBitmap.create( imageConfiguration, 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -281,9 +247,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } @@ -291,9 +255,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Future _updateMarkerBytesImage(BuildContext context) async { - final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf( - context, - ); + final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context); final Size bitmapLogicalSize = _getMarkerReferenceSize(); final double? imagePixelRatio = _scalingEnabled ? devicePixelRatio : null; @@ -307,10 +269,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); @@ -319,9 +278,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/move_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/move_camera.dart index 5fc48e659246..28ce96f2b55f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/move_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/move_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MoveCameraPage extends GoogleMapExampleAppPage { - const MoveCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control'); + const MoveCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control'); @override Widget build(BuildContext context) { @@ -46,9 +45,7 @@ class MoveCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -75,9 +72,7 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -99,19 +94,14 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.moveCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), @@ -121,9 +111,7 @@ class MoveCameraState extends State { children: [ TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0)), - ); + mapController?.moveCamera(CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0))); }, child: const Text('zoomBy with focus'), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/padding.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/padding.dart index a0f4f8521c8e..82136d27cd8c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/padding.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/padding.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PaddingPage extends GoogleMapExampleAppPage { - const PaddingPage({super.key}) - : super(const Icon(Icons.map), 'Add padding to the map'); + const PaddingPage({super.key}) : super(const Icon(Icons.map), 'Add padding to the map'); @override Widget build(BuildContext context) { @@ -38,19 +37,14 @@ class MarkerIconsBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), padding: _padding, ); final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), const Padding( padding: EdgeInsets.only(top: 20), @@ -65,10 +59,7 @@ class MarkerIconsBodyState extends State { columnChildren.addAll([_paddingInput(), _buttons()]); - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _onMapCreated(ExampleGoogleMapController controllerParam) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_advanced_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_advanced_marker.dart index 08a886c11041..61c0898fed88 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_advanced_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_advanced_marker.dart @@ -53,18 +53,18 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { this.controller = controller; }); - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; }); + }); + }); } void _onMarkerTapped(MarkerId markerId) { @@ -73,17 +73,11 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; markerPosition = null; @@ -108,10 +102,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -177,16 +168,10 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { void _changePosition(MarkerId markerId) { final AdvancedMarker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -239,9 +224,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -249,9 +232,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -266,9 +247,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -289,9 +268,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { /// Performs customizations of the [marker] to mark it as selected or not. AdvancedMarker copyWithSelectedState(AdvancedMarker marker, bool isSelected) { - return marker.copyWith( - iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected), - ); + return marker.copyWith(iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected)); } @override @@ -308,8 +285,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, @@ -340,9 +316,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -351,70 +325,49 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( onPressed: selectedId == null ? null - : () => - _setMarkerIcon(selectedId, _getMarkerIcon(context)), + : () => _setMarkerIcon(selectedId, _getMarkerIcon(context)), child: const Text('set glyph text'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_circle.dart index 3c0335bfd18b..6bd22df33ef2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_circle.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { - const PlaceCirclePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place circle'); + const PlaceCirclePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place circle'); @override Widget build(BuildContext context) { @@ -38,12 +37,7 @@ class PlaceCircleBodyState extends State { // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling circle stroke width int widthsIndex = 0; @@ -133,9 +127,7 @@ class PlaceCircleBodyState extends State { void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { - circles[circleId] = circle.copyWith( - strokeWidthParam: widths[++widthsIndex % widths.length], - ); + circles[circleId] = circle.copyWith(strokeWidthParam: widths[++widthsIndex % widths.length]); }); } @@ -171,15 +163,11 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_marker.dart index 77ba3787d8e7..43f16a23979a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_marker.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceMarkerPage extends GoogleMapExampleAppPage { - const PlaceMarkerPage({super.key}) - : super(const Icon(Icons.place), 'Place marker'); + const PlaceMarkerPage({super.key}) : super(const Icon(Icons.place), 'Place marker'); @override Widget build(BuildContext context) { @@ -61,10 +60,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -170,16 +166,10 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { void _changePosition(MarkerId markerId) { final Marker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -232,9 +222,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -242,9 +230,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -259,9 +245,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -311,9 +295,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -322,63 +304,43 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( @@ -430,12 +392,10 @@ class AdvancedMarkersCapabilityStatus extends StatefulWidget { final ExampleGoogleMapController? controller; @override - State createState() => - _AdvancedMarkersCapabilityStatusState(); + State createState() => _AdvancedMarkersCapabilityStatusState(); } -class _AdvancedMarkersCapabilityStatusState - extends State { +class _AdvancedMarkersCapabilityStatusState extends State { /// Whether map supports advanced markers. bool? _isAdvancedMarkersAvailable; @@ -456,21 +416,19 @@ class _AdvancedMarkersCapabilityStatusState void _checkCapabilityIfNeeded() { final ExampleGoogleMapController? controller = widget.controller; - if (controller != null && - _isAdvancedMarkersAvailable == null && - !_isFetching) { + if (controller != null && _isAdvancedMarkersAvailable == null && !_isFetching) { _isFetching = true; - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - _isFetching = false; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; + _isFetching = false; + }); + }); } } @@ -481,8 +439,7 @@ class _AdvancedMarkersCapabilityStatusState child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polygon.dart index 70ad42c93724..d7c518cdf48d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polygon.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolygonPage extends GoogleMapExampleAppPage { - const PlacePolygonPage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polygon'); + const PlacePolygonPage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polygon'); @override Widget build(BuildContext context) { @@ -39,12 +38,7 @@ class PlacePolygonBodyState extends State { // Values when toggling polygon color int strokeColorsIndex = 0; int fillColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polygon width int widthsIndex = 0; @@ -149,9 +143,7 @@ class PlacePolygonBodyState extends State { void _addHoles(PolygonId polygonId) { final Polygon polygon = polygons[polygonId]!; setState(() { - polygons[polygonId] = polygon.copyWith( - holesParam: _createHoles(polygonId), - ); + polygons[polygonId] = polygon.copyWith(holesParam: _createHoles(polygonId)); }); } @@ -194,15 +186,11 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -232,9 +220,7 @@ class PlacePolygonBodyState extends State { child: const Text('remove holes'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polyline.dart index 8703ffcbd68f..a60d106bbe0b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/place_polyline.dart @@ -12,8 +12,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolylinePage extends GoogleMapExampleAppPage { - const PlacePolylinePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polyline'); + const PlacePolylinePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polyline'); @override Widget build(BuildContext context) { @@ -38,23 +37,14 @@ class PlacePolylineBodyState extends State { // Values when toggling polyline color int colorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polyline width int widthsIndex = 0; List widths = [10, 20, 5]; int jointTypesIndex = 0; - List jointTypes = [ - JointType.mitered, - JointType.bevel, - JointType.round, - ]; + List jointTypes = [JointType.mitered, JointType.bevel, JointType.round]; // Values when toggling polyline end cap type int endCapsIndex = 0; @@ -133,36 +123,28 @@ class PlacePolylineBodyState extends State { void _toggleGeodesic(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - geodesicParam: !polyline.geodesic, - ); + polylines[polylineId] = polyline.copyWith(geodesicParam: !polyline.geodesic); }); } void _toggleVisible(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - visibleParam: !polyline.visible, - ); + polylines[polylineId] = polyline.copyWith(visibleParam: !polyline.visible); }); } void _changeColor(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - colorParam: colors[++colorsIndex % colors.length], - ); + polylines[polylineId] = polyline.copyWith(colorParam: colors[++colorsIndex % colors.length]); }); } void _changeWidth(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - widthParam: widths[++widthsIndex % widths.length], - ); + polylines[polylineId] = polyline.copyWith(widthParam: widths[++widthsIndex % widths.length]); }); } @@ -237,15 +219,11 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -259,15 +237,11 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) ? null : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( @@ -289,9 +263,7 @@ class PlacePolylineBodyState extends State { child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) ? null : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/scrolling_map.dart index e5a8ec2ce5a6..443544402c31 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/scrolling_map.dart @@ -15,8 +15,7 @@ import 'page.dart'; const LatLng _center = LatLng(32.080664, 34.9563837); class ScrollingMapPage extends GoogleMapExampleAppPage { - const ScrollingMapPage({super.key}) - : super(const Icon(Icons.map), 'Scrolling map'); + const ScrollingMapPage({super.key}) : super(const Icon(Icons.map), 'Scrolling map'); @override Widget build(BuildContext context) { @@ -45,15 +44,10 @@ class ScrollingMapBody extends StatelessWidget { width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), gestureRecognizers: // >{ - Factory( - () => EagerGestureRecognizer(), - ), + Factory(() => EagerGestureRecognizer()), }, ), ), @@ -70,19 +64,14 @@ class ScrollingMapBody extends StatelessWidget { const Text("This map doesn't consume the vertical drags."), const Padding( padding: EdgeInsets.only(bottom: 12.0), - child: Text( - 'It still gets other gestures (e.g scale or tap).', - ), + child: Text('It still gets other gestures (e.g scale or tap).'), ), Center( child: SizedBox( width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), markers: { Marker( markerId: const MarkerId('test_marker_id'), @@ -93,12 +82,9 @@ class ScrollingMapBody extends StatelessWidget { ), ), }, - gestureRecognizers: - >{ - Factory( - () => ScaleGestureRecognizer(), - ), - }, + gestureRecognizers: >{ + Factory(() => ScaleGestureRecognizer()), + }, ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/snapshot.dart index 6f1624234ec4..906b3de2ecff 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/snapshot.dart @@ -53,8 +53,7 @@ class _SnapshotBodyState extends State<_SnapshotBody> { TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = await _mapController - ?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/tile_overlay.dart index cefa70eb34d5..3f3a26b6ab89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/lib/tile_overlay.dart @@ -14,8 +14,7 @@ import 'example_google_map.dart'; import 'page.dart'; class TileOverlayPage extends GoogleMapExampleAppPage { - const TileOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Tile overlay'); + const TileOverlayPage({super.key}) : super(const Icon(Icons.map), 'Tile overlay'); @override Widget build(BuildContext context) { @@ -90,18 +89,9 @@ class TileOverlayBodyState extends State { ), ), ), - TextButton( - onPressed: _addTileOverlay, - child: const Text('Add tile overlay'), - ), - TextButton( - onPressed: _removeTileOverlay, - child: const Text('Remove tile overlay'), - ), - TextButton( - onPressed: _clearTileCache, - child: const Text('Clear tile cache'), - ), + TextButton(onPressed: _addTileOverlay, child: const Text('Add tile overlay')), + TextButton(onPressed: _removeTileOverlay, child: const Text('Remove tile overlay')), + TextButton(onPressed: _clearTileCache, child: const Text('Clear tile cache')), ], ); } @@ -125,22 +115,14 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/example_google_map_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/example_google_map_test.dart index 261fc473e8bb..6aa25acb4b63 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/example_google_map_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/example_google_map_test.dart @@ -107,17 +107,12 @@ void main() { const p1 = Polygon(polygonId: PolygonId('polygon_1')); const p2 = Polygon(polygonId: PolygonId('polygon_2')); const p3 = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1); - const p3updated = Polygon( - polygonId: PolygonId('polygon_3'), - strokeWidth: 2, - ); + const p3updated = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polygons: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polygons: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -149,9 +144,7 @@ void main() { // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polylines: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polylines: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -163,9 +156,7 @@ void main() { expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[1].polylinesToAdd, {p3}); - expect(map.polylineUpdates[1].polylineIdsToRemove, { - p2.polylineId, - }); + expect(map.polylineUpdates[1].polylineIdsToRemove, {p2.polylineId}); expect(map.polylineUpdates[2].polylinesToChange, {p3updated}); expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/fake_google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/fake_google_maps_flutter_platform.dart index 899a7709c548..3e8beefc78c4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/fake_google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/example/test/fake_google_maps_flutter_platform.dart @@ -17,8 +17,7 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { List createdIds = []; /// A map of creation IDs to fake map instances. - Map mapInstances = - {}; + Map mapInstances = {}; PlatformMapStateRecorder get lastCreatedMap => mapInstances[createdIds.last]!; @@ -41,46 +40,31 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { Future init(int mapId) async {} @override - Future updateMapConfiguration( - MapConfiguration update, { - required int mapId, - }) async { + Future updateMapConfiguration(MapConfiguration update, {required int mapId}) async { mapInstances[mapId]?.mapConfiguration = update; await _fakeDelay(); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { mapInstances[mapId]?.markerUpdates.add(markerUpdates); await _fakeDelay(); } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { mapInstances[mapId]?.polygonUpdates.add(polygonUpdates); await _fakeDelay(); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { mapInstances[mapId]?.polylineUpdates.add(polylineUpdates); await _fakeDelay(); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { mapInstances[mapId]?.circleUpdates.add(circleUpdates); await _fakeDelay(); } @@ -113,16 +97,10 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async {} + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async {} @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future animateCameraWithConfiguration( @@ -132,55 +110,34 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { }) async {} @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future setMapStyle(String? mapStyle, {required int mapId}) async {} @override Future getVisibleRegion({required int mapId}) async { - return LatLngBounds( - southwest: const LatLng(0, 0), - northeast: const LatLng(0, 0), - ); + return LatLngBounds(southwest: const LatLng(0, 0), northeast: const LatLng(0, 0)); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return const ScreenCoordinate(x: 0, y: 0); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return const LatLng(0, 0); } @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return false; } @@ -312,24 +269,14 @@ class PlatformMapStateRecorder { this.mapConfiguration = const MapConfiguration(), }) { clusterManagerUpdates.add( - ClusterManagerUpdates.from( - const {}, - mapObjects.clusterManagers, - ), + ClusterManagerUpdates.from(const {}, mapObjects.clusterManagers), ); groundOverlayUpdates.add( - GroundOverlayUpdates.from( - const {}, - mapObjects.groundOverlays, - ), + GroundOverlayUpdates.from(const {}, mapObjects.groundOverlays), ); markerUpdates.add(MarkerUpdates.from(const {}, mapObjects.markers)); - polygonUpdates.add( - PolygonUpdates.from(const {}, mapObjects.polygons), - ); - polylineUpdates.add( - PolylineUpdates.from(const {}, mapObjects.polylines), - ); + polygonUpdates.add(PolygonUpdates.from(const {}, mapObjects.polygons)); + polylineUpdates.add(PolylineUpdates.from(const {}, mapObjects.polylines)); circleUpdates.add(CircleUpdates.from(const {}, mapObjects.circles)); tileOverlaySets.add(mapObjects.tileOverlays); } @@ -343,8 +290,6 @@ class PlatformMapStateRecorder { final List polylineUpdates = []; final List circleUpdates = []; final List> tileOverlaySets = >[]; - final List clusterManagerUpdates = - []; - final List groundOverlayUpdates = - []; + final List clusterManagerUpdates = []; + final List groundOverlayUpdates = []; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_map_inspector_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_map_inspector_ios.dart index a0057b9fdc54..a0d3b46c6cbb 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_map_inspector_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_map_inspector_ios.dart @@ -14,9 +14,8 @@ import 'messages.g.dart'; class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { /// Creates an inspector API instance for a given map ID from /// [inspectorProvider]. - GoogleMapsInspectorIOS( - MapsInspectorApi? Function(int mapId) inspectorProvider, - ) : _inspectorProvider = inspectorProvider; + GoogleMapsInspectorIOS(MapsInspectorApi? Function(int mapId) inspectorProvider) + : _inspectorProvider = inspectorProvider; final MapsInspectorApi? Function(int mapId) _inspectorProvider; @@ -53,17 +52,12 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { @override Future getMinMaxZoomLevels({required int mapId}) async { - final PlatformZoomRange zoomLevels = await _inspectorProvider( - mapId, - )!.getZoomRange(); + final PlatformZoomRange zoomLevels = await _inspectorProvider(mapId)!.getZoomRange(); return MinMaxZoomPreference(zoomLevels.min, zoomLevels.max); } @override - Future getTileOverlayInfo( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) async { final PlatformTileLayer? tileInfo = await _inspectorProvider( mapId, )!.getTileOverlayInfo(tileOverlayId.value); @@ -83,10 +77,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { bool supportsGettingHeatmapInfo() => true; @override - Future getHeatmapInfo( - HeatmapId heatmapId, { - required int mapId, - }) async { + Future getHeatmapInfo(HeatmapId heatmapId, {required int mapId}) async { final PlatformHeatmap? heatmapInfo = await _inspectorProvider( mapId, )!.getHeatmapInfo(heatmapId.value); @@ -140,24 +131,15 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { transparency: groundOverlayInfo.transparency, visible: groundOverlayInfo.visible, clickable: groundOverlayInfo.clickable, - anchor: Offset( - groundOverlayInfo.anchor!.x, - groundOverlayInfo.anchor!.y, - ), + anchor: Offset(groundOverlayInfo.anchor!.x, groundOverlayInfo.anchor!.y), zoomLevel: groundOverlayInfo.zoomLevel, ); } else if (bounds != null) { return GroundOverlay.fromBounds( groundOverlayId: groundOverlayId, bounds: LatLngBounds( - southwest: LatLng( - bounds.southwest.latitude, - bounds.southwest.longitude, - ), - northeast: LatLng( - bounds.northeast.latitude, - bounds.northeast.longitude, - ), + southwest: LatLng(bounds.southwest.latitude, bounds.southwest.longitude), + northeast: LatLng(bounds.northeast.latitude, bounds.northeast.longitude), ), image: dummyImage, zIndex: groundOverlayInfo.zIndex, @@ -202,13 +184,8 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { required int mapId, required ClusterManagerId clusterManagerId, }) async { - return (await _inspectorProvider( - mapId, - )!.getClusters(clusterManagerId.value)) - .map( - (PlatformCluster cluster) => - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ) + return (await _inspectorProvider(mapId)!.getClusters(clusterManagerId.value)) + .map((PlatformCluster cluster) => GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)) .toList(); } @@ -221,19 +198,14 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { mapId, )!.getCameraPosition(); return CameraPosition( - target: LatLng( - cameraPosition.target.latitude, - cameraPosition.target.longitude, - ), + target: LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude), bearing: cameraPosition.bearing, tilt: cameraPosition.tilt, zoom: cameraPosition.zoom, ); } - static HeatmapGradient? _deserializeHeatmapGradient( - PlatformHeatmapGradient? gradient, - ) { + static HeatmapGradient? _deserializeHeatmapGradient(PlatformHeatmapGradient? gradient) { if (gradient == null) { return null; } @@ -243,12 +215,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { _mapEnumerated( gradient.colors, (PlatformColor color, int i) => HeatmapGradientColor( - Color.from( - red: color.red, - green: color.green, - blue: color.blue, - alpha: color.alpha, - ), + Color.from(red: color.red, green: color.green, blue: color.blue, alpha: color.alpha), gradient.startPoints[i], ), ).toList(), @@ -256,9 +223,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { ); } - static WeightedLatLng _deserializeWeightedLatLng( - PlatformWeightedLatLng weightedLatLng, - ) { + static WeightedLatLng _deserializeWeightedLatLng(PlatformWeightedLatLng weightedLatLng) { return WeightedLatLng( LatLng(weightedLatLng.point.latitude, weightedLatLng.point.longitude), weight: weightedLatLng.weight, @@ -266,10 +231,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { } } -Iterable _mapEnumerated( - Iterable iterable, - E Function(T, int) fn, -) sync* { +Iterable _mapEnumerated(Iterable iterable, E Function(T, int) fn) sync* { var index = 0; for (final item in iterable) { yield fn(item, index++); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_maps_flutter_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_maps_flutter_ios.dart index c1709a97ad52..c0c8db027c8d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_maps_flutter_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/google_maps_flutter_ios.dart @@ -43,9 +43,8 @@ class UnknownMapIDError extends Error { /// An implementation of [GoogleMapsFlutterPlatform] for iOS. class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Creates a new Android maps implementation instance. - GoogleMapsFlutterIOS({ - @visibleForTesting MapsApi Function(int mapId)? apiProvider, - }) : _apiProvider = apiProvider ?? _productionApiProvider; + GoogleMapsFlutterIOS({@visibleForTesting MapsApi Function(int mapId)? apiProvider}) + : _apiProvider = apiProvider ?? _productionApiProvider; /// Registers the iOS implementation of GoogleMapsFlutterPlatform. static void registerWith() { @@ -59,8 +58,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// The per-map handlers for callbacks from the host side. @visibleForTesting - final Map hostMapHandlers = - {}; + final Map hostMapHandlers = {}; /// Accesses the MapsApi associated to the passed mapId. MapsApi _hostApi(int mapId) { @@ -84,8 +82,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { mapId, _mapEventStreamController, tileOverlayProvider: (TileOverlayId tileOverlayId) { - final Map? tileOverlaysForMap = - _tileOverlays[mapId]; + final Map? tileOverlaysForMap = _tileOverlays[mapId]; return tileOverlaysForMap?[tileOverlayId]; }, ); @@ -127,9 +124,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { StreamController>.broadcast(); // Returns a filtered view of the events in the _controller, by mapId. - Stream> _events(int mapId) => _mapEventStreamController - .stream - .where((MapEvent event) => event.mapId == mapId); + Stream> _events(int mapId) => + _mapEventStreamController.stream.where((MapEvent event) => event.mapId == mapId); @override Stream onCameraMoveStarted({required int mapId}) { @@ -207,30 +203,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateMapConfiguration( - MapConfiguration configuration, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromMapConfiguration(configuration), - ); + Future updateMapConfiguration(MapConfiguration configuration, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromMapConfiguration(configuration)); } @override - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromOptionsJson(optionsUpdate), - ); + Future updateMapOptions(Map optionsUpdate, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromOptionsJson(optionsUpdate)); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) { return _hostApi(mapId).updateMarkers( markerUpdates.markersToAdd.map(_platformMarkerFromMarker).toList(), markerUpdates.markersToChange.map(_platformMarkerFromMarker).toList(), @@ -239,42 +226,25 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) { return _hostApi(mapId).updatePolygons( polygonUpdates.polygonsToAdd.map(_platformPolygonFromPolygon).toList(), polygonUpdates.polygonsToChange.map(_platformPolygonFromPolygon).toList(), - polygonUpdates.polygonIdsToRemove - .map((PolygonId id) => id.value) - .toList(), + polygonUpdates.polygonIdsToRemove.map((PolygonId id) => id.value).toList(), ); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) { return _hostApi(mapId).updatePolylines( - polylineUpdates.polylinesToAdd - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylinesToChange - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylineIdsToRemove - .map((PolylineId id) => id.value) - .toList(), + polylineUpdates.polylinesToAdd.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylinesToChange.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylineIdsToRemove.map((PolylineId id) => id.value).toList(), ); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) { return _hostApi(mapId).updateCircles( circleUpdates.circlesToAdd.map(_platformCircleFromCircle).toList(), circleUpdates.circlesToChange.map(_platformCircleFromCircle).toList(), @@ -283,41 +253,26 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) { return _hostApi(mapId).updateHeatmaps( heatmapUpdates.heatmapsToAdd.map(_platformHeatmapFromHeatmap).toList(), heatmapUpdates.heatmapsToChange.map(_platformHeatmapFromHeatmap).toList(), - heatmapUpdates.heatmapIdsToRemove - .map((HeatmapId id) => id.value) - .toList(), + heatmapUpdates.heatmapIdsToRemove.map((HeatmapId id) => id.value).toList(), ); } @override - Future updateTileOverlays({ - required Set newTileOverlays, - required int mapId, - }) { - final Map? currentTileOverlays = - _tileOverlays[mapId]; + Future updateTileOverlays({required Set newTileOverlays, required int mapId}) { + final Map? currentTileOverlays = _tileOverlays[mapId]; final Set previousSet = currentTileOverlays != null ? currentTileOverlays.values.toSet() : {}; final updates = _TileOverlayUpdates.from(previousSet, newTileOverlays); _tileOverlays[mapId] = keyTileOverlayId(newTileOverlays); return _hostApi(mapId).updateTileOverlays( - updates.tileOverlaysToAdd - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlaysToChange - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlayIdsToRemove - .map((TileOverlayId id) => id.value) - .toList(), + updates.tileOverlaysToAdd.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlaysToChange.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlayIdsToRemove.map((TileOverlayId id) => id.value).toList(), ); } @@ -356,17 +311,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { groundOverlayUpdates.groundOverlaysToChange .map(_platformGroundOverlayFromGroundOverlay) .toList(), - groundOverlayUpdates.groundOverlayIdsToRemove - .map((GroundOverlayId id) => id.value) - .toList(), + groundOverlayUpdates.groundOverlayIdsToRemove.map((GroundOverlayId id) => id.value).toList(), ); } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) { return _hostApi(mapId).clearTileCache(tileOverlayId.value); } @@ -393,16 +343,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) { - return _hostApi( - mapId, - ).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); + return _hostApi(mapId).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); } @override Future setMapStyle(String? mapStyle, {required int mapId}) async { - final String? errorDescription = await _hostApi( - mapId, - ).setStyle(mapStyle ?? ''); + final String? errorDescription = await _hostApi(mapId).setStyle(mapStyle ?? ''); if (errorDescription != null) { throw MapStyleException(errorDescription); } @@ -410,32 +356,20 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future getVisibleRegion({required int mapId}) async { - return _latLngBoundsFromPlatformLatLngBounds( - await _hostApi(mapId).getVisibleRegion(), - ); + return _latLngBoundsFromPlatformLatLngBounds(await _hostApi(mapId).getVisibleRegion()); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return _screenCoordinateFromPlatformPoint( - await _hostApi( - mapId, - ).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), + await _hostApi(mapId).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), ); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return _latLngFromPlatformLatLng( - await _hostApi( - mapId, - ).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), + await _hostApi(mapId).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), ); } @@ -450,10 +384,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) { return _hostApi(mapId).isInfoWindowShown(markerId.value); } @@ -497,21 +428,11 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { widgetConfiguration.initialCameraPosition, ), mapConfiguration: mapConfiguration, - initialMarkers: mapObjects.markers - .map(_platformMarkerFromMarker) - .toList(), - initialPolygons: mapObjects.polygons - .map(_platformPolygonFromPolygon) - .toList(), - initialPolylines: mapObjects.polylines - .map(_platformPolylineFromPolyline) - .toList(), - initialCircles: mapObjects.circles - .map(_platformCircleFromCircle) - .toList(), - initialHeatmaps: mapObjects.heatmaps - .map(_platformHeatmapFromHeatmap) - .toList(), + initialMarkers: mapObjects.markers.map(_platformMarkerFromMarker).toList(), + initialPolygons: mapObjects.polygons.map(_platformPolygonFromPolygon).toList(), + initialPolylines: mapObjects.polylines.map(_platformPolylineFromPolyline).toList(), + initialCircles: mapObjects.circles.map(_platformCircleFromCircle).toList(), + initialHeatmaps: mapObjects.heatmaps.map(_platformHeatmapFromHeatmap).toList(), initialTileOverlays: mapObjects.tileOverlays .map(_platformTileOverlayFromTileOverlay) .toList(), @@ -545,9 +466,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { onPlatformViewCreated, widgetConfiguration: widgetConfiguration, mapObjects: mapObjects, - mapConfiguration: _platformMapConfigurationFromMapConfiguration( - mapConfiguration, - ), + mapConfiguration: _platformMapConfigurationFromMapConfiguration(mapConfiguration), ); } @@ -629,19 +548,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static ScreenCoordinate _screenCoordinateFromPlatformPoint( - PlatformPoint point, - ) { + static ScreenCoordinate _screenCoordinateFromPlatformPoint(PlatformPoint point) { return ScreenCoordinate(x: point.x.round(), y: point.y.round()); } - static PlatformPoint _platformPointFromScreenCoordinate( - ScreenCoordinate coordinate, - ) { - return PlatformPoint( - x: coordinate.x.toDouble(), - y: coordinate.y.toDouble(), - ); + static PlatformPoint _platformPointFromScreenCoordinate(ScreenCoordinate coordinate) { + return PlatformPoint(x: coordinate.x.toDouble(), y: coordinate.y.toDouble()); } static PlatformPoint _platformPointFromOffset(Offset offset) { @@ -670,9 +582,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { final HeatmapGradient? gradient = heatmap.gradient; return PlatformHeatmap( heatmapId: heatmap.heatmapId.value, - data: heatmap.data - .map(_platformWeightedLatLngFromWeightedLatLng) - .toList(), + data: heatmap.data.map(_platformWeightedLatLngFromWeightedLatLng).toList(), gradient: _platformHeatmapGradientFromHeatmapGradient(gradient), opacity: heatmap.opacity, radius: heatmap.radius.radius, @@ -691,16 +601,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { colors: gradient.colors .map((HeatmapGradientColor c) => _platformColorFromColor(c.color)) .toList(), - startPoints: gradient.colors - .map((HeatmapGradientColor c) => c.startPoint) - .toList(), + startPoints: gradient.colors.map((HeatmapGradientColor c) => c.startPoint).toList(), colorMapSize: gradient.colorMapSize, ); } - static PlatformInfoWindow _platformInfoWindowFromInfoWindow( - InfoWindow window, - ) { + static PlatformInfoWindow _platformInfoWindowFromInfoWindow(InfoWindow window) { return PlatformInfoWindow( title: window.title, snippet: window.snippet, @@ -724,9 +630,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { markerId: marker.markerId.value, clusterManagerId: marker.clusterManagerId?.value, collisionBehavior: marker is AdvancedMarker - ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( - marker.collisionBehavior, - ) + ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior(marker.collisionBehavior) : null, ); } @@ -736,9 +640,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ) { return PlatformGroundOverlay( groundOverlayId: groundOverlay.groundOverlayId.value, - anchor: groundOverlay.anchor != null - ? _platformPointFromOffset(groundOverlay.anchor!) - : null, + anchor: groundOverlay.anchor != null ? _platformPointFromOffset(groundOverlay.anchor!) : null, image: platformBitmapFromBitmapDescriptor(groundOverlay.image), position: groundOverlay.position != null ? _platformLatLngFromLatLng(groundOverlay.position!) @@ -754,12 +656,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolygon _platformPolygonFromPolygon(Polygon polygon) { - final List points = polygon.points - .map(_platformLatLngFromLatLng) - .toList(); - final List> holes = polygon.holes.map(( - List hole, - ) { + final List points = polygon.points.map(_platformLatLngFromLatLng).toList(); + final List> holes = polygon.holes.map((List hole) { return hole.map(_platformLatLngFromLatLng).toList(); }).toList(); return PlatformPolygon( @@ -777,9 +675,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolyline _platformPolylineFromPolyline(Polyline polyline) { - final List points = polyline.points - .map(_platformLatLngFromLatLng) - .toList(); + final List points = polyline.points.map(_platformLatLngFromLatLng).toList(); final List pattern = polyline.patterns .map(platformPatternItemFromPatternItem) .toList(); @@ -797,9 +693,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static PlatformTileOverlay _platformTileOverlayFromTileOverlay( - TileOverlay tileOverlay, - ) { + static PlatformTileOverlay _platformTileOverlayFromTileOverlay(TileOverlay tileOverlay) { return PlatformTileOverlay( tileOverlayId: tileOverlay.tileOverlayId.value, fadeIn: tileOverlay.fadeIn, @@ -813,22 +707,16 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { static PlatformClusterManager _platformClusterManagerFromClusterManager( ClusterManager clusterManager, ) { - return PlatformClusterManager( - identifier: clusterManager.clusterManagerId.value, - ); + return PlatformClusterManager(identifier: clusterManager.clusterManagerId.value); } - static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate( - CameraUpdate update, - ) { + static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate(CameraUpdate update) { switch (update.updateType) { case CameraUpdateType.newCameraPosition: update as CameraUpdateNewCameraPosition; return PlatformCameraUpdate( cameraUpdate: PlatformCameraUpdateNewCameraPosition( - cameraPosition: _platformCameraPositionFromCameraPosition( - update.cameraPosition, - ), + cameraPosition: _platformCameraPositionFromCameraPosition(update.cameraPosition), ), ); case CameraUpdateType.newLatLng: @@ -856,9 +744,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomTo: update as CameraUpdateZoomTo; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom)); case CameraUpdateType.zoomBy: update as CameraUpdateZoomBy; final Offset? focus = update.focus; @@ -870,30 +756,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomIn: update as CameraUpdateZoomIn; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: false), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: false)); case CameraUpdateType.zoomOut: update as CameraUpdateZoomOut; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: true), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: true)); case CameraUpdateType.scrollBy: update as CameraUpdateScrollBy; return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateScrollBy( - dx: update.dx, - dy: update.dy, - ), + cameraUpdate: PlatformCameraUpdateScrollBy(dx: update.dx, dy: update.dy), ); } } /// Converts [MapBitmapScaling] from platform interface to [PlatformMapBitmapScaling] Pigeon. @visibleForTesting - static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling( - MapBitmapScaling scaling, - ) { + static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling(MapBitmapScaling scaling) { switch (scaling) { case MapBitmapScaling.auto: return PlatformMapBitmapScaling.auto; @@ -913,8 +790,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [MarkersCollisionBehavior] from platform interface to /// [PlatformMarkerCollisionBehavior] Pigeon. @visibleForTesting - static PlatformMarkerCollisionBehavior - platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( + static PlatformMarkerCollisionBehavior platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( MarkerCollisionBehavior collisionBehavior, ) { switch (collisionBehavior) { @@ -937,14 +813,10 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [BitmapDescriptor] from platform interface to [PlatformBitmap] pigeon. @visibleForTesting - static PlatformBitmap platformBitmapFromBitmapDescriptor( - BitmapDescriptor bitmap, - ) { + static PlatformBitmap platformBitmapFromBitmapDescriptor(BitmapDescriptor bitmap) { switch (bitmap) { case final DefaultMarker marker: - return PlatformBitmap( - bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble()), - ); + return PlatformBitmap(bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble())); // Clients may still use this deprecated format, so it must be supported. // ignore: deprecated_member_use case final BytesBitmap bytes: @@ -974,9 +846,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapAssetMap( assetName: asset.assetName, - bitmapScaling: platformMapBitmapScalingFromScaling( - asset.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(asset.bitmapScaling), imagePixelRatio: asset.imagePixelRatio, width: asset.width, height: asset.height, @@ -986,9 +856,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapBytesMap( byteData: bytes.byteData, - bitmapScaling: platformMapBitmapScalingFromScaling( - bytes.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(bytes.bitmapScaling), imagePixelRatio: bytes.imagePixelRatio, width: bytes.width, height: bytes.height, @@ -1026,9 +894,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { bitmap: PlatformBitmapPinConfig( backgroundColor: backgroundColor, borderColor: borderColor, - glyphBitmap: platformBitmapFromBitmapDescriptor( - bitmapGlyph.bitmap, - ), + glyphBitmap: platformBitmapFromBitmapDescriptor(bitmapGlyph.bitmap), ), ); case null: @@ -1050,10 +916,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { 'Glyph type "${pinConfig.glyph.runtimeType}" has not been implemented', ); default: - throw ArgumentError( - 'Unrecognized type of bitmap ${bitmap.runtimeType}', - 'bitmap', - ); + throw ArgumentError('Unrecognized type of bitmap ${bitmap.runtimeType}', 'bitmap'); } } } @@ -1063,11 +926,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { class HostMapMessageHandler implements MapsCallbackApi { /// Creates a new handler that listens for events from map [mapId], and /// broadcasts them to [streamController]. - HostMapMessageHandler( - this.mapId, - this.streamController, { - required this.tileOverlayProvider, - }) { + HostMapMessageHandler(this.mapId, this.streamController, {required this.tileOverlayProvider}) { MapsCallbackApi.setUp(this, messageChannelSuffix: mapId.toString()); } @@ -1092,17 +951,11 @@ class HostMapMessageHandler implements MapsCallbackApi { PlatformPoint location, int zoom, ) async { - final TileOverlay? tileOverlay = tileOverlayProvider( - TileOverlayId(tileOverlayId), - ); + final TileOverlay? tileOverlay = tileOverlayProvider(TileOverlayId(tileOverlayId)); final TileProvider? tileProvider = tileOverlay?.tileProvider; final Tile tile = tileProvider == null ? TileProvider.noTile - : await tileProvider.getTile( - location.x.round(), - location.y.round(), - zoom, - ); + : await tileProvider.getTile(location.x.round(), location.y.round(), zoom); return _platformTileFromTile(tile); } @@ -1139,10 +992,7 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onClusterTap(PlatformCluster cluster) { streamController.add( - ClusterTapEvent( - mapId, - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ), + ClusterTapEvent(mapId, GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)), ); } @@ -1153,41 +1003,27 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onLongPress(PlatformLatLng position) { - streamController.add( - MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position))); } @override void onMarkerDrag(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragStart(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragStartEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragStartEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragEnd(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEndEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEndEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @@ -1208,35 +1044,24 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onGroundOverlayTap(String groundOverlayId) { - streamController.add( - GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId)), - ); + streamController.add(GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId))); } @override void onTap(PlatformLatLng position) { - streamController.add( - MapTapEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapTapEvent(mapId, _latLngFromPlatformLatLng(position))); } } PlatformColor _platformColorFromColor(Color color) { - return PlatformColor( - red: color.r, - green: color.g, - blue: color.b, - alpha: color.a, - ); + return PlatformColor(red: color.r, green: color.g, blue: color.b, alpha: color.a); } LatLng _latLngFromPlatformLatLng(PlatformLatLng latLng) { return LatLng(latLng.latitude, latLng.longitude); } -LatLngBounds _latLngBoundsFromPlatformLatLngBounds( - PlatformLatLngBounds bounds, -) { +LatLngBounds _latLngBoundsFromPlatformLatLngBounds(PlatformLatLngBounds bounds) { return LatLngBounds( southwest: _latLngFromPlatformLatLng(bounds.southwest), northeast: _latLngFromPlatformLatLng(bounds.northeast), @@ -1247,9 +1072,7 @@ PlatformLatLng _platformLatLngFromLatLng(LatLng latLng) { return PlatformLatLng(latitude: latLng.latitude, longitude: latLng.longitude); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( - LatLngBounds? bounds, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds(LatLngBounds? bounds) { if (bounds == null) { return null; } @@ -1259,9 +1082,7 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( ); } -PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng( - WeightedLatLng weightedLatLng, -) { +PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng(WeightedLatLng weightedLatLng) { return PlatformWeightedLatLng( point: _platformLatLngFromLatLng(weightedLatLng.point), weight: weightedLatLng.weight, @@ -1273,9 +1094,7 @@ PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBounds( ) { return bounds == null ? null - : PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds), - ); + : PlatformCameraTargetBounds(bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds)); } PlatformTile _platformTileFromTile(Tile tile) { @@ -1306,12 +1125,8 @@ PlatformMapType? _platformMapTypeFromMapType(MapType? type) { return PlatformMapType.normal; } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference( - MinMaxZoomPreference? zoomPref, -) { - return zoomPref == null - ? null - : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference(MinMaxZoomPreference? zoomPref) { + return zoomPref == null ? null : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); } PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { @@ -1325,18 +1140,14 @@ PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { ); } -PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( - MapConfiguration config, -) { +PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration(MapConfiguration config) { return PlatformMapConfiguration( compassEnabled: config.compassEnabled, cameraTargetBounds: _platformCameraTargetBoundsFromCameraTargetBounds( config.cameraTargetBounds, ), mapType: _platformMapTypeFromMapType(config.mapType), - minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference( - config.minMaxZoomPreference, - ), + minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference(config.minMaxZoomPreference), rotateGesturesEnabled: config.rotateGesturesEnabled, scrollGesturesEnabled: config.scrollGesturesEnabled, tiltGesturesEnabled: config.tiltGesturesEnabled, @@ -1348,9 +1159,7 @@ PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( indoorViewEnabled: config.indoorViewEnabled, trafficEnabled: config.trafficEnabled, buildingsEnabled: config.buildingsEnabled, - markerType: _platformMarkerTypeFromMarkerType( - config.markerType ?? MarkerType.marker, - ), + markerType: _platformMarkerTypeFromMarkerType(config.markerType ?? MarkerType.marker), mapId: config.mapId, style: config.style, ); @@ -1374,14 +1183,11 @@ PlatformMarkerType _platformMarkerTypeFromMarkerType(MarkerType markerType) { } // For supporting the deprecated updateMapOptions API. -PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( - Map options, -) { +PlatformMapConfiguration _platformMapConfigurationFromOptionsJson(Map options) { // All of these hard-coded values and structures come from // google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart // to support this legacy API that relied on cross-package magic strings. - final List? padding = (options['padding'] as List?) - ?.cast(); + final List? padding = (options['padding'] as List?)?.cast(); final mapType = options['mapType'] as int?; return PlatformMapConfiguration( compassEnabled: options['compassEnabled'] as bool?, @@ -1416,9 +1222,7 @@ PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( ); } -PlatformCameraPosition _platformCameraPositionFromCameraPosition( - CameraPosition position, -) { +PlatformCameraPosition _platformCameraPositionFromCameraPosition(CameraPosition position) { return PlatformCameraPosition( bearing: position.bearing, target: _platformLatLngFromLatLng(position.target), @@ -1446,9 +1250,7 @@ PlatformLatLng _platformLatLngFromLatLngJson(Object latLngJson) { return PlatformLatLng(latitude: list[0], longitude: list[1]); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( - Object? boundsJson, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson(Object? boundsJson) { if (boundsJson == null) { return null; } @@ -1460,28 +1262,24 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( ); } -PlatformCameraTargetBounds? -_platformCameraTargetBoundsFromCameraTargetBoundsJson(Object? targetJson) { +PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBoundsJson( + Object? targetJson, +) { if (targetJson == null) { return null; } // See `CameraTargetBounds.toJson`. return PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBoundsJson( - (targetJson as List)[0], - ), + bounds: _platformLatLngBoundsFromLatLngBoundsJson((targetJson as List)[0]), ); } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson( - Object? zoomPrefsJson, -) { +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson(Object? zoomPrefsJson) { if (zoomPrefsJson == null) { return null; } // See `MinMaxZoomPreference.toJson`. - final List minMaxZoom = (zoomPrefsJson as List) - .cast(); + final List minMaxZoom = (zoomPrefsJson as List).cast(); return PlatformZoomRange(min: minMaxZoom[0], max: minMaxZoom[1]); } @@ -1514,16 +1312,10 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { return PlatformPatternItem(type: PlatformPatternItemType.dot); case PatternItemType.dash: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.dash, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.dash, length: length); case PatternItemType.gap: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.gap, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.gap, length: length); } // The enum comes from a different package, which could get a new value at @@ -1540,15 +1332,13 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { // interface, and remove this copy. class _TileOverlayUpdates extends MapsObjectUpdates { /// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s. - _TileOverlayUpdates.from(super.previous, super.current) - : super.from(objectName: 'tileOverlay'); + _TileOverlayUpdates.from(super.previous, super.current) : super.from(objectName: 'tileOverlay'); /// Set of TileOverlays to be added in this update. Set get tileOverlaysToAdd => objectsToAdd; /// Set of TileOverlayIds to be removed in this update. - Set get tileOverlayIdsToRemove => - objectIdsToRemove.cast(); + Set get tileOverlayIdsToRemove => objectIdsToRemove.cast(); /// Set of TileOverlays to be changed in this update. Set get tileOverlaysToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/messages.g.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/messages.g.dart index 87fd64fcb0bc..be134f058b12 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/messages.g.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/lib/src/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -187,8 +181,7 @@ class PlatformCameraUpdateNewCameraPosition { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewCameraPosition || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewCameraPosition || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -224,8 +217,7 @@ class PlatformCameraUpdateNewLatLng { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLng || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLng || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -241,10 +233,7 @@ class PlatformCameraUpdateNewLatLng { /// Pigeon equivalent of NewLatLngBounds class PlatformCameraUpdateNewLatLngBounds { - PlatformCameraUpdateNewLatLngBounds({ - required this.bounds, - required this.padding, - }); + PlatformCameraUpdateNewLatLngBounds({required this.bounds, required this.padding}); PlatformLatLngBounds bounds; @@ -269,8 +258,7 @@ class PlatformCameraUpdateNewLatLngBounds { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -311,8 +299,7 @@ class PlatformCameraUpdateNewLatLngZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -344,17 +331,13 @@ class PlatformCameraUpdateScrollBy { static PlatformCameraUpdateScrollBy decode(Object result) { result as List; - return PlatformCameraUpdateScrollBy( - dx: result[0]! as double, - dy: result[1]! as double, - ); + return PlatformCameraUpdateScrollBy(dx: result[0]! as double, dy: result[1]! as double); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateScrollBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateScrollBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -395,8 +378,7 @@ class PlatformCameraUpdateZoomBy { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -432,8 +414,7 @@ class PlatformCameraUpdateZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -469,8 +450,7 @@ class PlatformCameraUpdateZoomTo { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomTo || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomTo || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1255,14 +1235,7 @@ class PlatformTileOverlay { int tileSize; List _toList() { - return [ - tileOverlayId, - fadeIn, - transparency, - zIndex, - visible, - tileSize, - ]; + return [tileOverlayId, fadeIn, transparency, zIndex, visible, tileSize]; } Object encode() { @@ -1368,10 +1341,7 @@ class PlatformLatLng { static PlatformLatLng decode(Object result) { result as List; - return PlatformLatLng( - latitude: result[0]! as double, - longitude: result[1]! as double, - ); + return PlatformLatLng(latitude: result[0]! as double, longitude: result[1]! as double); } @override @@ -1451,16 +1421,13 @@ class PlatformCameraTargetBounds { static PlatformCameraTargetBounds decode(Object result) { result as List; - return PlatformCameraTargetBounds( - bounds: result[0] as PlatformLatLngBounds?, - ); + return PlatformCameraTargetBounds(bounds: result[0] as PlatformLatLngBounds?); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraTargetBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraTargetBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1630,20 +1597,16 @@ class PlatformMapViewCreationParams { initialPolygons: (result[4] as List?)!.cast(), initialPolylines: (result[5] as List?)!.cast(), initialHeatmaps: (result[6] as List?)!.cast(), - initialTileOverlays: (result[7] as List?)! - .cast(), - initialClusterManagers: (result[8] as List?)! - .cast(), - initialGroundOverlays: (result[9] as List?)! - .cast(), + initialTileOverlays: (result[7] as List?)!.cast(), + initialClusterManagers: (result[8] as List?)!.cast(), + initialGroundOverlays: (result[9] as List?)!.cast(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapViewCreationParams || - other.runtimeType != runtimeType) { + if (other is! PlatformMapViewCreationParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1770,8 +1733,7 @@ class PlatformMapConfiguration { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapConfiguration || - other.runtimeType != runtimeType) { + if (other is! PlatformMapConfiguration || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1841,10 +1803,7 @@ class PlatformSize { static PlatformSize decode(Object result) { result as List; - return PlatformSize( - width: result[0]! as double, - height: result[1]! as double, - ); + return PlatformSize(width: result[0]! as double, height: result[1]! as double); } @override @@ -1866,12 +1825,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); double red; @@ -1986,10 +1940,7 @@ class PlatformZoomRange { static PlatformZoomRange decode(Object result) { result as List; - return PlatformZoomRange( - min: result[0] as double?, - max: result[1] as double?, - ); + return PlatformZoomRange(min: result[0] as double?, max: result[1] as double?); } @override @@ -2076,8 +2027,7 @@ class PlatformBitmapDefaultMarker { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapDefaultMarker || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapDefaultMarker || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2109,10 +2059,7 @@ class PlatformBitmapBytes { static PlatformBitmapBytes decode(Object result) { result as List; - return PlatformBitmapBytes( - byteData: result[0]! as Uint8List, - size: result[1] as PlatformSize?, - ); + return PlatformBitmapBytes(byteData: result[0]! as Uint8List, size: result[1] as PlatformSize?); } @override @@ -2150,10 +2097,7 @@ class PlatformBitmapAsset { static PlatformBitmapAsset decode(Object result) { result as List; - return PlatformBitmapAsset( - name: result[0]! as String, - pkg: result[1] as String?, - ); + return PlatformBitmapAsset(name: result[0]! as String, pkg: result[1] as String?); } @override @@ -2175,11 +2119,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); String name; @@ -2207,8 +2147,7 @@ class PlatformBitmapAssetImage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapAssetImage || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapAssetImage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2568,9 +2507,7 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PlatformMapType.values[value]; case 130: final value = readValue(buffer) as int?; - return value == null - ? null - : PlatformMarkerCollisionBehavior.values[value]; + return value == null ? null : PlatformMarkerCollisionBehavior.values[value]; case 131: final value = readValue(buffer) as int?; return value == null ? null : PlatformJointType.values[value]; @@ -2721,9 +2658,7 @@ class MapsApi { /// /// Only non-null configuration values will result in updates; options with /// null values will remain unchanged. - Future updateMapConfiguration( - PlatformMapConfiguration configuration, - ) async { + Future updateMapConfiguration(PlatformMapConfiguration configuration) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.updateMapConfiguration$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2731,9 +2666,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [configuration], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([configuration]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2761,9 +2694,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2791,9 +2726,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2820,9 +2757,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2850,9 +2788,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2880,9 +2820,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2910,9 +2852,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2940,9 +2884,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2970,9 +2916,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2996,9 +2944,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [latLng], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([latLng]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3027,9 +2973,9 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [screenCoordinate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + screenCoordinate, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3088,9 +3034,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraUpdate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3107,10 +3051,7 @@ class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. - Future animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ) async { + Future animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.animateCamera$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3118,9 +3059,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate, durationMilliseconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraUpdate, + durationMilliseconds, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3173,9 +3115,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3199,9 +3139,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3226,9 +3164,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3261,9 +3197,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [style], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([style]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3315,9 +3249,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3436,20 +3368,14 @@ abstract class MapsCallbackApi { void onGroundOverlayTap(String groundOverlayId); /// Called to get data for a map tile. - Future getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + Future getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); static void setUp( MapsCallbackApi? api, { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMoveStarted$messageChannelSuffix', @@ -3488,8 +3414,7 @@ abstract class MapsCallbackApi { 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null.', ); final List args = (message as List?)!; - final PlatformCameraPosition? arg_cameraPosition = - (args[0] as PlatformCameraPosition?); + final PlatformCameraPosition? arg_cameraPosition = (args[0] as PlatformCameraPosition?); assert( arg_cameraPosition != null, 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null, expected non-null PlatformCameraPosition.', @@ -3998,13 +3923,11 @@ class MapsPlatformViewApi { /// Constructor for [MapsPlatformViewApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsPlatformViewApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsPlatformViewApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4019,9 +3942,7 @@ class MapsPlatformViewApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [type], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([type]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4042,13 +3963,11 @@ class MapsInspectorApi { /// Constructor for [MapsInspectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsInspectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsInspectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4287,9 +4206,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4304,9 +4221,7 @@ class MapsInspectorApi { } } - Future getGroundOverlayInfo( - String groundOverlayId, - ) async { + Future getGroundOverlayInfo(String groundOverlayId) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsInspectorApi.getGroundOverlayInfo$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4314,9 +4229,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [groundOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([groundOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4339,9 +4252,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [heatmapId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([heatmapId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4392,9 +4303,9 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [clusterManagerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + clusterManagerId, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4410,8 +4321,7 @@ class MapsInspectorApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/pigeons/messages.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/pigeons/messages.dart index d86ff8472237..51d82926642f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/pigeons/messages.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/pigeons/messages.dart @@ -510,12 +510,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); final double red; final double green; @@ -587,11 +582,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); final String name; final double scale; final PlatformSize? size; @@ -685,10 +676,7 @@ abstract class MapsApi { /// Updates the set of custer managers for clusters on the map. @ObjCSelector('updateClusterManagersByAdding:removing:') - void updateClusterManagers( - List toAdd, - List idsToRemove, - ); + void updateClusterManagers(List toAdd, List idsToRemove); /// Updates the set of markers on the map. @ObjCSelector('updateMarkersByAdding:changing:removing:') @@ -750,10 +738,7 @@ abstract class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. @ObjCSelector('animateCameraWithUpdate:duration:') - void animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ); + void animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds); /// Gets the current map zoom level. @ObjCSelector('currentZoomLevel') @@ -866,11 +851,7 @@ abstract class MapsCallbackApi { /// Called to get data for a map tile. @async @ObjCSelector('tileWithOverlayIdentifier:location:zoom:') - PlatformTile getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + PlatformTile getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); } /// Dummy interface to force generation of the platform view creation params, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.dart index 486884bc81d1..c2fa99cac0dd 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.dart @@ -43,28 +43,18 @@ void main() { test('getScreenCoordinate converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const latLng = LatLng(10, 20); const expectedCoord = ScreenCoordinate(x: 30, y: 40); when(api.getScreenCoordinate(any)).thenAnswer( - (_) async => PlatformPoint( - x: expectedCoord.x.toDouble(), - y: expectedCoord.y.toDouble(), - ), + (_) async => PlatformPoint(x: expectedCoord.x.toDouble(), y: expectedCoord.y.toDouble()), ); - final ScreenCoordinate coord = await maps.getScreenCoordinate( - latLng, - mapId: mapId, - ); + final ScreenCoordinate coord = await maps.getScreenCoordinate(latLng, mapId: mapId); expect(coord, expectedCoord); - final VerificationResult verification = verify( - api.getScreenCoordinate(captureAny), - ); + final VerificationResult verification = verify(api.getScreenCoordinate(captureAny)); final passedLatLng = verification.captured[0] as PlatformLatLng; expect(passedLatLng.latitude, latLng.latitude); expect(passedLatLng.longitude, latLng.longitude); @@ -72,18 +62,14 @@ void main() { test('getLatLng converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const expectedLatLng = LatLng(10, 20); const coord = ScreenCoordinate(x: 30, y: 40); when(api.getLatLng(any)).thenAnswer( - (_) async => PlatformLatLng( - latitude: expectedLatLng.latitude, - longitude: expectedLatLng.longitude, - ), + (_) async => + PlatformLatLng(latitude: expectedLatLng.latitude, longitude: expectedLatLng.longitude), ); final LatLng latLng = await maps.getLatLng(coord, mapId: mapId); @@ -96,9 +82,7 @@ void main() { test('getVisibleRegion converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. final expectedBounds = LatLngBounds( @@ -124,9 +108,7 @@ void main() { test('moveCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.moveCamera(update, mapId: mapId); @@ -141,16 +123,12 @@ void main() { test('animateCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.animateCamera(update, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -161,24 +139,14 @@ void main() { test('animateCameraWithConfiguration calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); - const configuration = CameraUpdateAnimationConfiguration( - duration: Duration(seconds: 1), - ); + const configuration = CameraUpdateAnimationConfiguration(duration: Duration(seconds: 1)); expect(configuration.duration?.inSeconds, 1); - await maps.animateCameraWithConfiguration( - update, - configuration, - mapId: mapId, - ); + await maps.animateCameraWithConfiguration(update, configuration, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -191,9 +159,7 @@ void main() { test('getZoomLevel passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const expectedZoom = 4.2; when(api.getZoomLevel()).thenAnswer((_) async => expectedZoom); @@ -204,9 +170,7 @@ void main() { test('showInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.showMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -216,9 +180,7 @@ void main() { test('hideInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.hideMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -228,27 +190,17 @@ void main() { test('isInfoWindowShown calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; when(api.isInfoWindowShown(markedId)).thenAnswer((_) async => true); - expect( - await maps.isMarkerInfoWindowShown( - const MarkerId(markedId), - mapId: mapId, - ), - true, - ); + expect(await maps.isMarkerInfoWindowShown(const MarkerId(markedId), mapId: mapId), true); }); test('takeSnapshot calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final fakeSnapshot = Uint8List(10); when(api.takeSnapshot()).thenAnswer((_) async => fakeSnapshot); @@ -258,9 +210,7 @@ void main() { test('clearTileCache calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const tileOverlayId = 'overlay'; await maps.clearTileCache(const TileOverlayId(tileOverlayId), mapId: mapId); @@ -270,16 +220,11 @@ void main() { test('updateMapConfiguration passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = MapConfiguration( compassEnabled: true, @@ -288,9 +233,7 @@ void main() { ); await maps.updateMapConfiguration(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -319,16 +262,11 @@ void main() { test('updateMapOptions passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = { 'compassEnabled': true, @@ -337,9 +275,7 @@ void main() { }; await maps.updateMapOptions(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -368,19 +304,14 @@ void main() { test('updateCircles passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Circle(circleId: CircleId('1')); const object2old = Circle(circleId: CircleId('2')); final Circle object2new = object2old.copyWith(radiusParam: 42); const object3 = Circle(circleId: CircleId('3')); await maps.updateCircles( - CircleUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + CircleUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -427,17 +358,12 @@ void main() { test('updateClusterManagers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = ClusterManager(clusterManagerId: ClusterManagerId('1')); const object3 = ClusterManager(clusterManagerId: ClusterManagerId('3')); await maps.updateClusterManagers( - ClusterManagerUpdates.from( - {object1}, - {object3}, - ), + ClusterManagerUpdates.from({object1}, {object3}), mapId: mapId, ); @@ -458,19 +384,14 @@ void main() { test('updateMarkers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Marker(markerId: MarkerId('1')); const object2old = Marker(markerId: MarkerId('2')); final Marker object2new = object2old.copyWith(rotationParam: 42); const object3 = Marker(markerId: MarkerId('3')); await maps.updateMarkers( - MarkerUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + MarkerUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -495,9 +416,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -523,9 +442,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -543,21 +460,17 @@ void main() { test('updateMarkers passes expected arguments (AdvancedMarkers)', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final object1 = AdvancedMarker(markerId: const MarkerId('1')); final object2old = AdvancedMarker(markerId: const MarkerId('2')); final AdvancedMarker object2new = object2old.copyWith( rotationParam: 42, - collisionBehaviorParam: - advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, + collisionBehaviorParam: advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, ); final object3 = AdvancedMarker( markerId: const MarkerId('3'), - collisionBehavior: - advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, + collisionBehavior: advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, ); await maps.updateMarkers( MarkerUpdates.from( @@ -588,9 +501,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -622,9 +533,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -648,19 +557,14 @@ void main() { test('updatePolygons passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polygon(polygonId: PolygonId('1')); const object2old = Polygon(polygonId: PolygonId('2')); final Polygon object2new = object2old.copyWith(strokeWidthParam: 42); const object3 = Polygon(polygonId: PolygonId('3')); await maps.updatePolygons( - PolygonUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolygonUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -707,9 +611,7 @@ void main() { test('updatePolylines passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polyline(polylineId: PolylineId('1')); const object2old = Polyline(polylineId: PolylineId('2')); @@ -718,20 +620,14 @@ void main() { startCapParam: Cap.squareCap, endCapParam: Cap.buttCap, ); - final Cap customCap = Cap.customCapFromBitmap( - BitmapDescriptor.defaultMarker, - refWidth: 15, - ); + final Cap customCap = Cap.customCapFromBitmap(BitmapDescriptor.defaultMarker, refWidth: 15); final object3 = Polyline( polylineId: const PolylineId('3'), startCap: customCap, endCap: Cap.roundCap, ); await maps.updatePolylines( - PolylineUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolylineUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -746,10 +642,7 @@ void main() { expect(actual.consumesTapEvents, expected.consumeTapEvents); _expectColorsEqual(actual.color, expected.color); expect(actual.geodesic, expected.geodesic); - expect( - actual.jointType, - platformJointTypeFromJointType(expected.jointType), - ); + expect(actual.jointType, platformJointTypeFromJointType(expected.jointType)); expect(actual.visible, expected.visible); expect(actual.width, expected.width); expect(actual.zIndex, expected.zIndex); @@ -759,8 +652,7 @@ void main() { expect(point?.longitude, actual.points[i].longitude); } expect(actual.patterns.length, expected.patterns.length); - for (final (int i, PlatformPatternItem? pattern) - in actual.patterns.indexed) { + for (final (int i, PlatformPatternItem? pattern) in actual.patterns.indexed) { expect( pattern?.encode(), platformPatternItemFromPatternItem(expected.patterns[i]).encode(), @@ -781,9 +673,7 @@ void main() { test('updateTileOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = TileOverlay(tileOverlayId: TileOverlayId('1')); const object2old = TileOverlay(tileOverlayId: TileOverlayId('2')); @@ -830,9 +720,7 @@ void main() { test('updateGroundOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final image = AssetMapBitmap( 'assets/red_square.png', @@ -842,18 +730,12 @@ void main() { final object1 = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('1'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final object2old = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('2'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final GroundOverlay object2new = object2old.copyWith( @@ -895,22 +777,10 @@ void main() { expect(firstChanged.anchor?.x, object2new.anchor?.dx); expect(firstChanged.anchor?.y, object2new.anchor?.dy); expect(firstChanged.bearing, object2new.bearing); - expect( - firstChanged.bounds?.northeast.latitude, - object2new.bounds?.northeast.latitude, - ); - expect( - firstChanged.bounds?.northeast.longitude, - object2new.bounds?.northeast.longitude, - ); - expect( - firstChanged.bounds?.southwest.latitude, - object2new.bounds?.southwest.latitude, - ); - expect( - firstChanged.bounds?.southwest.longitude, - object2new.bounds?.southwest.longitude, - ); + expect(firstChanged.bounds?.northeast.latitude, object2new.bounds?.northeast.latitude); + expect(firstChanged.bounds?.northeast.longitude, object2new.bounds?.northeast.longitude); + expect(firstChanged.bounds?.southwest.latitude, object2new.bounds?.southwest.latitude); + expect(firstChanged.bounds?.southwest.longitude, object2new.bounds?.southwest.longitude); expect(firstChanged.visible, object2new.visible); expect(firstChanged.clickable, object2new.clickable); expect(firstChanged.zIndex, object2new.zIndex); @@ -932,22 +802,10 @@ void main() { expect(firstAdded.anchor?.x, object3.anchor?.dx); expect(firstAdded.anchor?.y, object3.anchor?.dy); expect(firstAdded.bearing, object3.bearing); - expect( - firstAdded.bounds?.northeast.latitude, - object3.bounds?.northeast.latitude, - ); - expect( - firstAdded.bounds?.northeast.longitude, - object3.bounds?.northeast.longitude, - ); - expect( - firstAdded.bounds?.southwest.latitude, - object3.bounds?.southwest.latitude, - ); - expect( - firstAdded.bounds?.southwest.longitude, - object3.bounds?.southwest.longitude, - ); + expect(firstAdded.bounds?.northeast.latitude, object3.bounds?.northeast.latitude); + expect(firstAdded.bounds?.northeast.longitude, object3.bounds?.northeast.longitude); + expect(firstAdded.bounds?.southwest.latitude, object3.bounds?.southwest.latitude); + expect(firstAdded.bounds?.southwest.longitude, object3.bounds?.southwest.longitude); expect(firstAdded.visible, object3.visible); expect(firstAdded.clickable, object3.clickable); expect(firstAdded.zIndex, object3.zIndex); @@ -957,48 +815,39 @@ void main() { expect(firstAdded.transparency, object3.transparency); expect( firstAdded.image.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.image, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.image).bitmap.runtimeType, ); } }); - test( - 'updateGroundOverlays throws assertion error on unsupported ground overlays', - () async { - const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + test('updateGroundOverlays throws assertion error on unsupported ground overlays', () async { + const mapId = 1; + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); - final image = AssetMapBitmap( - 'assets/red_square.png', - imagePixelRatio: 1.0, - bitmapScaling: MapBitmapScaling.none, - ); + final image = AssetMapBitmap( + 'assets/red_square.png', + imagePixelRatio: 1.0, + bitmapScaling: MapBitmapScaling.none, + ); - final object3 = GroundOverlay.fromPosition( - groundOverlayId: const GroundOverlayId('1'), - position: const LatLng(10, 20), - // Assert should be thrown because zoomLevel is not set for position-based - // ground overlay on iOS. - // ignore: avoid_redundant_argument_values - zoomLevel: null, - image: image, - ); + final object3 = GroundOverlay.fromPosition( + groundOverlayId: const GroundOverlayId('1'), + position: const LatLng(10, 20), + // Assert should be thrown because zoomLevel is not set for position-based + // ground overlay on iOS. + // ignore: avoid_redundant_argument_values + zoomLevel: null, + image: image, + ); - expect( - () async => maps.updateGroundOverlays( - GroundOverlayUpdates.from(const {}, { - object3, - }), - mapId: mapId, - ), - throwsAssertionError, - ); - }, - ); + expect( + () async => maps.updateGroundOverlays( + GroundOverlayUpdates.from(const {}, {object3}), + mapId: mapId, + ), + throwsAssertionError, + ); + }); test('markers send drag event to correct streams', () async { const mapId = 1; @@ -1008,19 +857,13 @@ void main() { final fakePosition = PlatformLatLng(latitude: 1.0, longitude: 1.0); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final markerDragStartStream = StreamQueue( maps.onMarkerDragStart(mapId: mapId), ); - final markerDragStream = StreamQueue( - maps.onMarkerDrag(mapId: mapId), - ); - final markerDragEndStream = StreamQueue( - maps.onMarkerDragEnd(mapId: mapId), - ); + final markerDragStream = StreamQueue(maps.onMarkerDrag(mapId: mapId)); + final markerDragEndStream = StreamQueue(maps.onMarkerDragEnd(mapId: mapId)); // Simulate messages from the native side. callbackHandler.onMarkerDragStart(dragStartId, fakePosition); @@ -1037,9 +880,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onMarkerTap(mapId: mapId)); @@ -1054,9 +895,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onCircleTap(mapId: mapId)); @@ -1083,13 +922,9 @@ void main() { ); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onClusterTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onClusterTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onClusterTap(cluster); @@ -1099,15 +934,9 @@ void main() { expect(eventValue.position.latitude, fakePosition.latitude); expect(eventValue.position.longitude, fakePosition.longitude); expect(eventValue.bounds.southwest.latitude, fakeBounds.southwest.latitude); - expect( - eventValue.bounds.southwest.longitude, - fakeBounds.southwest.longitude, - ); + expect(eventValue.bounds.southwest.longitude, fakeBounds.southwest.longitude); expect(eventValue.bounds.northeast.latitude, fakeBounds.northeast.latitude); - expect( - eventValue.bounds.northeast.longitude, - fakeBounds.northeast.longitude, - ); + expect(eventValue.bounds.northeast.longitude, fakeBounds.northeast.longitude); expect(eventValue.markerIds.length, markerIds.length); expect(eventValue.markerIds.first.value, markerIds.first); }); @@ -1117,13 +946,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolygonTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolygonTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolygonTap(objectId); @@ -1136,13 +961,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolylineTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolylineTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolylineTap(objectId); @@ -1155,13 +976,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onGroundOverlayTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onGroundOverlayTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onGroundOverlayTap(objectId); @@ -1171,9 +988,7 @@ void main() { test('moveCamera calls through with expected newCameraPosition', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); const position = CameraPosition(target: latLng); @@ -1182,24 +997,15 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; update as CameraUpdateNewCameraPosition; - expect( - typedUpdate.cameraPosition.target.latitude, - update.cameraPosition.target.latitude, - ); - expect( - typedUpdate.cameraPosition.target.longitude, - update.cameraPosition.target.longitude, - ); + expect(typedUpdate.cameraPosition.target.latitude, update.cameraPosition.target.latitude); + expect(typedUpdate.cameraPosition.target.longitude, update.cameraPosition.target.longitude); }); test('moveCamera calls through with expected newLatLng', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLng(latLng); @@ -1207,8 +1013,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; update as CameraUpdateNewLatLng; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1216,9 +1021,7 @@ void main() { test('moveCamera calls through with expected newLatLngBounds', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final latLng = LatLngBounds( northeast: const LatLng(10.0, 20.0), @@ -1229,33 +1032,18 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; update as CameraUpdateNewLatLngBounds; - expect( - typedUpdate.bounds.northeast.latitude, - update.bounds.northeast.latitude, - ); - expect( - typedUpdate.bounds.northeast.longitude, - update.bounds.northeast.longitude, - ); - expect( - typedUpdate.bounds.southwest.latitude, - update.bounds.southwest.latitude, - ); - expect( - typedUpdate.bounds.southwest.longitude, - update.bounds.southwest.longitude, - ); + expect(typedUpdate.bounds.northeast.latitude, update.bounds.northeast.latitude); + expect(typedUpdate.bounds.northeast.longitude, update.bounds.northeast.longitude); + expect(typedUpdate.bounds.southwest.latitude, update.bounds.southwest.latitude); + expect(typedUpdate.bounds.southwest.longitude, update.bounds.southwest.longitude); expect(typedUpdate.padding, update.padding); }); test('moveCamera calls through with expected newLatLngZoom', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLngZoom(latLng, 2.0); @@ -1263,8 +1051,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; update as CameraUpdateNewLatLngZoom; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1273,9 +1060,7 @@ void main() { test('moveCamera calls through with expected zoomBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const focus = Offset(10.0, 20.0); final CameraUpdate update = CameraUpdate.zoomBy(2.0, focus); @@ -1292,9 +1077,7 @@ void main() { test('moveCamera calls through with expected zoomTo', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomTo(2.0); await maps.moveCamera(update, mapId: mapId); @@ -1308,9 +1091,7 @@ void main() { test('moveCamera calls through with expected zoomIn', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomIn(); await maps.moveCamera(update, mapId: mapId); @@ -1323,9 +1104,7 @@ void main() { test('moveCamera calls through with expected zoomOut', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomOut(); await maps.moveCamera(update, mapId: mapId); @@ -1338,23 +1117,20 @@ void main() { test('MapBitmapScaling to PlatformMapBitmapScaling', () { expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.auto, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.auto), PlatformMapBitmapScaling.auto, ); expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.none, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.none), PlatformMapBitmapScaling.none, ); }); test('DefaultMarker bitmap to PlatformBitmap', () { final BitmapDescriptor bitmap = BitmapDescriptor.defaultMarkerWithHue(10.0); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapDefaultMarker; expect(typedBitmap.hue, 10.0); @@ -1368,8 +1144,9 @@ void main() { width: 100.0, height: 200.0, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapBytesMap; expect(typedBitmap.byteData, data); @@ -1381,14 +1158,10 @@ void main() { test('AssetMapBitmap bitmap to PlatformBitmap', () { const assetName = 'fake_asset_name'; - final bitmap = AssetMapBitmap( - assetName, - imagePixelRatio: 2.0, - width: 100.0, - height: 200.0, + final bitmap = AssetMapBitmap(assetName, imagePixelRatio: 2.0, width: 100.0, height: 200.0); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapAssetMap; expect(typedBitmap.assetName, assetName); @@ -1402,31 +1175,28 @@ void main() { const cloudMapId = '000000000000000'; // Dummy map ID. final passedCloudMapIdCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null) { - final String? passedMapId = - creationParams.mapConfiguration.mapId; - if (passedMapId != null) { - passedCloudMapIdCompleter.complete(passedMapId); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null) { + final String? passedMapId = creationParams.mapConfiguration.mapId; + if (passedMapId != null) { + passedCloudMapIdCompleter.complete(passedMapId); } } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1437,10 +1207,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: const MapConfiguration(mapId: cloudMapId), @@ -1462,30 +1229,25 @@ void main() { ) async { final passedMarkerTypeCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null && - !passedMarkerTypeCompleter.isCompleted) { - passedMarkerTypeCompleter.complete( - creationParams.mapConfiguration.markerType, - ); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null && !passedMarkerTypeCompleter.isCompleted) { + passedMarkerTypeCompleter.complete(creationParams.mapConfiguration.markerType); } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1496,10 +1258,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: MapConfiguration(markerType: markerType), @@ -1513,11 +1272,10 @@ void main() { testWidgets('passes advancedMarker when MarkerType.advancedMarker is set', ( WidgetTester tester, ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams( - tester, - MarkerType.advancedMarker, - ); + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.advancedMarker, + ); expect( passedMarkerType, @@ -1527,31 +1285,29 @@ void main() { ); }); - testWidgets('passes marker when MarkerType.marker is set', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, MarkerType.marker); + testWidgets('passes marker when MarkerType.marker is set', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.marker, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should pass marker on PlatformView creation when MarkerType.marker is set', + reason: 'Should pass marker on PlatformView creation when MarkerType.marker is set', ); }); - testWidgets('passes marker when markerType is null', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, null); + testWidgets('passes marker when markerType is null', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + null, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should default to marker on PlatformView creation when markerType is null', + reason: 'Should default to marker on PlatformView creation when markerType is null', ); }); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.mocks.dart index 443bc62e1739..3dc2f91066a7 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/test/google_maps_flutter_ios_test.mocks.dart @@ -29,14 +29,12 @@ class _FakePlatformPoint_0 extends _i1.SmartFake implements _i2.PlatformPoint { : super(parent, parentInvocation); } -class _FakePlatformLatLng_1 extends _i1.SmartFake - implements _i2.PlatformLatLng { +class _FakePlatformLatLng_1 extends _i1.SmartFake implements _i2.PlatformLatLng { _FakePlatformLatLng_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePlatformLatLngBounds_2 extends _i1.SmartFake - implements _i2.PlatformLatLngBounds { +class _FakePlatformLatLngBounds_2 extends _i1.SmartFake implements _i2.PlatformLatLngBounds { _FakePlatformLatLngBounds_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -46,315 +44,229 @@ class _FakePlatformLatLngBounds_2 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockMapsApi extends _i1.Mock implements _i2.MapsApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future waitForMap() => - (super.noSuchMethod( - Invocation.method(#waitForMap, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future waitForMap() => (super.noSuchMethod( + Invocation.method(#waitForMap, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future updateMapConfiguration( - _i2.PlatformMapConfiguration? configuration, - ) => + _i4.Future updateMapConfiguration(_i2.PlatformMapConfiguration? configuration) => (super.noSuchMethod( - Invocation.method(#updateMapConfiguration, [configuration]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#updateMapConfiguration, [configuration]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateCircles( List<_i2.PlatformCircle>? toAdd, List<_i2.PlatformCircle>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateHeatmaps( List<_i2.PlatformHeatmap>? toAdd, List<_i2.PlatformHeatmap>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateClusterManagers( List<_i2.PlatformClusterManager>? toAdd, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateMarkers( List<_i2.PlatformMarker>? toAdd, List<_i2.PlatformMarker>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolygons( List<_i2.PlatformPolygon>? toAdd, List<_i2.PlatformPolygon>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolylines( List<_i2.PlatformPolyline>? toAdd, List<_i2.PlatformPolyline>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateTileOverlays( List<_i2.PlatformTileOverlay>? toAdd, List<_i2.PlatformTileOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateTileOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateTileOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateGroundOverlays( List<_i2.PlatformGroundOverlay>? toAdd, List<_i2.PlatformGroundOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateGroundOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateGroundOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformPoint> getScreenCoordinate( - _i2.PlatformLatLng? latLng, - ) => + _i4.Future<_i2.PlatformPoint> getScreenCoordinate(_i2.PlatformLatLng? latLng) => (super.noSuchMethod( - Invocation.method(#getScreenCoordinate, [latLng]), - returnValue: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - ) - as _i4.Future<_i2.PlatformPoint>); + Invocation.method(#getScreenCoordinate, [latLng]), + returnValue: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + ) as _i4.Future<_i2.PlatformPoint>); @override - _i4.Future<_i2.PlatformLatLng> getLatLng( - _i2.PlatformPoint? screenCoordinate, - ) => + _i4.Future<_i2.PlatformLatLng> getLatLng(_i2.PlatformPoint? screenCoordinate) => (super.noSuchMethod( - Invocation.method(#getLatLng, [screenCoordinate]), - returnValue: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLng>); + Invocation.method(#getLatLng, [screenCoordinate]), + returnValue: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + ) as _i4.Future<_i2.PlatformLatLng>); @override - _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => - (super.noSuchMethod( - Invocation.method(#getVisibleRegion, []), - returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLngBounds>); + _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => (super.noSuchMethod( + Invocation.method(#getVisibleRegion, []), + returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + ) as _i4.Future<_i2.PlatformLatLngBounds>); @override - _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => - (super.noSuchMethod( - Invocation.method(#moveCamera, [cameraUpdate]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => (super.noSuchMethod( + Invocation.method(#moveCamera, [cameraUpdate]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future animateCamera( _i2.PlatformCameraUpdate? cameraUpdate, int? durationMilliseconds, - ) => - (super.noSuchMethod( - Invocation.method(#animateCamera, [ - cameraUpdate, - durationMilliseconds, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#animateCamera, [cameraUpdate, durationMilliseconds]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getZoomLevel() => (super.noSuchMethod( + Invocation.method(#getZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future showInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#showInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future showInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#showInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future hideInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#hideInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future hideInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#hideInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future isInfoWindowShown(String? markerId) => - (super.noSuchMethod( - Invocation.method(#isInfoWindowShown, [markerId]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isInfoWindowShown(String? markerId) => (super.noSuchMethod( + Invocation.method(#isInfoWindowShown, [markerId]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future setStyle(String? style) => - (super.noSuchMethod( - Invocation.method(#setStyle, [style]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setStyle(String? style) => (super.noSuchMethod( + Invocation.method(#setStyle, [style]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getLastStyleError() => - (super.noSuchMethod( - Invocation.method(#getLastStyleError, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getLastStyleError() => (super.noSuchMethod( + Invocation.method(#getLastStyleError, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future clearTileCache(String? tileOverlayId) => - (super.noSuchMethod( - Invocation.method(#clearTileCache, [tileOverlayId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future clearTileCache(String? tileOverlayId) => (super.noSuchMethod( + Invocation.method(#clearTileCache, [tileOverlayId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i5.Uint8List?> takeSnapshot() => - (super.noSuchMethod( - Invocation.method(#takeSnapshot, []), - returnValue: _i4.Future<_i5.Uint8List?>.value(), - returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), - ) - as _i4.Future<_i5.Uint8List?>); + _i4.Future<_i5.Uint8List?> takeSnapshot() => (super.noSuchMethod( + Invocation.method(#takeSnapshot, []), + returnValue: _i4.Future<_i5.Uint8List?>.value(), + returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), + ) as _i4.Future<_i5.Uint8List?>); @override - _i4.Future isAdvancedMarkersAvailable() => - (super.noSuchMethod( - Invocation.method(#isAdvancedMarkersAvailable, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isAdvancedMarkersAvailable() => (super.noSuchMethod( + Invocation.method(#isAdvancedMarkersAvailable, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/run_tests.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/run_tests.dart index f49c29eaf7fe..af88ecc57b9c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/run_tests.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/run_tests.dart @@ -25,9 +25,7 @@ Future main(List args) async { exit(0); } - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); final sharedSourceRoot = Directory( p.join(packageRoot.parent.path, 'google_maps_flutter_ios_shared_code'), @@ -129,16 +127,11 @@ Future _validatePackageSharedCode( required bool log, }) async { var hasDiffs = false; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/sync_shared_files.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/sync_shared_files.dart index fbbd50d0a499..8711068a5604 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/sync_shared_files.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/sync_shared_files.dart @@ -18,23 +18,15 @@ import 'utils.dart'; const String _sharedSourceRootName = 'google_maps_flutter_ios_shared_code'; Future main(List args) async { - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); - final sharedSourceRoot = Directory( - p.join(packageRoot.parent.path, _sharedSourceRootName), - ); + final sharedSourceRoot = Directory(p.join(packageRoot.parent.path, _sharedSourceRootName)); _syncSharedFiles(packageRoot, packageName, sharedSourceRoot); _reportUnsharedFiles(packageRoot, packageName, sharedSourceRoot); } -void _syncSharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _syncSharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List otherImplementationPackages = sharedSourceRoot.parent .listSync() .whereType() @@ -49,16 +41,11 @@ void _syncSharedFiles( final copiedFiles = []; final missingFiles = []; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { @@ -88,10 +75,7 @@ void _syncSharedFiles( final String otherPackagePath = p.join( packageRoot.parent.path, otherPackageName, - packageRelativePathForSharedSourceRelativePath( - otherPackageName, - relativePath, - ), + packageRelativePathForSharedSourceRelativePath(otherPackageName, relativePath), ); _syncFile(packageFile, otherPackagePath, otherPackageName); } @@ -105,9 +89,7 @@ void _syncSharedFiles( } } if (missingFiles.isNotEmpty) { - print( - 'This package is missing the following files from the shared source:', - ); + print('This package is missing the following files from the shared source:'); for (final file in missingFiles) { print(' $file'); } @@ -123,11 +105,7 @@ void _syncSharedFiles( /// If the file needs special handling of package names that appear within the /// contents of the file, it will update the package name in the file to match /// the destination package name. -void _syncFile( - File source, - String destinationPath, - String destinationPackageName, -) { +void _syncFile(File source, String destinationPath, String destinationPackageName) { source.copySync(destinationPath); if ([ // The Pigeon definition file has output paths that must use the @@ -136,10 +114,7 @@ void _syncFile( // The mock needs to import the package. '.mocks.dart', ].any((pattern) => source.absolute.path.contains(pattern))) { - updatePackageNameInPathReferences( - File(destinationPath), - destinationPackageName, - ); + updatePackageNameInPathReferences(File(destinationPath), destinationPackageName); } // Native unit tests need to import the Swift package. if (source.absolute.path.contains('/RunnerTests/')) { @@ -147,11 +122,7 @@ void _syncFile( } } -void _reportUnsharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _reportUnsharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List unsharedFiles = unexpectedUnsharedSourceFiles( packageRoot, packageName, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/utils.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/utils.dart index c4b2b9b83433..fc75925d7304 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/utils.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk10/tool/utils.dart @@ -21,10 +21,7 @@ List unexpectedUnsharedSourceFiles( .listSync(recursive: true) .whereType() // Only report code files. - .where( - (file) => - ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith), - ) + .where((file) => ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith)) // Flutter-generated files aren't expected to be shared. .where((file) => !file.path.contains('GeneratedPluginRegistrant')) // Ignore intermediate file directories. @@ -64,10 +61,7 @@ String packageRelativePathForSharedSourceRelativePath( String packageName, String sharedSourceRelativePath, ) { - return sharedSourceRelativePath.replaceAll( - '/google_maps_flutter_ios/', - '/$packageName/', - ); + return sharedSourceRelativePath.replaceAll('/google_maps_flutter_ios/', '/$packageName/'); } /// Returns the contents of the file with any differences caused only by the @@ -76,10 +70,7 @@ String normalizedFileContents(File file) { return file .readAsStringSync() // Ignore differences caused only by the package name. - .replaceAll( - RegExp(r'google_maps_flutter_ios_[\w\d]+'), - 'google_maps_flutter_ios', - ) + .replaceAll(RegExp(r'google_maps_flutter_ios_[\w\d]+'), 'google_maps_flutter_ios') // Package name diffs could change line wrapping, so collapse whitespace. .replaceAll(RegExp(r'[\s\n]+'), ' ') .trim(); @@ -106,10 +97,7 @@ void updatePackageNameInPathReferences(File file, String packageName) { /// package by name. void updatePackageNameInImports(File file, String packageName) { final String newContents = file.readAsStringSync().replaceAllMapped( - RegExp( - r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', - multiLine: true, - ), + RegExp(r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', multiLine: true), (match) => '${match.group(1)}import $packageName${match.group(2)}', ); file.writeAsStringSync(newContents); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/integration_test/google_maps_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/integration_test/google_maps_test.dart index f1c15e56e975..86260596009a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/integration_test/google_maps_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/integration_test/google_maps_test.dart @@ -41,8 +41,9 @@ final LatLngBounds _testCameraBounds = LatLngBounds( northeast: const LatLng(50, -65), southwest: const LatLng(28.5, -123), ); -final ValueVariant _cameraUpdateTypeVariants = - ValueVariant(CameraUpdateType.values.toSet()); +final ValueVariant _cameraUpdateTypeVariants = ValueVariant( + CameraUpdateType.values.toSet(), +); void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -66,8 +67,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool compassEnabled = await inspector.isCompassEnabled(mapId: mapId); expect(compassEnabled, false); @@ -106,11 +106,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled(mapId: mapId); // This is only supported on Android, so should always return false. expect(mapToolbarEnabled, false); }); @@ -136,14 +133,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final ExampleGoogleMapController controller = await controllerCompleter.future; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; - MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( - mapId: controller.mapId, - ); + MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels(mapId: controller.mapId); expect(zoomLevel, equals(initialZoomLevel)); await tester.pumpWidget( @@ -183,11 +176,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled(mapId: mapId); expect(zoomGesturesEnabled, false); await tester.pumpWidget( @@ -225,11 +215,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); /// Zoom Controls functionality is not available on iOS at the moment. expect(zoomControlsEnabled, false); @@ -254,11 +241,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, false); await tester.pumpWidget( @@ -274,9 +258,7 @@ void main() { ), ); - rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, true); }); @@ -299,11 +281,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled(mapId: mapId); expect(tiltGesturesEnabled, false); await tester.pumpWidget( @@ -342,11 +321,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, false); await tester.pumpWidget( @@ -362,9 +338,7 @@ void main() { ), ); - scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, true); }); @@ -387,8 +361,7 @@ void main() { ), ), ); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; await tester.pumpAndSettle(); @@ -397,8 +370,9 @@ void main() { // https://github.com/flutter/flutter/issues/54758 await Future.delayed(const Duration(seconds: 1)); - final ScreenCoordinate coordinate = await mapController - .getScreenCoordinate(_kInitialCameraPosition.target); + final ScreenCoordinate coordinate = await mapController.getScreenCoordinate( + _kInitialCameraPosition.target, + ); final Rect rect = tester.getRect(find.byKey(key)); expect(coordinate.x, (rect.center.dx - rect.topLeft.dx).round()); expect(coordinate.y, (rect.center.dy - rect.topLeft.dy).round()); @@ -434,11 +408,9 @@ void main() { ); await tester.pumpAndSettle(); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; - final LatLngBounds firstVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds firstVisibleRegion = await mapController.getVisibleRegion(); expect(firstVisibleRegion, isNotNull); expect(firstVisibleRegion.southwest, isNotNull); @@ -464,21 +436,15 @@ void main() { expect(firstVisibleRegion.contains(northEast), isFalse); expect(firstVisibleRegion.contains(southWest), isFalse); - final latLngBounds = LatLngBounds( - southwest: southWest, - northeast: northEast, - ); + final latLngBounds = LatLngBounds(southwest: southWest, northeast: northEast); // TODO(iskakaushik): non-zero padding is needed for some device configurations // https://github.com/flutter/flutter/issues/30575 const double padding = 0; - await mapController.moveCamera( - CameraUpdate.newLatLngBounds(latLngBounds, padding), - ); + await mapController.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController.getVisibleRegion(); expect(secondVisibleRegion, isNotNull); expect(secondVisibleRegion.southwest, isNotNull); @@ -511,8 +477,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool isTrafficEnabled = await inspector.isTrafficEnabled(mapId: mapId); expect(isTrafficEnabled, true); @@ -551,11 +516,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool isBuildingsEnabled = await inspector.areBuildingsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool isBuildingsEnabled = await inspector.areBuildingsEnabled(mapId: mapId); expect(isBuildingsEnabled, true); }); @@ -577,11 +539,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); await tester.pumpWidget( @@ -598,15 +557,11 @@ void main() { ), ); - myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value false', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value false', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -625,16 +580,12 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value true', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value true', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -652,10 +603,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); }); @@ -676,19 +625,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - const mapStyle = - '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - mapStyle, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + const mapStyle = '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; + await GoogleMapsFlutterPlatform.instance.setMapStyle(mapStyle, mapId: controller.mapId); }); - testWidgets('testSetMapStyle invalid Json String', ( - WidgetTester tester, - ) async { + testWidgets('testSetMapStyle invalid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -705,8 +647,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; try { await GoogleMapsFlutterPlatform.instance.setMapStyle( @@ -737,12 +678,8 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - null, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + await GoogleMapsFlutterPlatform.instance.setMapStyle(null, mapId: controller.mapId); }); testWidgets('testGetLatLng', (WidgetTester tester) async { @@ -762,8 +699,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -772,13 +708,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng topLeft = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); + final LatLng topLeft = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); expect(topLeft, northWest); }); @@ -802,8 +733,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -841,8 +771,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -851,13 +780,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); - final ScreenCoordinate topLeft = await controller.getScreenCoordinate( - northWest, - ); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); + final ScreenCoordinate topLeft = await controller.getScreenCoordinate(northWest); expect(topLeft, const ScreenCoordinate(x: 0, y: 0)); }, // TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825 @@ -880,8 +804,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpWidget( Directionality( @@ -917,9 +840,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController googleMapController) { controllerCompleter.complete(googleMapController); @@ -928,12 +849,9 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, false); await controller.showMarkerInfoWindow(marker.markerId); @@ -945,9 +863,7 @@ void main() { expect(iwVisibleStatus, false); }); - testWidgets('updating a marker does not hide its info window', ( - WidgetTester tester, - ) async { + testWidgets('updating a marker does not hide its info window', (WidgetTester tester) async { final Key key = GlobalKey(); const marker = Marker( markerId: MarkerId('marker'), @@ -955,9 +871,7 @@ void main() { ); var markers = {marker}; - const clusterManager = ClusterManager( - clusterManagerId: ClusterManagerId('cluster_manager'), - ); + const clusterManager = ClusterManager(clusterManagerId: ClusterManagerId('cluster_manager')); final clusterManagers = {clusterManager}; final controllerCompleter = Completer(); @@ -967,9 +881,7 @@ void main() { textDirection: TextDirection.ltr, child: ExampleGoogleMap( key: key, - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, clusterManagers: clusterManagers, onMapCreated: (ExampleGoogleMapController googleMapController) { @@ -979,13 +891,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await controller.showMarkerInfoWindow(marker.markerId); - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, true); // Update marker and ensure the info window remains visible when added to a @@ -1031,8 +940,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final Uint8List? bytes = await controller.takeSnapshot(); expect(bytes?.isNotEmpty, true); }, @@ -1072,8 +980,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( tileOverlay1.mapsId, @@ -1086,18 +993,12 @@ void main() { expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.2, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); - expect( - tileOverlayInfo2.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }); @@ -1132,8 +1033,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final tileOverlay1New = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), @@ -1171,10 +1071,7 @@ void main() { expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); @@ -1205,8 +1102,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1249,10 +1145,7 @@ void main() { final marker = Marker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1260,8 +1153,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1278,8 +1170,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1296,8 +1187,7 @@ void main() { final MarkerId markerIdToMove = markers.entries .firstWhere( (MapEntry entry) => - entry.value.clusterManagerId == - clusterManagers.first.clusterManagerId, + entry.value.clusterManagerId == clusterManagers.first.clusterManagerId, ) .key; markers[markerIdToMove] = _copyMarkerWithClusterManagerId( @@ -1385,10 +1275,7 @@ void main() { final marker = AdvancedMarker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1396,8 +1283,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1415,8 +1301,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1431,10 +1316,7 @@ void main() { // Remove markers from clusterManagers and test that clusterManagers are empty. for (final MapEntry entry in markers.entries) { - markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId( - entry.value, - null, - ); + markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId(entry.value, null); } await tester.pumpWidget( Directionality( @@ -1490,15 +1372,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNotNull); }); - testWidgets('getStyleError returns null for a valid style', ( - WidgetTester tester, - ) async { + testWidgets('getStyleError returns null for a valid style', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -1517,8 +1396,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNull); }); @@ -1534,9 +1412,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1546,25 +1422,18 @@ void main() { }); testWidgets('markerWithAssetMapBitmapCreate', (WidgetTester tester) async { - final imageConfiguration = ImageConfiguration( - devicePixelRatio: tester.view.devicePixelRatio, - ); + final imageConfiguration = ImageConfiguration(devicePixelRatio: tester.view.devicePixelRatio); final markers = { Marker( markerId: const MarkerId('1'), - icon: await AssetMapBitmap.create( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await AssetMapBitmap.create(imageConfiguration, 'assets/red_square.png'), ), }; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1578,10 +1447,7 @@ void main() { final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; @@ -1589,9 +1455,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1602,19 +1466,13 @@ void main() { testWidgets('markerWithLegacyAsset', (WidgetTester tester) async { //tester.view.devicePixelRatio = 2.0; - const imageConfiguration = ImageConfiguration( - devicePixelRatio: 2.0, - size: Size(100, 100), - ); + const imageConfiguration = ImageConfiguration(devicePixelRatio: 2.0, size: Size(100, 100)); final markers = { Marker( markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. // ignore: deprecated_member_use - icon: await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await BitmapDescriptor.fromAssetImage(imageConfiguration, 'assets/red_square.png'), ), }; final controllerCompleter = Completer(); @@ -1622,9 +1480,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1648,9 +1504,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1690,19 +1544,13 @@ void main() { ), ); - void expectGroundOverlayEquals( - GroundOverlay source, - GroundOverlay response, - ) { + void expectGroundOverlayEquals(GroundOverlay source, GroundOverlay response) { expect(response.groundOverlayId, source.groundOverlayId); expect( response.transparency, moreOrLessEquals(source.transparency, epsilon: _floatTolerance), ); - expect( - response.bearing, - moreOrLessEquals(source.bearing, epsilon: _floatTolerance), - ); + expect(response.bearing, moreOrLessEquals(source.bearing, epsilon: _floatTolerance)); // Only test bounds if it was given in the original object if (source.bounds != null) { @@ -1717,14 +1565,8 @@ void main() { expect(response.clickable, source.clickable); expect(response.zIndex, source.zIndex); expect(response.zoomLevel, source.zoomLevel); - expect( - response.anchor?.dx, - moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance), - ); - expect( - response.anchor?.dy, - moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance), - ); + expect(response.anchor?.dx, moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance)); + expect(response.anchor?.dy, moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance)); } testWidgets('set ground overlays correctly', (WidgetTester tester) async { @@ -1754,38 +1596,29 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayBoundsInfo2 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPositionInfo1 = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1, - groundOverlayBoundsInfo1, - ); - expectGroundOverlayEquals( - groundOverlayBounds2, - groundOverlayBoundsInfo2, - ); - expectGroundOverlayEquals( - groundOverlayPosition1, - groundOverlayPositionInfo1, - ); + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds2.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPositionInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1, groundOverlayBoundsInfo1); + expectGroundOverlayEquals(groundOverlayBounds2, groundOverlayBoundsInfo2); + expectGroundOverlayEquals(groundOverlayPosition1, groundOverlayPositionInfo1); } }); - testWidgets('update ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('update ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1795,10 +1628,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1807,26 +1637,23 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - - final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); - - final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + + final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); + + final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); await tester.pumpWidget( Directionality( @@ -1834,10 +1661,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1New, - groundOverlayPosition1New, - }, + groundOverlays: {groundOverlayBounds1New, groundOverlayPosition1New}, onMapCreated: (ExampleGoogleMapController controller) { fail('update: OnMapCreated should get called only once.'); }, @@ -1848,28 +1672,21 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPosition1Info = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1New, - groundOverlayBounds1Info, - ); - expectGroundOverlayEquals( - groundOverlayPosition1New, - groundOverlayPosition1Info, - ); + final GroundOverlay groundOverlayBounds1Info = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPosition1Info = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1New, groundOverlayBounds1Info); + expectGroundOverlayEquals(groundOverlayPosition1New, groundOverlayPosition1Info); } }); - testWidgets('remove ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('remove ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1879,10 +1696,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1891,8 +1705,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1910,10 +1723,14 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay? groundOverlayBounds1Info = await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId); - final GroundOverlay? groundOverlayPositionInfo = await inspector - .getGroundOverlayInfo(groundOverlayPosition1.mapsId, mapId: mapId); + final GroundOverlay? groundOverlayBounds1Info = await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ); + final GroundOverlay? groundOverlayPositionInfo = await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ); expect(groundOverlayBounds1Info, isNull); expect(groundOverlayPositionInfo, isNull); @@ -1926,8 +1743,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -1939,8 +1755,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { cameraIdleCompleter.complete(); } }, @@ -1951,8 +1766,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -1972,8 +1786,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -1988,8 +1803,9 @@ void main() { await cameraIdleCompleter.future; // After onCameraIdle event, the camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2019,8 +1835,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -2044,8 +1859,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { stopwatch.stop(); cameraIdleCompleter.complete(); } @@ -2057,8 +1871,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -2090,15 +1903,10 @@ void main() { // For short animation duration, check that the animation is completed // faster than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - lessThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, lessThan(animationDurationMiddlePoint)); // Reset camera to initial position before testing long duration. - await controller.moveCamera( - CameraUpdate.newCameraPosition(_kInitialCameraPosition), - ); + await controller.moveCamera(CameraUpdate.newCameraPosition(_kInitialCameraPosition)); await tester.pumpAndSettle(); // Create completer for camera idle event. @@ -2121,8 +1929,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -2138,14 +1947,12 @@ void main() { // For longer animation duration, check that the animation is completed // slower than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - greaterThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, greaterThan(animationDurationMiddlePoint)); // Camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2179,9 +1986,7 @@ void main() { Directionality( textDirection: ui.TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 20.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 20.0)), markers: markers, markerType: MarkerType.advancedMarker, onMapCreated: (ExampleGoogleMapController controller) => @@ -2212,31 +2017,20 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, @@ -2286,23 +2080,15 @@ AdvancedMarker _copyAdvancedMarkerWithClusterManagerId( CameraUpdate _getCameraUpdateForType(CameraUpdateType type) { return switch (type) { - CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition( - _kTestCameraPosition, - ), + CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition(_kTestCameraPosition), CameraUpdateType.newLatLng => CameraUpdate.newLatLng(_kTestMapCenter), - CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds( - _testCameraBounds, - 0, - ), + CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds(_testCameraBounds, 0), CameraUpdateType.newLatLngZoom => CameraUpdate.newLatLngZoom( _kTestMapCenter, _kTestCameraZoomLevel, ), CameraUpdateType.scrollBy => CameraUpdate.scrollBy(10, 10), - CameraUpdateType.zoomBy => CameraUpdate.zoomBy( - _kTestZoomByAmount, - const Offset(1, 1), - ), + CameraUpdateType.zoomBy => CameraUpdate.zoomBy(_kTestZoomByAmount, const Offset(1, 1)), CameraUpdateType.zoomTo => CameraUpdate.zoomTo(_kTestCameraZoomLevel), CameraUpdateType.zoomIn => CameraUpdate.zoomIn(), CameraUpdateType.zoomOut => CameraUpdate.zoomOut(), @@ -2322,29 +2108,16 @@ Future _checkCameraUpdateByType( switch (type) { case CameraUpdateType.newCameraPosition: - expect( - currentPosition.bearing, - wrapMatcher(equals(_kTestCameraPosition.bearing)), - ); - expect( - currentPosition.zoom, - wrapMatcher(equals(_kTestCameraPosition.zoom)), - ); - expect( - currentPosition.tilt, - wrapMatcher(equals(_kTestCameraPosition.tilt)), - ); + expect(currentPosition.bearing, wrapMatcher(equals(_kTestCameraPosition.bearing))); + expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraPosition.zoom))); + expect(currentPosition.tilt, wrapMatcher(equals(_kTestCameraPosition.tilt))); expect( currentPosition.target.latitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.latitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.latitude, latLngThreshold)), ); expect( currentPosition.target.longitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLng: expect( @@ -2359,15 +2132,11 @@ Future _checkCameraUpdateByType( final LatLngBounds bounds = await controller.getVisibleRegion(); expect( bounds.northeast.longitude, - wrapMatcher( - closeTo(_testCameraBounds.northeast.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.northeast.longitude, latLngThreshold)), ); expect( bounds.southwest.longitude, - wrapMatcher( - closeTo(_testCameraBounds.southwest.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.southwest.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLngZoom: expect( @@ -2382,20 +2151,11 @@ Future _checkCameraUpdateByType( case CameraUpdateType.scrollBy: // For scrollBy, just check that the location has changed. if (oldPosition != null) { - expect( - currentPosition.target.latitude, - isNot(equals(oldPosition.target.latitude)), - ); - expect( - currentPosition.target.longitude, - isNot(equals(oldPosition.target.longitude)), - ); + expect(currentPosition.target.latitude, isNot(equals(oldPosition.target.latitude))); + expect(currentPosition.target.longitude, isNot(equals(oldPosition.target.longitude))); } case CameraUpdateType.zoomBy: - expect( - currentPosition.zoom, - wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount)), - ); + expect(currentPosition.zoom, wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount))); case CameraUpdateType.zoomTo: expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraZoomLevel))); case CameraUpdateType.zoomIn: diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_marker_icons.dart index 5069f3f900af..ff45dd833cef 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_marker_icons.dart @@ -33,8 +33,7 @@ class _AdvancedMarkerIconsBody extends StatefulWidget { final String? mapId; @override - State<_AdvancedMarkerIconsBody> createState() => - _AdvancedMarkerIconsBodyState(); + State<_AdvancedMarkerIconsBody> createState() => _AdvancedMarkerIconsBodyState(); } class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { @@ -51,10 +50,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: (ExampleGoogleMapController controller) { setState(() { @@ -73,29 +69,22 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { const ImageConfiguration(size: Size(12, 12)), 'assets/red_square.png', ); - final AssetMapBitmap largeAsset = - await BitmapDescriptor.asset( - const ImageConfiguration(size: Size(36, 36)), - 'assets/red_square.png', - ); + final AssetMapBitmap largeAsset = await BitmapDescriptor.asset( + const ImageConfiguration(size: Size(36, 36)), + 'assets/red_square.png', + ); setState(() { _markers.addAll([ // Default icon AdvancedMarker( markerId: const MarkerId('1'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude + 1), ), // Custom pin colors AdvancedMarker( markerId: const MarkerId('2'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.black, @@ -105,26 +94,17 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Pin with text AdvancedMarker( markerId: const MarkerId('3'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude + 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.blue, backgroundColor: Colors.white, - glyph: const TextGlyph( - text: 'Hi!', - textColor: Colors.blue, - ), + glyph: const TextGlyph(text: 'Hi!', textColor: Colors.blue), ), ), // Pin with bitmap AdvancedMarker( markerId: const MarkerId('4'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.white, @@ -134,10 +114,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Custom marker icon AdvancedMarker( markerId: const MarkerId('5'), - position: LatLng( - _kMapCenter.latitude, - _kMapCenter.longitude, - ), + position: LatLng(_kMapCenter.latitude, _kMapCenter.longitude), icon: largeAsset, ), ]); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_markers_clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_markers_clustering.dart index 1787e9077a50..985566ee454f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_markers_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/advanced_markers_clustering.dart @@ -16,10 +16,7 @@ import 'page.dart'; class AdvancedMarkersClusteringPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkersClusteringPage({super.key, required this.mapId}) - : super( - const Icon(Icons.place_outlined), - 'Manage clusters of advanced markers', - ); + : super(const Icon(Icons.place_outlined), 'Manage clusters of advanced markers'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -78,8 +75,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -107,17 +103,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; }); } @@ -159,14 +149,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -210,9 +197,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/animate_camera.dart index 001006fb54be..d278e2c5b3b6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/animate_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class AnimateCameraPage extends GoogleMapExampleAppPage { - const AnimateCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control, animated'); + const AnimateCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control, animated'); @override Widget build(BuildContext context) { @@ -58,9 +57,7 @@ class AnimateCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -88,9 +85,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), duration: _cameraUpdateAnimationDuration, ); }, @@ -114,10 +109,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), duration: _cameraUpdateAnimationDuration, ); }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/clustering.dart index 18e9af8c1be8..e7ea5e7ddefc 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/clustering.dart @@ -13,8 +13,7 @@ import 'page.dart'; /// Page for demonstrating marker clustering support. class ClusteringPage extends GoogleMapExampleAppPage { /// Default Constructor. - const ClusteringPage({super.key}) - : super(const Icon(Icons.place), 'Manage clustering'); + const ClusteringPage({super.key}) : super(const Icon(Icons.place), 'Manage clustering'); @override Widget build(BuildContext context) { @@ -61,8 +60,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -95,10 +93,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = _copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = _copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -134,8 +129,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -144,14 +138,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -190,9 +181,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); @@ -239,8 +228,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { TextButton( onPressed: clusterManagers.isEmpty ? null - : () => - _removeClusterManager(clusterManagers.values.last), + : () => _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -248,8 +236,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { Wrap( alignment: WrapAlignment.spaceEvenly, children: [ - for (final MapEntry - clusterEntry + for (final MapEntry clusterEntry in clusterManagers.entries) TextButton( onPressed: () => _addMarkersToCluster(clusterEntry.value), @@ -272,9 +259,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { child: const Text('Remove selected marker'), ), TextButton( - onPressed: markers.isEmpty - ? null - : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty ? null : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/collision_behavior.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/collision_behavior.dart index a6a8ef8aec70..f93d850a6836 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/collision_behavior.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/collision_behavior.dart @@ -15,10 +15,7 @@ import 'place_marker.dart'; class AdvancedMarkerCollisionBehaviorPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkerCollisionBehaviorPage({super.key, required this.mapId}) - : super( - const Icon(Icons.not_listed_location), - 'Advanced marker collision behavior', - ); + : super(const Icon(Icons.not_listed_location), 'Advanced marker collision behavior'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -35,12 +32,10 @@ class _CollisionBehaviorPageBody extends StatefulWidget { final String? mapId; @override - State<_CollisionBehaviorPageBody> createState() => - _CollisionBehaviorPageBodyState(); + State<_CollisionBehaviorPageBody> createState() => _CollisionBehaviorPageBodyState(); } -class _CollisionBehaviorPageBodyState - extends State<_CollisionBehaviorPageBody> { +class _CollisionBehaviorPageBodyState extends State<_CollisionBehaviorPageBody> { static const LatLng center = LatLng(-33.86711, 151.1947171); static const double zoomOutLevel = 9; static const double zoomInLevel = 12; @@ -78,10 +73,7 @@ class _CollisionBehaviorPageBodyState child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: center, - zoom: zoomInLevel, - ), + initialCameraPosition: const CameraPosition(target: center, zoom: zoomInLevel), markers: Set.of(markers), tiltGesturesEnabled: false, zoomGesturesEnabled: false, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/custom_marker_icon.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/custom_marker_icon.dart index 548146c6206c..3391ba1bcba2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/custom_marker_icon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/custom_marker_icon.dart @@ -20,9 +20,7 @@ Future createCustomMarkerIconImage({required Size size}) async { size.height.floor(), ); - final ByteData? bytes = await image.toByteData( - format: ui.ImageByteFormat.png, - ); + final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); return bytes!; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/example_google_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/example_google_map.dart index 2b8a8243d381..e18943a3345f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/example_google_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/example_google_map.dart @@ -47,10 +47,7 @@ class ExampleGoogleMapController { if (_googleMapState.widget.onCameraMove != null) { GoogleMapsFlutterPlatform.instance .onCameraMove(mapId: mapId) - .listen( - (CameraMoveEvent e) => - _googleMapState.widget.onCameraMove!(e.value), - ); + .listen((CameraMoveEvent e) => _googleMapState.widget.onCameraMove!(e.value)); } if (_googleMapState.widget.onCameraIdle != null) { GoogleMapsFlutterPlatform.instance @@ -62,27 +59,16 @@ class ExampleGoogleMapController { .listen((MarkerTapEvent e) => _googleMapState.onMarkerTap(e.value)); GoogleMapsFlutterPlatform.instance .onMarkerDragStart(mapId: mapId) - .listen( - (MarkerDragStartEvent e) => - _googleMapState.onMarkerDragStart(e.value, e.position), - ); + .listen((MarkerDragStartEvent e) => _googleMapState.onMarkerDragStart(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDrag(mapId: mapId) - .listen( - (MarkerDragEvent e) => - _googleMapState.onMarkerDrag(e.value, e.position), - ); + .listen((MarkerDragEvent e) => _googleMapState.onMarkerDrag(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDragEnd(mapId: mapId) - .listen( - (MarkerDragEndEvent e) => - _googleMapState.onMarkerDragEnd(e.value, e.position), - ); + .listen((MarkerDragEndEvent e) => _googleMapState.onMarkerDragEnd(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onInfoWindowTap(mapId: mapId) - .listen( - (InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value), - ); + .listen((InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value)); GoogleMapsFlutterPlatform.instance .onPolylineTap(mapId: mapId) .listen((PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value)); @@ -94,18 +80,13 @@ class ExampleGoogleMapController { .listen((CircleTapEvent e) => _googleMapState.onCircleTap(e.value)); GoogleMapsFlutterPlatform.instance .onGroundOverlayTap(mapId: mapId) - .listen( - (GroundOverlayTapEvent e) => - _googleMapState.onGroundOverlayTap(e.value), - ); + .listen((GroundOverlayTapEvent e) => _googleMapState.onGroundOverlayTap(e.value)); GoogleMapsFlutterPlatform.instance .onTap(mapId: mapId) .listen((MapTapEvent e) => _googleMapState.onTap(e.position)); GoogleMapsFlutterPlatform.instance .onLongPress(mapId: mapId) - .listen( - (MapLongPressEvent e) => _googleMapState.onLongPress(e.position), - ); + .listen((MapLongPressEvent e) => _googleMapState.onLongPress(e.position)); GoogleMapsFlutterPlatform.instance .onClusterTap(mapId: mapId) .listen((ClusterTapEvent e) => _googleMapState.onClusterTap(e.value)); @@ -113,24 +94,16 @@ class ExampleGoogleMapController { /// Updates configuration options of the map user interface. Future _updateMapConfiguration(MapConfiguration update) { - return GoogleMapsFlutterPlatform.instance.updateMapConfiguration( - update, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMapConfiguration(update, mapId: mapId); } /// Updates marker configuration. Future _updateMarkers(MarkerUpdates markerUpdates) { - return GoogleMapsFlutterPlatform.instance.updateMarkers( - markerUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMarkers(markerUpdates, mapId: mapId); } /// Updates cluster manager configuration. - Future _updateClusterManagers( - ClusterManagerUpdates clusterManagerUpdates, - ) { + Future _updateClusterManagers(ClusterManagerUpdates clusterManagerUpdates) { return GoogleMapsFlutterPlatform.instance.updateClusterManagers( clusterManagerUpdates, mapId: mapId, @@ -138,9 +111,7 @@ class ExampleGoogleMapController { } /// Updates ground overlay configuration. - Future _updateGroundOverlays( - GroundOverlayUpdates groundOverlayUpdates, - ) { + Future _updateGroundOverlays(GroundOverlayUpdates groundOverlayUpdates) { return GoogleMapsFlutterPlatform.instance.updateGroundOverlays( groundOverlayUpdates, mapId: mapId, @@ -149,26 +120,17 @@ class ExampleGoogleMapController { /// Updates polygon configuration. Future _updatePolygons(PolygonUpdates polygonUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolygons( - polygonUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolygons(polygonUpdates, mapId: mapId); } /// Updates polyline configuration. Future _updatePolylines(PolylineUpdates polylineUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolylines( - polylineUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolylines(polylineUpdates, mapId: mapId); } /// Updates circle configuration. Future _updateCircles(CircleUpdates circleUpdates) { - return GoogleMapsFlutterPlatform.instance.updateCircles( - circleUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateCircles(circleUpdates, mapId: mapId); } /// Updates tile overlays configuration. @@ -182,10 +144,7 @@ class ExampleGoogleMapController { /// Clears the tile cache so that all tiles will be requested again from the /// [TileProvider]. Future clearTileCache(TileOverlayId tileOverlayId) async { - return GoogleMapsFlutterPlatform.instance.clearTileCache( - tileOverlayId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.clearTileCache(tileOverlayId, mapId: mapId); } /// Starts an animated change of the map camera position. @@ -199,10 +158,7 @@ class ExampleGoogleMapController { /// Changes the map camera position. Future moveCamera(CameraUpdate cameraUpdate) { - return GoogleMapsFlutterPlatform.instance.moveCamera( - cameraUpdate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.moveCamera(cameraUpdate, mapId: mapId); } /// Return [LatLngBounds] defining the region that is visible in a map. @@ -212,42 +168,27 @@ class ExampleGoogleMapController { /// Return [ScreenCoordinate] of the [LatLng] in the current map view. Future getScreenCoordinate(LatLng latLng) { - return GoogleMapsFlutterPlatform.instance.getScreenCoordinate( - latLng, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getScreenCoordinate(latLng, mapId: mapId); } /// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view. Future getLatLng(ScreenCoordinate screenCoordinate) { - return GoogleMapsFlutterPlatform.instance.getLatLng( - screenCoordinate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getLatLng(screenCoordinate, mapId: mapId); } /// Programmatically show the Info Window for a [Marker]. Future showMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow(markerId, mapId: mapId); } /// Programmatically hide the Info Window for a [Marker]. Future hideMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow(markerId, mapId: mapId); } /// Returns `true` when the [InfoWindow] is showing, `false` otherwise. Future isMarkerInfoWindowShown(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown(markerId, mapId: mapId); } /// Returns the current zoom level of the map @@ -267,9 +208,7 @@ class ExampleGoogleMapController { /// Returns true if [AdvancedMarker]s can be used with this map. Future isAdvancedMarkersAvailable() { - return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable( - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: mapId); } /// Disposes of the platform resources @@ -446,17 +385,14 @@ class ExampleGoogleMap extends StatefulWidget { class _ExampleGoogleMapState extends State { final int _mapId = _nextMapCreationId++; - final Completer _controller = - Completer(); + final Completer _controller = Completer(); Map _markers = {}; Map _polygons = {}; Map _polylines = {}; Map _circles = {}; - Map _clusterManagers = - {}; - Map _groundOverlays = - {}; + Map _clusterManagers = {}; + Map _groundOverlays = {}; late MapConfiguration _mapConfiguration; @override @@ -466,9 +402,7 @@ class _ExampleGoogleMapState extends State { onPlatformViewCreated, widgetConfiguration: MapWidgetConfiguration( textDirection: - widget.layoutDirection ?? - Directionality.maybeOf(context) ?? - TextDirection.ltr, + widget.layoutDirection ?? Directionality.maybeOf(context) ?? TextDirection.ltr, initialCameraPosition: widget.initialCameraPosition, gestureRecognizers: widget.gestureRecognizers, ), @@ -498,9 +432,7 @@ class _ExampleGoogleMapState extends State { @override void dispose() { - _controller.future.then( - (ExampleGoogleMapController controller) => controller.dispose(), - ); + _controller.future.then((ExampleGoogleMapController controller) => controller.dispose()); super.dispose(); } @@ -531,9 +463,7 @@ class _ExampleGoogleMapState extends State { Future _updateMarkers() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateMarkers( - MarkerUpdates.from(_markers.values.toSet(), widget.markers), - ), + controller._updateMarkers(MarkerUpdates.from(_markers.values.toSet(), widget.markers)), ); _markers = keyByMarkerId(widget.markers); } @@ -542,10 +472,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateClusterManagers( - ClusterManagerUpdates.from( - _clusterManagers.values.toSet(), - widget.clusterManagers, - ), + ClusterManagerUpdates.from(_clusterManagers.values.toSet(), widget.clusterManagers), ), ); _clusterManagers = keyByClusterManagerId(widget.clusterManagers); @@ -555,10 +482,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateGroundOverlays( - GroundOverlayUpdates.from( - _groundOverlays.values.toSet(), - widget.groundOverlays, - ), + GroundOverlayUpdates.from(_groundOverlays.values.toSet(), widget.groundOverlays), ), ); _groundOverlays = keyByGroundOverlayId(widget.groundOverlays); @@ -567,9 +491,7 @@ class _ExampleGoogleMapState extends State { Future _updatePolygons() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updatePolygons( - PolygonUpdates.from(_polygons.values.toSet(), widget.polygons), - ), + controller._updatePolygons(PolygonUpdates.from(_polygons.values.toSet(), widget.polygons)), ); _polygons = keyByPolygonId(widget.polygons); } @@ -587,9 +509,7 @@ class _ExampleGoogleMapState extends State { Future _updateCircles() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateCircles( - CircleUpdates.from(_circles.values.toSet(), widget.circles), - ), + controller._updateCircles(CircleUpdates.from(_circles.values.toSet(), widget.circles)), ); _circles = keyByCircleId(widget.circles); } @@ -600,12 +520,11 @@ class _ExampleGoogleMapState extends State { } Future onPlatformViewCreated(int id) async { - final ExampleGoogleMapController controller = - await ExampleGoogleMapController._init( - id, - widget.initialCameraPosition, - this, - ); + final ExampleGoogleMapController controller = await ExampleGoogleMapController._init( + id, + widget.initialCameraPosition, + this, + ); _controller.complete(controller); unawaited(_updateTileOverlays()); widget.onMapCreated?.call(controller); @@ -656,8 +575,7 @@ class _ExampleGoogleMapState extends State { } void onClusterTap(Cluster cluster) { - final ClusterManager? clusterManager = - _clusterManagers[cluster.clusterManagerId]; + final ClusterManager? clusterManager = _clusterManagers[cluster.clusterManagerId]; clusterManager?.onClusterTap?.call(cluster); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/ground_overlay.dart index 00a7d8126539..878f5c9200a2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/ground_overlay.dart @@ -13,8 +13,7 @@ import 'page.dart'; enum _GroundOverlayPlacing { position, bounds } class GroundOverlayPage extends GoogleMapExampleAppPage { - const GroundOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Ground overlay'); + const GroundOverlayPage({super.key}) : super(const Icon(Icons.map), 'Ground overlay'); @override Widget build(BuildContext context) { @@ -132,9 +131,7 @@ class GroundOverlayBodyState extends State { // Adjusts the bearing by 10 degrees, wrapping around at 360 degrees. // 10 is the increment, 350 degrees of the full circle -10. _groundOverlay = _groundOverlay!.copyWith( - bearingParam: _groundOverlay!.bearing >= 350 - ? 0 - : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, ); }); } @@ -143,9 +140,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { final transparency = _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; - _groundOverlay = _groundOverlay!.copyWith( - transparencyParam: transparency, - ); + _groundOverlay = _groundOverlay!.copyWith(transparencyParam: transparency); }); } @@ -167,8 +162,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.bounds); setState(() { - _currentGroundOverlayBounds = - _currentGroundOverlayBounds == _groundOverlayBounds1 + _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 ? _groundOverlayBounds2 : _groundOverlayBounds1; }); @@ -181,9 +175,7 @@ class GroundOverlayBodyState extends State { void _toggleVisible() { assert(_groundOverlay != null); setState(() { - _groundOverlay = _groundOverlay!.copyWith( - visibleParam: !_groundOverlay!.visible, - ); + _groundOverlay = _groundOverlay!.copyWith(visibleParam: !_groundOverlay!.visible); }); } @@ -223,9 +215,7 @@ class GroundOverlayBodyState extends State { @override Widget build(BuildContext context) { - final overlays = { - if (_groundOverlay != null) _groundOverlay!, - }; + final overlays = {if (_groundOverlay != null) _groundOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -233,10 +223,7 @@ class GroundOverlayBodyState extends State { children: [ Expanded( child: ExampleGoogleMap( - initialCameraPosition: CameraPosition( - target: _mapCenter, - zoom: 14.0, - ), + initialCameraPosition: CameraPosition(target: _mapCenter, zoom: 14.0), groundOverlays: overlays, onMapCreated: _onMapCreated, ), @@ -258,9 +245,7 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeTransparency(), + onPressed: _groundOverlay == null ? null : () => _changeTransparency(), child: const Text('change transparency'), ), TextButton( @@ -282,23 +267,17 @@ class GroundOverlayBodyState extends State { TextButton( onPressed: _groundOverlay == null ? null : () => _changeType(), child: Text( - _placingType == _GroundOverlayPlacing.position - ? 'use bounds' - : 'use position', + _placingType == _GroundOverlayPlacing.position ? 'use bounds' : 'use position', ), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changePosition(), child: const Text('change position'), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.bounds || _groundOverlay == null ? null : () => _changeBounds(), child: const Text('change bounds'), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_click.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_click.dart index a786197d5205..49ecd2656bab 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_click.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_click.dart @@ -58,42 +58,25 @@ class _MapClickBodyState extends State<_MapClickBody> { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; if (mapController != null) { final lastTap = 'Tap:\n${_lastTap ?? ""}\n'; final lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; + columnChildren.add(Center(child: Text(lastTap, textAlign: TextAlign.center))); columnChildren.add( - Center(child: Text(lastTap, textAlign: TextAlign.center)), - ); - columnChildren.add( - Center( - child: Text( - _lastTap != null ? 'Tapped' : '', - textAlign: TextAlign.center, - ), - ), - ); - columnChildren.add( - Center(child: Text(lastLongPress, textAlign: TextAlign.center)), + Center(child: Text(_lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center)), ); + columnChildren.add(Center(child: Text(lastLongPress, textAlign: TextAlign.center))); columnChildren.add( Center( - child: Text( - _lastLongPress != null ? 'Long pressed' : '', - textAlign: TextAlign.center, - ), + child: Text(_lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } Future onMapCreated(ExampleGoogleMapController controller) async { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_coordinates.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_coordinates.dart index 646301db99ae..51a68e8d5cf4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_coordinates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_coordinates.dart @@ -16,8 +16,7 @@ const CameraPosition _kInitialPosition = CameraPosition( ); class MapCoordinatesPage extends GoogleMapExampleAppPage { - const MapCoordinatesPage({super.key}) - : super(const Icon(Icons.map), 'Map coordinates'); + const MapCoordinatesPage({super.key}) : super(const Icon(Icons.map), 'Map coordinates'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { final googleMap = ExampleGoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, - onCameraIdle: - _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 + onCameraIdle: _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 ); return NotificationListener( @@ -61,13 +59,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { children: [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox( - width: 300.0, - height: 200.0, - child: googleMap, - ), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), // Add a block at the bottom of this list to allow validation that the visible region of the map // does not change when scrolled under the safe view on iOS. diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_map_id.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_map_id.dart index 94a01eb03368..89ba5c25396f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_map_id.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_map_id.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { - const MapIdPage({super.key}) - : super(const Icon(Icons.map), 'Cloud-based maps styling'); + const MapIdPage({super.key}) : super(const Icon(Icons.map), 'Cloud-based maps styling'); @override Widget build(BuildContext context) { @@ -49,10 +48,7 @@ class MapIdBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), key: _key, mapId: _mapId, ); @@ -60,9 +56,7 @@ class MapIdBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), Padding( padding: const EdgeInsets.all(10.0), @@ -80,10 +74,7 @@ class MapIdBodyState extends State { ), ]; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_ui.dart index 258c88170924..d7e7ff773a64 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/map_ui.dart @@ -84,9 +84,7 @@ class MapUiBodyState extends State { Widget _latLngBoundsToggler() { return TextButton( child: Text( - _cameraTargetBounds.bounds == null - ? 'bound camera target' - : 'release camera target', + _cameraTargetBounds.bounds == null ? 'bound camera target' : 'release camera target', ), onPressed: () { setState(() { @@ -100,9 +98,7 @@ class MapUiBodyState extends State { Widget _zoomBoundsToggler() { return TextButton( - child: Text( - _minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom', - ), + child: Text(_minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom'), onPressed: () { setState(() { _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null @@ -114,8 +110,7 @@ class MapUiBodyState extends State { } Widget _mapTypeCycler() { - final MapType nextType = - MapType.values[(_mapType.index + 1) % MapType.values.length]; + final MapType nextType = MapType.values[(_mapType.index + 1) % MapType.values.length]; return TextButton( child: Text('change map type to $nextType'), onPressed: () { @@ -172,9 +167,7 @@ class MapUiBodyState extends State { Widget _zoomControlsToggler() { return TextButton( - child: Text( - '${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls', - ), + child: Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'), onPressed: () { setState(() { _zoomControlsEnabled = !_zoomControlsEnabled; @@ -196,9 +189,7 @@ class MapUiBodyState extends State { Widget _myLocationToggler() { return TextButton( - child: Text( - '${_myLocationEnabled ? 'disable' : 'enable'} my location marker', - ), + child: Text('${_myLocationEnabled ? 'disable' : 'enable'} my location marker'), onPressed: () { setState(() { _myLocationEnabled = !_myLocationEnabled; @@ -209,9 +200,7 @@ class MapUiBodyState extends State { Widget _myLocationButtonToggler() { return TextButton( - child: Text( - '${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button', - ), + child: Text('${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'), onPressed: () { setState(() { _myLocationButtonEnabled = !_myLocationButtonEnabled; @@ -240,9 +229,7 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = _nightMode - ? await _getFileData('assets/night_mode.json') - : ''; + final String style = _nightMode ? await _getFileData('assets/night_mode.json') : ''; setState(() { _mapStyle = style; }); @@ -275,9 +262,7 @@ class MapUiBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; @@ -313,10 +298,7 @@ class MapUiBodyState extends State { ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _updateCameraPosition(CameraPosition position) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/marker_icons.dart index d4ac8d6ac597..84d13ac32e89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/marker_icons.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MarkerIconsPage extends GoogleMapExampleAppPage { - const MarkerIconsPage({super.key}) - : super(const Icon(Icons.image), 'Marker icons'); + const MarkerIconsPage({super.key}) : super(const Icon(Icons.image), 'Marker icons'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { AssetMapBitmap? _markerIconAsset; BytesMapBitmap? _markerIconBytes; final int _markersAmountPerType = 15; - bool get _customSizeEnabled => - _currentSizeOption != _MarkerSizeOption.original; + bool get _customSizeEnabled => _currentSizeOption != _MarkerSizeOption.original; @override Widget build(BuildContext context) { @@ -64,10 +62,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { width: 350.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: _onMapCreated, ), @@ -75,11 +70,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ), TextButton( onPressed: () => _toggleScaling(context), - child: Text( - _scalingEnabled - ? 'Disable auto scaling' - : 'Enable auto scaling', - ), + child: Text(_scalingEnabled ? 'Disable auto scaling' : 'Enable auto scaling'), ), if (_scalingEnabled) ...[ Container( @@ -91,10 +82,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'Reference box with size of ${referenceSize.width} x ${referenceSize.height} in logical pixels.', ), const SizedBox(height: 10), - Image.asset( - 'assets/red_square.png', - scale: _mipMapsEnabled ? null : 1.0, - ), + Image.asset('assets/red_square.png', scale: _mipMapsEnabled ? null : 1.0), const Text('Asset image rendered with flutter'), const SizedBox(height: 10), Row( @@ -112,9 +100,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { }); } }, - items: _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { + items: _MarkerSizeOption.values.map((_MarkerSizeOption option) { return DropdownMenuItem<_MarkerSizeOption>( value: option, child: Text(_getMarkerSizeOptionName(option)), @@ -126,9 +112,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ], TextButton( onPressed: () => _toggleMipMaps(context), - child: Text( - _mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps', - ), + child: Text(_mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps'), ), ], ), @@ -179,15 +163,9 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { if (width != null && height != null) { return Size(width, height); } else if (width != null) { - return Size( - width, - width * _markerAssetImageSize.height / _markerAssetImageSize.width, - ); + return Size(width, width * _markerAssetImageSize.height / _markerAssetImageSize.width); } else if (height != null) { - return Size( - height * _markerAssetImageSize.width / _markerAssetImageSize.height, - height, - ); + return Size(height * _markerAssetImageSize.width / _markerAssetImageSize.height, height); } else { return _markerAssetImageSize; } @@ -210,10 +188,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createAssetMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude - 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude - 1); return Marker( markerId: MarkerId('marker_asset_$index'), @@ -223,10 +198,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createBytesMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude + 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude + 1); return Marker( markerId: MarkerId('marker_bytes_$index'), @@ -252,26 +224,20 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { - final ImageConfiguration imageConfiguration = - createLocalImageConfiguration(context); + final ImageConfiguration imageConfiguration = createLocalImageConfiguration(context); assetMapBitmap = await AssetMapBitmap.create( imageConfiguration, 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -281,9 +247,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } @@ -291,9 +255,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Future _updateMarkerBytesImage(BuildContext context) async { - final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf( - context, - ); + final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context); final Size bitmapLogicalSize = _getMarkerReferenceSize(); final double? imagePixelRatio = _scalingEnabled ? devicePixelRatio : null; @@ -307,10 +269,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); @@ -319,9 +278,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/move_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/move_camera.dart index 5fc48e659246..28ce96f2b55f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/move_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/move_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MoveCameraPage extends GoogleMapExampleAppPage { - const MoveCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control'); + const MoveCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control'); @override Widget build(BuildContext context) { @@ -46,9 +45,7 @@ class MoveCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -75,9 +72,7 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -99,19 +94,14 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.moveCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), @@ -121,9 +111,7 @@ class MoveCameraState extends State { children: [ TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0)), - ); + mapController?.moveCamera(CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0))); }, child: const Text('zoomBy with focus'), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/padding.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/padding.dart index a0f4f8521c8e..82136d27cd8c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/padding.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/padding.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PaddingPage extends GoogleMapExampleAppPage { - const PaddingPage({super.key}) - : super(const Icon(Icons.map), 'Add padding to the map'); + const PaddingPage({super.key}) : super(const Icon(Icons.map), 'Add padding to the map'); @override Widget build(BuildContext context) { @@ -38,19 +37,14 @@ class MarkerIconsBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), padding: _padding, ); final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), const Padding( padding: EdgeInsets.only(top: 20), @@ -65,10 +59,7 @@ class MarkerIconsBodyState extends State { columnChildren.addAll([_paddingInput(), _buttons()]); - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _onMapCreated(ExampleGoogleMapController controllerParam) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_advanced_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_advanced_marker.dart index 08a886c11041..61c0898fed88 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_advanced_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_advanced_marker.dart @@ -53,18 +53,18 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { this.controller = controller; }); - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; }); + }); + }); } void _onMarkerTapped(MarkerId markerId) { @@ -73,17 +73,11 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; markerPosition = null; @@ -108,10 +102,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -177,16 +168,10 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { void _changePosition(MarkerId markerId) { final AdvancedMarker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -239,9 +224,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -249,9 +232,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -266,9 +247,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -289,9 +268,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { /// Performs customizations of the [marker] to mark it as selected or not. AdvancedMarker copyWithSelectedState(AdvancedMarker marker, bool isSelected) { - return marker.copyWith( - iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected), - ); + return marker.copyWith(iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected)); } @override @@ -308,8 +285,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, @@ -340,9 +316,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -351,70 +325,49 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( onPressed: selectedId == null ? null - : () => - _setMarkerIcon(selectedId, _getMarkerIcon(context)), + : () => _setMarkerIcon(selectedId, _getMarkerIcon(context)), child: const Text('set glyph text'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_circle.dart index 3c0335bfd18b..6bd22df33ef2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_circle.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { - const PlaceCirclePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place circle'); + const PlaceCirclePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place circle'); @override Widget build(BuildContext context) { @@ -38,12 +37,7 @@ class PlaceCircleBodyState extends State { // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling circle stroke width int widthsIndex = 0; @@ -133,9 +127,7 @@ class PlaceCircleBodyState extends State { void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { - circles[circleId] = circle.copyWith( - strokeWidthParam: widths[++widthsIndex % widths.length], - ); + circles[circleId] = circle.copyWith(strokeWidthParam: widths[++widthsIndex % widths.length]); }); } @@ -171,15 +163,11 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_marker.dart index 77ba3787d8e7..43f16a23979a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_marker.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceMarkerPage extends GoogleMapExampleAppPage { - const PlaceMarkerPage({super.key}) - : super(const Icon(Icons.place), 'Place marker'); + const PlaceMarkerPage({super.key}) : super(const Icon(Icons.place), 'Place marker'); @override Widget build(BuildContext context) { @@ -61,10 +60,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -170,16 +166,10 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { void _changePosition(MarkerId markerId) { final Marker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -232,9 +222,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -242,9 +230,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -259,9 +245,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -311,9 +295,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -322,63 +304,43 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( @@ -430,12 +392,10 @@ class AdvancedMarkersCapabilityStatus extends StatefulWidget { final ExampleGoogleMapController? controller; @override - State createState() => - _AdvancedMarkersCapabilityStatusState(); + State createState() => _AdvancedMarkersCapabilityStatusState(); } -class _AdvancedMarkersCapabilityStatusState - extends State { +class _AdvancedMarkersCapabilityStatusState extends State { /// Whether map supports advanced markers. bool? _isAdvancedMarkersAvailable; @@ -456,21 +416,19 @@ class _AdvancedMarkersCapabilityStatusState void _checkCapabilityIfNeeded() { final ExampleGoogleMapController? controller = widget.controller; - if (controller != null && - _isAdvancedMarkersAvailable == null && - !_isFetching) { + if (controller != null && _isAdvancedMarkersAvailable == null && !_isFetching) { _isFetching = true; - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - _isFetching = false; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; + _isFetching = false; + }); + }); } } @@ -481,8 +439,7 @@ class _AdvancedMarkersCapabilityStatusState child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polygon.dart index 70ad42c93724..d7c518cdf48d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polygon.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolygonPage extends GoogleMapExampleAppPage { - const PlacePolygonPage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polygon'); + const PlacePolygonPage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polygon'); @override Widget build(BuildContext context) { @@ -39,12 +38,7 @@ class PlacePolygonBodyState extends State { // Values when toggling polygon color int strokeColorsIndex = 0; int fillColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polygon width int widthsIndex = 0; @@ -149,9 +143,7 @@ class PlacePolygonBodyState extends State { void _addHoles(PolygonId polygonId) { final Polygon polygon = polygons[polygonId]!; setState(() { - polygons[polygonId] = polygon.copyWith( - holesParam: _createHoles(polygonId), - ); + polygons[polygonId] = polygon.copyWith(holesParam: _createHoles(polygonId)); }); } @@ -194,15 +186,11 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -232,9 +220,7 @@ class PlacePolygonBodyState extends State { child: const Text('remove holes'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polyline.dart index 8703ffcbd68f..a60d106bbe0b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/place_polyline.dart @@ -12,8 +12,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolylinePage extends GoogleMapExampleAppPage { - const PlacePolylinePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polyline'); + const PlacePolylinePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polyline'); @override Widget build(BuildContext context) { @@ -38,23 +37,14 @@ class PlacePolylineBodyState extends State { // Values when toggling polyline color int colorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polyline width int widthsIndex = 0; List widths = [10, 20, 5]; int jointTypesIndex = 0; - List jointTypes = [ - JointType.mitered, - JointType.bevel, - JointType.round, - ]; + List jointTypes = [JointType.mitered, JointType.bevel, JointType.round]; // Values when toggling polyline end cap type int endCapsIndex = 0; @@ -133,36 +123,28 @@ class PlacePolylineBodyState extends State { void _toggleGeodesic(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - geodesicParam: !polyline.geodesic, - ); + polylines[polylineId] = polyline.copyWith(geodesicParam: !polyline.geodesic); }); } void _toggleVisible(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - visibleParam: !polyline.visible, - ); + polylines[polylineId] = polyline.copyWith(visibleParam: !polyline.visible); }); } void _changeColor(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - colorParam: colors[++colorsIndex % colors.length], - ); + polylines[polylineId] = polyline.copyWith(colorParam: colors[++colorsIndex % colors.length]); }); } void _changeWidth(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - widthParam: widths[++widthsIndex % widths.length], - ); + polylines[polylineId] = polyline.copyWith(widthParam: widths[++widthsIndex % widths.length]); }); } @@ -237,15 +219,11 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -259,15 +237,11 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) ? null : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( @@ -289,9 +263,7 @@ class PlacePolylineBodyState extends State { child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) ? null : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/scrolling_map.dart index e5a8ec2ce5a6..443544402c31 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/scrolling_map.dart @@ -15,8 +15,7 @@ import 'page.dart'; const LatLng _center = LatLng(32.080664, 34.9563837); class ScrollingMapPage extends GoogleMapExampleAppPage { - const ScrollingMapPage({super.key}) - : super(const Icon(Icons.map), 'Scrolling map'); + const ScrollingMapPage({super.key}) : super(const Icon(Icons.map), 'Scrolling map'); @override Widget build(BuildContext context) { @@ -45,15 +44,10 @@ class ScrollingMapBody extends StatelessWidget { width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), gestureRecognizers: // >{ - Factory( - () => EagerGestureRecognizer(), - ), + Factory(() => EagerGestureRecognizer()), }, ), ), @@ -70,19 +64,14 @@ class ScrollingMapBody extends StatelessWidget { const Text("This map doesn't consume the vertical drags."), const Padding( padding: EdgeInsets.only(bottom: 12.0), - child: Text( - 'It still gets other gestures (e.g scale or tap).', - ), + child: Text('It still gets other gestures (e.g scale or tap).'), ), Center( child: SizedBox( width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), markers: { Marker( markerId: const MarkerId('test_marker_id'), @@ -93,12 +82,9 @@ class ScrollingMapBody extends StatelessWidget { ), ), }, - gestureRecognizers: - >{ - Factory( - () => ScaleGestureRecognizer(), - ), - }, + gestureRecognizers: >{ + Factory(() => ScaleGestureRecognizer()), + }, ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/snapshot.dart index 6f1624234ec4..906b3de2ecff 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/snapshot.dart @@ -53,8 +53,7 @@ class _SnapshotBodyState extends State<_SnapshotBody> { TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = await _mapController - ?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/tile_overlay.dart index cefa70eb34d5..3f3a26b6ab89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/lib/tile_overlay.dart @@ -14,8 +14,7 @@ import 'example_google_map.dart'; import 'page.dart'; class TileOverlayPage extends GoogleMapExampleAppPage { - const TileOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Tile overlay'); + const TileOverlayPage({super.key}) : super(const Icon(Icons.map), 'Tile overlay'); @override Widget build(BuildContext context) { @@ -90,18 +89,9 @@ class TileOverlayBodyState extends State { ), ), ), - TextButton( - onPressed: _addTileOverlay, - child: const Text('Add tile overlay'), - ), - TextButton( - onPressed: _removeTileOverlay, - child: const Text('Remove tile overlay'), - ), - TextButton( - onPressed: _clearTileCache, - child: const Text('Clear tile cache'), - ), + TextButton(onPressed: _addTileOverlay, child: const Text('Add tile overlay')), + TextButton(onPressed: _removeTileOverlay, child: const Text('Remove tile overlay')), + TextButton(onPressed: _clearTileCache, child: const Text('Clear tile cache')), ], ); } @@ -125,22 +115,14 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/example_google_map_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/example_google_map_test.dart index 261fc473e8bb..6aa25acb4b63 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/example_google_map_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/example_google_map_test.dart @@ -107,17 +107,12 @@ void main() { const p1 = Polygon(polygonId: PolygonId('polygon_1')); const p2 = Polygon(polygonId: PolygonId('polygon_2')); const p3 = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1); - const p3updated = Polygon( - polygonId: PolygonId('polygon_3'), - strokeWidth: 2, - ); + const p3updated = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polygons: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polygons: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -149,9 +144,7 @@ void main() { // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polylines: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polylines: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -163,9 +156,7 @@ void main() { expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[1].polylinesToAdd, {p3}); - expect(map.polylineUpdates[1].polylineIdsToRemove, { - p2.polylineId, - }); + expect(map.polylineUpdates[1].polylineIdsToRemove, {p2.polylineId}); expect(map.polylineUpdates[2].polylinesToChange, {p3updated}); expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/fake_google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/fake_google_maps_flutter_platform.dart index 899a7709c548..3e8beefc78c4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/fake_google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/example/test/fake_google_maps_flutter_platform.dart @@ -17,8 +17,7 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { List createdIds = []; /// A map of creation IDs to fake map instances. - Map mapInstances = - {}; + Map mapInstances = {}; PlatformMapStateRecorder get lastCreatedMap => mapInstances[createdIds.last]!; @@ -41,46 +40,31 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { Future init(int mapId) async {} @override - Future updateMapConfiguration( - MapConfiguration update, { - required int mapId, - }) async { + Future updateMapConfiguration(MapConfiguration update, {required int mapId}) async { mapInstances[mapId]?.mapConfiguration = update; await _fakeDelay(); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { mapInstances[mapId]?.markerUpdates.add(markerUpdates); await _fakeDelay(); } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { mapInstances[mapId]?.polygonUpdates.add(polygonUpdates); await _fakeDelay(); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { mapInstances[mapId]?.polylineUpdates.add(polylineUpdates); await _fakeDelay(); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { mapInstances[mapId]?.circleUpdates.add(circleUpdates); await _fakeDelay(); } @@ -113,16 +97,10 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async {} + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async {} @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future animateCameraWithConfiguration( @@ -132,55 +110,34 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { }) async {} @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future setMapStyle(String? mapStyle, {required int mapId}) async {} @override Future getVisibleRegion({required int mapId}) async { - return LatLngBounds( - southwest: const LatLng(0, 0), - northeast: const LatLng(0, 0), - ); + return LatLngBounds(southwest: const LatLng(0, 0), northeast: const LatLng(0, 0)); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return const ScreenCoordinate(x: 0, y: 0); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return const LatLng(0, 0); } @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return false; } @@ -312,24 +269,14 @@ class PlatformMapStateRecorder { this.mapConfiguration = const MapConfiguration(), }) { clusterManagerUpdates.add( - ClusterManagerUpdates.from( - const {}, - mapObjects.clusterManagers, - ), + ClusterManagerUpdates.from(const {}, mapObjects.clusterManagers), ); groundOverlayUpdates.add( - GroundOverlayUpdates.from( - const {}, - mapObjects.groundOverlays, - ), + GroundOverlayUpdates.from(const {}, mapObjects.groundOverlays), ); markerUpdates.add(MarkerUpdates.from(const {}, mapObjects.markers)); - polygonUpdates.add( - PolygonUpdates.from(const {}, mapObjects.polygons), - ); - polylineUpdates.add( - PolylineUpdates.from(const {}, mapObjects.polylines), - ); + polygonUpdates.add(PolygonUpdates.from(const {}, mapObjects.polygons)); + polylineUpdates.add(PolylineUpdates.from(const {}, mapObjects.polylines)); circleUpdates.add(CircleUpdates.from(const {}, mapObjects.circles)); tileOverlaySets.add(mapObjects.tileOverlays); } @@ -343,8 +290,6 @@ class PlatformMapStateRecorder { final List polylineUpdates = []; final List circleUpdates = []; final List> tileOverlaySets = >[]; - final List clusterManagerUpdates = - []; - final List groundOverlayUpdates = - []; + final List clusterManagerUpdates = []; + final List groundOverlayUpdates = []; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_map_inspector_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_map_inspector_ios.dart index a0057b9fdc54..a0d3b46c6cbb 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_map_inspector_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_map_inspector_ios.dart @@ -14,9 +14,8 @@ import 'messages.g.dart'; class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { /// Creates an inspector API instance for a given map ID from /// [inspectorProvider]. - GoogleMapsInspectorIOS( - MapsInspectorApi? Function(int mapId) inspectorProvider, - ) : _inspectorProvider = inspectorProvider; + GoogleMapsInspectorIOS(MapsInspectorApi? Function(int mapId) inspectorProvider) + : _inspectorProvider = inspectorProvider; final MapsInspectorApi? Function(int mapId) _inspectorProvider; @@ -53,17 +52,12 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { @override Future getMinMaxZoomLevels({required int mapId}) async { - final PlatformZoomRange zoomLevels = await _inspectorProvider( - mapId, - )!.getZoomRange(); + final PlatformZoomRange zoomLevels = await _inspectorProvider(mapId)!.getZoomRange(); return MinMaxZoomPreference(zoomLevels.min, zoomLevels.max); } @override - Future getTileOverlayInfo( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) async { final PlatformTileLayer? tileInfo = await _inspectorProvider( mapId, )!.getTileOverlayInfo(tileOverlayId.value); @@ -83,10 +77,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { bool supportsGettingHeatmapInfo() => true; @override - Future getHeatmapInfo( - HeatmapId heatmapId, { - required int mapId, - }) async { + Future getHeatmapInfo(HeatmapId heatmapId, {required int mapId}) async { final PlatformHeatmap? heatmapInfo = await _inspectorProvider( mapId, )!.getHeatmapInfo(heatmapId.value); @@ -140,24 +131,15 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { transparency: groundOverlayInfo.transparency, visible: groundOverlayInfo.visible, clickable: groundOverlayInfo.clickable, - anchor: Offset( - groundOverlayInfo.anchor!.x, - groundOverlayInfo.anchor!.y, - ), + anchor: Offset(groundOverlayInfo.anchor!.x, groundOverlayInfo.anchor!.y), zoomLevel: groundOverlayInfo.zoomLevel, ); } else if (bounds != null) { return GroundOverlay.fromBounds( groundOverlayId: groundOverlayId, bounds: LatLngBounds( - southwest: LatLng( - bounds.southwest.latitude, - bounds.southwest.longitude, - ), - northeast: LatLng( - bounds.northeast.latitude, - bounds.northeast.longitude, - ), + southwest: LatLng(bounds.southwest.latitude, bounds.southwest.longitude), + northeast: LatLng(bounds.northeast.latitude, bounds.northeast.longitude), ), image: dummyImage, zIndex: groundOverlayInfo.zIndex, @@ -202,13 +184,8 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { required int mapId, required ClusterManagerId clusterManagerId, }) async { - return (await _inspectorProvider( - mapId, - )!.getClusters(clusterManagerId.value)) - .map( - (PlatformCluster cluster) => - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ) + return (await _inspectorProvider(mapId)!.getClusters(clusterManagerId.value)) + .map((PlatformCluster cluster) => GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)) .toList(); } @@ -221,19 +198,14 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { mapId, )!.getCameraPosition(); return CameraPosition( - target: LatLng( - cameraPosition.target.latitude, - cameraPosition.target.longitude, - ), + target: LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude), bearing: cameraPosition.bearing, tilt: cameraPosition.tilt, zoom: cameraPosition.zoom, ); } - static HeatmapGradient? _deserializeHeatmapGradient( - PlatformHeatmapGradient? gradient, - ) { + static HeatmapGradient? _deserializeHeatmapGradient(PlatformHeatmapGradient? gradient) { if (gradient == null) { return null; } @@ -243,12 +215,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { _mapEnumerated( gradient.colors, (PlatformColor color, int i) => HeatmapGradientColor( - Color.from( - red: color.red, - green: color.green, - blue: color.blue, - alpha: color.alpha, - ), + Color.from(red: color.red, green: color.green, blue: color.blue, alpha: color.alpha), gradient.startPoints[i], ), ).toList(), @@ -256,9 +223,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { ); } - static WeightedLatLng _deserializeWeightedLatLng( - PlatformWeightedLatLng weightedLatLng, - ) { + static WeightedLatLng _deserializeWeightedLatLng(PlatformWeightedLatLng weightedLatLng) { return WeightedLatLng( LatLng(weightedLatLng.point.latitude, weightedLatLng.point.longitude), weight: weightedLatLng.weight, @@ -266,10 +231,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { } } -Iterable _mapEnumerated( - Iterable iterable, - E Function(T, int) fn, -) sync* { +Iterable _mapEnumerated(Iterable iterable, E Function(T, int) fn) sync* { var index = 0; for (final item in iterable) { yield fn(item, index++); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_maps_flutter_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_maps_flutter_ios.dart index c1709a97ad52..c0c8db027c8d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_maps_flutter_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/google_maps_flutter_ios.dart @@ -43,9 +43,8 @@ class UnknownMapIDError extends Error { /// An implementation of [GoogleMapsFlutterPlatform] for iOS. class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Creates a new Android maps implementation instance. - GoogleMapsFlutterIOS({ - @visibleForTesting MapsApi Function(int mapId)? apiProvider, - }) : _apiProvider = apiProvider ?? _productionApiProvider; + GoogleMapsFlutterIOS({@visibleForTesting MapsApi Function(int mapId)? apiProvider}) + : _apiProvider = apiProvider ?? _productionApiProvider; /// Registers the iOS implementation of GoogleMapsFlutterPlatform. static void registerWith() { @@ -59,8 +58,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// The per-map handlers for callbacks from the host side. @visibleForTesting - final Map hostMapHandlers = - {}; + final Map hostMapHandlers = {}; /// Accesses the MapsApi associated to the passed mapId. MapsApi _hostApi(int mapId) { @@ -84,8 +82,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { mapId, _mapEventStreamController, tileOverlayProvider: (TileOverlayId tileOverlayId) { - final Map? tileOverlaysForMap = - _tileOverlays[mapId]; + final Map? tileOverlaysForMap = _tileOverlays[mapId]; return tileOverlaysForMap?[tileOverlayId]; }, ); @@ -127,9 +124,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { StreamController>.broadcast(); // Returns a filtered view of the events in the _controller, by mapId. - Stream> _events(int mapId) => _mapEventStreamController - .stream - .where((MapEvent event) => event.mapId == mapId); + Stream> _events(int mapId) => + _mapEventStreamController.stream.where((MapEvent event) => event.mapId == mapId); @override Stream onCameraMoveStarted({required int mapId}) { @@ -207,30 +203,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateMapConfiguration( - MapConfiguration configuration, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromMapConfiguration(configuration), - ); + Future updateMapConfiguration(MapConfiguration configuration, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromMapConfiguration(configuration)); } @override - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromOptionsJson(optionsUpdate), - ); + Future updateMapOptions(Map optionsUpdate, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromOptionsJson(optionsUpdate)); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) { return _hostApi(mapId).updateMarkers( markerUpdates.markersToAdd.map(_platformMarkerFromMarker).toList(), markerUpdates.markersToChange.map(_platformMarkerFromMarker).toList(), @@ -239,42 +226,25 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) { return _hostApi(mapId).updatePolygons( polygonUpdates.polygonsToAdd.map(_platformPolygonFromPolygon).toList(), polygonUpdates.polygonsToChange.map(_platformPolygonFromPolygon).toList(), - polygonUpdates.polygonIdsToRemove - .map((PolygonId id) => id.value) - .toList(), + polygonUpdates.polygonIdsToRemove.map((PolygonId id) => id.value).toList(), ); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) { return _hostApi(mapId).updatePolylines( - polylineUpdates.polylinesToAdd - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylinesToChange - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylineIdsToRemove - .map((PolylineId id) => id.value) - .toList(), + polylineUpdates.polylinesToAdd.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylinesToChange.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylineIdsToRemove.map((PolylineId id) => id.value).toList(), ); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) { return _hostApi(mapId).updateCircles( circleUpdates.circlesToAdd.map(_platformCircleFromCircle).toList(), circleUpdates.circlesToChange.map(_platformCircleFromCircle).toList(), @@ -283,41 +253,26 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) { return _hostApi(mapId).updateHeatmaps( heatmapUpdates.heatmapsToAdd.map(_platformHeatmapFromHeatmap).toList(), heatmapUpdates.heatmapsToChange.map(_platformHeatmapFromHeatmap).toList(), - heatmapUpdates.heatmapIdsToRemove - .map((HeatmapId id) => id.value) - .toList(), + heatmapUpdates.heatmapIdsToRemove.map((HeatmapId id) => id.value).toList(), ); } @override - Future updateTileOverlays({ - required Set newTileOverlays, - required int mapId, - }) { - final Map? currentTileOverlays = - _tileOverlays[mapId]; + Future updateTileOverlays({required Set newTileOverlays, required int mapId}) { + final Map? currentTileOverlays = _tileOverlays[mapId]; final Set previousSet = currentTileOverlays != null ? currentTileOverlays.values.toSet() : {}; final updates = _TileOverlayUpdates.from(previousSet, newTileOverlays); _tileOverlays[mapId] = keyTileOverlayId(newTileOverlays); return _hostApi(mapId).updateTileOverlays( - updates.tileOverlaysToAdd - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlaysToChange - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlayIdsToRemove - .map((TileOverlayId id) => id.value) - .toList(), + updates.tileOverlaysToAdd.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlaysToChange.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlayIdsToRemove.map((TileOverlayId id) => id.value).toList(), ); } @@ -356,17 +311,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { groundOverlayUpdates.groundOverlaysToChange .map(_platformGroundOverlayFromGroundOverlay) .toList(), - groundOverlayUpdates.groundOverlayIdsToRemove - .map((GroundOverlayId id) => id.value) - .toList(), + groundOverlayUpdates.groundOverlayIdsToRemove.map((GroundOverlayId id) => id.value).toList(), ); } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) { return _hostApi(mapId).clearTileCache(tileOverlayId.value); } @@ -393,16 +343,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) { - return _hostApi( - mapId, - ).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); + return _hostApi(mapId).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); } @override Future setMapStyle(String? mapStyle, {required int mapId}) async { - final String? errorDescription = await _hostApi( - mapId, - ).setStyle(mapStyle ?? ''); + final String? errorDescription = await _hostApi(mapId).setStyle(mapStyle ?? ''); if (errorDescription != null) { throw MapStyleException(errorDescription); } @@ -410,32 +356,20 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future getVisibleRegion({required int mapId}) async { - return _latLngBoundsFromPlatformLatLngBounds( - await _hostApi(mapId).getVisibleRegion(), - ); + return _latLngBoundsFromPlatformLatLngBounds(await _hostApi(mapId).getVisibleRegion()); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return _screenCoordinateFromPlatformPoint( - await _hostApi( - mapId, - ).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), + await _hostApi(mapId).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), ); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return _latLngFromPlatformLatLng( - await _hostApi( - mapId, - ).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), + await _hostApi(mapId).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), ); } @@ -450,10 +384,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) { return _hostApi(mapId).isInfoWindowShown(markerId.value); } @@ -497,21 +428,11 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { widgetConfiguration.initialCameraPosition, ), mapConfiguration: mapConfiguration, - initialMarkers: mapObjects.markers - .map(_platformMarkerFromMarker) - .toList(), - initialPolygons: mapObjects.polygons - .map(_platformPolygonFromPolygon) - .toList(), - initialPolylines: mapObjects.polylines - .map(_platformPolylineFromPolyline) - .toList(), - initialCircles: mapObjects.circles - .map(_platformCircleFromCircle) - .toList(), - initialHeatmaps: mapObjects.heatmaps - .map(_platformHeatmapFromHeatmap) - .toList(), + initialMarkers: mapObjects.markers.map(_platformMarkerFromMarker).toList(), + initialPolygons: mapObjects.polygons.map(_platformPolygonFromPolygon).toList(), + initialPolylines: mapObjects.polylines.map(_platformPolylineFromPolyline).toList(), + initialCircles: mapObjects.circles.map(_platformCircleFromCircle).toList(), + initialHeatmaps: mapObjects.heatmaps.map(_platformHeatmapFromHeatmap).toList(), initialTileOverlays: mapObjects.tileOverlays .map(_platformTileOverlayFromTileOverlay) .toList(), @@ -545,9 +466,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { onPlatformViewCreated, widgetConfiguration: widgetConfiguration, mapObjects: mapObjects, - mapConfiguration: _platformMapConfigurationFromMapConfiguration( - mapConfiguration, - ), + mapConfiguration: _platformMapConfigurationFromMapConfiguration(mapConfiguration), ); } @@ -629,19 +548,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static ScreenCoordinate _screenCoordinateFromPlatformPoint( - PlatformPoint point, - ) { + static ScreenCoordinate _screenCoordinateFromPlatformPoint(PlatformPoint point) { return ScreenCoordinate(x: point.x.round(), y: point.y.round()); } - static PlatformPoint _platformPointFromScreenCoordinate( - ScreenCoordinate coordinate, - ) { - return PlatformPoint( - x: coordinate.x.toDouble(), - y: coordinate.y.toDouble(), - ); + static PlatformPoint _platformPointFromScreenCoordinate(ScreenCoordinate coordinate) { + return PlatformPoint(x: coordinate.x.toDouble(), y: coordinate.y.toDouble()); } static PlatformPoint _platformPointFromOffset(Offset offset) { @@ -670,9 +582,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { final HeatmapGradient? gradient = heatmap.gradient; return PlatformHeatmap( heatmapId: heatmap.heatmapId.value, - data: heatmap.data - .map(_platformWeightedLatLngFromWeightedLatLng) - .toList(), + data: heatmap.data.map(_platformWeightedLatLngFromWeightedLatLng).toList(), gradient: _platformHeatmapGradientFromHeatmapGradient(gradient), opacity: heatmap.opacity, radius: heatmap.radius.radius, @@ -691,16 +601,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { colors: gradient.colors .map((HeatmapGradientColor c) => _platformColorFromColor(c.color)) .toList(), - startPoints: gradient.colors - .map((HeatmapGradientColor c) => c.startPoint) - .toList(), + startPoints: gradient.colors.map((HeatmapGradientColor c) => c.startPoint).toList(), colorMapSize: gradient.colorMapSize, ); } - static PlatformInfoWindow _platformInfoWindowFromInfoWindow( - InfoWindow window, - ) { + static PlatformInfoWindow _platformInfoWindowFromInfoWindow(InfoWindow window) { return PlatformInfoWindow( title: window.title, snippet: window.snippet, @@ -724,9 +630,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { markerId: marker.markerId.value, clusterManagerId: marker.clusterManagerId?.value, collisionBehavior: marker is AdvancedMarker - ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( - marker.collisionBehavior, - ) + ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior(marker.collisionBehavior) : null, ); } @@ -736,9 +640,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ) { return PlatformGroundOverlay( groundOverlayId: groundOverlay.groundOverlayId.value, - anchor: groundOverlay.anchor != null - ? _platformPointFromOffset(groundOverlay.anchor!) - : null, + anchor: groundOverlay.anchor != null ? _platformPointFromOffset(groundOverlay.anchor!) : null, image: platformBitmapFromBitmapDescriptor(groundOverlay.image), position: groundOverlay.position != null ? _platformLatLngFromLatLng(groundOverlay.position!) @@ -754,12 +656,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolygon _platformPolygonFromPolygon(Polygon polygon) { - final List points = polygon.points - .map(_platformLatLngFromLatLng) - .toList(); - final List> holes = polygon.holes.map(( - List hole, - ) { + final List points = polygon.points.map(_platformLatLngFromLatLng).toList(); + final List> holes = polygon.holes.map((List hole) { return hole.map(_platformLatLngFromLatLng).toList(); }).toList(); return PlatformPolygon( @@ -777,9 +675,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolyline _platformPolylineFromPolyline(Polyline polyline) { - final List points = polyline.points - .map(_platformLatLngFromLatLng) - .toList(); + final List points = polyline.points.map(_platformLatLngFromLatLng).toList(); final List pattern = polyline.patterns .map(platformPatternItemFromPatternItem) .toList(); @@ -797,9 +693,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static PlatformTileOverlay _platformTileOverlayFromTileOverlay( - TileOverlay tileOverlay, - ) { + static PlatformTileOverlay _platformTileOverlayFromTileOverlay(TileOverlay tileOverlay) { return PlatformTileOverlay( tileOverlayId: tileOverlay.tileOverlayId.value, fadeIn: tileOverlay.fadeIn, @@ -813,22 +707,16 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { static PlatformClusterManager _platformClusterManagerFromClusterManager( ClusterManager clusterManager, ) { - return PlatformClusterManager( - identifier: clusterManager.clusterManagerId.value, - ); + return PlatformClusterManager(identifier: clusterManager.clusterManagerId.value); } - static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate( - CameraUpdate update, - ) { + static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate(CameraUpdate update) { switch (update.updateType) { case CameraUpdateType.newCameraPosition: update as CameraUpdateNewCameraPosition; return PlatformCameraUpdate( cameraUpdate: PlatformCameraUpdateNewCameraPosition( - cameraPosition: _platformCameraPositionFromCameraPosition( - update.cameraPosition, - ), + cameraPosition: _platformCameraPositionFromCameraPosition(update.cameraPosition), ), ); case CameraUpdateType.newLatLng: @@ -856,9 +744,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomTo: update as CameraUpdateZoomTo; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom)); case CameraUpdateType.zoomBy: update as CameraUpdateZoomBy; final Offset? focus = update.focus; @@ -870,30 +756,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomIn: update as CameraUpdateZoomIn; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: false), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: false)); case CameraUpdateType.zoomOut: update as CameraUpdateZoomOut; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: true), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: true)); case CameraUpdateType.scrollBy: update as CameraUpdateScrollBy; return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateScrollBy( - dx: update.dx, - dy: update.dy, - ), + cameraUpdate: PlatformCameraUpdateScrollBy(dx: update.dx, dy: update.dy), ); } } /// Converts [MapBitmapScaling] from platform interface to [PlatformMapBitmapScaling] Pigeon. @visibleForTesting - static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling( - MapBitmapScaling scaling, - ) { + static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling(MapBitmapScaling scaling) { switch (scaling) { case MapBitmapScaling.auto: return PlatformMapBitmapScaling.auto; @@ -913,8 +790,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [MarkersCollisionBehavior] from platform interface to /// [PlatformMarkerCollisionBehavior] Pigeon. @visibleForTesting - static PlatformMarkerCollisionBehavior - platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( + static PlatformMarkerCollisionBehavior platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( MarkerCollisionBehavior collisionBehavior, ) { switch (collisionBehavior) { @@ -937,14 +813,10 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [BitmapDescriptor] from platform interface to [PlatformBitmap] pigeon. @visibleForTesting - static PlatformBitmap platformBitmapFromBitmapDescriptor( - BitmapDescriptor bitmap, - ) { + static PlatformBitmap platformBitmapFromBitmapDescriptor(BitmapDescriptor bitmap) { switch (bitmap) { case final DefaultMarker marker: - return PlatformBitmap( - bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble()), - ); + return PlatformBitmap(bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble())); // Clients may still use this deprecated format, so it must be supported. // ignore: deprecated_member_use case final BytesBitmap bytes: @@ -974,9 +846,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapAssetMap( assetName: asset.assetName, - bitmapScaling: platformMapBitmapScalingFromScaling( - asset.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(asset.bitmapScaling), imagePixelRatio: asset.imagePixelRatio, width: asset.width, height: asset.height, @@ -986,9 +856,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapBytesMap( byteData: bytes.byteData, - bitmapScaling: platformMapBitmapScalingFromScaling( - bytes.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(bytes.bitmapScaling), imagePixelRatio: bytes.imagePixelRatio, width: bytes.width, height: bytes.height, @@ -1026,9 +894,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { bitmap: PlatformBitmapPinConfig( backgroundColor: backgroundColor, borderColor: borderColor, - glyphBitmap: platformBitmapFromBitmapDescriptor( - bitmapGlyph.bitmap, - ), + glyphBitmap: platformBitmapFromBitmapDescriptor(bitmapGlyph.bitmap), ), ); case null: @@ -1050,10 +916,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { 'Glyph type "${pinConfig.glyph.runtimeType}" has not been implemented', ); default: - throw ArgumentError( - 'Unrecognized type of bitmap ${bitmap.runtimeType}', - 'bitmap', - ); + throw ArgumentError('Unrecognized type of bitmap ${bitmap.runtimeType}', 'bitmap'); } } } @@ -1063,11 +926,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { class HostMapMessageHandler implements MapsCallbackApi { /// Creates a new handler that listens for events from map [mapId], and /// broadcasts them to [streamController]. - HostMapMessageHandler( - this.mapId, - this.streamController, { - required this.tileOverlayProvider, - }) { + HostMapMessageHandler(this.mapId, this.streamController, {required this.tileOverlayProvider}) { MapsCallbackApi.setUp(this, messageChannelSuffix: mapId.toString()); } @@ -1092,17 +951,11 @@ class HostMapMessageHandler implements MapsCallbackApi { PlatformPoint location, int zoom, ) async { - final TileOverlay? tileOverlay = tileOverlayProvider( - TileOverlayId(tileOverlayId), - ); + final TileOverlay? tileOverlay = tileOverlayProvider(TileOverlayId(tileOverlayId)); final TileProvider? tileProvider = tileOverlay?.tileProvider; final Tile tile = tileProvider == null ? TileProvider.noTile - : await tileProvider.getTile( - location.x.round(), - location.y.round(), - zoom, - ); + : await tileProvider.getTile(location.x.round(), location.y.round(), zoom); return _platformTileFromTile(tile); } @@ -1139,10 +992,7 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onClusterTap(PlatformCluster cluster) { streamController.add( - ClusterTapEvent( - mapId, - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ), + ClusterTapEvent(mapId, GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)), ); } @@ -1153,41 +1003,27 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onLongPress(PlatformLatLng position) { - streamController.add( - MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position))); } @override void onMarkerDrag(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragStart(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragStartEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragStartEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragEnd(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEndEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEndEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @@ -1208,35 +1044,24 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onGroundOverlayTap(String groundOverlayId) { - streamController.add( - GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId)), - ); + streamController.add(GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId))); } @override void onTap(PlatformLatLng position) { - streamController.add( - MapTapEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapTapEvent(mapId, _latLngFromPlatformLatLng(position))); } } PlatformColor _platformColorFromColor(Color color) { - return PlatformColor( - red: color.r, - green: color.g, - blue: color.b, - alpha: color.a, - ); + return PlatformColor(red: color.r, green: color.g, blue: color.b, alpha: color.a); } LatLng _latLngFromPlatformLatLng(PlatformLatLng latLng) { return LatLng(latLng.latitude, latLng.longitude); } -LatLngBounds _latLngBoundsFromPlatformLatLngBounds( - PlatformLatLngBounds bounds, -) { +LatLngBounds _latLngBoundsFromPlatformLatLngBounds(PlatformLatLngBounds bounds) { return LatLngBounds( southwest: _latLngFromPlatformLatLng(bounds.southwest), northeast: _latLngFromPlatformLatLng(bounds.northeast), @@ -1247,9 +1072,7 @@ PlatformLatLng _platformLatLngFromLatLng(LatLng latLng) { return PlatformLatLng(latitude: latLng.latitude, longitude: latLng.longitude); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( - LatLngBounds? bounds, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds(LatLngBounds? bounds) { if (bounds == null) { return null; } @@ -1259,9 +1082,7 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( ); } -PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng( - WeightedLatLng weightedLatLng, -) { +PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng(WeightedLatLng weightedLatLng) { return PlatformWeightedLatLng( point: _platformLatLngFromLatLng(weightedLatLng.point), weight: weightedLatLng.weight, @@ -1273,9 +1094,7 @@ PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBounds( ) { return bounds == null ? null - : PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds), - ); + : PlatformCameraTargetBounds(bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds)); } PlatformTile _platformTileFromTile(Tile tile) { @@ -1306,12 +1125,8 @@ PlatformMapType? _platformMapTypeFromMapType(MapType? type) { return PlatformMapType.normal; } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference( - MinMaxZoomPreference? zoomPref, -) { - return zoomPref == null - ? null - : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference(MinMaxZoomPreference? zoomPref) { + return zoomPref == null ? null : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); } PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { @@ -1325,18 +1140,14 @@ PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { ); } -PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( - MapConfiguration config, -) { +PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration(MapConfiguration config) { return PlatformMapConfiguration( compassEnabled: config.compassEnabled, cameraTargetBounds: _platformCameraTargetBoundsFromCameraTargetBounds( config.cameraTargetBounds, ), mapType: _platformMapTypeFromMapType(config.mapType), - minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference( - config.minMaxZoomPreference, - ), + minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference(config.minMaxZoomPreference), rotateGesturesEnabled: config.rotateGesturesEnabled, scrollGesturesEnabled: config.scrollGesturesEnabled, tiltGesturesEnabled: config.tiltGesturesEnabled, @@ -1348,9 +1159,7 @@ PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( indoorViewEnabled: config.indoorViewEnabled, trafficEnabled: config.trafficEnabled, buildingsEnabled: config.buildingsEnabled, - markerType: _platformMarkerTypeFromMarkerType( - config.markerType ?? MarkerType.marker, - ), + markerType: _platformMarkerTypeFromMarkerType(config.markerType ?? MarkerType.marker), mapId: config.mapId, style: config.style, ); @@ -1374,14 +1183,11 @@ PlatformMarkerType _platformMarkerTypeFromMarkerType(MarkerType markerType) { } // For supporting the deprecated updateMapOptions API. -PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( - Map options, -) { +PlatformMapConfiguration _platformMapConfigurationFromOptionsJson(Map options) { // All of these hard-coded values and structures come from // google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart // to support this legacy API that relied on cross-package magic strings. - final List? padding = (options['padding'] as List?) - ?.cast(); + final List? padding = (options['padding'] as List?)?.cast(); final mapType = options['mapType'] as int?; return PlatformMapConfiguration( compassEnabled: options['compassEnabled'] as bool?, @@ -1416,9 +1222,7 @@ PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( ); } -PlatformCameraPosition _platformCameraPositionFromCameraPosition( - CameraPosition position, -) { +PlatformCameraPosition _platformCameraPositionFromCameraPosition(CameraPosition position) { return PlatformCameraPosition( bearing: position.bearing, target: _platformLatLngFromLatLng(position.target), @@ -1446,9 +1250,7 @@ PlatformLatLng _platformLatLngFromLatLngJson(Object latLngJson) { return PlatformLatLng(latitude: list[0], longitude: list[1]); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( - Object? boundsJson, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson(Object? boundsJson) { if (boundsJson == null) { return null; } @@ -1460,28 +1262,24 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( ); } -PlatformCameraTargetBounds? -_platformCameraTargetBoundsFromCameraTargetBoundsJson(Object? targetJson) { +PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBoundsJson( + Object? targetJson, +) { if (targetJson == null) { return null; } // See `CameraTargetBounds.toJson`. return PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBoundsJson( - (targetJson as List)[0], - ), + bounds: _platformLatLngBoundsFromLatLngBoundsJson((targetJson as List)[0]), ); } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson( - Object? zoomPrefsJson, -) { +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson(Object? zoomPrefsJson) { if (zoomPrefsJson == null) { return null; } // See `MinMaxZoomPreference.toJson`. - final List minMaxZoom = (zoomPrefsJson as List) - .cast(); + final List minMaxZoom = (zoomPrefsJson as List).cast(); return PlatformZoomRange(min: minMaxZoom[0], max: minMaxZoom[1]); } @@ -1514,16 +1312,10 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { return PlatformPatternItem(type: PlatformPatternItemType.dot); case PatternItemType.dash: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.dash, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.dash, length: length); case PatternItemType.gap: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.gap, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.gap, length: length); } // The enum comes from a different package, which could get a new value at @@ -1540,15 +1332,13 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { // interface, and remove this copy. class _TileOverlayUpdates extends MapsObjectUpdates { /// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s. - _TileOverlayUpdates.from(super.previous, super.current) - : super.from(objectName: 'tileOverlay'); + _TileOverlayUpdates.from(super.previous, super.current) : super.from(objectName: 'tileOverlay'); /// Set of TileOverlays to be added in this update. Set get tileOverlaysToAdd => objectsToAdd; /// Set of TileOverlayIds to be removed in this update. - Set get tileOverlayIdsToRemove => - objectIdsToRemove.cast(); + Set get tileOverlayIdsToRemove => objectIdsToRemove.cast(); /// Set of TileOverlays to be changed in this update. Set get tileOverlaysToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/messages.g.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/messages.g.dart index 87fd64fcb0bc..be134f058b12 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/messages.g.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/lib/src/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -187,8 +181,7 @@ class PlatformCameraUpdateNewCameraPosition { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewCameraPosition || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewCameraPosition || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -224,8 +217,7 @@ class PlatformCameraUpdateNewLatLng { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLng || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLng || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -241,10 +233,7 @@ class PlatformCameraUpdateNewLatLng { /// Pigeon equivalent of NewLatLngBounds class PlatformCameraUpdateNewLatLngBounds { - PlatformCameraUpdateNewLatLngBounds({ - required this.bounds, - required this.padding, - }); + PlatformCameraUpdateNewLatLngBounds({required this.bounds, required this.padding}); PlatformLatLngBounds bounds; @@ -269,8 +258,7 @@ class PlatformCameraUpdateNewLatLngBounds { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -311,8 +299,7 @@ class PlatformCameraUpdateNewLatLngZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -344,17 +331,13 @@ class PlatformCameraUpdateScrollBy { static PlatformCameraUpdateScrollBy decode(Object result) { result as List; - return PlatformCameraUpdateScrollBy( - dx: result[0]! as double, - dy: result[1]! as double, - ); + return PlatformCameraUpdateScrollBy(dx: result[0]! as double, dy: result[1]! as double); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateScrollBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateScrollBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -395,8 +378,7 @@ class PlatformCameraUpdateZoomBy { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -432,8 +414,7 @@ class PlatformCameraUpdateZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -469,8 +450,7 @@ class PlatformCameraUpdateZoomTo { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomTo || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomTo || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1255,14 +1235,7 @@ class PlatformTileOverlay { int tileSize; List _toList() { - return [ - tileOverlayId, - fadeIn, - transparency, - zIndex, - visible, - tileSize, - ]; + return [tileOverlayId, fadeIn, transparency, zIndex, visible, tileSize]; } Object encode() { @@ -1368,10 +1341,7 @@ class PlatformLatLng { static PlatformLatLng decode(Object result) { result as List; - return PlatformLatLng( - latitude: result[0]! as double, - longitude: result[1]! as double, - ); + return PlatformLatLng(latitude: result[0]! as double, longitude: result[1]! as double); } @override @@ -1451,16 +1421,13 @@ class PlatformCameraTargetBounds { static PlatformCameraTargetBounds decode(Object result) { result as List; - return PlatformCameraTargetBounds( - bounds: result[0] as PlatformLatLngBounds?, - ); + return PlatformCameraTargetBounds(bounds: result[0] as PlatformLatLngBounds?); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraTargetBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraTargetBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1630,20 +1597,16 @@ class PlatformMapViewCreationParams { initialPolygons: (result[4] as List?)!.cast(), initialPolylines: (result[5] as List?)!.cast(), initialHeatmaps: (result[6] as List?)!.cast(), - initialTileOverlays: (result[7] as List?)! - .cast(), - initialClusterManagers: (result[8] as List?)! - .cast(), - initialGroundOverlays: (result[9] as List?)! - .cast(), + initialTileOverlays: (result[7] as List?)!.cast(), + initialClusterManagers: (result[8] as List?)!.cast(), + initialGroundOverlays: (result[9] as List?)!.cast(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapViewCreationParams || - other.runtimeType != runtimeType) { + if (other is! PlatformMapViewCreationParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1770,8 +1733,7 @@ class PlatformMapConfiguration { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapConfiguration || - other.runtimeType != runtimeType) { + if (other is! PlatformMapConfiguration || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1841,10 +1803,7 @@ class PlatformSize { static PlatformSize decode(Object result) { result as List; - return PlatformSize( - width: result[0]! as double, - height: result[1]! as double, - ); + return PlatformSize(width: result[0]! as double, height: result[1]! as double); } @override @@ -1866,12 +1825,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); double red; @@ -1986,10 +1940,7 @@ class PlatformZoomRange { static PlatformZoomRange decode(Object result) { result as List; - return PlatformZoomRange( - min: result[0] as double?, - max: result[1] as double?, - ); + return PlatformZoomRange(min: result[0] as double?, max: result[1] as double?); } @override @@ -2076,8 +2027,7 @@ class PlatformBitmapDefaultMarker { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapDefaultMarker || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapDefaultMarker || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2109,10 +2059,7 @@ class PlatformBitmapBytes { static PlatformBitmapBytes decode(Object result) { result as List; - return PlatformBitmapBytes( - byteData: result[0]! as Uint8List, - size: result[1] as PlatformSize?, - ); + return PlatformBitmapBytes(byteData: result[0]! as Uint8List, size: result[1] as PlatformSize?); } @override @@ -2150,10 +2097,7 @@ class PlatformBitmapAsset { static PlatformBitmapAsset decode(Object result) { result as List; - return PlatformBitmapAsset( - name: result[0]! as String, - pkg: result[1] as String?, - ); + return PlatformBitmapAsset(name: result[0]! as String, pkg: result[1] as String?); } @override @@ -2175,11 +2119,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); String name; @@ -2207,8 +2147,7 @@ class PlatformBitmapAssetImage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapAssetImage || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapAssetImage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2568,9 +2507,7 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PlatformMapType.values[value]; case 130: final value = readValue(buffer) as int?; - return value == null - ? null - : PlatformMarkerCollisionBehavior.values[value]; + return value == null ? null : PlatformMarkerCollisionBehavior.values[value]; case 131: final value = readValue(buffer) as int?; return value == null ? null : PlatformJointType.values[value]; @@ -2721,9 +2658,7 @@ class MapsApi { /// /// Only non-null configuration values will result in updates; options with /// null values will remain unchanged. - Future updateMapConfiguration( - PlatformMapConfiguration configuration, - ) async { + Future updateMapConfiguration(PlatformMapConfiguration configuration) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.updateMapConfiguration$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2731,9 +2666,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [configuration], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([configuration]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2761,9 +2694,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2791,9 +2726,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2820,9 +2757,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2850,9 +2788,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2880,9 +2820,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2910,9 +2852,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2940,9 +2884,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2970,9 +2916,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2996,9 +2944,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [latLng], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([latLng]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3027,9 +2973,9 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [screenCoordinate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + screenCoordinate, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3088,9 +3034,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraUpdate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3107,10 +3051,7 @@ class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. - Future animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ) async { + Future animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.animateCamera$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3118,9 +3059,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate, durationMilliseconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraUpdate, + durationMilliseconds, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3173,9 +3115,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3199,9 +3139,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3226,9 +3164,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3261,9 +3197,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [style], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([style]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3315,9 +3249,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3436,20 +3368,14 @@ abstract class MapsCallbackApi { void onGroundOverlayTap(String groundOverlayId); /// Called to get data for a map tile. - Future getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + Future getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); static void setUp( MapsCallbackApi? api, { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMoveStarted$messageChannelSuffix', @@ -3488,8 +3414,7 @@ abstract class MapsCallbackApi { 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null.', ); final List args = (message as List?)!; - final PlatformCameraPosition? arg_cameraPosition = - (args[0] as PlatformCameraPosition?); + final PlatformCameraPosition? arg_cameraPosition = (args[0] as PlatformCameraPosition?); assert( arg_cameraPosition != null, 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null, expected non-null PlatformCameraPosition.', @@ -3998,13 +3923,11 @@ class MapsPlatformViewApi { /// Constructor for [MapsPlatformViewApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsPlatformViewApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsPlatformViewApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4019,9 +3942,7 @@ class MapsPlatformViewApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [type], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([type]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4042,13 +3963,11 @@ class MapsInspectorApi { /// Constructor for [MapsInspectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsInspectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsInspectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4287,9 +4206,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4304,9 +4221,7 @@ class MapsInspectorApi { } } - Future getGroundOverlayInfo( - String groundOverlayId, - ) async { + Future getGroundOverlayInfo(String groundOverlayId) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsInspectorApi.getGroundOverlayInfo$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4314,9 +4229,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [groundOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([groundOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4339,9 +4252,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [heatmapId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([heatmapId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4392,9 +4303,9 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [clusterManagerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + clusterManagerId, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4410,8 +4321,7 @@ class MapsInspectorApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/pigeons/messages.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/pigeons/messages.dart index 82235e3afb63..3c69cc451040 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/pigeons/messages.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/pigeons/messages.dart @@ -510,12 +510,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); final double red; final double green; @@ -587,11 +582,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); final String name; final double scale; final PlatformSize? size; @@ -685,10 +676,7 @@ abstract class MapsApi { /// Updates the set of custer managers for clusters on the map. @ObjCSelector('updateClusterManagersByAdding:removing:') - void updateClusterManagers( - List toAdd, - List idsToRemove, - ); + void updateClusterManagers(List toAdd, List idsToRemove); /// Updates the set of markers on the map. @ObjCSelector('updateMarkersByAdding:changing:removing:') @@ -750,10 +738,7 @@ abstract class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. @ObjCSelector('animateCameraWithUpdate:duration:') - void animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ); + void animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds); /// Gets the current map zoom level. @ObjCSelector('currentZoomLevel') @@ -866,11 +851,7 @@ abstract class MapsCallbackApi { /// Called to get data for a map tile. @async @ObjCSelector('tileWithOverlayIdentifier:location:zoom:') - PlatformTile getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + PlatformTile getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); } /// Dummy interface to force generation of the platform view creation params, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.dart index 486884bc81d1..c2fa99cac0dd 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.dart @@ -43,28 +43,18 @@ void main() { test('getScreenCoordinate converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const latLng = LatLng(10, 20); const expectedCoord = ScreenCoordinate(x: 30, y: 40); when(api.getScreenCoordinate(any)).thenAnswer( - (_) async => PlatformPoint( - x: expectedCoord.x.toDouble(), - y: expectedCoord.y.toDouble(), - ), + (_) async => PlatformPoint(x: expectedCoord.x.toDouble(), y: expectedCoord.y.toDouble()), ); - final ScreenCoordinate coord = await maps.getScreenCoordinate( - latLng, - mapId: mapId, - ); + final ScreenCoordinate coord = await maps.getScreenCoordinate(latLng, mapId: mapId); expect(coord, expectedCoord); - final VerificationResult verification = verify( - api.getScreenCoordinate(captureAny), - ); + final VerificationResult verification = verify(api.getScreenCoordinate(captureAny)); final passedLatLng = verification.captured[0] as PlatformLatLng; expect(passedLatLng.latitude, latLng.latitude); expect(passedLatLng.longitude, latLng.longitude); @@ -72,18 +62,14 @@ void main() { test('getLatLng converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const expectedLatLng = LatLng(10, 20); const coord = ScreenCoordinate(x: 30, y: 40); when(api.getLatLng(any)).thenAnswer( - (_) async => PlatformLatLng( - latitude: expectedLatLng.latitude, - longitude: expectedLatLng.longitude, - ), + (_) async => + PlatformLatLng(latitude: expectedLatLng.latitude, longitude: expectedLatLng.longitude), ); final LatLng latLng = await maps.getLatLng(coord, mapId: mapId); @@ -96,9 +82,7 @@ void main() { test('getVisibleRegion converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. final expectedBounds = LatLngBounds( @@ -124,9 +108,7 @@ void main() { test('moveCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.moveCamera(update, mapId: mapId); @@ -141,16 +123,12 @@ void main() { test('animateCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.animateCamera(update, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -161,24 +139,14 @@ void main() { test('animateCameraWithConfiguration calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); - const configuration = CameraUpdateAnimationConfiguration( - duration: Duration(seconds: 1), - ); + const configuration = CameraUpdateAnimationConfiguration(duration: Duration(seconds: 1)); expect(configuration.duration?.inSeconds, 1); - await maps.animateCameraWithConfiguration( - update, - configuration, - mapId: mapId, - ); + await maps.animateCameraWithConfiguration(update, configuration, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -191,9 +159,7 @@ void main() { test('getZoomLevel passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const expectedZoom = 4.2; when(api.getZoomLevel()).thenAnswer((_) async => expectedZoom); @@ -204,9 +170,7 @@ void main() { test('showInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.showMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -216,9 +180,7 @@ void main() { test('hideInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.hideMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -228,27 +190,17 @@ void main() { test('isInfoWindowShown calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; when(api.isInfoWindowShown(markedId)).thenAnswer((_) async => true); - expect( - await maps.isMarkerInfoWindowShown( - const MarkerId(markedId), - mapId: mapId, - ), - true, - ); + expect(await maps.isMarkerInfoWindowShown(const MarkerId(markedId), mapId: mapId), true); }); test('takeSnapshot calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final fakeSnapshot = Uint8List(10); when(api.takeSnapshot()).thenAnswer((_) async => fakeSnapshot); @@ -258,9 +210,7 @@ void main() { test('clearTileCache calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const tileOverlayId = 'overlay'; await maps.clearTileCache(const TileOverlayId(tileOverlayId), mapId: mapId); @@ -270,16 +220,11 @@ void main() { test('updateMapConfiguration passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = MapConfiguration( compassEnabled: true, @@ -288,9 +233,7 @@ void main() { ); await maps.updateMapConfiguration(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -319,16 +262,11 @@ void main() { test('updateMapOptions passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = { 'compassEnabled': true, @@ -337,9 +275,7 @@ void main() { }; await maps.updateMapOptions(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -368,19 +304,14 @@ void main() { test('updateCircles passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Circle(circleId: CircleId('1')); const object2old = Circle(circleId: CircleId('2')); final Circle object2new = object2old.copyWith(radiusParam: 42); const object3 = Circle(circleId: CircleId('3')); await maps.updateCircles( - CircleUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + CircleUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -427,17 +358,12 @@ void main() { test('updateClusterManagers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = ClusterManager(clusterManagerId: ClusterManagerId('1')); const object3 = ClusterManager(clusterManagerId: ClusterManagerId('3')); await maps.updateClusterManagers( - ClusterManagerUpdates.from( - {object1}, - {object3}, - ), + ClusterManagerUpdates.from({object1}, {object3}), mapId: mapId, ); @@ -458,19 +384,14 @@ void main() { test('updateMarkers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Marker(markerId: MarkerId('1')); const object2old = Marker(markerId: MarkerId('2')); final Marker object2new = object2old.copyWith(rotationParam: 42); const object3 = Marker(markerId: MarkerId('3')); await maps.updateMarkers( - MarkerUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + MarkerUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -495,9 +416,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -523,9 +442,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -543,21 +460,17 @@ void main() { test('updateMarkers passes expected arguments (AdvancedMarkers)', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final object1 = AdvancedMarker(markerId: const MarkerId('1')); final object2old = AdvancedMarker(markerId: const MarkerId('2')); final AdvancedMarker object2new = object2old.copyWith( rotationParam: 42, - collisionBehaviorParam: - advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, + collisionBehaviorParam: advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, ); final object3 = AdvancedMarker( markerId: const MarkerId('3'), - collisionBehavior: - advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, + collisionBehavior: advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, ); await maps.updateMarkers( MarkerUpdates.from( @@ -588,9 +501,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -622,9 +533,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -648,19 +557,14 @@ void main() { test('updatePolygons passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polygon(polygonId: PolygonId('1')); const object2old = Polygon(polygonId: PolygonId('2')); final Polygon object2new = object2old.copyWith(strokeWidthParam: 42); const object3 = Polygon(polygonId: PolygonId('3')); await maps.updatePolygons( - PolygonUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolygonUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -707,9 +611,7 @@ void main() { test('updatePolylines passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polyline(polylineId: PolylineId('1')); const object2old = Polyline(polylineId: PolylineId('2')); @@ -718,20 +620,14 @@ void main() { startCapParam: Cap.squareCap, endCapParam: Cap.buttCap, ); - final Cap customCap = Cap.customCapFromBitmap( - BitmapDescriptor.defaultMarker, - refWidth: 15, - ); + final Cap customCap = Cap.customCapFromBitmap(BitmapDescriptor.defaultMarker, refWidth: 15); final object3 = Polyline( polylineId: const PolylineId('3'), startCap: customCap, endCap: Cap.roundCap, ); await maps.updatePolylines( - PolylineUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolylineUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -746,10 +642,7 @@ void main() { expect(actual.consumesTapEvents, expected.consumeTapEvents); _expectColorsEqual(actual.color, expected.color); expect(actual.geodesic, expected.geodesic); - expect( - actual.jointType, - platformJointTypeFromJointType(expected.jointType), - ); + expect(actual.jointType, platformJointTypeFromJointType(expected.jointType)); expect(actual.visible, expected.visible); expect(actual.width, expected.width); expect(actual.zIndex, expected.zIndex); @@ -759,8 +652,7 @@ void main() { expect(point?.longitude, actual.points[i].longitude); } expect(actual.patterns.length, expected.patterns.length); - for (final (int i, PlatformPatternItem? pattern) - in actual.patterns.indexed) { + for (final (int i, PlatformPatternItem? pattern) in actual.patterns.indexed) { expect( pattern?.encode(), platformPatternItemFromPatternItem(expected.patterns[i]).encode(), @@ -781,9 +673,7 @@ void main() { test('updateTileOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = TileOverlay(tileOverlayId: TileOverlayId('1')); const object2old = TileOverlay(tileOverlayId: TileOverlayId('2')); @@ -830,9 +720,7 @@ void main() { test('updateGroundOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final image = AssetMapBitmap( 'assets/red_square.png', @@ -842,18 +730,12 @@ void main() { final object1 = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('1'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final object2old = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('2'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final GroundOverlay object2new = object2old.copyWith( @@ -895,22 +777,10 @@ void main() { expect(firstChanged.anchor?.x, object2new.anchor?.dx); expect(firstChanged.anchor?.y, object2new.anchor?.dy); expect(firstChanged.bearing, object2new.bearing); - expect( - firstChanged.bounds?.northeast.latitude, - object2new.bounds?.northeast.latitude, - ); - expect( - firstChanged.bounds?.northeast.longitude, - object2new.bounds?.northeast.longitude, - ); - expect( - firstChanged.bounds?.southwest.latitude, - object2new.bounds?.southwest.latitude, - ); - expect( - firstChanged.bounds?.southwest.longitude, - object2new.bounds?.southwest.longitude, - ); + expect(firstChanged.bounds?.northeast.latitude, object2new.bounds?.northeast.latitude); + expect(firstChanged.bounds?.northeast.longitude, object2new.bounds?.northeast.longitude); + expect(firstChanged.bounds?.southwest.latitude, object2new.bounds?.southwest.latitude); + expect(firstChanged.bounds?.southwest.longitude, object2new.bounds?.southwest.longitude); expect(firstChanged.visible, object2new.visible); expect(firstChanged.clickable, object2new.clickable); expect(firstChanged.zIndex, object2new.zIndex); @@ -932,22 +802,10 @@ void main() { expect(firstAdded.anchor?.x, object3.anchor?.dx); expect(firstAdded.anchor?.y, object3.anchor?.dy); expect(firstAdded.bearing, object3.bearing); - expect( - firstAdded.bounds?.northeast.latitude, - object3.bounds?.northeast.latitude, - ); - expect( - firstAdded.bounds?.northeast.longitude, - object3.bounds?.northeast.longitude, - ); - expect( - firstAdded.bounds?.southwest.latitude, - object3.bounds?.southwest.latitude, - ); - expect( - firstAdded.bounds?.southwest.longitude, - object3.bounds?.southwest.longitude, - ); + expect(firstAdded.bounds?.northeast.latitude, object3.bounds?.northeast.latitude); + expect(firstAdded.bounds?.northeast.longitude, object3.bounds?.northeast.longitude); + expect(firstAdded.bounds?.southwest.latitude, object3.bounds?.southwest.latitude); + expect(firstAdded.bounds?.southwest.longitude, object3.bounds?.southwest.longitude); expect(firstAdded.visible, object3.visible); expect(firstAdded.clickable, object3.clickable); expect(firstAdded.zIndex, object3.zIndex); @@ -957,48 +815,39 @@ void main() { expect(firstAdded.transparency, object3.transparency); expect( firstAdded.image.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.image, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.image).bitmap.runtimeType, ); } }); - test( - 'updateGroundOverlays throws assertion error on unsupported ground overlays', - () async { - const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + test('updateGroundOverlays throws assertion error on unsupported ground overlays', () async { + const mapId = 1; + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); - final image = AssetMapBitmap( - 'assets/red_square.png', - imagePixelRatio: 1.0, - bitmapScaling: MapBitmapScaling.none, - ); + final image = AssetMapBitmap( + 'assets/red_square.png', + imagePixelRatio: 1.0, + bitmapScaling: MapBitmapScaling.none, + ); - final object3 = GroundOverlay.fromPosition( - groundOverlayId: const GroundOverlayId('1'), - position: const LatLng(10, 20), - // Assert should be thrown because zoomLevel is not set for position-based - // ground overlay on iOS. - // ignore: avoid_redundant_argument_values - zoomLevel: null, - image: image, - ); + final object3 = GroundOverlay.fromPosition( + groundOverlayId: const GroundOverlayId('1'), + position: const LatLng(10, 20), + // Assert should be thrown because zoomLevel is not set for position-based + // ground overlay on iOS. + // ignore: avoid_redundant_argument_values + zoomLevel: null, + image: image, + ); - expect( - () async => maps.updateGroundOverlays( - GroundOverlayUpdates.from(const {}, { - object3, - }), - mapId: mapId, - ), - throwsAssertionError, - ); - }, - ); + expect( + () async => maps.updateGroundOverlays( + GroundOverlayUpdates.from(const {}, {object3}), + mapId: mapId, + ), + throwsAssertionError, + ); + }); test('markers send drag event to correct streams', () async { const mapId = 1; @@ -1008,19 +857,13 @@ void main() { final fakePosition = PlatformLatLng(latitude: 1.0, longitude: 1.0); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final markerDragStartStream = StreamQueue( maps.onMarkerDragStart(mapId: mapId), ); - final markerDragStream = StreamQueue( - maps.onMarkerDrag(mapId: mapId), - ); - final markerDragEndStream = StreamQueue( - maps.onMarkerDragEnd(mapId: mapId), - ); + final markerDragStream = StreamQueue(maps.onMarkerDrag(mapId: mapId)); + final markerDragEndStream = StreamQueue(maps.onMarkerDragEnd(mapId: mapId)); // Simulate messages from the native side. callbackHandler.onMarkerDragStart(dragStartId, fakePosition); @@ -1037,9 +880,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onMarkerTap(mapId: mapId)); @@ -1054,9 +895,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onCircleTap(mapId: mapId)); @@ -1083,13 +922,9 @@ void main() { ); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onClusterTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onClusterTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onClusterTap(cluster); @@ -1099,15 +934,9 @@ void main() { expect(eventValue.position.latitude, fakePosition.latitude); expect(eventValue.position.longitude, fakePosition.longitude); expect(eventValue.bounds.southwest.latitude, fakeBounds.southwest.latitude); - expect( - eventValue.bounds.southwest.longitude, - fakeBounds.southwest.longitude, - ); + expect(eventValue.bounds.southwest.longitude, fakeBounds.southwest.longitude); expect(eventValue.bounds.northeast.latitude, fakeBounds.northeast.latitude); - expect( - eventValue.bounds.northeast.longitude, - fakeBounds.northeast.longitude, - ); + expect(eventValue.bounds.northeast.longitude, fakeBounds.northeast.longitude); expect(eventValue.markerIds.length, markerIds.length); expect(eventValue.markerIds.first.value, markerIds.first); }); @@ -1117,13 +946,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolygonTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolygonTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolygonTap(objectId); @@ -1136,13 +961,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolylineTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolylineTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolylineTap(objectId); @@ -1155,13 +976,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onGroundOverlayTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onGroundOverlayTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onGroundOverlayTap(objectId); @@ -1171,9 +988,7 @@ void main() { test('moveCamera calls through with expected newCameraPosition', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); const position = CameraPosition(target: latLng); @@ -1182,24 +997,15 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; update as CameraUpdateNewCameraPosition; - expect( - typedUpdate.cameraPosition.target.latitude, - update.cameraPosition.target.latitude, - ); - expect( - typedUpdate.cameraPosition.target.longitude, - update.cameraPosition.target.longitude, - ); + expect(typedUpdate.cameraPosition.target.latitude, update.cameraPosition.target.latitude); + expect(typedUpdate.cameraPosition.target.longitude, update.cameraPosition.target.longitude); }); test('moveCamera calls through with expected newLatLng', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLng(latLng); @@ -1207,8 +1013,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; update as CameraUpdateNewLatLng; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1216,9 +1021,7 @@ void main() { test('moveCamera calls through with expected newLatLngBounds', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final latLng = LatLngBounds( northeast: const LatLng(10.0, 20.0), @@ -1229,33 +1032,18 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; update as CameraUpdateNewLatLngBounds; - expect( - typedUpdate.bounds.northeast.latitude, - update.bounds.northeast.latitude, - ); - expect( - typedUpdate.bounds.northeast.longitude, - update.bounds.northeast.longitude, - ); - expect( - typedUpdate.bounds.southwest.latitude, - update.bounds.southwest.latitude, - ); - expect( - typedUpdate.bounds.southwest.longitude, - update.bounds.southwest.longitude, - ); + expect(typedUpdate.bounds.northeast.latitude, update.bounds.northeast.latitude); + expect(typedUpdate.bounds.northeast.longitude, update.bounds.northeast.longitude); + expect(typedUpdate.bounds.southwest.latitude, update.bounds.southwest.latitude); + expect(typedUpdate.bounds.southwest.longitude, update.bounds.southwest.longitude); expect(typedUpdate.padding, update.padding); }); test('moveCamera calls through with expected newLatLngZoom', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLngZoom(latLng, 2.0); @@ -1263,8 +1051,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; update as CameraUpdateNewLatLngZoom; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1273,9 +1060,7 @@ void main() { test('moveCamera calls through with expected zoomBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const focus = Offset(10.0, 20.0); final CameraUpdate update = CameraUpdate.zoomBy(2.0, focus); @@ -1292,9 +1077,7 @@ void main() { test('moveCamera calls through with expected zoomTo', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomTo(2.0); await maps.moveCamera(update, mapId: mapId); @@ -1308,9 +1091,7 @@ void main() { test('moveCamera calls through with expected zoomIn', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomIn(); await maps.moveCamera(update, mapId: mapId); @@ -1323,9 +1104,7 @@ void main() { test('moveCamera calls through with expected zoomOut', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomOut(); await maps.moveCamera(update, mapId: mapId); @@ -1338,23 +1117,20 @@ void main() { test('MapBitmapScaling to PlatformMapBitmapScaling', () { expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.auto, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.auto), PlatformMapBitmapScaling.auto, ); expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.none, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.none), PlatformMapBitmapScaling.none, ); }); test('DefaultMarker bitmap to PlatformBitmap', () { final BitmapDescriptor bitmap = BitmapDescriptor.defaultMarkerWithHue(10.0); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapDefaultMarker; expect(typedBitmap.hue, 10.0); @@ -1368,8 +1144,9 @@ void main() { width: 100.0, height: 200.0, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapBytesMap; expect(typedBitmap.byteData, data); @@ -1381,14 +1158,10 @@ void main() { test('AssetMapBitmap bitmap to PlatformBitmap', () { const assetName = 'fake_asset_name'; - final bitmap = AssetMapBitmap( - assetName, - imagePixelRatio: 2.0, - width: 100.0, - height: 200.0, + final bitmap = AssetMapBitmap(assetName, imagePixelRatio: 2.0, width: 100.0, height: 200.0); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapAssetMap; expect(typedBitmap.assetName, assetName); @@ -1402,31 +1175,28 @@ void main() { const cloudMapId = '000000000000000'; // Dummy map ID. final passedCloudMapIdCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null) { - final String? passedMapId = - creationParams.mapConfiguration.mapId; - if (passedMapId != null) { - passedCloudMapIdCompleter.complete(passedMapId); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null) { + final String? passedMapId = creationParams.mapConfiguration.mapId; + if (passedMapId != null) { + passedCloudMapIdCompleter.complete(passedMapId); } } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1437,10 +1207,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: const MapConfiguration(mapId: cloudMapId), @@ -1462,30 +1229,25 @@ void main() { ) async { final passedMarkerTypeCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null && - !passedMarkerTypeCompleter.isCompleted) { - passedMarkerTypeCompleter.complete( - creationParams.mapConfiguration.markerType, - ); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null && !passedMarkerTypeCompleter.isCompleted) { + passedMarkerTypeCompleter.complete(creationParams.mapConfiguration.markerType); } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1496,10 +1258,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: MapConfiguration(markerType: markerType), @@ -1513,11 +1272,10 @@ void main() { testWidgets('passes advancedMarker when MarkerType.advancedMarker is set', ( WidgetTester tester, ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams( - tester, - MarkerType.advancedMarker, - ); + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.advancedMarker, + ); expect( passedMarkerType, @@ -1527,31 +1285,29 @@ void main() { ); }); - testWidgets('passes marker when MarkerType.marker is set', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, MarkerType.marker); + testWidgets('passes marker when MarkerType.marker is set', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.marker, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should pass marker on PlatformView creation when MarkerType.marker is set', + reason: 'Should pass marker on PlatformView creation when MarkerType.marker is set', ); }); - testWidgets('passes marker when markerType is null', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, null); + testWidgets('passes marker when markerType is null', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + null, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should default to marker on PlatformView creation when markerType is null', + reason: 'Should default to marker on PlatformView creation when markerType is null', ); }); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.mocks.dart index 1dc745d619de..dc29285572ae 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/test/google_maps_flutter_ios_test.mocks.dart @@ -29,14 +29,12 @@ class _FakePlatformPoint_0 extends _i1.SmartFake implements _i2.PlatformPoint { : super(parent, parentInvocation); } -class _FakePlatformLatLng_1 extends _i1.SmartFake - implements _i2.PlatformLatLng { +class _FakePlatformLatLng_1 extends _i1.SmartFake implements _i2.PlatformLatLng { _FakePlatformLatLng_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePlatformLatLngBounds_2 extends _i1.SmartFake - implements _i2.PlatformLatLngBounds { +class _FakePlatformLatLngBounds_2 extends _i1.SmartFake implements _i2.PlatformLatLngBounds { _FakePlatformLatLngBounds_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -46,315 +44,229 @@ class _FakePlatformLatLngBounds_2 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockMapsApi extends _i1.Mock implements _i2.MapsApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future waitForMap() => - (super.noSuchMethod( - Invocation.method(#waitForMap, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future waitForMap() => (super.noSuchMethod( + Invocation.method(#waitForMap, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future updateMapConfiguration( - _i2.PlatformMapConfiguration? configuration, - ) => + _i4.Future updateMapConfiguration(_i2.PlatformMapConfiguration? configuration) => (super.noSuchMethod( - Invocation.method(#updateMapConfiguration, [configuration]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#updateMapConfiguration, [configuration]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateCircles( List<_i2.PlatformCircle>? toAdd, List<_i2.PlatformCircle>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateHeatmaps( List<_i2.PlatformHeatmap>? toAdd, List<_i2.PlatformHeatmap>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateClusterManagers( List<_i2.PlatformClusterManager>? toAdd, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateMarkers( List<_i2.PlatformMarker>? toAdd, List<_i2.PlatformMarker>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolygons( List<_i2.PlatformPolygon>? toAdd, List<_i2.PlatformPolygon>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolylines( List<_i2.PlatformPolyline>? toAdd, List<_i2.PlatformPolyline>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateTileOverlays( List<_i2.PlatformTileOverlay>? toAdd, List<_i2.PlatformTileOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateTileOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateTileOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateGroundOverlays( List<_i2.PlatformGroundOverlay>? toAdd, List<_i2.PlatformGroundOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateGroundOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateGroundOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformPoint> getScreenCoordinate( - _i2.PlatformLatLng? latLng, - ) => + _i4.Future<_i2.PlatformPoint> getScreenCoordinate(_i2.PlatformLatLng? latLng) => (super.noSuchMethod( - Invocation.method(#getScreenCoordinate, [latLng]), - returnValue: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - ) - as _i4.Future<_i2.PlatformPoint>); + Invocation.method(#getScreenCoordinate, [latLng]), + returnValue: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + ) as _i4.Future<_i2.PlatformPoint>); @override - _i4.Future<_i2.PlatformLatLng> getLatLng( - _i2.PlatformPoint? screenCoordinate, - ) => + _i4.Future<_i2.PlatformLatLng> getLatLng(_i2.PlatformPoint? screenCoordinate) => (super.noSuchMethod( - Invocation.method(#getLatLng, [screenCoordinate]), - returnValue: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLng>); + Invocation.method(#getLatLng, [screenCoordinate]), + returnValue: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + ) as _i4.Future<_i2.PlatformLatLng>); @override - _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => - (super.noSuchMethod( - Invocation.method(#getVisibleRegion, []), - returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLngBounds>); + _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => (super.noSuchMethod( + Invocation.method(#getVisibleRegion, []), + returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + ) as _i4.Future<_i2.PlatformLatLngBounds>); @override - _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => - (super.noSuchMethod( - Invocation.method(#moveCamera, [cameraUpdate]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => (super.noSuchMethod( + Invocation.method(#moveCamera, [cameraUpdate]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future animateCamera( _i2.PlatformCameraUpdate? cameraUpdate, int? durationMilliseconds, - ) => - (super.noSuchMethod( - Invocation.method(#animateCamera, [ - cameraUpdate, - durationMilliseconds, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#animateCamera, [cameraUpdate, durationMilliseconds]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getZoomLevel() => (super.noSuchMethod( + Invocation.method(#getZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future showInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#showInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future showInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#showInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future hideInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#hideInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future hideInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#hideInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future isInfoWindowShown(String? markerId) => - (super.noSuchMethod( - Invocation.method(#isInfoWindowShown, [markerId]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isInfoWindowShown(String? markerId) => (super.noSuchMethod( + Invocation.method(#isInfoWindowShown, [markerId]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future setStyle(String? style) => - (super.noSuchMethod( - Invocation.method(#setStyle, [style]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setStyle(String? style) => (super.noSuchMethod( + Invocation.method(#setStyle, [style]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getLastStyleError() => - (super.noSuchMethod( - Invocation.method(#getLastStyleError, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getLastStyleError() => (super.noSuchMethod( + Invocation.method(#getLastStyleError, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future clearTileCache(String? tileOverlayId) => - (super.noSuchMethod( - Invocation.method(#clearTileCache, [tileOverlayId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future clearTileCache(String? tileOverlayId) => (super.noSuchMethod( + Invocation.method(#clearTileCache, [tileOverlayId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i5.Uint8List?> takeSnapshot() => - (super.noSuchMethod( - Invocation.method(#takeSnapshot, []), - returnValue: _i4.Future<_i5.Uint8List?>.value(), - returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), - ) - as _i4.Future<_i5.Uint8List?>); + _i4.Future<_i5.Uint8List?> takeSnapshot() => (super.noSuchMethod( + Invocation.method(#takeSnapshot, []), + returnValue: _i4.Future<_i5.Uint8List?>.value(), + returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), + ) as _i4.Future<_i5.Uint8List?>); @override - _i4.Future isAdvancedMarkersAvailable() => - (super.noSuchMethod( - Invocation.method(#isAdvancedMarkersAvailable, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isAdvancedMarkersAvailable() => (super.noSuchMethod( + Invocation.method(#isAdvancedMarkersAvailable, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/run_tests.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/run_tests.dart index f49c29eaf7fe..af88ecc57b9c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/run_tests.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/run_tests.dart @@ -25,9 +25,7 @@ Future main(List args) async { exit(0); } - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); final sharedSourceRoot = Directory( p.join(packageRoot.parent.path, 'google_maps_flutter_ios_shared_code'), @@ -129,16 +127,11 @@ Future _validatePackageSharedCode( required bool log, }) async { var hasDiffs = false; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/sync_shared_files.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/sync_shared_files.dart index fbbd50d0a499..8711068a5604 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/sync_shared_files.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/sync_shared_files.dart @@ -18,23 +18,15 @@ import 'utils.dart'; const String _sharedSourceRootName = 'google_maps_flutter_ios_shared_code'; Future main(List args) async { - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); - final sharedSourceRoot = Directory( - p.join(packageRoot.parent.path, _sharedSourceRootName), - ); + final sharedSourceRoot = Directory(p.join(packageRoot.parent.path, _sharedSourceRootName)); _syncSharedFiles(packageRoot, packageName, sharedSourceRoot); _reportUnsharedFiles(packageRoot, packageName, sharedSourceRoot); } -void _syncSharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _syncSharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List otherImplementationPackages = sharedSourceRoot.parent .listSync() .whereType() @@ -49,16 +41,11 @@ void _syncSharedFiles( final copiedFiles = []; final missingFiles = []; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { @@ -88,10 +75,7 @@ void _syncSharedFiles( final String otherPackagePath = p.join( packageRoot.parent.path, otherPackageName, - packageRelativePathForSharedSourceRelativePath( - otherPackageName, - relativePath, - ), + packageRelativePathForSharedSourceRelativePath(otherPackageName, relativePath), ); _syncFile(packageFile, otherPackagePath, otherPackageName); } @@ -105,9 +89,7 @@ void _syncSharedFiles( } } if (missingFiles.isNotEmpty) { - print( - 'This package is missing the following files from the shared source:', - ); + print('This package is missing the following files from the shared source:'); for (final file in missingFiles) { print(' $file'); } @@ -123,11 +105,7 @@ void _syncSharedFiles( /// If the file needs special handling of package names that appear within the /// contents of the file, it will update the package name in the file to match /// the destination package name. -void _syncFile( - File source, - String destinationPath, - String destinationPackageName, -) { +void _syncFile(File source, String destinationPath, String destinationPackageName) { source.copySync(destinationPath); if ([ // The Pigeon definition file has output paths that must use the @@ -136,10 +114,7 @@ void _syncFile( // The mock needs to import the package. '.mocks.dart', ].any((pattern) => source.absolute.path.contains(pattern))) { - updatePackageNameInPathReferences( - File(destinationPath), - destinationPackageName, - ); + updatePackageNameInPathReferences(File(destinationPath), destinationPackageName); } // Native unit tests need to import the Swift package. if (source.absolute.path.contains('/RunnerTests/')) { @@ -147,11 +122,7 @@ void _syncFile( } } -void _reportUnsharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _reportUnsharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List unsharedFiles = unexpectedUnsharedSourceFiles( packageRoot, packageName, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/utils.dart b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/utils.dart index c4b2b9b83433..fc75925d7304 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/utils.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_sdk9/tool/utils.dart @@ -21,10 +21,7 @@ List unexpectedUnsharedSourceFiles( .listSync(recursive: true) .whereType() // Only report code files. - .where( - (file) => - ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith), - ) + .where((file) => ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith)) // Flutter-generated files aren't expected to be shared. .where((file) => !file.path.contains('GeneratedPluginRegistrant')) // Ignore intermediate file directories. @@ -64,10 +61,7 @@ String packageRelativePathForSharedSourceRelativePath( String packageName, String sharedSourceRelativePath, ) { - return sharedSourceRelativePath.replaceAll( - '/google_maps_flutter_ios/', - '/$packageName/', - ); + return sharedSourceRelativePath.replaceAll('/google_maps_flutter_ios/', '/$packageName/'); } /// Returns the contents of the file with any differences caused only by the @@ -76,10 +70,7 @@ String normalizedFileContents(File file) { return file .readAsStringSync() // Ignore differences caused only by the package name. - .replaceAll( - RegExp(r'google_maps_flutter_ios_[\w\d]+'), - 'google_maps_flutter_ios', - ) + .replaceAll(RegExp(r'google_maps_flutter_ios_[\w\d]+'), 'google_maps_flutter_ios') // Package name diffs could change line wrapping, so collapse whitespace. .replaceAll(RegExp(r'[\s\n]+'), ' ') .trim(); @@ -106,10 +97,7 @@ void updatePackageNameInPathReferences(File file, String packageName) { /// package by name. void updatePackageNameInImports(File file, String packageName) { final String newContents = file.readAsStringSync().replaceAllMapped( - RegExp( - r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', - multiLine: true, - ), + RegExp(r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', multiLine: true), (match) => '${match.group(1)}import $packageName${match.group(2)}', ); file.writeAsStringSync(newContents); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/integration_test/google_maps_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/integration_test/google_maps_test.dart index f1c15e56e975..86260596009a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/integration_test/google_maps_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/integration_test/google_maps_test.dart @@ -41,8 +41,9 @@ final LatLngBounds _testCameraBounds = LatLngBounds( northeast: const LatLng(50, -65), southwest: const LatLng(28.5, -123), ); -final ValueVariant _cameraUpdateTypeVariants = - ValueVariant(CameraUpdateType.values.toSet()); +final ValueVariant _cameraUpdateTypeVariants = ValueVariant( + CameraUpdateType.values.toSet(), +); void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -66,8 +67,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool compassEnabled = await inspector.isCompassEnabled(mapId: mapId); expect(compassEnabled, false); @@ -106,11 +106,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool mapToolbarEnabled = await inspector.isMapToolbarEnabled(mapId: mapId); // This is only supported on Android, so should always return false. expect(mapToolbarEnabled, false); }); @@ -136,14 +133,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final ExampleGoogleMapController controller = await controllerCompleter.future; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; - MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( - mapId: controller.mapId, - ); + MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels(mapId: controller.mapId); expect(zoomLevel, equals(initialZoomLevel)); await tester.pumpWidget( @@ -183,11 +176,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled(mapId: mapId); expect(zoomGesturesEnabled, false); await tester.pumpWidget( @@ -225,11 +215,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); /// Zoom Controls functionality is not available on iOS at the moment. expect(zoomControlsEnabled, false); @@ -254,11 +241,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, false); await tester.pumpWidget( @@ -274,9 +258,7 @@ void main() { ), ); - rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, true); }); @@ -299,11 +281,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled(mapId: mapId); expect(tiltGesturesEnabled, false); await tester.pumpWidget( @@ -342,11 +321,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, false); await tester.pumpWidget( @@ -362,9 +338,7 @@ void main() { ), ); - scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, true); }); @@ -387,8 +361,7 @@ void main() { ), ), ); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; await tester.pumpAndSettle(); @@ -397,8 +370,9 @@ void main() { // https://github.com/flutter/flutter/issues/54758 await Future.delayed(const Duration(seconds: 1)); - final ScreenCoordinate coordinate = await mapController - .getScreenCoordinate(_kInitialCameraPosition.target); + final ScreenCoordinate coordinate = await mapController.getScreenCoordinate( + _kInitialCameraPosition.target, + ); final Rect rect = tester.getRect(find.byKey(key)); expect(coordinate.x, (rect.center.dx - rect.topLeft.dx).round()); expect(coordinate.y, (rect.center.dy - rect.topLeft.dy).round()); @@ -434,11 +408,9 @@ void main() { ); await tester.pumpAndSettle(); - final ExampleGoogleMapController mapController = - await mapControllerCompleter.future; + final ExampleGoogleMapController mapController = await mapControllerCompleter.future; - final LatLngBounds firstVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds firstVisibleRegion = await mapController.getVisibleRegion(); expect(firstVisibleRegion, isNotNull); expect(firstVisibleRegion.southwest, isNotNull); @@ -464,21 +436,15 @@ void main() { expect(firstVisibleRegion.contains(northEast), isFalse); expect(firstVisibleRegion.contains(southWest), isFalse); - final latLngBounds = LatLngBounds( - southwest: southWest, - northeast: northEast, - ); + final latLngBounds = LatLngBounds(southwest: southWest, northeast: northEast); // TODO(iskakaushik): non-zero padding is needed for some device configurations // https://github.com/flutter/flutter/issues/30575 const double padding = 0; - await mapController.moveCamera( - CameraUpdate.newLatLngBounds(latLngBounds, padding), - ); + await mapController.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController.getVisibleRegion(); expect(secondVisibleRegion, isNotNull); expect(secondVisibleRegion.southwest, isNotNull); @@ -511,8 +477,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; bool isTrafficEnabled = await inspector.isTrafficEnabled(mapId: mapId); expect(isTrafficEnabled, true); @@ -551,11 +516,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool isBuildingsEnabled = await inspector.areBuildingsEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool isBuildingsEnabled = await inspector.areBuildingsEnabled(mapId: mapId); expect(isBuildingsEnabled, true); }); @@ -577,11 +539,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); await tester.pumpWidget( @@ -598,15 +557,11 @@ void main() { ), ); - myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value false', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value false', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -625,16 +580,12 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value true', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value true', (WidgetTester tester) async { final Key key = GlobalKey(); final mapIdCompleter = Completer(); @@ -652,10 +603,8 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); }); @@ -676,19 +625,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - const mapStyle = - '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - mapStyle, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + const mapStyle = '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; + await GoogleMapsFlutterPlatform.instance.setMapStyle(mapStyle, mapId: controller.mapId); }); - testWidgets('testSetMapStyle invalid Json String', ( - WidgetTester tester, - ) async { + testWidgets('testSetMapStyle invalid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -705,8 +647,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; try { await GoogleMapsFlutterPlatform.instance.setMapStyle( @@ -737,12 +678,8 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; - await GoogleMapsFlutterPlatform.instance.setMapStyle( - null, - mapId: controller.mapId, - ); + final ExampleGoogleMapController controller = await controllerCompleter.future; + await GoogleMapsFlutterPlatform.instance.setMapStyle(null, mapId: controller.mapId); }); testWidgets('testGetLatLng', (WidgetTester tester) async { @@ -762,8 +699,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -772,13 +708,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng topLeft = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); + final LatLng topLeft = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); expect(topLeft, northWest); }); @@ -802,8 +733,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -841,8 +771,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and `mapControllerCompleter.complete(controller)` above should happen @@ -851,13 +780,8 @@ void main() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); - final ScreenCoordinate topLeft = await controller.getScreenCoordinate( - northWest, - ); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); + final ScreenCoordinate topLeft = await controller.getScreenCoordinate(northWest); expect(topLeft, const ScreenCoordinate(x: 0, y: 0)); }, // TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825 @@ -880,8 +804,7 @@ void main() { ), ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpWidget( Directionality( @@ -917,9 +840,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController googleMapController) { controllerCompleter.complete(googleMapController); @@ -928,12 +849,9 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, false); await controller.showMarkerInfoWindow(marker.markerId); @@ -945,9 +863,7 @@ void main() { expect(iwVisibleStatus, false); }); - testWidgets('updating a marker does not hide its info window', ( - WidgetTester tester, - ) async { + testWidgets('updating a marker does not hide its info window', (WidgetTester tester) async { final Key key = GlobalKey(); const marker = Marker( markerId: MarkerId('marker'), @@ -955,9 +871,7 @@ void main() { ); var markers = {marker}; - const clusterManager = ClusterManager( - clusterManagerId: ClusterManagerId('cluster_manager'), - ); + const clusterManager = ClusterManager(clusterManagerId: ClusterManagerId('cluster_manager')); final clusterManagers = {clusterManager}; final controllerCompleter = Completer(); @@ -967,9 +881,7 @@ void main() { textDirection: TextDirection.ltr, child: ExampleGoogleMap( key: key, - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, clusterManagers: clusterManagers, onMapCreated: (ExampleGoogleMapController googleMapController) { @@ -979,13 +891,10 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await controller.showMarkerInfoWindow(marker.markerId); - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, true); // Update marker and ensure the info window remains visible when added to a @@ -1031,8 +940,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final Uint8List? bytes = await controller.takeSnapshot(); expect(bytes?.isNotEmpty, true); }, @@ -1072,8 +980,7 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final TileOverlay tileOverlayInfo1 = (await inspector.getTileOverlayInfo( tileOverlay1.mapsId, @@ -1086,18 +993,12 @@ void main() { expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.2, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); - expect( - tileOverlayInfo2.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }); @@ -1132,8 +1033,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final tileOverlay1New = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), @@ -1171,10 +1071,7 @@ void main() { expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); @@ -1205,8 +1102,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1249,10 +1145,7 @@ void main() { final marker = Marker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1260,8 +1153,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1278,8 +1170,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1296,8 +1187,7 @@ void main() { final MarkerId markerIdToMove = markers.entries .firstWhere( (MapEntry entry) => - entry.value.clusterManagerId == - clusterManagers.first.clusterManagerId, + entry.value.clusterManagerId == clusterManagers.first.clusterManagerId, ) .key; markers[markerIdToMove] = _copyMarkerWithClusterManagerId( @@ -1385,10 +1275,7 @@ void main() { final marker = AdvancedMarker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - _kInitialMapCenter.latitude + i, - _kInitialMapCenter.longitude, - ), + position: LatLng(_kInitialMapCenter.latitude + i, _kInitialMapCenter.longitude), ); markers[markerId] = marker; } @@ -1396,8 +1283,7 @@ void main() { final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1415,8 +1301,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( @@ -1431,10 +1316,7 @@ void main() { // Remove markers from clusterManagers and test that clusterManagers are empty. for (final MapEntry entry in markers.entries) { - markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId( - entry.value, - null, - ); + markers[entry.key] = _copyAdvancedMarkerWithClusterManagerId(entry.value, null); } await tester.pumpWidget( Directionality( @@ -1490,15 +1372,12 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNotNull); }); - testWidgets('getStyleError returns null for a valid style', ( - WidgetTester tester, - ) async { + testWidgets('getStyleError returns null for a valid style', (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); @@ -1517,8 +1396,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; final String? error = await controller.getStyleError(); expect(error, isNull); }); @@ -1534,9 +1412,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1546,25 +1422,18 @@ void main() { }); testWidgets('markerWithAssetMapBitmapCreate', (WidgetTester tester) async { - final imageConfiguration = ImageConfiguration( - devicePixelRatio: tester.view.devicePixelRatio, - ); + final imageConfiguration = ImageConfiguration(devicePixelRatio: tester.view.devicePixelRatio); final markers = { Marker( markerId: const MarkerId('1'), - icon: await AssetMapBitmap.create( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await AssetMapBitmap.create(imageConfiguration, 'assets/red_square.png'), ), }; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1578,10 +1447,7 @@ void main() { final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; @@ -1589,9 +1455,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, ), ), @@ -1602,19 +1466,13 @@ void main() { testWidgets('markerWithLegacyAsset', (WidgetTester tester) async { //tester.view.devicePixelRatio = 2.0; - const imageConfiguration = ImageConfiguration( - devicePixelRatio: 2.0, - size: Size(100, 100), - ); + const imageConfiguration = ImageConfiguration(devicePixelRatio: 2.0, size: Size(100, 100)); final markers = { Marker( markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. // ignore: deprecated_member_use - icon: await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await BitmapDescriptor.fromAssetImage(imageConfiguration, 'assets/red_square.png'), ), }; final controllerCompleter = Completer(); @@ -1622,9 +1480,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1648,9 +1504,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 15.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), markers: markers, onMapCreated: (ExampleGoogleMapController controller) => controllerCompleter.complete(controller), @@ -1690,19 +1544,13 @@ void main() { ), ); - void expectGroundOverlayEquals( - GroundOverlay source, - GroundOverlay response, - ) { + void expectGroundOverlayEquals(GroundOverlay source, GroundOverlay response) { expect(response.groundOverlayId, source.groundOverlayId); expect( response.transparency, moreOrLessEquals(source.transparency, epsilon: _floatTolerance), ); - expect( - response.bearing, - moreOrLessEquals(source.bearing, epsilon: _floatTolerance), - ); + expect(response.bearing, moreOrLessEquals(source.bearing, epsilon: _floatTolerance)); // Only test bounds if it was given in the original object if (source.bounds != null) { @@ -1717,14 +1565,8 @@ void main() { expect(response.clickable, source.clickable); expect(response.zIndex, source.zIndex); expect(response.zoomLevel, source.zoomLevel); - expect( - response.anchor?.dx, - moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance), - ); - expect( - response.anchor?.dy, - moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance), - ); + expect(response.anchor?.dx, moreOrLessEquals(source.anchor!.dx, epsilon: _floatTolerance)); + expect(response.anchor?.dy, moreOrLessEquals(source.anchor!.dy, epsilon: _floatTolerance)); } testWidgets('set ground overlays correctly', (WidgetTester tester) async { @@ -1754,38 +1596,29 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBoundsInfo1 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayBoundsInfo2 = (await inspector - .getGroundOverlayInfo(groundOverlayBounds2.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPositionInfo1 = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1, - groundOverlayBoundsInfo1, - ); - expectGroundOverlayEquals( - groundOverlayBounds2, - groundOverlayBoundsInfo2, - ); - expectGroundOverlayEquals( - groundOverlayPosition1, - groundOverlayPositionInfo1, - ); + final GroundOverlay groundOverlayBoundsInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayBoundsInfo2 = (await inspector.getGroundOverlayInfo( + groundOverlayBounds2.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPositionInfo1 = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1, groundOverlayBoundsInfo1); + expectGroundOverlayEquals(groundOverlayBounds2, groundOverlayBoundsInfo2); + expectGroundOverlayEquals(groundOverlayPosition1, groundOverlayPositionInfo1); } }); - testWidgets('update ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('update ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1795,10 +1628,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1807,26 +1637,23 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; - - final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); - - final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1 - .copyWith( - bearingParam: 10, - clickableParam: false, - transparencyParam: 0.5, - visibleParam: false, - zIndexParam: 10, - ); + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; + + final GroundOverlay groundOverlayBounds1New = groundOverlayBounds1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); + + final GroundOverlay groundOverlayPosition1New = groundOverlayPosition1.copyWith( + bearingParam: 10, + clickableParam: false, + transparencyParam: 0.5, + visibleParam: false, + zIndexParam: 10, + ); await tester.pumpWidget( Directionality( @@ -1834,10 +1661,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1New, - groundOverlayPosition1New, - }, + groundOverlays: {groundOverlayBounds1New, groundOverlayPosition1New}, onMapCreated: (ExampleGoogleMapController controller) { fail('update: OnMapCreated should get called only once.'); }, @@ -1848,28 +1672,21 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay groundOverlayBounds1Info = (await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId))!; - final GroundOverlay groundOverlayPosition1Info = (await inspector - .getGroundOverlayInfo( - groundOverlayPosition1.mapsId, - mapId: mapId, - ))!; - - expectGroundOverlayEquals( - groundOverlayBounds1New, - groundOverlayBounds1Info, - ); - expectGroundOverlayEquals( - groundOverlayPosition1New, - groundOverlayPosition1Info, - ); + final GroundOverlay groundOverlayBounds1Info = (await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ))!; + final GroundOverlay groundOverlayPosition1Info = (await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ))!; + + expectGroundOverlayEquals(groundOverlayBounds1New, groundOverlayBounds1Info); + expectGroundOverlayEquals(groundOverlayPosition1New, groundOverlayPosition1Info); } }); - testWidgets('remove ground overlays correctly', ( - WidgetTester tester, - ) async { + testWidgets('remove ground overlays correctly', (WidgetTester tester) async { final mapIdCompleter = Completer(); final Key key = GlobalKey(); @@ -1879,10 +1696,7 @@ void main() { child: ExampleGoogleMap( key: key, initialCameraPosition: _kInitialCameraPosition, - groundOverlays: { - groundOverlayBounds1, - groundOverlayPosition1, - }, + groundOverlays: {groundOverlayBounds1, groundOverlayPosition1}, onMapCreated: (ExampleGoogleMapController controller) { mapIdCompleter.complete(controller.mapId); }, @@ -1891,8 +1705,7 @@ void main() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -1910,10 +1723,14 @@ void main() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingGroundOverlayInfo()) { - final GroundOverlay? groundOverlayBounds1Info = await inspector - .getGroundOverlayInfo(groundOverlayBounds1.mapsId, mapId: mapId); - final GroundOverlay? groundOverlayPositionInfo = await inspector - .getGroundOverlayInfo(groundOverlayPosition1.mapsId, mapId: mapId); + final GroundOverlay? groundOverlayBounds1Info = await inspector.getGroundOverlayInfo( + groundOverlayBounds1.mapsId, + mapId: mapId, + ); + final GroundOverlay? groundOverlayPositionInfo = await inspector.getGroundOverlayInfo( + groundOverlayPosition1.mapsId, + mapId: mapId, + ); expect(groundOverlayBounds1Info, isNull); expect(groundOverlayPositionInfo, isNull); @@ -1926,8 +1743,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -1939,8 +1755,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { cameraIdleCompleter.complete(); } }, @@ -1951,8 +1766,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -1972,8 +1786,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -1988,8 +1803,9 @@ void main() { await cameraIdleCompleter.future; // After onCameraIdle event, the camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2019,8 +1835,7 @@ void main() { (WidgetTester tester) async { final Key key = GlobalKey(); final controllerCompleter = Completer(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; /// Completer to track when the camera has come to rest. Completer? cameraIdleCompleter; @@ -2044,8 +1859,7 @@ void main() { key: key, initialCameraPosition: _kInitialCameraPosition, onCameraIdle: () { - if (cameraIdleCompleter != null && - !cameraIdleCompleter.isCompleted) { + if (cameraIdleCompleter != null && !cameraIdleCompleter.isCompleted) { stopwatch.stop(); cameraIdleCompleter.complete(); } @@ -2057,8 +1871,7 @@ void main() { ), ); - final ExampleGoogleMapController controller = - await controllerCompleter.future; + final ExampleGoogleMapController controller = await controllerCompleter.future; await tester.pumpAndSettle(); // TODO(cyanglaz): Remove this after we added `mapRendered` callback, and @@ -2090,15 +1903,10 @@ void main() { // For short animation duration, check that the animation is completed // faster than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - lessThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, lessThan(animationDurationMiddlePoint)); // Reset camera to initial position before testing long duration. - await controller.moveCamera( - CameraUpdate.newCameraPosition(_kInitialCameraPosition), - ); + await controller.moveCamera(CameraUpdate.newCameraPosition(_kInitialCameraPosition)); await tester.pumpAndSettle(); // Create completer for camera idle event. @@ -2121,8 +1929,9 @@ void main() { // Immediately after calling animateCamera, check that the camera hasn't // reached its final position. This relies on the assumption that the // camera move is animated and won't complete instantly. - final CameraPosition beforeFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition beforeFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, @@ -2138,14 +1947,12 @@ void main() { // For longer animation duration, check that the animation is completed // slower than the midpoint benchmark. - expect( - stopwatch.elapsedMilliseconds, - greaterThan(animationDurationMiddlePoint), - ); + expect(stopwatch.elapsedMilliseconds, greaterThan(animationDurationMiddlePoint)); // Camera should be at the final position. - final CameraPosition afterFinishedPosition = await inspector - .getCameraPosition(mapId: controller.mapId); + final CameraPosition afterFinishedPosition = await inspector.getCameraPosition( + mapId: controller.mapId, + ); await _checkCameraUpdateByType( _cameraUpdateTypeVariants.currentValue!, afterFinishedPosition, @@ -2179,9 +1986,7 @@ void main() { Directionality( textDirection: ui.TextDirection.ltr, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: LatLng(10.0, 20.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(10.0, 20.0)), markers: markers, markerType: MarkerType.advancedMarker, onMapCreated: (ExampleGoogleMapController controller) => @@ -2212,31 +2017,20 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, @@ -2286,23 +2080,15 @@ AdvancedMarker _copyAdvancedMarkerWithClusterManagerId( CameraUpdate _getCameraUpdateForType(CameraUpdateType type) { return switch (type) { - CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition( - _kTestCameraPosition, - ), + CameraUpdateType.newCameraPosition => CameraUpdate.newCameraPosition(_kTestCameraPosition), CameraUpdateType.newLatLng => CameraUpdate.newLatLng(_kTestMapCenter), - CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds( - _testCameraBounds, - 0, - ), + CameraUpdateType.newLatLngBounds => CameraUpdate.newLatLngBounds(_testCameraBounds, 0), CameraUpdateType.newLatLngZoom => CameraUpdate.newLatLngZoom( _kTestMapCenter, _kTestCameraZoomLevel, ), CameraUpdateType.scrollBy => CameraUpdate.scrollBy(10, 10), - CameraUpdateType.zoomBy => CameraUpdate.zoomBy( - _kTestZoomByAmount, - const Offset(1, 1), - ), + CameraUpdateType.zoomBy => CameraUpdate.zoomBy(_kTestZoomByAmount, const Offset(1, 1)), CameraUpdateType.zoomTo => CameraUpdate.zoomTo(_kTestCameraZoomLevel), CameraUpdateType.zoomIn => CameraUpdate.zoomIn(), CameraUpdateType.zoomOut => CameraUpdate.zoomOut(), @@ -2322,29 +2108,16 @@ Future _checkCameraUpdateByType( switch (type) { case CameraUpdateType.newCameraPosition: - expect( - currentPosition.bearing, - wrapMatcher(equals(_kTestCameraPosition.bearing)), - ); - expect( - currentPosition.zoom, - wrapMatcher(equals(_kTestCameraPosition.zoom)), - ); - expect( - currentPosition.tilt, - wrapMatcher(equals(_kTestCameraPosition.tilt)), - ); + expect(currentPosition.bearing, wrapMatcher(equals(_kTestCameraPosition.bearing))); + expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraPosition.zoom))); + expect(currentPosition.tilt, wrapMatcher(equals(_kTestCameraPosition.tilt))); expect( currentPosition.target.latitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.latitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.latitude, latLngThreshold)), ); expect( currentPosition.target.longitude, - wrapMatcher( - closeTo(_kTestCameraPosition.target.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_kTestCameraPosition.target.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLng: expect( @@ -2359,15 +2132,11 @@ Future _checkCameraUpdateByType( final LatLngBounds bounds = await controller.getVisibleRegion(); expect( bounds.northeast.longitude, - wrapMatcher( - closeTo(_testCameraBounds.northeast.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.northeast.longitude, latLngThreshold)), ); expect( bounds.southwest.longitude, - wrapMatcher( - closeTo(_testCameraBounds.southwest.longitude, latLngThreshold), - ), + wrapMatcher(closeTo(_testCameraBounds.southwest.longitude, latLngThreshold)), ); case CameraUpdateType.newLatLngZoom: expect( @@ -2382,20 +2151,11 @@ Future _checkCameraUpdateByType( case CameraUpdateType.scrollBy: // For scrollBy, just check that the location has changed. if (oldPosition != null) { - expect( - currentPosition.target.latitude, - isNot(equals(oldPosition.target.latitude)), - ); - expect( - currentPosition.target.longitude, - isNot(equals(oldPosition.target.longitude)), - ); + expect(currentPosition.target.latitude, isNot(equals(oldPosition.target.latitude))); + expect(currentPosition.target.longitude, isNot(equals(oldPosition.target.longitude))); } case CameraUpdateType.zoomBy: - expect( - currentPosition.zoom, - wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount)), - ); + expect(currentPosition.zoom, wrapMatcher(equals(_kInitialZoomLevel + _kTestZoomByAmount))); case CameraUpdateType.zoomTo: expect(currentPosition.zoom, wrapMatcher(equals(_kTestCameraZoomLevel))); case CameraUpdateType.zoomIn: diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_marker_icons.dart index 5069f3f900af..ff45dd833cef 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_marker_icons.dart @@ -33,8 +33,7 @@ class _AdvancedMarkerIconsBody extends StatefulWidget { final String? mapId; @override - State<_AdvancedMarkerIconsBody> createState() => - _AdvancedMarkerIconsBodyState(); + State<_AdvancedMarkerIconsBody> createState() => _AdvancedMarkerIconsBodyState(); } class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { @@ -51,10 +50,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: (ExampleGoogleMapController controller) { setState(() { @@ -73,29 +69,22 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { const ImageConfiguration(size: Size(12, 12)), 'assets/red_square.png', ); - final AssetMapBitmap largeAsset = - await BitmapDescriptor.asset( - const ImageConfiguration(size: Size(36, 36)), - 'assets/red_square.png', - ); + final AssetMapBitmap largeAsset = await BitmapDescriptor.asset( + const ImageConfiguration(size: Size(36, 36)), + 'assets/red_square.png', + ); setState(() { _markers.addAll([ // Default icon AdvancedMarker( markerId: const MarkerId('1'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude + 1), ), // Custom pin colors AdvancedMarker( markerId: const MarkerId('2'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.black, @@ -105,26 +94,17 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Pin with text AdvancedMarker( markerId: const MarkerId('3'), - position: LatLng( - _kMapCenter.latitude - 1, - _kMapCenter.longitude + 1, - ), + position: LatLng(_kMapCenter.latitude - 1, _kMapCenter.longitude + 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.blue, backgroundColor: Colors.white, - glyph: const TextGlyph( - text: 'Hi!', - textColor: Colors.blue, - ), + glyph: const TextGlyph(text: 'Hi!', textColor: Colors.blue), ), ), // Pin with bitmap AdvancedMarker( markerId: const MarkerId('4'), - position: LatLng( - _kMapCenter.latitude + 1, - _kMapCenter.longitude - 1, - ), + position: LatLng(_kMapCenter.latitude + 1, _kMapCenter.longitude - 1), icon: BitmapDescriptor.pinConfig( borderColor: Colors.red, backgroundColor: Colors.white, @@ -134,10 +114,7 @@ class _AdvancedMarkerIconsBodyState extends State<_AdvancedMarkerIconsBody> { // Custom marker icon AdvancedMarker( markerId: const MarkerId('5'), - position: LatLng( - _kMapCenter.latitude, - _kMapCenter.longitude, - ), + position: LatLng(_kMapCenter.latitude, _kMapCenter.longitude), icon: largeAsset, ), ]); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_markers_clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_markers_clustering.dart index 1787e9077a50..985566ee454f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_markers_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/advanced_markers_clustering.dart @@ -16,10 +16,7 @@ import 'page.dart'; class AdvancedMarkersClusteringPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkersClusteringPage({super.key, required this.mapId}) - : super( - const Icon(Icons.place_outlined), - 'Manage clusters of advanced markers', - ); + : super(const Icon(Icons.place_outlined), 'Manage clusters of advanced markers'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -78,8 +75,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -107,17 +103,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; }); } @@ -159,14 +149,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -210,9 +197,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/animate_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/animate_camera.dart index 001006fb54be..d278e2c5b3b6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/animate_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class AnimateCameraPage extends GoogleMapExampleAppPage { - const AnimateCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control, animated'); + const AnimateCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control, animated'); @override Widget build(BuildContext context) { @@ -58,9 +57,7 @@ class AnimateCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -88,9 +85,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), duration: _cameraUpdateAnimationDuration, ); }, @@ -114,10 +109,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), duration: _cameraUpdateAnimationDuration, ); }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/clustering.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/clustering.dart index 18e9af8c1be8..e7ea5e7ddefc 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/clustering.dart @@ -13,8 +13,7 @@ import 'page.dart'; /// Page for demonstrating marker clustering support. class ClusteringPage extends GoogleMapExampleAppPage { /// Default Constructor. - const ClusteringPage({super.key}) - : super(const Icon(Icons.place), 'Manage clustering'); + const ClusteringPage({super.key}) : super(const Icon(Icons.place), 'Manage clustering'); @override Widget build(BuildContext context) { @@ -61,8 +60,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { ExampleGoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -95,10 +93,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = _copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = _copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -134,8 +129,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -144,14 +138,11 @@ class _ClusteringBodyState extends State<_ClusteringBody> { void _addMarkersToCluster(ClusterManager clusterManager) { for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { - final markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. @@ -190,9 +181,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); @@ -239,8 +228,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { TextButton( onPressed: clusterManagers.isEmpty ? null - : () => - _removeClusterManager(clusterManagers.values.last), + : () => _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -248,8 +236,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { Wrap( alignment: WrapAlignment.spaceEvenly, children: [ - for (final MapEntry - clusterEntry + for (final MapEntry clusterEntry in clusterManagers.entries) TextButton( onPressed: () => _addMarkersToCluster(clusterEntry.value), @@ -272,9 +259,7 @@ class _ClusteringBodyState extends State<_ClusteringBody> { child: const Text('Remove selected marker'), ), TextButton( - onPressed: markers.isEmpty - ? null - : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty ? null : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/collision_behavior.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/collision_behavior.dart index a6a8ef8aec70..f93d850a6836 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/collision_behavior.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/collision_behavior.dart @@ -15,10 +15,7 @@ import 'place_marker.dart'; class AdvancedMarkerCollisionBehaviorPage extends GoogleMapExampleAppPage { /// Default constructor. const AdvancedMarkerCollisionBehaviorPage({super.key, required this.mapId}) - : super( - const Icon(Icons.not_listed_location), - 'Advanced marker collision behavior', - ); + : super(const Icon(Icons.not_listed_location), 'Advanced marker collision behavior'); /// Map ID to use for the GoogleMap. final String? mapId; @@ -35,12 +32,10 @@ class _CollisionBehaviorPageBody extends StatefulWidget { final String? mapId; @override - State<_CollisionBehaviorPageBody> createState() => - _CollisionBehaviorPageBodyState(); + State<_CollisionBehaviorPageBody> createState() => _CollisionBehaviorPageBodyState(); } -class _CollisionBehaviorPageBodyState - extends State<_CollisionBehaviorPageBody> { +class _CollisionBehaviorPageBodyState extends State<_CollisionBehaviorPageBody> { static const LatLng center = LatLng(-33.86711, 151.1947171); static const double zoomOutLevel = 9; static const double zoomInLevel = 12; @@ -78,10 +73,7 @@ class _CollisionBehaviorPageBodyState child: ExampleGoogleMap( mapId: widget.mapId, markerType: MarkerType.advancedMarker, - initialCameraPosition: const CameraPosition( - target: center, - zoom: zoomInLevel, - ), + initialCameraPosition: const CameraPosition(target: center, zoom: zoomInLevel), markers: Set.of(markers), tiltGesturesEnabled: false, zoomGesturesEnabled: false, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/custom_marker_icon.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/custom_marker_icon.dart index 548146c6206c..3391ba1bcba2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/custom_marker_icon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/custom_marker_icon.dart @@ -20,9 +20,7 @@ Future createCustomMarkerIconImage({required Size size}) async { size.height.floor(), ); - final ByteData? bytes = await image.toByteData( - format: ui.ImageByteFormat.png, - ); + final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); return bytes!; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/example_google_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/example_google_map.dart index 2b8a8243d381..e18943a3345f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/example_google_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/example_google_map.dart @@ -47,10 +47,7 @@ class ExampleGoogleMapController { if (_googleMapState.widget.onCameraMove != null) { GoogleMapsFlutterPlatform.instance .onCameraMove(mapId: mapId) - .listen( - (CameraMoveEvent e) => - _googleMapState.widget.onCameraMove!(e.value), - ); + .listen((CameraMoveEvent e) => _googleMapState.widget.onCameraMove!(e.value)); } if (_googleMapState.widget.onCameraIdle != null) { GoogleMapsFlutterPlatform.instance @@ -62,27 +59,16 @@ class ExampleGoogleMapController { .listen((MarkerTapEvent e) => _googleMapState.onMarkerTap(e.value)); GoogleMapsFlutterPlatform.instance .onMarkerDragStart(mapId: mapId) - .listen( - (MarkerDragStartEvent e) => - _googleMapState.onMarkerDragStart(e.value, e.position), - ); + .listen((MarkerDragStartEvent e) => _googleMapState.onMarkerDragStart(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDrag(mapId: mapId) - .listen( - (MarkerDragEvent e) => - _googleMapState.onMarkerDrag(e.value, e.position), - ); + .listen((MarkerDragEvent e) => _googleMapState.onMarkerDrag(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onMarkerDragEnd(mapId: mapId) - .listen( - (MarkerDragEndEvent e) => - _googleMapState.onMarkerDragEnd(e.value, e.position), - ); + .listen((MarkerDragEndEvent e) => _googleMapState.onMarkerDragEnd(e.value, e.position)); GoogleMapsFlutterPlatform.instance .onInfoWindowTap(mapId: mapId) - .listen( - (InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value), - ); + .listen((InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value)); GoogleMapsFlutterPlatform.instance .onPolylineTap(mapId: mapId) .listen((PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value)); @@ -94,18 +80,13 @@ class ExampleGoogleMapController { .listen((CircleTapEvent e) => _googleMapState.onCircleTap(e.value)); GoogleMapsFlutterPlatform.instance .onGroundOverlayTap(mapId: mapId) - .listen( - (GroundOverlayTapEvent e) => - _googleMapState.onGroundOverlayTap(e.value), - ); + .listen((GroundOverlayTapEvent e) => _googleMapState.onGroundOverlayTap(e.value)); GoogleMapsFlutterPlatform.instance .onTap(mapId: mapId) .listen((MapTapEvent e) => _googleMapState.onTap(e.position)); GoogleMapsFlutterPlatform.instance .onLongPress(mapId: mapId) - .listen( - (MapLongPressEvent e) => _googleMapState.onLongPress(e.position), - ); + .listen((MapLongPressEvent e) => _googleMapState.onLongPress(e.position)); GoogleMapsFlutterPlatform.instance .onClusterTap(mapId: mapId) .listen((ClusterTapEvent e) => _googleMapState.onClusterTap(e.value)); @@ -113,24 +94,16 @@ class ExampleGoogleMapController { /// Updates configuration options of the map user interface. Future _updateMapConfiguration(MapConfiguration update) { - return GoogleMapsFlutterPlatform.instance.updateMapConfiguration( - update, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMapConfiguration(update, mapId: mapId); } /// Updates marker configuration. Future _updateMarkers(MarkerUpdates markerUpdates) { - return GoogleMapsFlutterPlatform.instance.updateMarkers( - markerUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateMarkers(markerUpdates, mapId: mapId); } /// Updates cluster manager configuration. - Future _updateClusterManagers( - ClusterManagerUpdates clusterManagerUpdates, - ) { + Future _updateClusterManagers(ClusterManagerUpdates clusterManagerUpdates) { return GoogleMapsFlutterPlatform.instance.updateClusterManagers( clusterManagerUpdates, mapId: mapId, @@ -138,9 +111,7 @@ class ExampleGoogleMapController { } /// Updates ground overlay configuration. - Future _updateGroundOverlays( - GroundOverlayUpdates groundOverlayUpdates, - ) { + Future _updateGroundOverlays(GroundOverlayUpdates groundOverlayUpdates) { return GoogleMapsFlutterPlatform.instance.updateGroundOverlays( groundOverlayUpdates, mapId: mapId, @@ -149,26 +120,17 @@ class ExampleGoogleMapController { /// Updates polygon configuration. Future _updatePolygons(PolygonUpdates polygonUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolygons( - polygonUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolygons(polygonUpdates, mapId: mapId); } /// Updates polyline configuration. Future _updatePolylines(PolylineUpdates polylineUpdates) { - return GoogleMapsFlutterPlatform.instance.updatePolylines( - polylineUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updatePolylines(polylineUpdates, mapId: mapId); } /// Updates circle configuration. Future _updateCircles(CircleUpdates circleUpdates) { - return GoogleMapsFlutterPlatform.instance.updateCircles( - circleUpdates, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.updateCircles(circleUpdates, mapId: mapId); } /// Updates tile overlays configuration. @@ -182,10 +144,7 @@ class ExampleGoogleMapController { /// Clears the tile cache so that all tiles will be requested again from the /// [TileProvider]. Future clearTileCache(TileOverlayId tileOverlayId) async { - return GoogleMapsFlutterPlatform.instance.clearTileCache( - tileOverlayId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.clearTileCache(tileOverlayId, mapId: mapId); } /// Starts an animated change of the map camera position. @@ -199,10 +158,7 @@ class ExampleGoogleMapController { /// Changes the map camera position. Future moveCamera(CameraUpdate cameraUpdate) { - return GoogleMapsFlutterPlatform.instance.moveCamera( - cameraUpdate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.moveCamera(cameraUpdate, mapId: mapId); } /// Return [LatLngBounds] defining the region that is visible in a map. @@ -212,42 +168,27 @@ class ExampleGoogleMapController { /// Return [ScreenCoordinate] of the [LatLng] in the current map view. Future getScreenCoordinate(LatLng latLng) { - return GoogleMapsFlutterPlatform.instance.getScreenCoordinate( - latLng, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getScreenCoordinate(latLng, mapId: mapId); } /// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view. Future getLatLng(ScreenCoordinate screenCoordinate) { - return GoogleMapsFlutterPlatform.instance.getLatLng( - screenCoordinate, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.getLatLng(screenCoordinate, mapId: mapId); } /// Programmatically show the Info Window for a [Marker]. Future showMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.showMarkerInfoWindow(markerId, mapId: mapId); } /// Programmatically hide the Info Window for a [Marker]. Future hideMarkerInfoWindow(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.hideMarkerInfoWindow(markerId, mapId: mapId); } /// Returns `true` when the [InfoWindow] is showing, `false` otherwise. Future isMarkerInfoWindowShown(MarkerId markerId) { - return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown( - markerId, - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isMarkerInfoWindowShown(markerId, mapId: mapId); } /// Returns the current zoom level of the map @@ -267,9 +208,7 @@ class ExampleGoogleMapController { /// Returns true if [AdvancedMarker]s can be used with this map. Future isAdvancedMarkersAvailable() { - return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable( - mapId: mapId, - ); + return GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: mapId); } /// Disposes of the platform resources @@ -446,17 +385,14 @@ class ExampleGoogleMap extends StatefulWidget { class _ExampleGoogleMapState extends State { final int _mapId = _nextMapCreationId++; - final Completer _controller = - Completer(); + final Completer _controller = Completer(); Map _markers = {}; Map _polygons = {}; Map _polylines = {}; Map _circles = {}; - Map _clusterManagers = - {}; - Map _groundOverlays = - {}; + Map _clusterManagers = {}; + Map _groundOverlays = {}; late MapConfiguration _mapConfiguration; @override @@ -466,9 +402,7 @@ class _ExampleGoogleMapState extends State { onPlatformViewCreated, widgetConfiguration: MapWidgetConfiguration( textDirection: - widget.layoutDirection ?? - Directionality.maybeOf(context) ?? - TextDirection.ltr, + widget.layoutDirection ?? Directionality.maybeOf(context) ?? TextDirection.ltr, initialCameraPosition: widget.initialCameraPosition, gestureRecognizers: widget.gestureRecognizers, ), @@ -498,9 +432,7 @@ class _ExampleGoogleMapState extends State { @override void dispose() { - _controller.future.then( - (ExampleGoogleMapController controller) => controller.dispose(), - ); + _controller.future.then((ExampleGoogleMapController controller) => controller.dispose()); super.dispose(); } @@ -531,9 +463,7 @@ class _ExampleGoogleMapState extends State { Future _updateMarkers() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateMarkers( - MarkerUpdates.from(_markers.values.toSet(), widget.markers), - ), + controller._updateMarkers(MarkerUpdates.from(_markers.values.toSet(), widget.markers)), ); _markers = keyByMarkerId(widget.markers); } @@ -542,10 +472,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateClusterManagers( - ClusterManagerUpdates.from( - _clusterManagers.values.toSet(), - widget.clusterManagers, - ), + ClusterManagerUpdates.from(_clusterManagers.values.toSet(), widget.clusterManagers), ), ); _clusterManagers = keyByClusterManagerId(widget.clusterManagers); @@ -555,10 +482,7 @@ class _ExampleGoogleMapState extends State { final ExampleGoogleMapController controller = await _controller.future; unawaited( controller._updateGroundOverlays( - GroundOverlayUpdates.from( - _groundOverlays.values.toSet(), - widget.groundOverlays, - ), + GroundOverlayUpdates.from(_groundOverlays.values.toSet(), widget.groundOverlays), ), ); _groundOverlays = keyByGroundOverlayId(widget.groundOverlays); @@ -567,9 +491,7 @@ class _ExampleGoogleMapState extends State { Future _updatePolygons() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updatePolygons( - PolygonUpdates.from(_polygons.values.toSet(), widget.polygons), - ), + controller._updatePolygons(PolygonUpdates.from(_polygons.values.toSet(), widget.polygons)), ); _polygons = keyByPolygonId(widget.polygons); } @@ -587,9 +509,7 @@ class _ExampleGoogleMapState extends State { Future _updateCircles() async { final ExampleGoogleMapController controller = await _controller.future; unawaited( - controller._updateCircles( - CircleUpdates.from(_circles.values.toSet(), widget.circles), - ), + controller._updateCircles(CircleUpdates.from(_circles.values.toSet(), widget.circles)), ); _circles = keyByCircleId(widget.circles); } @@ -600,12 +520,11 @@ class _ExampleGoogleMapState extends State { } Future onPlatformViewCreated(int id) async { - final ExampleGoogleMapController controller = - await ExampleGoogleMapController._init( - id, - widget.initialCameraPosition, - this, - ); + final ExampleGoogleMapController controller = await ExampleGoogleMapController._init( + id, + widget.initialCameraPosition, + this, + ); _controller.complete(controller); unawaited(_updateTileOverlays()); widget.onMapCreated?.call(controller); @@ -656,8 +575,7 @@ class _ExampleGoogleMapState extends State { } void onClusterTap(Cluster cluster) { - final ClusterManager? clusterManager = - _clusterManagers[cluster.clusterManagerId]; + final ClusterManager? clusterManager = _clusterManagers[cluster.clusterManagerId]; clusterManager?.onClusterTap?.call(cluster); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/ground_overlay.dart index 00a7d8126539..878f5c9200a2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/ground_overlay.dart @@ -13,8 +13,7 @@ import 'page.dart'; enum _GroundOverlayPlacing { position, bounds } class GroundOverlayPage extends GoogleMapExampleAppPage { - const GroundOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Ground overlay'); + const GroundOverlayPage({super.key}) : super(const Icon(Icons.map), 'Ground overlay'); @override Widget build(BuildContext context) { @@ -132,9 +131,7 @@ class GroundOverlayBodyState extends State { // Adjusts the bearing by 10 degrees, wrapping around at 360 degrees. // 10 is the increment, 350 degrees of the full circle -10. _groundOverlay = _groundOverlay!.copyWith( - bearingParam: _groundOverlay!.bearing >= 350 - ? 0 - : _groundOverlay!.bearing + 10, + bearingParam: _groundOverlay!.bearing >= 350 ? 0 : _groundOverlay!.bearing + 10, ); }); } @@ -143,9 +140,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); setState(() { final transparency = _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; - _groundOverlay = _groundOverlay!.copyWith( - transparencyParam: transparency, - ); + _groundOverlay = _groundOverlay!.copyWith(transparencyParam: transparency); }); } @@ -167,8 +162,7 @@ class GroundOverlayBodyState extends State { assert(_groundOverlay != null); assert(_placingType == _GroundOverlayPlacing.bounds); setState(() { - _currentGroundOverlayBounds = - _currentGroundOverlayBounds == _groundOverlayBounds1 + _currentGroundOverlayBounds = _currentGroundOverlayBounds == _groundOverlayBounds1 ? _groundOverlayBounds2 : _groundOverlayBounds1; }); @@ -181,9 +175,7 @@ class GroundOverlayBodyState extends State { void _toggleVisible() { assert(_groundOverlay != null); setState(() { - _groundOverlay = _groundOverlay!.copyWith( - visibleParam: !_groundOverlay!.visible, - ); + _groundOverlay = _groundOverlay!.copyWith(visibleParam: !_groundOverlay!.visible); }); } @@ -223,9 +215,7 @@ class GroundOverlayBodyState extends State { @override Widget build(BuildContext context) { - final overlays = { - if (_groundOverlay != null) _groundOverlay!, - }; + final overlays = {if (_groundOverlay != null) _groundOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -233,10 +223,7 @@ class GroundOverlayBodyState extends State { children: [ Expanded( child: ExampleGoogleMap( - initialCameraPosition: CameraPosition( - target: _mapCenter, - zoom: 14.0, - ), + initialCameraPosition: CameraPosition(target: _mapCenter, zoom: 14.0), groundOverlays: overlays, onMapCreated: _onMapCreated, ), @@ -258,9 +245,7 @@ class GroundOverlayBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: _groundOverlay == null - ? null - : () => _changeTransparency(), + onPressed: _groundOverlay == null ? null : () => _changeTransparency(), child: const Text('change transparency'), ), TextButton( @@ -282,23 +267,17 @@ class GroundOverlayBodyState extends State { TextButton( onPressed: _groundOverlay == null ? null : () => _changeType(), child: Text( - _placingType == _GroundOverlayPlacing.position - ? 'use bounds' - : 'use position', + _placingType == _GroundOverlayPlacing.position ? 'use bounds' : 'use position', ), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.position || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.position || _groundOverlay == null ? null : () => _changePosition(), child: const Text('change position'), ), TextButton( - onPressed: - _placingType != _GroundOverlayPlacing.bounds || - _groundOverlay == null + onPressed: _placingType != _GroundOverlayPlacing.bounds || _groundOverlay == null ? null : () => _changeBounds(), child: const Text('change bounds'), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_click.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_click.dart index a786197d5205..49ecd2656bab 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_click.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_click.dart @@ -58,42 +58,25 @@ class _MapClickBodyState extends State<_MapClickBody> { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; if (mapController != null) { final lastTap = 'Tap:\n${_lastTap ?? ""}\n'; final lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; + columnChildren.add(Center(child: Text(lastTap, textAlign: TextAlign.center))); columnChildren.add( - Center(child: Text(lastTap, textAlign: TextAlign.center)), - ); - columnChildren.add( - Center( - child: Text( - _lastTap != null ? 'Tapped' : '', - textAlign: TextAlign.center, - ), - ), - ); - columnChildren.add( - Center(child: Text(lastLongPress, textAlign: TextAlign.center)), + Center(child: Text(_lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center)), ); + columnChildren.add(Center(child: Text(lastLongPress, textAlign: TextAlign.center))); columnChildren.add( Center( - child: Text( - _lastLongPress != null ? 'Long pressed' : '', - textAlign: TextAlign.center, - ), + child: Text(_lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } Future onMapCreated(ExampleGoogleMapController controller) async { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_coordinates.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_coordinates.dart index 646301db99ae..51a68e8d5cf4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_coordinates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_coordinates.dart @@ -16,8 +16,7 @@ const CameraPosition _kInitialPosition = CameraPosition( ); class MapCoordinatesPage extends GoogleMapExampleAppPage { - const MapCoordinatesPage({super.key}) - : super(const Icon(Icons.map), 'Map coordinates'); + const MapCoordinatesPage({super.key}) : super(const Icon(Icons.map), 'Map coordinates'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { final googleMap = ExampleGoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, - onCameraIdle: - _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 + onCameraIdle: _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 ); return NotificationListener( @@ -61,13 +59,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { children: [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox( - width: 300.0, - height: 200.0, - child: googleMap, - ), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), // Add a block at the bottom of this list to allow validation that the visible region of the map // does not change when scrolled under the safe view on iOS. diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_map_id.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_map_id.dart index 94a01eb03368..89ba5c25396f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_map_id.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_map_id.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { - const MapIdPage({super.key}) - : super(const Icon(Icons.map), 'Cloud-based maps styling'); + const MapIdPage({super.key}) : super(const Icon(Icons.map), 'Cloud-based maps styling'); @override Widget build(BuildContext context) { @@ -49,10 +48,7 @@ class MapIdBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), key: _key, mapId: _mapId, ); @@ -60,9 +56,7 @@ class MapIdBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), Padding( padding: const EdgeInsets.all(10.0), @@ -80,10 +74,7 @@ class MapIdBodyState extends State { ), ]; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_ui.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_ui.dart index 258c88170924..d7e7ff773a64 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/map_ui.dart @@ -84,9 +84,7 @@ class MapUiBodyState extends State { Widget _latLngBoundsToggler() { return TextButton( child: Text( - _cameraTargetBounds.bounds == null - ? 'bound camera target' - : 'release camera target', + _cameraTargetBounds.bounds == null ? 'bound camera target' : 'release camera target', ), onPressed: () { setState(() { @@ -100,9 +98,7 @@ class MapUiBodyState extends State { Widget _zoomBoundsToggler() { return TextButton( - child: Text( - _minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom', - ), + child: Text(_minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom'), onPressed: () { setState(() { _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null @@ -114,8 +110,7 @@ class MapUiBodyState extends State { } Widget _mapTypeCycler() { - final MapType nextType = - MapType.values[(_mapType.index + 1) % MapType.values.length]; + final MapType nextType = MapType.values[(_mapType.index + 1) % MapType.values.length]; return TextButton( child: Text('change map type to $nextType'), onPressed: () { @@ -172,9 +167,7 @@ class MapUiBodyState extends State { Widget _zoomControlsToggler() { return TextButton( - child: Text( - '${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls', - ), + child: Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'), onPressed: () { setState(() { _zoomControlsEnabled = !_zoomControlsEnabled; @@ -196,9 +189,7 @@ class MapUiBodyState extends State { Widget _myLocationToggler() { return TextButton( - child: Text( - '${_myLocationEnabled ? 'disable' : 'enable'} my location marker', - ), + child: Text('${_myLocationEnabled ? 'disable' : 'enable'} my location marker'), onPressed: () { setState(() { _myLocationEnabled = !_myLocationEnabled; @@ -209,9 +200,7 @@ class MapUiBodyState extends State { Widget _myLocationButtonToggler() { return TextButton( - child: Text( - '${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button', - ), + child: Text('${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'), onPressed: () { setState(() { _myLocationButtonEnabled = !_myLocationButtonEnabled; @@ -240,9 +229,7 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = _nightMode - ? await _getFileData('assets/night_mode.json') - : ''; + final String style = _nightMode ? await _getFileData('assets/night_mode.json') : ''; setState(() { _mapStyle = style; }); @@ -275,9 +262,7 @@ class MapUiBodyState extends State { final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; @@ -313,10 +298,7 @@ class MapUiBodyState extends State { ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _updateCameraPosition(CameraPosition position) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/marker_icons.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/marker_icons.dart index d4ac8d6ac597..84d13ac32e89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/marker_icons.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MarkerIconsPage extends GoogleMapExampleAppPage { - const MarkerIconsPage({super.key}) - : super(const Icon(Icons.image), 'Marker icons'); + const MarkerIconsPage({super.key}) : super(const Icon(Icons.image), 'Marker icons'); @override Widget build(BuildContext context) { @@ -46,8 +45,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { AssetMapBitmap? _markerIconAsset; BytesMapBitmap? _markerIconBytes; final int _markersAmountPerType = 15; - bool get _customSizeEnabled => - _currentSizeOption != _MarkerSizeOption.original; + bool get _customSizeEnabled => _currentSizeOption != _MarkerSizeOption.original; @override Widget build(BuildContext context) { @@ -64,10 +62,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { width: 350.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: _onMapCreated, ), @@ -75,11 +70,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ), TextButton( onPressed: () => _toggleScaling(context), - child: Text( - _scalingEnabled - ? 'Disable auto scaling' - : 'Enable auto scaling', - ), + child: Text(_scalingEnabled ? 'Disable auto scaling' : 'Enable auto scaling'), ), if (_scalingEnabled) ...[ Container( @@ -91,10 +82,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'Reference box with size of ${referenceSize.width} x ${referenceSize.height} in logical pixels.', ), const SizedBox(height: 10), - Image.asset( - 'assets/red_square.png', - scale: _mipMapsEnabled ? null : 1.0, - ), + Image.asset('assets/red_square.png', scale: _mipMapsEnabled ? null : 1.0), const Text('Asset image rendered with flutter'), const SizedBox(height: 10), Row( @@ -112,9 +100,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { }); } }, - items: _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { + items: _MarkerSizeOption.values.map((_MarkerSizeOption option) { return DropdownMenuItem<_MarkerSizeOption>( value: option, child: Text(_getMarkerSizeOptionName(option)), @@ -126,9 +112,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { ], TextButton( onPressed: () => _toggleMipMaps(context), - child: Text( - _mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps', - ), + child: Text(_mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps'), ), ], ), @@ -179,15 +163,9 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { if (width != null && height != null) { return Size(width, height); } else if (width != null) { - return Size( - width, - width * _markerAssetImageSize.height / _markerAssetImageSize.width, - ); + return Size(width, width * _markerAssetImageSize.height / _markerAssetImageSize.width); } else if (height != null) { - return Size( - height * _markerAssetImageSize.width / _markerAssetImageSize.height, - height, - ); + return Size(height * _markerAssetImageSize.width / _markerAssetImageSize.height, height); } else { return _markerAssetImageSize; } @@ -210,10 +188,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createAssetMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude - 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude - 1); return Marker( markerId: MarkerId('marker_asset_$index'), @@ -223,10 +198,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Marker _createBytesMarker(int index) { - final position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude + 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude + 1); return Marker( markerId: MarkerId('marker_bytes_$index'), @@ -252,26 +224,20 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { - final ImageConfiguration imageConfiguration = - createLocalImageConfiguration(context); + final ImageConfiguration imageConfiguration = createLocalImageConfiguration(context); assetMapBitmap = await AssetMapBitmap.create( imageConfiguration, 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -281,9 +247,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } @@ -291,9 +255,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { } Future _updateMarkerBytesImage(BuildContext context) async { - final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf( - context, - ); + final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context); final Size bitmapLogicalSize = _getMarkerReferenceSize(); final double? imagePixelRatio = _scalingEnabled ? devicePixelRatio : null; @@ -307,10 +269,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); @@ -319,9 +278,7 @@ class _MarkerIconsBodyState extends State<_MarkerIconsBody> { imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/move_camera.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/move_camera.dart index 5fc48e659246..28ce96f2b55f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/move_camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/move_camera.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class MoveCameraPage extends GoogleMapExampleAppPage { - const MoveCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control'); + const MoveCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control'); @override Widget build(BuildContext context) { @@ -46,9 +45,7 @@ class MoveCameraState extends State { height: 200.0, child: ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -75,9 +72,7 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -99,19 +94,14 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.moveCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), @@ -121,9 +111,7 @@ class MoveCameraState extends State { children: [ TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0)), - ); + mapController?.moveCamera(CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0))); }, child: const Text('zoomBy with focus'), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/padding.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/padding.dart index a0f4f8521c8e..82136d27cd8c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/padding.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/padding.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PaddingPage extends GoogleMapExampleAppPage { - const PaddingPage({super.key}) - : super(const Icon(Icons.map), 'Add padding to the map'); + const PaddingPage({super.key}) : super(const Icon(Icons.map), 'Add padding to the map'); @override Widget build(BuildContext context) { @@ -38,19 +37,14 @@ class MarkerIconsBodyState extends State { Widget build(BuildContext context) { final googleMap = ExampleGoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), padding: _padding, ); final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), const Padding( padding: EdgeInsets.only(top: 20), @@ -65,10 +59,7 @@ class MarkerIconsBodyState extends State { columnChildren.addAll([_paddingInput(), _buttons()]); - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _onMapCreated(ExampleGoogleMapController controllerParam) { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_advanced_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_advanced_marker.dart index 08a886c11041..61c0898fed88 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_advanced_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_advanced_marker.dart @@ -53,18 +53,18 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { this.controller = controller; }); - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; }); + }); + }); } void _onMarkerTapped(MarkerId markerId) { @@ -73,17 +73,11 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final AdvancedMarker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final AdvancedMarker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; - final AdvancedMarker newMarker = copyWithSelectedState( - tappedMarker, - true, - ); + final AdvancedMarker newMarker = copyWithSelectedState(tappedMarker, true); markers[markerId] = newMarker; markerPosition = null; @@ -108,10 +102,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -177,16 +168,10 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { void _changePosition(MarkerId markerId) { final AdvancedMarker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -239,9 +224,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -249,9 +232,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -266,9 +247,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { final AdvancedMarker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -289,9 +268,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { /// Performs customizations of the [marker] to mark it as selected or not. AdvancedMarker copyWithSelectedState(AdvancedMarker marker, bool isSelected) { - return marker.copyWith( - iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected), - ); + return marker.copyWith(iconParam: _getMarkerBitmapDescriptor(isSelected: isSelected)); } @override @@ -308,8 +285,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, @@ -340,9 +316,7 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -351,70 +325,49 @@ class _PlaceAdvancedMarkerBodyState extends State<_PlaceAdvancedMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( onPressed: selectedId == null ? null - : () => - _setMarkerIcon(selectedId, _getMarkerIcon(context)), + : () => _setMarkerIcon(selectedId, _getMarkerIcon(context)), child: const Text('set glyph text'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_circle.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_circle.dart index 3c0335bfd18b..6bd22df33ef2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_circle.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { - const PlaceCirclePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place circle'); + const PlaceCirclePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place circle'); @override Widget build(BuildContext context) { @@ -38,12 +37,7 @@ class PlaceCircleBodyState extends State { // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling circle stroke width int widthsIndex = 0; @@ -133,9 +127,7 @@ class PlaceCircleBodyState extends State { void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { - circles[circleId] = circle.copyWith( - strokeWidthParam: widths[++widthsIndex % widths.length], - ); + circles[circleId] = circle.copyWith(strokeWidthParam: widths[++widthsIndex % widths.length]); }); } @@ -171,15 +163,11 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_marker.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_marker.dart index 77ba3787d8e7..43f16a23979a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_marker.dart @@ -16,8 +16,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlaceMarkerPage extends GoogleMapExampleAppPage { - const PlaceMarkerPage({super.key}) - : super(const Icon(Icons.place), 'Place marker'); + const PlaceMarkerPage({super.key}) : super(const Icon(Icons.place), 'Place marker'); @override Widget build(BuildContext context) { @@ -61,10 +60,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { setState(() { final MarkerId? previousMarkerId = selectedMarker; if (previousMarkerId != null && markers.containsKey(previousMarkerId)) { - final Marker resetOld = copyWithSelectedState( - markers[previousMarkerId]!, - false, - ); + final Marker resetOld = copyWithSelectedState(markers[previousMarkerId]!, false); markers[previousMarkerId] = resetOld; } selectedMarker = markerId; @@ -170,16 +166,10 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { void _changePosition(MarkerId markerId) { final Marker marker = markers[markerId]!; final LatLng current = marker.position; - final offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -232,9 +222,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -242,9 +230,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -259,9 +245,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { final Marker marker = markers[markerId]!; final int current = marker.zIndexInt; setState(() { - markers[markerId] = marker.copyWith( - zIndexIntParam: current == 12 ? 0 : current + 1, - ); + markers[markerId] = marker.copyWith(zIndexIntParam: current == 12 ? 0 : current + 1); }); } @@ -311,9 +295,7 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -322,63 +304,43 @@ class _PlaceMarkerBodyState extends State<_PlaceMarkerBody> { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( @@ -430,12 +392,10 @@ class AdvancedMarkersCapabilityStatus extends StatefulWidget { final ExampleGoogleMapController? controller; @override - State createState() => - _AdvancedMarkersCapabilityStatusState(); + State createState() => _AdvancedMarkersCapabilityStatusState(); } -class _AdvancedMarkersCapabilityStatusState - extends State { +class _AdvancedMarkersCapabilityStatusState extends State { /// Whether map supports advanced markers. bool? _isAdvancedMarkersAvailable; @@ -456,21 +416,19 @@ class _AdvancedMarkersCapabilityStatusState void _checkCapabilityIfNeeded() { final ExampleGoogleMapController? controller = widget.controller; - if (controller != null && - _isAdvancedMarkersAvailable == null && - !_isFetching) { + if (controller != null && _isAdvancedMarkersAvailable == null && !_isFetching) { _isFetching = true; - GoogleMapsFlutterPlatform.instance - .isAdvancedMarkersAvailable(mapId: controller.mapId) - .then((bool result) { - if (!mounted) { - return; - } - setState(() { - _isAdvancedMarkersAvailable = result; - _isFetching = false; - }); - }); + GoogleMapsFlutterPlatform.instance.isAdvancedMarkersAvailable(mapId: controller.mapId).then(( + bool result, + ) { + if (!mounted) { + return; + } + setState(() { + _isAdvancedMarkersAvailable = result; + _isFetching = false; + }); + }); } } @@ -481,8 +439,7 @@ class _AdvancedMarkersCapabilityStatusState child: Text( switch (_isAdvancedMarkersAvailable) { null => 'Checking map capabilities…', - true => - 'Map capabilities check result:\nthis map supports advanced markers', + true => 'Map capabilities check result:\nthis map supports advanced markers', false => "Map capabilities check result:\nthis map doesn't support advanced markers. Please check that map ID is provided and correct map renderer is used", }, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polygon.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polygon.dart index 70ad42c93724..d7c518cdf48d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polygon.dart @@ -11,8 +11,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolygonPage extends GoogleMapExampleAppPage { - const PlacePolygonPage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polygon'); + const PlacePolygonPage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polygon'); @override Widget build(BuildContext context) { @@ -39,12 +38,7 @@ class PlacePolygonBodyState extends State { // Values when toggling polygon color int strokeColorsIndex = 0; int fillColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polygon width int widthsIndex = 0; @@ -149,9 +143,7 @@ class PlacePolygonBodyState extends State { void _addHoles(PolygonId polygonId) { final Polygon polygon = polygons[polygonId]!; setState(() { - polygons[polygonId] = polygon.copyWith( - holesParam: _createHoles(polygonId), - ); + polygons[polygonId] = polygon.copyWith(holesParam: _createHoles(polygonId)); }); } @@ -194,15 +186,11 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -232,9 +220,7 @@ class PlacePolygonBodyState extends State { child: const Text('remove holes'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polyline.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polyline.dart index 8703ffcbd68f..a60d106bbe0b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/place_polyline.dart @@ -12,8 +12,7 @@ import 'example_google_map.dart'; import 'page.dart'; class PlacePolylinePage extends GoogleMapExampleAppPage { - const PlacePolylinePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polyline'); + const PlacePolylinePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polyline'); @override Widget build(BuildContext context) { @@ -38,23 +37,14 @@ class PlacePolylineBodyState extends State { // Values when toggling polyline color int colorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polyline width int widthsIndex = 0; List widths = [10, 20, 5]; int jointTypesIndex = 0; - List jointTypes = [ - JointType.mitered, - JointType.bevel, - JointType.round, - ]; + List jointTypes = [JointType.mitered, JointType.bevel, JointType.round]; // Values when toggling polyline end cap type int endCapsIndex = 0; @@ -133,36 +123,28 @@ class PlacePolylineBodyState extends State { void _toggleGeodesic(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - geodesicParam: !polyline.geodesic, - ); + polylines[polylineId] = polyline.copyWith(geodesicParam: !polyline.geodesic); }); } void _toggleVisible(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - visibleParam: !polyline.visible, - ); + polylines[polylineId] = polyline.copyWith(visibleParam: !polyline.visible); }); } void _changeColor(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - colorParam: colors[++colorsIndex % colors.length], - ); + polylines[polylineId] = polyline.copyWith(colorParam: colors[++colorsIndex % colors.length]); }); } void _changeWidth(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - widthParam: widths[++widthsIndex % widths.length], - ); + polylines[polylineId] = polyline.copyWith(widthParam: widths[++widthsIndex % widths.length]); }); } @@ -237,15 +219,11 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -259,15 +237,11 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) ? null : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( @@ -289,9 +263,7 @@ class PlacePolylineBodyState extends State { child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) ? null : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/scrolling_map.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/scrolling_map.dart index e5a8ec2ce5a6..443544402c31 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/scrolling_map.dart @@ -15,8 +15,7 @@ import 'page.dart'; const LatLng _center = LatLng(32.080664, 34.9563837); class ScrollingMapPage extends GoogleMapExampleAppPage { - const ScrollingMapPage({super.key}) - : super(const Icon(Icons.map), 'Scrolling map'); + const ScrollingMapPage({super.key}) : super(const Icon(Icons.map), 'Scrolling map'); @override Widget build(BuildContext context) { @@ -45,15 +44,10 @@ class ScrollingMapBody extends StatelessWidget { width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), gestureRecognizers: // >{ - Factory( - () => EagerGestureRecognizer(), - ), + Factory(() => EagerGestureRecognizer()), }, ), ), @@ -70,19 +64,14 @@ class ScrollingMapBody extends StatelessWidget { const Text("This map doesn't consume the vertical drags."), const Padding( padding: EdgeInsets.only(bottom: 12.0), - child: Text( - 'It still gets other gestures (e.g scale or tap).', - ), + child: Text('It still gets other gestures (e.g scale or tap).'), ), Center( child: SizedBox( width: 300.0, height: 300.0, child: ExampleGoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), markers: { Marker( markerId: const MarkerId('test_marker_id'), @@ -93,12 +82,9 @@ class ScrollingMapBody extends StatelessWidget { ), ), }, - gestureRecognizers: - >{ - Factory( - () => ScaleGestureRecognizer(), - ), - }, + gestureRecognizers: >{ + Factory(() => ScaleGestureRecognizer()), + }, ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/snapshot.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/snapshot.dart index 6f1624234ec4..906b3de2ecff 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/snapshot.dart @@ -53,8 +53,7 @@ class _SnapshotBodyState extends State<_SnapshotBody> { TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = await _mapController - ?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/tile_overlay.dart index cefa70eb34d5..3f3a26b6ab89 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/lib/tile_overlay.dart @@ -14,8 +14,7 @@ import 'example_google_map.dart'; import 'page.dart'; class TileOverlayPage extends GoogleMapExampleAppPage { - const TileOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Tile overlay'); + const TileOverlayPage({super.key}) : super(const Icon(Icons.map), 'Tile overlay'); @override Widget build(BuildContext context) { @@ -90,18 +89,9 @@ class TileOverlayBodyState extends State { ), ), ), - TextButton( - onPressed: _addTileOverlay, - child: const Text('Add tile overlay'), - ), - TextButton( - onPressed: _removeTileOverlay, - child: const Text('Remove tile overlay'), - ), - TextButton( - onPressed: _clearTileCache, - child: const Text('Clear tile cache'), - ), + TextButton(onPressed: _addTileOverlay, child: const Text('Add tile overlay')), + TextButton(onPressed: _removeTileOverlay, child: const Text('Remove tile overlay')), + TextButton(onPressed: _clearTileCache, child: const Text('Clear tile cache')), ], ); } @@ -125,22 +115,14 @@ class _DebugTileProvider implements TileProvider { final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); final textSpan = TextSpan(text: '$x,$y', style: textStyle); - final textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/example_google_map_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/example_google_map_test.dart index 261fc473e8bb..6aa25acb4b63 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/example_google_map_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/example_google_map_test.dart @@ -107,17 +107,12 @@ void main() { const p1 = Polygon(polygonId: PolygonId('polygon_1')); const p2 = Polygon(polygonId: PolygonId('polygon_2')); const p3 = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 1); - const p3updated = Polygon( - polygonId: PolygonId('polygon_3'), - strokeWidth: 2, - ); + const p3updated = Polygon(polygonId: PolygonId('polygon_3'), strokeWidth: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polygons: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polygons: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polygons: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -149,9 +144,7 @@ void main() { // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithObjects(polylines: {p1, p2})); await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3})); - await tester.pumpWidget( - _mapWithObjects(polylines: {p1, p3updated}), - ); + await tester.pumpWidget(_mapWithObjects(polylines: {p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; @@ -163,9 +156,7 @@ void main() { expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[1].polylinesToAdd, {p3}); - expect(map.polylineUpdates[1].polylineIdsToRemove, { - p2.polylineId, - }); + expect(map.polylineUpdates[1].polylineIdsToRemove, {p2.polylineId}); expect(map.polylineUpdates[2].polylinesToChange, {p3updated}); expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/fake_google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/fake_google_maps_flutter_platform.dart index 899a7709c548..3e8beefc78c4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/fake_google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/example/test/fake_google_maps_flutter_platform.dart @@ -17,8 +17,7 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { List createdIds = []; /// A map of creation IDs to fake map instances. - Map mapInstances = - {}; + Map mapInstances = {}; PlatformMapStateRecorder get lastCreatedMap => mapInstances[createdIds.last]!; @@ -41,46 +40,31 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { Future init(int mapId) async {} @override - Future updateMapConfiguration( - MapConfiguration update, { - required int mapId, - }) async { + Future updateMapConfiguration(MapConfiguration update, {required int mapId}) async { mapInstances[mapId]?.mapConfiguration = update; await _fakeDelay(); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { mapInstances[mapId]?.markerUpdates.add(markerUpdates); await _fakeDelay(); } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { mapInstances[mapId]?.polygonUpdates.add(polygonUpdates); await _fakeDelay(); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { mapInstances[mapId]?.polylineUpdates.add(polylineUpdates); await _fakeDelay(); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { mapInstances[mapId]?.circleUpdates.add(circleUpdates); await _fakeDelay(); } @@ -113,16 +97,10 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async {} + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async {} @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future animateCameraWithConfiguration( @@ -132,55 +110,34 @@ class FakeGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform { }) async {} @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async {} + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async {} @override Future setMapStyle(String? mapStyle, {required int mapId}) async {} @override Future getVisibleRegion({required int mapId}) async { - return LatLngBounds( - southwest: const LatLng(0, 0), - northeast: const LatLng(0, 0), - ); + return LatLngBounds(southwest: const LatLng(0, 0), northeast: const LatLng(0, 0)); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return const ScreenCoordinate(x: 0, y: 0); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return const LatLng(0, 0); } @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async {} + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async {} @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return false; } @@ -312,24 +269,14 @@ class PlatformMapStateRecorder { this.mapConfiguration = const MapConfiguration(), }) { clusterManagerUpdates.add( - ClusterManagerUpdates.from( - const {}, - mapObjects.clusterManagers, - ), + ClusterManagerUpdates.from(const {}, mapObjects.clusterManagers), ); groundOverlayUpdates.add( - GroundOverlayUpdates.from( - const {}, - mapObjects.groundOverlays, - ), + GroundOverlayUpdates.from(const {}, mapObjects.groundOverlays), ); markerUpdates.add(MarkerUpdates.from(const {}, mapObjects.markers)); - polygonUpdates.add( - PolygonUpdates.from(const {}, mapObjects.polygons), - ); - polylineUpdates.add( - PolylineUpdates.from(const {}, mapObjects.polylines), - ); + polygonUpdates.add(PolygonUpdates.from(const {}, mapObjects.polygons)); + polylineUpdates.add(PolylineUpdates.from(const {}, mapObjects.polylines)); circleUpdates.add(CircleUpdates.from(const {}, mapObjects.circles)); tileOverlaySets.add(mapObjects.tileOverlays); } @@ -343,8 +290,6 @@ class PlatformMapStateRecorder { final List polylineUpdates = []; final List circleUpdates = []; final List> tileOverlaySets = >[]; - final List clusterManagerUpdates = - []; - final List groundOverlayUpdates = - []; + final List clusterManagerUpdates = []; + final List groundOverlayUpdates = []; } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_map_inspector_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_map_inspector_ios.dart index a0057b9fdc54..a0d3b46c6cbb 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_map_inspector_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_map_inspector_ios.dart @@ -14,9 +14,8 @@ import 'messages.g.dart'; class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { /// Creates an inspector API instance for a given map ID from /// [inspectorProvider]. - GoogleMapsInspectorIOS( - MapsInspectorApi? Function(int mapId) inspectorProvider, - ) : _inspectorProvider = inspectorProvider; + GoogleMapsInspectorIOS(MapsInspectorApi? Function(int mapId) inspectorProvider) + : _inspectorProvider = inspectorProvider; final MapsInspectorApi? Function(int mapId) _inspectorProvider; @@ -53,17 +52,12 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { @override Future getMinMaxZoomLevels({required int mapId}) async { - final PlatformZoomRange zoomLevels = await _inspectorProvider( - mapId, - )!.getZoomRange(); + final PlatformZoomRange zoomLevels = await _inspectorProvider(mapId)!.getZoomRange(); return MinMaxZoomPreference(zoomLevels.min, zoomLevels.max); } @override - Future getTileOverlayInfo( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) async { final PlatformTileLayer? tileInfo = await _inspectorProvider( mapId, )!.getTileOverlayInfo(tileOverlayId.value); @@ -83,10 +77,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { bool supportsGettingHeatmapInfo() => true; @override - Future getHeatmapInfo( - HeatmapId heatmapId, { - required int mapId, - }) async { + Future getHeatmapInfo(HeatmapId heatmapId, {required int mapId}) async { final PlatformHeatmap? heatmapInfo = await _inspectorProvider( mapId, )!.getHeatmapInfo(heatmapId.value); @@ -140,24 +131,15 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { transparency: groundOverlayInfo.transparency, visible: groundOverlayInfo.visible, clickable: groundOverlayInfo.clickable, - anchor: Offset( - groundOverlayInfo.anchor!.x, - groundOverlayInfo.anchor!.y, - ), + anchor: Offset(groundOverlayInfo.anchor!.x, groundOverlayInfo.anchor!.y), zoomLevel: groundOverlayInfo.zoomLevel, ); } else if (bounds != null) { return GroundOverlay.fromBounds( groundOverlayId: groundOverlayId, bounds: LatLngBounds( - southwest: LatLng( - bounds.southwest.latitude, - bounds.southwest.longitude, - ), - northeast: LatLng( - bounds.northeast.latitude, - bounds.northeast.longitude, - ), + southwest: LatLng(bounds.southwest.latitude, bounds.southwest.longitude), + northeast: LatLng(bounds.northeast.latitude, bounds.northeast.longitude), ), image: dummyImage, zIndex: groundOverlayInfo.zIndex, @@ -202,13 +184,8 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { required int mapId, required ClusterManagerId clusterManagerId, }) async { - return (await _inspectorProvider( - mapId, - )!.getClusters(clusterManagerId.value)) - .map( - (PlatformCluster cluster) => - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ) + return (await _inspectorProvider(mapId)!.getClusters(clusterManagerId.value)) + .map((PlatformCluster cluster) => GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)) .toList(); } @@ -221,19 +198,14 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { mapId, )!.getCameraPosition(); return CameraPosition( - target: LatLng( - cameraPosition.target.latitude, - cameraPosition.target.longitude, - ), + target: LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude), bearing: cameraPosition.bearing, tilt: cameraPosition.tilt, zoom: cameraPosition.zoom, ); } - static HeatmapGradient? _deserializeHeatmapGradient( - PlatformHeatmapGradient? gradient, - ) { + static HeatmapGradient? _deserializeHeatmapGradient(PlatformHeatmapGradient? gradient) { if (gradient == null) { return null; } @@ -243,12 +215,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { _mapEnumerated( gradient.colors, (PlatformColor color, int i) => HeatmapGradientColor( - Color.from( - red: color.red, - green: color.green, - blue: color.blue, - alpha: color.alpha, - ), + Color.from(red: color.red, green: color.green, blue: color.blue, alpha: color.alpha), gradient.startPoints[i], ), ).toList(), @@ -256,9 +223,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { ); } - static WeightedLatLng _deserializeWeightedLatLng( - PlatformWeightedLatLng weightedLatLng, - ) { + static WeightedLatLng _deserializeWeightedLatLng(PlatformWeightedLatLng weightedLatLng) { return WeightedLatLng( LatLng(weightedLatLng.point.latitude, weightedLatLng.point.longitude), weight: weightedLatLng.weight, @@ -266,10 +231,7 @@ class GoogleMapsInspectorIOS extends GoogleMapsInspectorPlatform { } } -Iterable _mapEnumerated( - Iterable iterable, - E Function(T, int) fn, -) sync* { +Iterable _mapEnumerated(Iterable iterable, E Function(T, int) fn) sync* { var index = 0; for (final item in iterable) { yield fn(item, index++); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_maps_flutter_ios.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_maps_flutter_ios.dart index c1709a97ad52..c0c8db027c8d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_maps_flutter_ios.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/google_maps_flutter_ios.dart @@ -43,9 +43,8 @@ class UnknownMapIDError extends Error { /// An implementation of [GoogleMapsFlutterPlatform] for iOS. class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Creates a new Android maps implementation instance. - GoogleMapsFlutterIOS({ - @visibleForTesting MapsApi Function(int mapId)? apiProvider, - }) : _apiProvider = apiProvider ?? _productionApiProvider; + GoogleMapsFlutterIOS({@visibleForTesting MapsApi Function(int mapId)? apiProvider}) + : _apiProvider = apiProvider ?? _productionApiProvider; /// Registers the iOS implementation of GoogleMapsFlutterPlatform. static void registerWith() { @@ -59,8 +58,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// The per-map handlers for callbacks from the host side. @visibleForTesting - final Map hostMapHandlers = - {}; + final Map hostMapHandlers = {}; /// Accesses the MapsApi associated to the passed mapId. MapsApi _hostApi(int mapId) { @@ -84,8 +82,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { mapId, _mapEventStreamController, tileOverlayProvider: (TileOverlayId tileOverlayId) { - final Map? tileOverlaysForMap = - _tileOverlays[mapId]; + final Map? tileOverlaysForMap = _tileOverlays[mapId]; return tileOverlaysForMap?[tileOverlayId]; }, ); @@ -127,9 +124,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { StreamController>.broadcast(); // Returns a filtered view of the events in the _controller, by mapId. - Stream> _events(int mapId) => _mapEventStreamController - .stream - .where((MapEvent event) => event.mapId == mapId); + Stream> _events(int mapId) => + _mapEventStreamController.stream.where((MapEvent event) => event.mapId == mapId); @override Stream onCameraMoveStarted({required int mapId}) { @@ -207,30 +203,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateMapConfiguration( - MapConfiguration configuration, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromMapConfiguration(configuration), - ); + Future updateMapConfiguration(MapConfiguration configuration, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromMapConfiguration(configuration)); } @override - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) { - return _hostApi(mapId).updateMapConfiguration( - _platformMapConfigurationFromOptionsJson(optionsUpdate), - ); + Future updateMapOptions(Map optionsUpdate, {required int mapId}) { + return _hostApi( + mapId, + ).updateMapConfiguration(_platformMapConfigurationFromOptionsJson(optionsUpdate)); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) { return _hostApi(mapId).updateMarkers( markerUpdates.markersToAdd.map(_platformMarkerFromMarker).toList(), markerUpdates.markersToChange.map(_platformMarkerFromMarker).toList(), @@ -239,42 +226,25 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) { return _hostApi(mapId).updatePolygons( polygonUpdates.polygonsToAdd.map(_platformPolygonFromPolygon).toList(), polygonUpdates.polygonsToChange.map(_platformPolygonFromPolygon).toList(), - polygonUpdates.polygonIdsToRemove - .map((PolygonId id) => id.value) - .toList(), + polygonUpdates.polygonIdsToRemove.map((PolygonId id) => id.value).toList(), ); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) { return _hostApi(mapId).updatePolylines( - polylineUpdates.polylinesToAdd - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylinesToChange - .map(_platformPolylineFromPolyline) - .toList(), - polylineUpdates.polylineIdsToRemove - .map((PolylineId id) => id.value) - .toList(), + polylineUpdates.polylinesToAdd.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylinesToChange.map(_platformPolylineFromPolyline).toList(), + polylineUpdates.polylineIdsToRemove.map((PolylineId id) => id.value).toList(), ); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) { return _hostApi(mapId).updateCircles( circleUpdates.circlesToAdd.map(_platformCircleFromCircle).toList(), circleUpdates.circlesToChange.map(_platformCircleFromCircle).toList(), @@ -283,41 +253,26 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) { return _hostApi(mapId).updateHeatmaps( heatmapUpdates.heatmapsToAdd.map(_platformHeatmapFromHeatmap).toList(), heatmapUpdates.heatmapsToChange.map(_platformHeatmapFromHeatmap).toList(), - heatmapUpdates.heatmapIdsToRemove - .map((HeatmapId id) => id.value) - .toList(), + heatmapUpdates.heatmapIdsToRemove.map((HeatmapId id) => id.value).toList(), ); } @override - Future updateTileOverlays({ - required Set newTileOverlays, - required int mapId, - }) { - final Map? currentTileOverlays = - _tileOverlays[mapId]; + Future updateTileOverlays({required Set newTileOverlays, required int mapId}) { + final Map? currentTileOverlays = _tileOverlays[mapId]; final Set previousSet = currentTileOverlays != null ? currentTileOverlays.values.toSet() : {}; final updates = _TileOverlayUpdates.from(previousSet, newTileOverlays); _tileOverlays[mapId] = keyTileOverlayId(newTileOverlays); return _hostApi(mapId).updateTileOverlays( - updates.tileOverlaysToAdd - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlaysToChange - .map(_platformTileOverlayFromTileOverlay) - .toList(), - updates.tileOverlayIdsToRemove - .map((TileOverlayId id) => id.value) - .toList(), + updates.tileOverlaysToAdd.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlaysToChange.map(_platformTileOverlayFromTileOverlay).toList(), + updates.tileOverlayIdsToRemove.map((TileOverlayId id) => id.value).toList(), ); } @@ -356,17 +311,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { groundOverlayUpdates.groundOverlaysToChange .map(_platformGroundOverlayFromGroundOverlay) .toList(), - groundOverlayUpdates.groundOverlayIdsToRemove - .map((GroundOverlayId id) => id.value) - .toList(), + groundOverlayUpdates.groundOverlayIdsToRemove.map((GroundOverlayId id) => id.value).toList(), ); } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) { return _hostApi(mapId).clearTileCache(tileOverlayId.value); } @@ -393,16 +343,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) { - return _hostApi( - mapId, - ).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); + return _hostApi(mapId).moveCamera(_platformCameraUpdateFromCameraUpdate(cameraUpdate)); } @override Future setMapStyle(String? mapStyle, {required int mapId}) async { - final String? errorDescription = await _hostApi( - mapId, - ).setStyle(mapStyle ?? ''); + final String? errorDescription = await _hostApi(mapId).setStyle(mapStyle ?? ''); if (errorDescription != null) { throw MapStyleException(errorDescription); } @@ -410,32 +356,20 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { @override Future getVisibleRegion({required int mapId}) async { - return _latLngBoundsFromPlatformLatLngBounds( - await _hostApi(mapId).getVisibleRegion(), - ); + return _latLngBoundsFromPlatformLatLngBounds(await _hostApi(mapId).getVisibleRegion()); } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { return _screenCoordinateFromPlatformPoint( - await _hostApi( - mapId, - ).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), + await _hostApi(mapId).getScreenCoordinate(_platformLatLngFromLatLng(latLng)), ); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { return _latLngFromPlatformLatLng( - await _hostApi( - mapId, - ).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), + await _hostApi(mapId).getLatLng(_platformPointFromScreenCoordinate(screenCoordinate)), ); } @@ -450,10 +384,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) { return _hostApi(mapId).isInfoWindowShown(markerId.value); } @@ -497,21 +428,11 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { widgetConfiguration.initialCameraPosition, ), mapConfiguration: mapConfiguration, - initialMarkers: mapObjects.markers - .map(_platformMarkerFromMarker) - .toList(), - initialPolygons: mapObjects.polygons - .map(_platformPolygonFromPolygon) - .toList(), - initialPolylines: mapObjects.polylines - .map(_platformPolylineFromPolyline) - .toList(), - initialCircles: mapObjects.circles - .map(_platformCircleFromCircle) - .toList(), - initialHeatmaps: mapObjects.heatmaps - .map(_platformHeatmapFromHeatmap) - .toList(), + initialMarkers: mapObjects.markers.map(_platformMarkerFromMarker).toList(), + initialPolygons: mapObjects.polygons.map(_platformPolygonFromPolygon).toList(), + initialPolylines: mapObjects.polylines.map(_platformPolylineFromPolyline).toList(), + initialCircles: mapObjects.circles.map(_platformCircleFromCircle).toList(), + initialHeatmaps: mapObjects.heatmaps.map(_platformHeatmapFromHeatmap).toList(), initialTileOverlays: mapObjects.tileOverlays .map(_platformTileOverlayFromTileOverlay) .toList(), @@ -545,9 +466,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { onPlatformViewCreated, widgetConfiguration: widgetConfiguration, mapObjects: mapObjects, - mapConfiguration: _platformMapConfigurationFromMapConfiguration( - mapConfiguration, - ), + mapConfiguration: _platformMapConfigurationFromMapConfiguration(mapConfiguration), ); } @@ -629,19 +548,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static ScreenCoordinate _screenCoordinateFromPlatformPoint( - PlatformPoint point, - ) { + static ScreenCoordinate _screenCoordinateFromPlatformPoint(PlatformPoint point) { return ScreenCoordinate(x: point.x.round(), y: point.y.round()); } - static PlatformPoint _platformPointFromScreenCoordinate( - ScreenCoordinate coordinate, - ) { - return PlatformPoint( - x: coordinate.x.toDouble(), - y: coordinate.y.toDouble(), - ); + static PlatformPoint _platformPointFromScreenCoordinate(ScreenCoordinate coordinate) { + return PlatformPoint(x: coordinate.x.toDouble(), y: coordinate.y.toDouble()); } static PlatformPoint _platformPointFromOffset(Offset offset) { @@ -670,9 +582,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { final HeatmapGradient? gradient = heatmap.gradient; return PlatformHeatmap( heatmapId: heatmap.heatmapId.value, - data: heatmap.data - .map(_platformWeightedLatLngFromWeightedLatLng) - .toList(), + data: heatmap.data.map(_platformWeightedLatLngFromWeightedLatLng).toList(), gradient: _platformHeatmapGradientFromHeatmapGradient(gradient), opacity: heatmap.opacity, radius: heatmap.radius.radius, @@ -691,16 +601,12 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { colors: gradient.colors .map((HeatmapGradientColor c) => _platformColorFromColor(c.color)) .toList(), - startPoints: gradient.colors - .map((HeatmapGradientColor c) => c.startPoint) - .toList(), + startPoints: gradient.colors.map((HeatmapGradientColor c) => c.startPoint).toList(), colorMapSize: gradient.colorMapSize, ); } - static PlatformInfoWindow _platformInfoWindowFromInfoWindow( - InfoWindow window, - ) { + static PlatformInfoWindow _platformInfoWindowFromInfoWindow(InfoWindow window) { return PlatformInfoWindow( title: window.title, snippet: window.snippet, @@ -724,9 +630,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { markerId: marker.markerId.value, clusterManagerId: marker.clusterManagerId?.value, collisionBehavior: marker is AdvancedMarker - ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( - marker.collisionBehavior, - ) + ? platformMarkerCollisionBehaviorFromMarkerCollisionBehavior(marker.collisionBehavior) : null, ); } @@ -736,9 +640,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ) { return PlatformGroundOverlay( groundOverlayId: groundOverlay.groundOverlayId.value, - anchor: groundOverlay.anchor != null - ? _platformPointFromOffset(groundOverlay.anchor!) - : null, + anchor: groundOverlay.anchor != null ? _platformPointFromOffset(groundOverlay.anchor!) : null, image: platformBitmapFromBitmapDescriptor(groundOverlay.image), position: groundOverlay.position != null ? _platformLatLngFromLatLng(groundOverlay.position!) @@ -754,12 +656,8 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolygon _platformPolygonFromPolygon(Polygon polygon) { - final List points = polygon.points - .map(_platformLatLngFromLatLng) - .toList(); - final List> holes = polygon.holes.map(( - List hole, - ) { + final List points = polygon.points.map(_platformLatLngFromLatLng).toList(); + final List> holes = polygon.holes.map((List hole) { return hole.map(_platformLatLngFromLatLng).toList(); }).toList(); return PlatformPolygon( @@ -777,9 +675,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { } static PlatformPolyline _platformPolylineFromPolyline(Polyline polyline) { - final List points = polyline.points - .map(_platformLatLngFromLatLng) - .toList(); + final List points = polyline.points.map(_platformLatLngFromLatLng).toList(); final List pattern = polyline.patterns .map(platformPatternItemFromPatternItem) .toList(); @@ -797,9 +693,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); } - static PlatformTileOverlay _platformTileOverlayFromTileOverlay( - TileOverlay tileOverlay, - ) { + static PlatformTileOverlay _platformTileOverlayFromTileOverlay(TileOverlay tileOverlay) { return PlatformTileOverlay( tileOverlayId: tileOverlay.tileOverlayId.value, fadeIn: tileOverlay.fadeIn, @@ -813,22 +707,16 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { static PlatformClusterManager _platformClusterManagerFromClusterManager( ClusterManager clusterManager, ) { - return PlatformClusterManager( - identifier: clusterManager.clusterManagerId.value, - ); + return PlatformClusterManager(identifier: clusterManager.clusterManagerId.value); } - static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate( - CameraUpdate update, - ) { + static PlatformCameraUpdate _platformCameraUpdateFromCameraUpdate(CameraUpdate update) { switch (update.updateType) { case CameraUpdateType.newCameraPosition: update as CameraUpdateNewCameraPosition; return PlatformCameraUpdate( cameraUpdate: PlatformCameraUpdateNewCameraPosition( - cameraPosition: _platformCameraPositionFromCameraPosition( - update.cameraPosition, - ), + cameraPosition: _platformCameraPositionFromCameraPosition(update.cameraPosition), ), ); case CameraUpdateType.newLatLng: @@ -856,9 +744,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomTo: update as CameraUpdateZoomTo; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoomTo(zoom: update.zoom)); case CameraUpdateType.zoomBy: update as CameraUpdateZoomBy; final Offset? focus = update.focus; @@ -870,30 +756,21 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { ); case CameraUpdateType.zoomIn: update as CameraUpdateZoomIn; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: false), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: false)); case CameraUpdateType.zoomOut: update as CameraUpdateZoomOut; - return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateZoom(out: true), - ); + return PlatformCameraUpdate(cameraUpdate: PlatformCameraUpdateZoom(out: true)); case CameraUpdateType.scrollBy: update as CameraUpdateScrollBy; return PlatformCameraUpdate( - cameraUpdate: PlatformCameraUpdateScrollBy( - dx: update.dx, - dy: update.dy, - ), + cameraUpdate: PlatformCameraUpdateScrollBy(dx: update.dx, dy: update.dy), ); } } /// Converts [MapBitmapScaling] from platform interface to [PlatformMapBitmapScaling] Pigeon. @visibleForTesting - static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling( - MapBitmapScaling scaling, - ) { + static PlatformMapBitmapScaling platformMapBitmapScalingFromScaling(MapBitmapScaling scaling) { switch (scaling) { case MapBitmapScaling.auto: return PlatformMapBitmapScaling.auto; @@ -913,8 +790,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [MarkersCollisionBehavior] from platform interface to /// [PlatformMarkerCollisionBehavior] Pigeon. @visibleForTesting - static PlatformMarkerCollisionBehavior - platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( + static PlatformMarkerCollisionBehavior platformMarkerCollisionBehaviorFromMarkerCollisionBehavior( MarkerCollisionBehavior collisionBehavior, ) { switch (collisionBehavior) { @@ -937,14 +813,10 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { /// Converts [BitmapDescriptor] from platform interface to [PlatformBitmap] pigeon. @visibleForTesting - static PlatformBitmap platformBitmapFromBitmapDescriptor( - BitmapDescriptor bitmap, - ) { + static PlatformBitmap platformBitmapFromBitmapDescriptor(BitmapDescriptor bitmap) { switch (bitmap) { case final DefaultMarker marker: - return PlatformBitmap( - bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble()), - ); + return PlatformBitmap(bitmap: PlatformBitmapDefaultMarker(hue: marker.hue?.toDouble())); // Clients may still use this deprecated format, so it must be supported. // ignore: deprecated_member_use case final BytesBitmap bytes: @@ -974,9 +846,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapAssetMap( assetName: asset.assetName, - bitmapScaling: platformMapBitmapScalingFromScaling( - asset.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(asset.bitmapScaling), imagePixelRatio: asset.imagePixelRatio, width: asset.width, height: asset.height, @@ -986,9 +856,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { return PlatformBitmap( bitmap: PlatformBitmapBytesMap( byteData: bytes.byteData, - bitmapScaling: platformMapBitmapScalingFromScaling( - bytes.bitmapScaling, - ), + bitmapScaling: platformMapBitmapScalingFromScaling(bytes.bitmapScaling), imagePixelRatio: bytes.imagePixelRatio, width: bytes.width, height: bytes.height, @@ -1026,9 +894,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { bitmap: PlatformBitmapPinConfig( backgroundColor: backgroundColor, borderColor: borderColor, - glyphBitmap: platformBitmapFromBitmapDescriptor( - bitmapGlyph.bitmap, - ), + glyphBitmap: platformBitmapFromBitmapDescriptor(bitmapGlyph.bitmap), ), ); case null: @@ -1050,10 +916,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { 'Glyph type "${pinConfig.glyph.runtimeType}" has not been implemented', ); default: - throw ArgumentError( - 'Unrecognized type of bitmap ${bitmap.runtimeType}', - 'bitmap', - ); + throw ArgumentError('Unrecognized type of bitmap ${bitmap.runtimeType}', 'bitmap'); } } } @@ -1063,11 +926,7 @@ class GoogleMapsFlutterIOS extends GoogleMapsFlutterPlatform { class HostMapMessageHandler implements MapsCallbackApi { /// Creates a new handler that listens for events from map [mapId], and /// broadcasts them to [streamController]. - HostMapMessageHandler( - this.mapId, - this.streamController, { - required this.tileOverlayProvider, - }) { + HostMapMessageHandler(this.mapId, this.streamController, {required this.tileOverlayProvider}) { MapsCallbackApi.setUp(this, messageChannelSuffix: mapId.toString()); } @@ -1092,17 +951,11 @@ class HostMapMessageHandler implements MapsCallbackApi { PlatformPoint location, int zoom, ) async { - final TileOverlay? tileOverlay = tileOverlayProvider( - TileOverlayId(tileOverlayId), - ); + final TileOverlay? tileOverlay = tileOverlayProvider(TileOverlayId(tileOverlayId)); final TileProvider? tileProvider = tileOverlay?.tileProvider; final Tile tile = tileProvider == null ? TileProvider.noTile - : await tileProvider.getTile( - location.x.round(), - location.y.round(), - zoom, - ); + : await tileProvider.getTile(location.x.round(), location.y.round(), zoom); return _platformTileFromTile(tile); } @@ -1139,10 +992,7 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onClusterTap(PlatformCluster cluster) { streamController.add( - ClusterTapEvent( - mapId, - GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster), - ), + ClusterTapEvent(mapId, GoogleMapsFlutterIOS.clusterFromPlatformCluster(cluster)), ); } @@ -1153,41 +1003,27 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onLongPress(PlatformLatLng position) { - streamController.add( - MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapLongPressEvent(mapId, _latLngFromPlatformLatLng(position))); } @override void onMarkerDrag(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragStart(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragStartEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragStartEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @override void onMarkerDragEnd(String markerId, PlatformLatLng position) { streamController.add( - MarkerDragEndEvent( - mapId, - _latLngFromPlatformLatLng(position), - MarkerId(markerId), - ), + MarkerDragEndEvent(mapId, _latLngFromPlatformLatLng(position), MarkerId(markerId)), ); } @@ -1208,35 +1044,24 @@ class HostMapMessageHandler implements MapsCallbackApi { @override void onGroundOverlayTap(String groundOverlayId) { - streamController.add( - GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId)), - ); + streamController.add(GroundOverlayTapEvent(mapId, GroundOverlayId(groundOverlayId))); } @override void onTap(PlatformLatLng position) { - streamController.add( - MapTapEvent(mapId, _latLngFromPlatformLatLng(position)), - ); + streamController.add(MapTapEvent(mapId, _latLngFromPlatformLatLng(position))); } } PlatformColor _platformColorFromColor(Color color) { - return PlatformColor( - red: color.r, - green: color.g, - blue: color.b, - alpha: color.a, - ); + return PlatformColor(red: color.r, green: color.g, blue: color.b, alpha: color.a); } LatLng _latLngFromPlatformLatLng(PlatformLatLng latLng) { return LatLng(latLng.latitude, latLng.longitude); } -LatLngBounds _latLngBoundsFromPlatformLatLngBounds( - PlatformLatLngBounds bounds, -) { +LatLngBounds _latLngBoundsFromPlatformLatLngBounds(PlatformLatLngBounds bounds) { return LatLngBounds( southwest: _latLngFromPlatformLatLng(bounds.southwest), northeast: _latLngFromPlatformLatLng(bounds.northeast), @@ -1247,9 +1072,7 @@ PlatformLatLng _platformLatLngFromLatLng(LatLng latLng) { return PlatformLatLng(latitude: latLng.latitude, longitude: latLng.longitude); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( - LatLngBounds? bounds, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds(LatLngBounds? bounds) { if (bounds == null) { return null; } @@ -1259,9 +1082,7 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBounds( ); } -PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng( - WeightedLatLng weightedLatLng, -) { +PlatformWeightedLatLng _platformWeightedLatLngFromWeightedLatLng(WeightedLatLng weightedLatLng) { return PlatformWeightedLatLng( point: _platformLatLngFromLatLng(weightedLatLng.point), weight: weightedLatLng.weight, @@ -1273,9 +1094,7 @@ PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBounds( ) { return bounds == null ? null - : PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds), - ); + : PlatformCameraTargetBounds(bounds: _platformLatLngBoundsFromLatLngBounds(bounds.bounds)); } PlatformTile _platformTileFromTile(Tile tile) { @@ -1306,12 +1125,8 @@ PlatformMapType? _platformMapTypeFromMapType(MapType? type) { return PlatformMapType.normal; } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference( - MinMaxZoomPreference? zoomPref, -) { - return zoomPref == null - ? null - : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreference(MinMaxZoomPreference? zoomPref) { + return zoomPref == null ? null : PlatformZoomRange(min: zoomPref.minZoom, max: zoomPref.maxZoom); } PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { @@ -1325,18 +1140,14 @@ PlatformEdgeInsets? _platformEdgeInsetsFromEdgeInsets(EdgeInsets? insets) { ); } -PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( - MapConfiguration config, -) { +PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration(MapConfiguration config) { return PlatformMapConfiguration( compassEnabled: config.compassEnabled, cameraTargetBounds: _platformCameraTargetBoundsFromCameraTargetBounds( config.cameraTargetBounds, ), mapType: _platformMapTypeFromMapType(config.mapType), - minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference( - config.minMaxZoomPreference, - ), + minMaxZoomPreference: _platformZoomRangeFromMinMaxZoomPreference(config.minMaxZoomPreference), rotateGesturesEnabled: config.rotateGesturesEnabled, scrollGesturesEnabled: config.scrollGesturesEnabled, tiltGesturesEnabled: config.tiltGesturesEnabled, @@ -1348,9 +1159,7 @@ PlatformMapConfiguration _platformMapConfigurationFromMapConfiguration( indoorViewEnabled: config.indoorViewEnabled, trafficEnabled: config.trafficEnabled, buildingsEnabled: config.buildingsEnabled, - markerType: _platformMarkerTypeFromMarkerType( - config.markerType ?? MarkerType.marker, - ), + markerType: _platformMarkerTypeFromMarkerType(config.markerType ?? MarkerType.marker), mapId: config.mapId, style: config.style, ); @@ -1374,14 +1183,11 @@ PlatformMarkerType _platformMarkerTypeFromMarkerType(MarkerType markerType) { } // For supporting the deprecated updateMapOptions API. -PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( - Map options, -) { +PlatformMapConfiguration _platformMapConfigurationFromOptionsJson(Map options) { // All of these hard-coded values and structures come from // google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart // to support this legacy API that relied on cross-package magic strings. - final List? padding = (options['padding'] as List?) - ?.cast(); + final List? padding = (options['padding'] as List?)?.cast(); final mapType = options['mapType'] as int?; return PlatformMapConfiguration( compassEnabled: options['compassEnabled'] as bool?, @@ -1416,9 +1222,7 @@ PlatformMapConfiguration _platformMapConfigurationFromOptionsJson( ); } -PlatformCameraPosition _platformCameraPositionFromCameraPosition( - CameraPosition position, -) { +PlatformCameraPosition _platformCameraPositionFromCameraPosition(CameraPosition position) { return PlatformCameraPosition( bearing: position.bearing, target: _platformLatLngFromLatLng(position.target), @@ -1446,9 +1250,7 @@ PlatformLatLng _platformLatLngFromLatLngJson(Object latLngJson) { return PlatformLatLng(latitude: list[0], longitude: list[1]); } -PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( - Object? boundsJson, -) { +PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson(Object? boundsJson) { if (boundsJson == null) { return null; } @@ -1460,28 +1262,24 @@ PlatformLatLngBounds? _platformLatLngBoundsFromLatLngBoundsJson( ); } -PlatformCameraTargetBounds? -_platformCameraTargetBoundsFromCameraTargetBoundsJson(Object? targetJson) { +PlatformCameraTargetBounds? _platformCameraTargetBoundsFromCameraTargetBoundsJson( + Object? targetJson, +) { if (targetJson == null) { return null; } // See `CameraTargetBounds.toJson`. return PlatformCameraTargetBounds( - bounds: _platformLatLngBoundsFromLatLngBoundsJson( - (targetJson as List)[0], - ), + bounds: _platformLatLngBoundsFromLatLngBoundsJson((targetJson as List)[0]), ); } -PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson( - Object? zoomPrefsJson, -) { +PlatformZoomRange? _platformZoomRangeFromMinMaxZoomPreferenceJson(Object? zoomPrefsJson) { if (zoomPrefsJson == null) { return null; } // See `MinMaxZoomPreference.toJson`. - final List minMaxZoom = (zoomPrefsJson as List) - .cast(); + final List minMaxZoom = (zoomPrefsJson as List).cast(); return PlatformZoomRange(min: minMaxZoom[0], max: minMaxZoom[1]); } @@ -1514,16 +1312,10 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { return PlatformPatternItem(type: PlatformPatternItemType.dot); case PatternItemType.dash: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.dash, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.dash, length: length); case PatternItemType.gap: final double length = (item as VariableLengthPatternItem).length; - return PlatformPatternItem( - type: PlatformPatternItemType.gap, - length: length, - ); + return PlatformPatternItem(type: PlatformPatternItemType.gap, length: length); } // The enum comes from a different package, which could get a new value at @@ -1540,15 +1332,13 @@ PlatformPatternItem platformPatternItemFromPatternItem(PatternItem item) { // interface, and remove this copy. class _TileOverlayUpdates extends MapsObjectUpdates { /// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s. - _TileOverlayUpdates.from(super.previous, super.current) - : super.from(objectName: 'tileOverlay'); + _TileOverlayUpdates.from(super.previous, super.current) : super.from(objectName: 'tileOverlay'); /// Set of TileOverlays to be added in this update. Set get tileOverlaysToAdd => objectsToAdd; /// Set of TileOverlayIds to be removed in this update. - Set get tileOverlayIdsToRemove => - objectIdsToRemove.cast(); + Set get tileOverlayIdsToRemove => objectIdsToRemove.cast(); /// Set of TileOverlays to be changed in this update. Set get tileOverlaysToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/messages.g.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/messages.g.dart index 87fd64fcb0bc..be134f058b12 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/messages.g.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/lib/src/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -187,8 +181,7 @@ class PlatformCameraUpdateNewCameraPosition { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewCameraPosition || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewCameraPosition || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -224,8 +217,7 @@ class PlatformCameraUpdateNewLatLng { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLng || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLng || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -241,10 +233,7 @@ class PlatformCameraUpdateNewLatLng { /// Pigeon equivalent of NewLatLngBounds class PlatformCameraUpdateNewLatLngBounds { - PlatformCameraUpdateNewLatLngBounds({ - required this.bounds, - required this.padding, - }); + PlatformCameraUpdateNewLatLngBounds({required this.bounds, required this.padding}); PlatformLatLngBounds bounds; @@ -269,8 +258,7 @@ class PlatformCameraUpdateNewLatLngBounds { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -311,8 +299,7 @@ class PlatformCameraUpdateNewLatLngZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateNewLatLngZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateNewLatLngZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -344,17 +331,13 @@ class PlatformCameraUpdateScrollBy { static PlatformCameraUpdateScrollBy decode(Object result) { result as List; - return PlatformCameraUpdateScrollBy( - dx: result[0]! as double, - dy: result[1]! as double, - ); + return PlatformCameraUpdateScrollBy(dx: result[0]! as double, dy: result[1]! as double); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateScrollBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateScrollBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -395,8 +378,7 @@ class PlatformCameraUpdateZoomBy { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomBy || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomBy || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -432,8 +414,7 @@ class PlatformCameraUpdateZoom { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoom || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoom || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -469,8 +450,7 @@ class PlatformCameraUpdateZoomTo { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraUpdateZoomTo || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraUpdateZoomTo || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1255,14 +1235,7 @@ class PlatformTileOverlay { int tileSize; List _toList() { - return [ - tileOverlayId, - fadeIn, - transparency, - zIndex, - visible, - tileSize, - ]; + return [tileOverlayId, fadeIn, transparency, zIndex, visible, tileSize]; } Object encode() { @@ -1368,10 +1341,7 @@ class PlatformLatLng { static PlatformLatLng decode(Object result) { result as List; - return PlatformLatLng( - latitude: result[0]! as double, - longitude: result[1]! as double, - ); + return PlatformLatLng(latitude: result[0]! as double, longitude: result[1]! as double); } @override @@ -1451,16 +1421,13 @@ class PlatformCameraTargetBounds { static PlatformCameraTargetBounds decode(Object result) { result as List; - return PlatformCameraTargetBounds( - bounds: result[0] as PlatformLatLngBounds?, - ); + return PlatformCameraTargetBounds(bounds: result[0] as PlatformLatLngBounds?); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformCameraTargetBounds || - other.runtimeType != runtimeType) { + if (other is! PlatformCameraTargetBounds || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1630,20 +1597,16 @@ class PlatformMapViewCreationParams { initialPolygons: (result[4] as List?)!.cast(), initialPolylines: (result[5] as List?)!.cast(), initialHeatmaps: (result[6] as List?)!.cast(), - initialTileOverlays: (result[7] as List?)! - .cast(), - initialClusterManagers: (result[8] as List?)! - .cast(), - initialGroundOverlays: (result[9] as List?)! - .cast(), + initialTileOverlays: (result[7] as List?)!.cast(), + initialClusterManagers: (result[8] as List?)!.cast(), + initialGroundOverlays: (result[9] as List?)!.cast(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapViewCreationParams || - other.runtimeType != runtimeType) { + if (other is! PlatformMapViewCreationParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1770,8 +1733,7 @@ class PlatformMapConfiguration { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformMapConfiguration || - other.runtimeType != runtimeType) { + if (other is! PlatformMapConfiguration || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1841,10 +1803,7 @@ class PlatformSize { static PlatformSize decode(Object result) { result as List; - return PlatformSize( - width: result[0]! as double, - height: result[1]! as double, - ); + return PlatformSize(width: result[0]! as double, height: result[1]! as double); } @override @@ -1866,12 +1825,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); double red; @@ -1986,10 +1940,7 @@ class PlatformZoomRange { static PlatformZoomRange decode(Object result) { result as List; - return PlatformZoomRange( - min: result[0] as double?, - max: result[1] as double?, - ); + return PlatformZoomRange(min: result[0] as double?, max: result[1] as double?); } @override @@ -2076,8 +2027,7 @@ class PlatformBitmapDefaultMarker { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapDefaultMarker || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapDefaultMarker || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2109,10 +2059,7 @@ class PlatformBitmapBytes { static PlatformBitmapBytes decode(Object result) { result as List; - return PlatformBitmapBytes( - byteData: result[0]! as Uint8List, - size: result[1] as PlatformSize?, - ); + return PlatformBitmapBytes(byteData: result[0]! as Uint8List, size: result[1] as PlatformSize?); } @override @@ -2150,10 +2097,7 @@ class PlatformBitmapAsset { static PlatformBitmapAsset decode(Object result) { result as List; - return PlatformBitmapAsset( - name: result[0]! as String, - pkg: result[1] as String?, - ); + return PlatformBitmapAsset(name: result[0]! as String, pkg: result[1] as String?); } @override @@ -2175,11 +2119,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); String name; @@ -2207,8 +2147,7 @@ class PlatformBitmapAssetImage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBitmapAssetImage || - other.runtimeType != runtimeType) { + if (other is! PlatformBitmapAssetImage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -2568,9 +2507,7 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PlatformMapType.values[value]; case 130: final value = readValue(buffer) as int?; - return value == null - ? null - : PlatformMarkerCollisionBehavior.values[value]; + return value == null ? null : PlatformMarkerCollisionBehavior.values[value]; case 131: final value = readValue(buffer) as int?; return value == null ? null : PlatformJointType.values[value]; @@ -2721,9 +2658,7 @@ class MapsApi { /// /// Only non-null configuration values will result in updates; options with /// null values will remain unchanged. - Future updateMapConfiguration( - PlatformMapConfiguration configuration, - ) async { + Future updateMapConfiguration(PlatformMapConfiguration configuration) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.updateMapConfiguration$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2731,9 +2666,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [configuration], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([configuration]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2761,9 +2694,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2791,9 +2726,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2820,9 +2757,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2850,9 +2788,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2880,9 +2820,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2910,9 +2852,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2940,9 +2884,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2970,9 +2916,11 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [toAdd, toChange, idsToRemove], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + toAdd, + toChange, + idsToRemove, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2996,9 +2944,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [latLng], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([latLng]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3027,9 +2973,9 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [screenCoordinate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + screenCoordinate, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3088,9 +3034,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([cameraUpdate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3107,10 +3051,7 @@ class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. - Future animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ) async { + Future animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsApi.animateCamera$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3118,9 +3059,10 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [cameraUpdate, durationMilliseconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + cameraUpdate, + durationMilliseconds, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3173,9 +3115,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3199,9 +3139,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3226,9 +3164,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [markerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([markerId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3261,9 +3197,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [style], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([style]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3315,9 +3249,7 @@ class MapsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3436,20 +3368,14 @@ abstract class MapsCallbackApi { void onGroundOverlayTap(String groundOverlayId); /// Called to get data for a map tile. - Future getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + Future getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); static void setUp( MapsCallbackApi? api, { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMoveStarted$messageChannelSuffix', @@ -3488,8 +3414,7 @@ abstract class MapsCallbackApi { 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null.', ); final List args = (message as List?)!; - final PlatformCameraPosition? arg_cameraPosition = - (args[0] as PlatformCameraPosition?); + final PlatformCameraPosition? arg_cameraPosition = (args[0] as PlatformCameraPosition?); assert( arg_cameraPosition != null, 'Argument for dev.flutter.pigeon.google_maps_flutter_ios.MapsCallbackApi.onCameraMove was null, expected non-null PlatformCameraPosition.', @@ -3998,13 +3923,11 @@ class MapsPlatformViewApi { /// Constructor for [MapsPlatformViewApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsPlatformViewApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsPlatformViewApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4019,9 +3942,7 @@ class MapsPlatformViewApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [type], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([type]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4042,13 +3963,11 @@ class MapsInspectorApi { /// Constructor for [MapsInspectorApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MapsInspectorApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MapsInspectorApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -4287,9 +4206,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [tileOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([tileOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4304,9 +4221,7 @@ class MapsInspectorApi { } } - Future getGroundOverlayInfo( - String groundOverlayId, - ) async { + Future getGroundOverlayInfo(String groundOverlayId) async { final pigeonVar_channelName = 'dev.flutter.pigeon.google_maps_flutter_ios.MapsInspectorApi.getGroundOverlayInfo$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4314,9 +4229,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [groundOverlayId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([groundOverlayId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4339,9 +4252,7 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [heatmapId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([heatmapId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4392,9 +4303,9 @@ class MapsInspectorApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [clusterManagerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + clusterManagerId, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4410,8 +4321,7 @@ class MapsInspectorApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/pigeons/messages.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/pigeons/messages.dart index 66e475c54232..a04e857d05fc 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/pigeons/messages.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/pigeons/messages.dart @@ -510,12 +510,7 @@ class PlatformSize { /// Pigeon representation of a color. class PlatformColor { - PlatformColor({ - required this.red, - required this.green, - required this.blue, - required this.alpha, - }); + PlatformColor({required this.red, required this.green, required this.blue, required this.alpha}); final double red; final double green; @@ -587,11 +582,7 @@ class PlatformBitmapAsset { /// Pigeon equivalent of [AssetImageBitmap]. class PlatformBitmapAssetImage { - PlatformBitmapAssetImage({ - required this.name, - required this.scale, - this.size, - }); + PlatformBitmapAssetImage({required this.name, required this.scale, this.size}); final String name; final double scale; final PlatformSize? size; @@ -685,10 +676,7 @@ abstract class MapsApi { /// Updates the set of custer managers for clusters on the map. @ObjCSelector('updateClusterManagersByAdding:removing:') - void updateClusterManagers( - List toAdd, - List idsToRemove, - ); + void updateClusterManagers(List toAdd, List idsToRemove); /// Updates the set of markers on the map. @ObjCSelector('updateMarkersByAdding:changing:removing:') @@ -750,10 +738,7 @@ abstract class MapsApi { /// Moves the camera according to [cameraUpdate], animating the update using a /// duration in milliseconds if provided. @ObjCSelector('animateCameraWithUpdate:duration:') - void animateCamera( - PlatformCameraUpdate cameraUpdate, - int? durationMilliseconds, - ); + void animateCamera(PlatformCameraUpdate cameraUpdate, int? durationMilliseconds); /// Gets the current map zoom level. @ObjCSelector('currentZoomLevel') @@ -866,11 +851,7 @@ abstract class MapsCallbackApi { /// Called to get data for a map tile. @async @ObjCSelector('tileWithOverlayIdentifier:location:zoom:') - PlatformTile getTileOverlayTile( - String tileOverlayId, - PlatformPoint location, - int zoom, - ); + PlatformTile getTileOverlayTile(String tileOverlayId, PlatformPoint location, int zoom); } /// Dummy interface to force generation of the platform view creation params, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.dart index 486884bc81d1..c2fa99cac0dd 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.dart @@ -43,28 +43,18 @@ void main() { test('getScreenCoordinate converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const latLng = LatLng(10, 20); const expectedCoord = ScreenCoordinate(x: 30, y: 40); when(api.getScreenCoordinate(any)).thenAnswer( - (_) async => PlatformPoint( - x: expectedCoord.x.toDouble(), - y: expectedCoord.y.toDouble(), - ), + (_) async => PlatformPoint(x: expectedCoord.x.toDouble(), y: expectedCoord.y.toDouble()), ); - final ScreenCoordinate coord = await maps.getScreenCoordinate( - latLng, - mapId: mapId, - ); + final ScreenCoordinate coord = await maps.getScreenCoordinate(latLng, mapId: mapId); expect(coord, expectedCoord); - final VerificationResult verification = verify( - api.getScreenCoordinate(captureAny), - ); + final VerificationResult verification = verify(api.getScreenCoordinate(captureAny)); final passedLatLng = verification.captured[0] as PlatformLatLng; expect(passedLatLng.latitude, latLng.latitude); expect(passedLatLng.longitude, latLng.longitude); @@ -72,18 +62,14 @@ void main() { test('getLatLng converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. const expectedLatLng = LatLng(10, 20); const coord = ScreenCoordinate(x: 30, y: 40); when(api.getLatLng(any)).thenAnswer( - (_) async => PlatformLatLng( - latitude: expectedLatLng.latitude, - longitude: expectedLatLng.longitude, - ), + (_) async => + PlatformLatLng(latitude: expectedLatLng.latitude, longitude: expectedLatLng.longitude), ); final LatLng latLng = await maps.getLatLng(coord, mapId: mapId); @@ -96,9 +82,7 @@ void main() { test('getVisibleRegion converts and passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Arbitrary values that are all different from each other. final expectedBounds = LatLngBounds( @@ -124,9 +108,7 @@ void main() { test('moveCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.moveCamera(update, mapId: mapId); @@ -141,16 +123,12 @@ void main() { test('animateCamera calls through with expected scrollBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); await maps.animateCamera(update, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -161,24 +139,14 @@ void main() { test('animateCameraWithConfiguration calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.scrollBy(10, 20); - const configuration = CameraUpdateAnimationConfiguration( - duration: Duration(seconds: 1), - ); + const configuration = CameraUpdateAnimationConfiguration(duration: Duration(seconds: 1)); expect(configuration.duration?.inSeconds, 1); - await maps.animateCameraWithConfiguration( - update, - configuration, - mapId: mapId, - ); + await maps.animateCameraWithConfiguration(update, configuration, mapId: mapId); - final VerificationResult verification = verify( - api.animateCamera(captureAny, captureAny), - ); + final VerificationResult verification = verify(api.animateCamera(captureAny, captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; final scroll = passedUpdate.cameraUpdate as PlatformCameraUpdateScrollBy; update as CameraUpdateScrollBy; @@ -191,9 +159,7 @@ void main() { test('getZoomLevel passes values correctly', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const expectedZoom = 4.2; when(api.getZoomLevel()).thenAnswer((_) async => expectedZoom); @@ -204,9 +170,7 @@ void main() { test('showInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.showMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -216,9 +180,7 @@ void main() { test('hideInfoWindow calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; await maps.hideMarkerInfoWindow(const MarkerId(markedId), mapId: mapId); @@ -228,27 +190,17 @@ void main() { test('isInfoWindowShown calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const markedId = 'a_marker'; when(api.isInfoWindowShown(markedId)).thenAnswer((_) async => true); - expect( - await maps.isMarkerInfoWindowShown( - const MarkerId(markedId), - mapId: mapId, - ), - true, - ); + expect(await maps.isMarkerInfoWindowShown(const MarkerId(markedId), mapId: mapId), true); }); test('takeSnapshot calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final fakeSnapshot = Uint8List(10); when(api.takeSnapshot()).thenAnswer((_) async => fakeSnapshot); @@ -258,9 +210,7 @@ void main() { test('clearTileCache calls through', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const tileOverlayId = 'overlay'; await maps.clearTileCache(const TileOverlayId(tileOverlayId), mapId: mapId); @@ -270,16 +220,11 @@ void main() { test('updateMapConfiguration passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = MapConfiguration( compassEnabled: true, @@ -288,9 +233,7 @@ void main() { ); await maps.updateMapConfiguration(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -319,16 +262,11 @@ void main() { test('updateMapOptions passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); // Set some arbitrary options. final cameraBounds = CameraTargetBounds( - LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), ); final config = { 'compassEnabled': true, @@ -337,9 +275,7 @@ void main() { }; await maps.updateMapOptions(config, mapId: mapId); - final VerificationResult verification = verify( - api.updateMapConfiguration(captureAny), - ); + final VerificationResult verification = verify(api.updateMapConfiguration(captureAny)); final passedConfig = verification.captured[0] as PlatformMapConfiguration; // Each set option should be present. expect(passedConfig.compassEnabled, true); @@ -368,19 +304,14 @@ void main() { test('updateCircles passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Circle(circleId: CircleId('1')); const object2old = Circle(circleId: CircleId('2')); final Circle object2new = object2old.copyWith(radiusParam: 42); const object3 = Circle(circleId: CircleId('3')); await maps.updateCircles( - CircleUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + CircleUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -427,17 +358,12 @@ void main() { test('updateClusterManagers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = ClusterManager(clusterManagerId: ClusterManagerId('1')); const object3 = ClusterManager(clusterManagerId: ClusterManagerId('3')); await maps.updateClusterManagers( - ClusterManagerUpdates.from( - {object1}, - {object3}, - ), + ClusterManagerUpdates.from({object1}, {object3}), mapId: mapId, ); @@ -458,19 +384,14 @@ void main() { test('updateMarkers passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Marker(markerId: MarkerId('1')); const object2old = Marker(markerId: MarkerId('2')); final Marker object2new = object2old.copyWith(rotationParam: 42); const object3 = Marker(markerId: MarkerId('3')); await maps.updateMarkers( - MarkerUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + MarkerUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -495,9 +416,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -523,9 +442,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -543,21 +460,17 @@ void main() { test('updateMarkers passes expected arguments (AdvancedMarkers)', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final object1 = AdvancedMarker(markerId: const MarkerId('1')); final object2old = AdvancedMarker(markerId: const MarkerId('2')); final AdvancedMarker object2new = object2old.copyWith( rotationParam: 42, - collisionBehaviorParam: - advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, + collisionBehaviorParam: advanced_marker.MarkerCollisionBehavior.optionalAndHidesLowerPriority, ); final object3 = AdvancedMarker( markerId: const MarkerId('3'), - collisionBehavior: - advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, + collisionBehavior: advanced_marker.MarkerCollisionBehavior.requiredAndHidesOptional, ); await maps.updateMarkers( MarkerUpdates.from( @@ -588,9 +501,7 @@ void main() { expect(firstChanged.flat, object2new.flat); expect( firstChanged.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object2new.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object2new.icon).bitmap.runtimeType, ); expect(firstChanged.infoWindow.title, object2new.infoWindow.title); expect(firstChanged.infoWindow.snippet, object2new.infoWindow.snippet); @@ -622,9 +533,7 @@ void main() { expect(firstAdded.flat, object3.flat); expect( firstAdded.icon.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.icon, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.icon).bitmap.runtimeType, ); expect(firstAdded.infoWindow.title, object3.infoWindow.title); expect(firstAdded.infoWindow.snippet, object3.infoWindow.snippet); @@ -648,19 +557,14 @@ void main() { test('updatePolygons passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polygon(polygonId: PolygonId('1')); const object2old = Polygon(polygonId: PolygonId('2')); final Polygon object2new = object2old.copyWith(strokeWidthParam: 42); const object3 = Polygon(polygonId: PolygonId('3')); await maps.updatePolygons( - PolygonUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolygonUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -707,9 +611,7 @@ void main() { test('updatePolylines passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = Polyline(polylineId: PolylineId('1')); const object2old = Polyline(polylineId: PolylineId('2')); @@ -718,20 +620,14 @@ void main() { startCapParam: Cap.squareCap, endCapParam: Cap.buttCap, ); - final Cap customCap = Cap.customCapFromBitmap( - BitmapDescriptor.defaultMarker, - refWidth: 15, - ); + final Cap customCap = Cap.customCapFromBitmap(BitmapDescriptor.defaultMarker, refWidth: 15); final object3 = Polyline( polylineId: const PolylineId('3'), startCap: customCap, endCap: Cap.roundCap, ); await maps.updatePolylines( - PolylineUpdates.from( - {object1, object2old}, - {object2new, object3}, - ), + PolylineUpdates.from({object1, object2old}, {object2new, object3}), mapId: mapId, ); @@ -746,10 +642,7 @@ void main() { expect(actual.consumesTapEvents, expected.consumeTapEvents); _expectColorsEqual(actual.color, expected.color); expect(actual.geodesic, expected.geodesic); - expect( - actual.jointType, - platformJointTypeFromJointType(expected.jointType), - ); + expect(actual.jointType, platformJointTypeFromJointType(expected.jointType)); expect(actual.visible, expected.visible); expect(actual.width, expected.width); expect(actual.zIndex, expected.zIndex); @@ -759,8 +652,7 @@ void main() { expect(point?.longitude, actual.points[i].longitude); } expect(actual.patterns.length, expected.patterns.length); - for (final (int i, PlatformPatternItem? pattern) - in actual.patterns.indexed) { + for (final (int i, PlatformPatternItem? pattern) in actual.patterns.indexed) { expect( pattern?.encode(), platformPatternItemFromPatternItem(expected.patterns[i]).encode(), @@ -781,9 +673,7 @@ void main() { test('updateTileOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const object1 = TileOverlay(tileOverlayId: TileOverlayId('1')); const object2old = TileOverlay(tileOverlayId: TileOverlayId('2')); @@ -830,9 +720,7 @@ void main() { test('updateGroundOverlays passes expected arguments', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final image = AssetMapBitmap( 'assets/red_square.png', @@ -842,18 +730,12 @@ void main() { final object1 = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('1'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final object2old = GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('2'), - bounds: LatLngBounds( - southwest: const LatLng(10, 20), - northeast: const LatLng(30, 40), - ), + bounds: LatLngBounds(southwest: const LatLng(10, 20), northeast: const LatLng(30, 40)), image: image, ); final GroundOverlay object2new = object2old.copyWith( @@ -895,22 +777,10 @@ void main() { expect(firstChanged.anchor?.x, object2new.anchor?.dx); expect(firstChanged.anchor?.y, object2new.anchor?.dy); expect(firstChanged.bearing, object2new.bearing); - expect( - firstChanged.bounds?.northeast.latitude, - object2new.bounds?.northeast.latitude, - ); - expect( - firstChanged.bounds?.northeast.longitude, - object2new.bounds?.northeast.longitude, - ); - expect( - firstChanged.bounds?.southwest.latitude, - object2new.bounds?.southwest.latitude, - ); - expect( - firstChanged.bounds?.southwest.longitude, - object2new.bounds?.southwest.longitude, - ); + expect(firstChanged.bounds?.northeast.latitude, object2new.bounds?.northeast.latitude); + expect(firstChanged.bounds?.northeast.longitude, object2new.bounds?.northeast.longitude); + expect(firstChanged.bounds?.southwest.latitude, object2new.bounds?.southwest.latitude); + expect(firstChanged.bounds?.southwest.longitude, object2new.bounds?.southwest.longitude); expect(firstChanged.visible, object2new.visible); expect(firstChanged.clickable, object2new.clickable); expect(firstChanged.zIndex, object2new.zIndex); @@ -932,22 +802,10 @@ void main() { expect(firstAdded.anchor?.x, object3.anchor?.dx); expect(firstAdded.anchor?.y, object3.anchor?.dy); expect(firstAdded.bearing, object3.bearing); - expect( - firstAdded.bounds?.northeast.latitude, - object3.bounds?.northeast.latitude, - ); - expect( - firstAdded.bounds?.northeast.longitude, - object3.bounds?.northeast.longitude, - ); - expect( - firstAdded.bounds?.southwest.latitude, - object3.bounds?.southwest.latitude, - ); - expect( - firstAdded.bounds?.southwest.longitude, - object3.bounds?.southwest.longitude, - ); + expect(firstAdded.bounds?.northeast.latitude, object3.bounds?.northeast.latitude); + expect(firstAdded.bounds?.northeast.longitude, object3.bounds?.northeast.longitude); + expect(firstAdded.bounds?.southwest.latitude, object3.bounds?.southwest.latitude); + expect(firstAdded.bounds?.southwest.longitude, object3.bounds?.southwest.longitude); expect(firstAdded.visible, object3.visible); expect(firstAdded.clickable, object3.clickable); expect(firstAdded.zIndex, object3.zIndex); @@ -957,48 +815,39 @@ void main() { expect(firstAdded.transparency, object3.transparency); expect( firstAdded.image.bitmap.runtimeType, - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( - object3.image, - ).bitmap.runtimeType, + GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(object3.image).bitmap.runtimeType, ); } }); - test( - 'updateGroundOverlays throws assertion error on unsupported ground overlays', - () async { - const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + test('updateGroundOverlays throws assertion error on unsupported ground overlays', () async { + const mapId = 1; + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); - final image = AssetMapBitmap( - 'assets/red_square.png', - imagePixelRatio: 1.0, - bitmapScaling: MapBitmapScaling.none, - ); + final image = AssetMapBitmap( + 'assets/red_square.png', + imagePixelRatio: 1.0, + bitmapScaling: MapBitmapScaling.none, + ); - final object3 = GroundOverlay.fromPosition( - groundOverlayId: const GroundOverlayId('1'), - position: const LatLng(10, 20), - // Assert should be thrown because zoomLevel is not set for position-based - // ground overlay on iOS. - // ignore: avoid_redundant_argument_values - zoomLevel: null, - image: image, - ); + final object3 = GroundOverlay.fromPosition( + groundOverlayId: const GroundOverlayId('1'), + position: const LatLng(10, 20), + // Assert should be thrown because zoomLevel is not set for position-based + // ground overlay on iOS. + // ignore: avoid_redundant_argument_values + zoomLevel: null, + image: image, + ); - expect( - () async => maps.updateGroundOverlays( - GroundOverlayUpdates.from(const {}, { - object3, - }), - mapId: mapId, - ), - throwsAssertionError, - ); - }, - ); + expect( + () async => maps.updateGroundOverlays( + GroundOverlayUpdates.from(const {}, {object3}), + mapId: mapId, + ), + throwsAssertionError, + ); + }); test('markers send drag event to correct streams', () async { const mapId = 1; @@ -1008,19 +857,13 @@ void main() { final fakePosition = PlatformLatLng(latitude: 1.0, longitude: 1.0); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final markerDragStartStream = StreamQueue( maps.onMarkerDragStart(mapId: mapId), ); - final markerDragStream = StreamQueue( - maps.onMarkerDrag(mapId: mapId), - ); - final markerDragEndStream = StreamQueue( - maps.onMarkerDragEnd(mapId: mapId), - ); + final markerDragStream = StreamQueue(maps.onMarkerDrag(mapId: mapId)); + final markerDragEndStream = StreamQueue(maps.onMarkerDragEnd(mapId: mapId)); // Simulate messages from the native side. callbackHandler.onMarkerDragStart(dragStartId, fakePosition); @@ -1037,9 +880,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onMarkerTap(mapId: mapId)); @@ -1054,9 +895,7 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); final stream = StreamQueue(maps.onCircleTap(mapId: mapId)); @@ -1083,13 +922,9 @@ void main() { ); final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onClusterTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onClusterTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onClusterTap(cluster); @@ -1099,15 +934,9 @@ void main() { expect(eventValue.position.latitude, fakePosition.latitude); expect(eventValue.position.longitude, fakePosition.longitude); expect(eventValue.bounds.southwest.latitude, fakeBounds.southwest.latitude); - expect( - eventValue.bounds.southwest.longitude, - fakeBounds.southwest.longitude, - ); + expect(eventValue.bounds.southwest.longitude, fakeBounds.southwest.longitude); expect(eventValue.bounds.northeast.latitude, fakeBounds.northeast.latitude); - expect( - eventValue.bounds.northeast.longitude, - fakeBounds.northeast.longitude, - ); + expect(eventValue.bounds.northeast.longitude, fakeBounds.northeast.longitude); expect(eventValue.markerIds.length, markerIds.length); expect(eventValue.markerIds.first.value, markerIds.first); }); @@ -1117,13 +946,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolygonTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolygonTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolygonTap(objectId); @@ -1136,13 +961,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onPolylineTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onPolylineTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onPolylineTap(objectId); @@ -1155,13 +976,9 @@ void main() { const objectId = 'object-id'; final maps = GoogleMapsFlutterIOS(); - final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized( - mapId, - ); + final HostMapMessageHandler callbackHandler = maps.ensureHandlerInitialized(mapId); - final stream = StreamQueue( - maps.onGroundOverlayTap(mapId: mapId), - ); + final stream = StreamQueue(maps.onGroundOverlayTap(mapId: mapId)); // Simulate message from the native side. callbackHandler.onGroundOverlayTap(objectId); @@ -1171,9 +988,7 @@ void main() { test('moveCamera calls through with expected newCameraPosition', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); const position = CameraPosition(target: latLng); @@ -1182,24 +997,15 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewCameraPosition; update as CameraUpdateNewCameraPosition; - expect( - typedUpdate.cameraPosition.target.latitude, - update.cameraPosition.target.latitude, - ); - expect( - typedUpdate.cameraPosition.target.longitude, - update.cameraPosition.target.longitude, - ); + expect(typedUpdate.cameraPosition.target.latitude, update.cameraPosition.target.latitude); + expect(typedUpdate.cameraPosition.target.longitude, update.cameraPosition.target.longitude); }); test('moveCamera calls through with expected newLatLng', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLng(latLng); @@ -1207,8 +1013,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLng; update as CameraUpdateNewLatLng; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1216,9 +1021,7 @@ void main() { test('moveCamera calls through with expected newLatLngBounds', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final latLng = LatLngBounds( northeast: const LatLng(10.0, 20.0), @@ -1229,33 +1032,18 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngBounds; update as CameraUpdateNewLatLngBounds; - expect( - typedUpdate.bounds.northeast.latitude, - update.bounds.northeast.latitude, - ); - expect( - typedUpdate.bounds.northeast.longitude, - update.bounds.northeast.longitude, - ); - expect( - typedUpdate.bounds.southwest.latitude, - update.bounds.southwest.latitude, - ); - expect( - typedUpdate.bounds.southwest.longitude, - update.bounds.southwest.longitude, - ); + expect(typedUpdate.bounds.northeast.latitude, update.bounds.northeast.latitude); + expect(typedUpdate.bounds.northeast.longitude, update.bounds.northeast.longitude); + expect(typedUpdate.bounds.southwest.latitude, update.bounds.southwest.latitude); + expect(typedUpdate.bounds.southwest.longitude, update.bounds.southwest.longitude); expect(typedUpdate.padding, update.padding); }); test('moveCamera calls through with expected newLatLngZoom', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const latLng = LatLng(10.0, 20.0); final CameraUpdate update = CameraUpdate.newLatLngZoom(latLng, 2.0); @@ -1263,8 +1051,7 @@ void main() { final VerificationResult verification = verify(api.moveCamera(captureAny)); final passedUpdate = verification.captured[0] as PlatformCameraUpdate; - final typedUpdate = - passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; + final typedUpdate = passedUpdate.cameraUpdate as PlatformCameraUpdateNewLatLngZoom; update as CameraUpdateNewLatLngZoom; expect(typedUpdate.latLng.latitude, update.latLng.latitude); expect(typedUpdate.latLng.longitude, update.latLng.longitude); @@ -1273,9 +1060,7 @@ void main() { test('moveCamera calls through with expected zoomBy', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); const focus = Offset(10.0, 20.0); final CameraUpdate update = CameraUpdate.zoomBy(2.0, focus); @@ -1292,9 +1077,7 @@ void main() { test('moveCamera calls through with expected zoomTo', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomTo(2.0); await maps.moveCamera(update, mapId: mapId); @@ -1308,9 +1091,7 @@ void main() { test('moveCamera calls through with expected zoomIn', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomIn(); await maps.moveCamera(update, mapId: mapId); @@ -1323,9 +1104,7 @@ void main() { test('moveCamera calls through with expected zoomOut', () async { const mapId = 1; - final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap( - mapId: mapId, - ); + final (GoogleMapsFlutterIOS maps, MockMapsApi api) = setUpMockMap(mapId: mapId); final CameraUpdate update = CameraUpdate.zoomOut(); await maps.moveCamera(update, mapId: mapId); @@ -1338,23 +1117,20 @@ void main() { test('MapBitmapScaling to PlatformMapBitmapScaling', () { expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.auto, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.auto), PlatformMapBitmapScaling.auto, ); expect( - GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling( - MapBitmapScaling.none, - ), + GoogleMapsFlutterIOS.platformMapBitmapScalingFromScaling(MapBitmapScaling.none), PlatformMapBitmapScaling.none, ); }); test('DefaultMarker bitmap to PlatformBitmap', () { final BitmapDescriptor bitmap = BitmapDescriptor.defaultMarkerWithHue(10.0); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapDefaultMarker; expect(typedBitmap.hue, 10.0); @@ -1368,8 +1144,9 @@ void main() { width: 100.0, height: 200.0, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, + ); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapBytesMap; expect(typedBitmap.byteData, data); @@ -1381,14 +1158,10 @@ void main() { test('AssetMapBitmap bitmap to PlatformBitmap', () { const assetName = 'fake_asset_name'; - final bitmap = AssetMapBitmap( - assetName, - imagePixelRatio: 2.0, - width: 100.0, - height: 200.0, + final bitmap = AssetMapBitmap(assetName, imagePixelRatio: 2.0, width: 100.0, height: 200.0); + final PlatformBitmap platformBitmap = GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor( + bitmap, ); - final PlatformBitmap platformBitmap = - GoogleMapsFlutterIOS.platformBitmapFromBitmapDescriptor(bitmap); expect(platformBitmap.bitmap, isA()); final typedBitmap = platformBitmap.bitmap as PlatformBitmapAssetMap; expect(typedBitmap.assetName, assetName); @@ -1402,31 +1175,28 @@ void main() { const cloudMapId = '000000000000000'; // Dummy map ID. final passedCloudMapIdCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null) { - final String? passedMapId = - creationParams.mapConfiguration.mapId; - if (passedMapId != null) { - passedCloudMapIdCompleter.complete(passedMapId); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null) { + final String? passedMapId = creationParams.mapConfiguration.mapId; + if (passedMapId != null) { + passedCloudMapIdCompleter.complete(passedMapId); } } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1437,10 +1207,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: const MapConfiguration(mapId: cloudMapId), @@ -1462,30 +1229,25 @@ void main() { ) async { final passedMarkerTypeCompleter = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform_views, ( - MethodCall methodCall, - ) { - if (methodCall.method == 'create') { - final args = Map.from( - methodCall.arguments as Map, - ); - if (args.containsKey('params')) { - final paramsUint8List = args['params'] as Uint8List; - final byteData = ByteData.sublistView(paramsUint8List); - final creationParams = - MapsApi.pigeonChannelCodec.decodeMessage(byteData) - as PlatformMapViewCreationParams?; - if (creationParams != null && - !passedMarkerTypeCompleter.isCompleted) { - passedMarkerTypeCompleter.complete( - creationParams.mapConfiguration.markerType, - ); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (MethodCall methodCall) { + if (methodCall.method == 'create') { + final args = Map.from(methodCall.arguments as Map); + if (args.containsKey('params')) { + final paramsUint8List = args['params'] as Uint8List; + final byteData = ByteData.sublistView(paramsUint8List); + final creationParams = MapsApi.pigeonChannelCodec.decodeMessage( + byteData, + ) as PlatformMapViewCreationParams?; + if (creationParams != null && !passedMarkerTypeCompleter.isCompleted) { + passedMarkerTypeCompleter.complete(creationParams.mapConfiguration.markerType); } } - return null; - }); + } + return null; + }, + ); final maps = GoogleMapsFlutterIOS(); @@ -1496,10 +1258,7 @@ void main() { 1, (int id) {}, widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: CameraPosition( - target: LatLng(0, 0), - zoom: 1, - ), + initialCameraPosition: CameraPosition(target: LatLng(0, 0), zoom: 1), textDirection: TextDirection.ltr, ), mapConfiguration: MapConfiguration(markerType: markerType), @@ -1513,11 +1272,10 @@ void main() { testWidgets('passes advancedMarker when MarkerType.advancedMarker is set', ( WidgetTester tester, ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams( - tester, - MarkerType.advancedMarker, - ); + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.advancedMarker, + ); expect( passedMarkerType, @@ -1527,31 +1285,29 @@ void main() { ); }); - testWidgets('passes marker when MarkerType.marker is set', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, MarkerType.marker); + testWidgets('passes marker when MarkerType.marker is set', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + MarkerType.marker, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should pass marker on PlatformView creation when MarkerType.marker is set', + reason: 'Should pass marker on PlatformView creation when MarkerType.marker is set', ); }); - testWidgets('passes marker when markerType is null', ( - WidgetTester tester, - ) async { - final PlatformMarkerType passedMarkerType = - await getMarkerTypeFromCreationParams(tester, null); + testWidgets('passes marker when markerType is null', (WidgetTester tester) async { + final PlatformMarkerType passedMarkerType = await getMarkerTypeFromCreationParams( + tester, + null, + ); expect( passedMarkerType, PlatformMarkerType.marker, - reason: - 'Should default to marker on PlatformView creation when markerType is null', + reason: 'Should default to marker on PlatformView creation when markerType is null', ); }); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.mocks.dart index e4ff2b78e188..a386c6d1e16e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/test/google_maps_flutter_ios_test.mocks.dart @@ -29,14 +29,12 @@ class _FakePlatformPoint_0 extends _i1.SmartFake implements _i2.PlatformPoint { : super(parent, parentInvocation); } -class _FakePlatformLatLng_1 extends _i1.SmartFake - implements _i2.PlatformLatLng { +class _FakePlatformLatLng_1 extends _i1.SmartFake implements _i2.PlatformLatLng { _FakePlatformLatLng_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePlatformLatLngBounds_2 extends _i1.SmartFake - implements _i2.PlatformLatLngBounds { +class _FakePlatformLatLngBounds_2 extends _i1.SmartFake implements _i2.PlatformLatLngBounds { _FakePlatformLatLngBounds_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -46,315 +44,229 @@ class _FakePlatformLatLngBounds_2 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockMapsApi extends _i1.Mock implements _i2.MapsApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future waitForMap() => - (super.noSuchMethod( - Invocation.method(#waitForMap, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future waitForMap() => (super.noSuchMethod( + Invocation.method(#waitForMap, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future updateMapConfiguration( - _i2.PlatformMapConfiguration? configuration, - ) => + _i4.Future updateMapConfiguration(_i2.PlatformMapConfiguration? configuration) => (super.noSuchMethod( - Invocation.method(#updateMapConfiguration, [configuration]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#updateMapConfiguration, [configuration]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateCircles( List<_i2.PlatformCircle>? toAdd, List<_i2.PlatformCircle>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateCircles, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateHeatmaps( List<_i2.PlatformHeatmap>? toAdd, List<_i2.PlatformHeatmap>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateHeatmaps, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateClusterManagers( List<_i2.PlatformClusterManager>? toAdd, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateClusterManagers, [toAdd, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateMarkers( List<_i2.PlatformMarker>? toAdd, List<_i2.PlatformMarker>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateMarkers, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolygons( List<_i2.PlatformPolygon>? toAdd, List<_i2.PlatformPolygon>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolygons, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updatePolylines( List<_i2.PlatformPolyline>? toAdd, List<_i2.PlatformPolyline>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updatePolylines, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateTileOverlays( List<_i2.PlatformTileOverlay>? toAdd, List<_i2.PlatformTileOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateTileOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateTileOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future updateGroundOverlays( List<_i2.PlatformGroundOverlay>? toAdd, List<_i2.PlatformGroundOverlay>? toChange, List? idsToRemove, - ) => - (super.noSuchMethod( - Invocation.method(#updateGroundOverlays, [ - toAdd, - toChange, - idsToRemove, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#updateGroundOverlays, [toAdd, toChange, idsToRemove]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformPoint> getScreenCoordinate( - _i2.PlatformLatLng? latLng, - ) => + _i4.Future<_i2.PlatformPoint> getScreenCoordinate(_i2.PlatformLatLng? latLng) => (super.noSuchMethod( - Invocation.method(#getScreenCoordinate, [latLng]), - returnValue: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( - _FakePlatformPoint_0( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - ) - as _i4.Future<_i2.PlatformPoint>); + Invocation.method(#getScreenCoordinate, [latLng]), + returnValue: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformPoint>.value( + _FakePlatformPoint_0(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + ) as _i4.Future<_i2.PlatformPoint>); @override - _i4.Future<_i2.PlatformLatLng> getLatLng( - _i2.PlatformPoint? screenCoordinate, - ) => + _i4.Future<_i2.PlatformLatLng> getLatLng(_i2.PlatformPoint? screenCoordinate) => (super.noSuchMethod( - Invocation.method(#getLatLng, [screenCoordinate]), - returnValue: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( - _FakePlatformLatLng_1( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLng>); + Invocation.method(#getLatLng, [screenCoordinate]), + returnValue: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLng>.value( + _FakePlatformLatLng_1(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + ) as _i4.Future<_i2.PlatformLatLng>); @override - _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => - (super.noSuchMethod( - Invocation.method(#getVisibleRegion, []), - returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformLatLngBounds>.value( - _FakePlatformLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - ) - as _i4.Future<_i2.PlatformLatLngBounds>); + _i4.Future<_i2.PlatformLatLngBounds> getVisibleRegion() => (super.noSuchMethod( + Invocation.method(#getVisibleRegion, []), + returnValue: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformLatLngBounds>.value( + _FakePlatformLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + ) as _i4.Future<_i2.PlatformLatLngBounds>); @override - _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => - (super.noSuchMethod( - Invocation.method(#moveCamera, [cameraUpdate]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future moveCamera(_i2.PlatformCameraUpdate? cameraUpdate) => (super.noSuchMethod( + Invocation.method(#moveCamera, [cameraUpdate]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future animateCamera( _i2.PlatformCameraUpdate? cameraUpdate, int? durationMilliseconds, - ) => - (super.noSuchMethod( - Invocation.method(#animateCamera, [ - cameraUpdate, - durationMilliseconds, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + ) => (super.noSuchMethod( + Invocation.method(#animateCamera, [cameraUpdate, durationMilliseconds]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getZoomLevel, []), - returnValue: _i4.Future.value(0.0), - returnValueForMissingStub: _i4.Future.value(0.0), - ) - as _i4.Future); + _i4.Future getZoomLevel() => (super.noSuchMethod( + Invocation.method(#getZoomLevel, []), + returnValue: _i4.Future.value(0.0), + returnValueForMissingStub: _i4.Future.value(0.0), + ) as _i4.Future); @override - _i4.Future showInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#showInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future showInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#showInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future hideInfoWindow(String? markerId) => - (super.noSuchMethod( - Invocation.method(#hideInfoWindow, [markerId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future hideInfoWindow(String? markerId) => (super.noSuchMethod( + Invocation.method(#hideInfoWindow, [markerId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future isInfoWindowShown(String? markerId) => - (super.noSuchMethod( - Invocation.method(#isInfoWindowShown, [markerId]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isInfoWindowShown(String? markerId) => (super.noSuchMethod( + Invocation.method(#isInfoWindowShown, [markerId]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future setStyle(String? style) => - (super.noSuchMethod( - Invocation.method(#setStyle, [style]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setStyle(String? style) => (super.noSuchMethod( + Invocation.method(#setStyle, [style]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future getLastStyleError() => - (super.noSuchMethod( - Invocation.method(#getLastStyleError, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getLastStyleError() => (super.noSuchMethod( + Invocation.method(#getLastStyleError, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future clearTileCache(String? tileOverlayId) => - (super.noSuchMethod( - Invocation.method(#clearTileCache, [tileOverlayId]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future clearTileCache(String? tileOverlayId) => (super.noSuchMethod( + Invocation.method(#clearTileCache, [tileOverlayId]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i5.Uint8List?> takeSnapshot() => - (super.noSuchMethod( - Invocation.method(#takeSnapshot, []), - returnValue: _i4.Future<_i5.Uint8List?>.value(), - returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), - ) - as _i4.Future<_i5.Uint8List?>); + _i4.Future<_i5.Uint8List?> takeSnapshot() => (super.noSuchMethod( + Invocation.method(#takeSnapshot, []), + returnValue: _i4.Future<_i5.Uint8List?>.value(), + returnValueForMissingStub: _i4.Future<_i5.Uint8List?>.value(), + ) as _i4.Future<_i5.Uint8List?>); @override - _i4.Future isAdvancedMarkersAvailable() => - (super.noSuchMethod( - Invocation.method(#isAdvancedMarkersAvailable, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isAdvancedMarkersAvailable() => (super.noSuchMethod( + Invocation.method(#isAdvancedMarkersAvailable, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); } diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/run_tests.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/run_tests.dart index f49c29eaf7fe..af88ecc57b9c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/run_tests.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/run_tests.dart @@ -25,9 +25,7 @@ Future main(List args) async { exit(0); } - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); final sharedSourceRoot = Directory( p.join(packageRoot.parent.path, 'google_maps_flutter_ios_shared_code'), @@ -129,16 +127,11 @@ Future _validatePackageSharedCode( required bool log, }) async { var hasDiffs = false; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/sync_shared_files.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/sync_shared_files.dart index fbbd50d0a499..8711068a5604 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/sync_shared_files.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/sync_shared_files.dart @@ -18,23 +18,15 @@ import 'utils.dart'; const String _sharedSourceRootName = 'google_maps_flutter_ios_shared_code'; Future main(List args) async { - final Directory packageRoot = Directory( - p.dirname(Platform.script.path), - ).parent; + final Directory packageRoot = Directory(p.dirname(Platform.script.path)).parent; final String packageName = p.basename(packageRoot.path); - final sharedSourceRoot = Directory( - p.join(packageRoot.parent.path, _sharedSourceRootName), - ); + final sharedSourceRoot = Directory(p.join(packageRoot.parent.path, _sharedSourceRootName)); _syncSharedFiles(packageRoot, packageName, sharedSourceRoot); _reportUnsharedFiles(packageRoot, packageName, sharedSourceRoot); } -void _syncSharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _syncSharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List otherImplementationPackages = sharedSourceRoot.parent .listSync() .whereType() @@ -49,16 +41,11 @@ void _syncSharedFiles( final copiedFiles = []; final missingFiles = []; - for (final FileSystemEntity entity in sharedSourceRoot.listSync( - recursive: true, - )) { + for (final FileSystemEntity entity in sharedSourceRoot.listSync(recursive: true)) { if (entity is! File) { continue; } - final String relativePath = p.relative( - entity.path, - from: sharedSourceRoot.path, - ); + final String relativePath = p.relative(entity.path, from: sharedSourceRoot.path); // The shared source README.md is not part of the shared source of truth, // just an explanation of this source-sharing system. if (relativePath == 'README.md') { @@ -88,10 +75,7 @@ void _syncSharedFiles( final String otherPackagePath = p.join( packageRoot.parent.path, otherPackageName, - packageRelativePathForSharedSourceRelativePath( - otherPackageName, - relativePath, - ), + packageRelativePathForSharedSourceRelativePath(otherPackageName, relativePath), ); _syncFile(packageFile, otherPackagePath, otherPackageName); } @@ -105,9 +89,7 @@ void _syncSharedFiles( } } if (missingFiles.isNotEmpty) { - print( - 'This package is missing the following files from the shared source:', - ); + print('This package is missing the following files from the shared source:'); for (final file in missingFiles) { print(' $file'); } @@ -123,11 +105,7 @@ void _syncSharedFiles( /// If the file needs special handling of package names that appear within the /// contents of the file, it will update the package name in the file to match /// the destination package name. -void _syncFile( - File source, - String destinationPath, - String destinationPackageName, -) { +void _syncFile(File source, String destinationPath, String destinationPackageName) { source.copySync(destinationPath); if ([ // The Pigeon definition file has output paths that must use the @@ -136,10 +114,7 @@ void _syncFile( // The mock needs to import the package. '.mocks.dart', ].any((pattern) => source.absolute.path.contains(pattern))) { - updatePackageNameInPathReferences( - File(destinationPath), - destinationPackageName, - ); + updatePackageNameInPathReferences(File(destinationPath), destinationPackageName); } // Native unit tests need to import the Swift package. if (source.absolute.path.contains('/RunnerTests/')) { @@ -147,11 +122,7 @@ void _syncFile( } } -void _reportUnsharedFiles( - Directory packageRoot, - String packageName, - Directory sharedSourceRoot, -) { +void _reportUnsharedFiles(Directory packageRoot, String packageName, Directory sharedSourceRoot) { final List unsharedFiles = unexpectedUnsharedSourceFiles( packageRoot, packageName, diff --git a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/utils.dart b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/utils.dart index c4b2b9b83433..fc75925d7304 100644 --- a/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/utils.dart +++ b/packages/google_maps_flutter/google_maps_flutter_ios_shared_code/tool/utils.dart @@ -21,10 +21,7 @@ List unexpectedUnsharedSourceFiles( .listSync(recursive: true) .whereType() // Only report code files. - .where( - (file) => - ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith), - ) + .where((file) => ['.swift', '.m', '.h', '.dart'].any(file.path.endsWith)) // Flutter-generated files aren't expected to be shared. .where((file) => !file.path.contains('GeneratedPluginRegistrant')) // Ignore intermediate file directories. @@ -64,10 +61,7 @@ String packageRelativePathForSharedSourceRelativePath( String packageName, String sharedSourceRelativePath, ) { - return sharedSourceRelativePath.replaceAll( - '/google_maps_flutter_ios/', - '/$packageName/', - ); + return sharedSourceRelativePath.replaceAll('/google_maps_flutter_ios/', '/$packageName/'); } /// Returns the contents of the file with any differences caused only by the @@ -76,10 +70,7 @@ String normalizedFileContents(File file) { return file .readAsStringSync() // Ignore differences caused only by the package name. - .replaceAll( - RegExp(r'google_maps_flutter_ios_[\w\d]+'), - 'google_maps_flutter_ios', - ) + .replaceAll(RegExp(r'google_maps_flutter_ios_[\w\d]+'), 'google_maps_flutter_ios') // Package name diffs could change line wrapping, so collapse whitespace. .replaceAll(RegExp(r'[\s\n]+'), ' ') .trim(); @@ -106,10 +97,7 @@ void updatePackageNameInPathReferences(File file, String packageName) { /// package by name. void updatePackageNameInImports(File file, String packageName) { final String newContents = file.readAsStringSync().replaceAllMapped( - RegExp( - r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', - multiLine: true, - ), + RegExp(r'^(@?)import google_maps_flutter_ios[_\w\d]*(;?)$', multiLine: true), (match) => '${match.group(1)}import $packageName${match.group(2)}', ); file.writeAsStringSync(newContents); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart index f9ad5d8def7b..19ec79818ab9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/method_channel_google_maps_flutter.dart @@ -71,9 +71,7 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { MethodChannel? channel = _channels[mapId]; if (channel == null) { channel = MethodChannel('plugins.flutter.io/google_maps_$mapId'); - channel.setMethodCallHandler( - (MethodCall call) => _handleMethodCall(call, mapId), - ); + channel.setMethodCallHandler((MethodCall call) => _handleMethodCall(call, mapId)); _channels[mapId] = channel; } return channel; @@ -99,9 +97,8 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { StreamController>.broadcast(); // Returns a filtered view of the events in the _controller, by mapId. - Stream> _events(int mapId) => _mapEventStreamController - .stream - .where((MapEvent event) => event.mapId == mapId); + Stream> _events(int mapId) => + _mapEventStreamController.stream.where((MapEvent event) => event.mapId == mapId); @override Stream onCameraMoveStarted({required int mapId}) { @@ -180,10 +177,7 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { case 'camera#onMove': final Map arguments = _getArgumentDictionary(call); _mapEventStreamController.add( - CameraMoveEvent( - mapId, - CameraPosition.fromMap(arguments['position'])!, - ), + CameraMoveEvent(mapId, CameraPosition.fromMap(arguments['position'])!), ); case 'camera#onIdle': _mapEventStreamController.add(CameraIdleEvent(mapId)); @@ -227,10 +221,7 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { case 'polyline#onTap': final Map arguments = _getArgumentDictionary(call); _mapEventStreamController.add( - PolylineTapEvent( - mapId, - PolylineId(arguments['polylineId']! as String), - ), + PolylineTapEvent(mapId, PolylineId(arguments['polylineId']! as String)), ); case 'polygon#onTap': final Map arguments = _getArgumentDictionary(call); @@ -244,9 +235,7 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { ); case 'map#onTap': final Map arguments = _getArgumentDictionary(call); - _mapEventStreamController.add( - MapTapEvent(mapId, LatLng.fromJson(arguments['position'])!), - ); + _mapEventStreamController.add(MapTapEvent(mapId, LatLng.fromJson(arguments['position'])!)); case 'map#onLongPress': final Map arguments = _getArgumentDictionary(call); _mapEventStreamController.add( @@ -254,11 +243,9 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { ); case 'tileOverlay#getTile': final Map arguments = _getArgumentDictionary(call); - final Map? tileOverlaysForThisMap = - _tileOverlays[mapId]; + final Map? tileOverlaysForThisMap = _tileOverlays[mapId]; final tileOverlayId = arguments['tileOverlayId']! as String; - final TileOverlay? tileOverlay = - tileOverlaysForThisMap?[TileOverlayId(tileOverlayId)]; + final TileOverlay? tileOverlay = tileOverlaysForThisMap?[TileOverlayId(tileOverlayId)]; final TileProvider? tileProvider = tileOverlay?.tileProvider; if (tileProvider == null) { return TileProvider.noTile.toJson(); @@ -271,17 +258,13 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { return tile.toJson(); case 'cluster#onTap': final Map arguments = _getArgumentDictionary(call); - final clusterManagerId = ClusterManagerId( - arguments['clusterManagerId']! as String, - ); + final clusterManagerId = ClusterManagerId(arguments['clusterManagerId']! as String); final LatLng position = LatLng.fromJson(arguments['position'])!; final Map> latLngData = (arguments['bounds']! as Map).map( - (dynamic key, dynamic object) => MapEntry>( - key as String, - object as List, - ), + (dynamic key, dynamic object) => + MapEntry>(key as String, object as List), ); final bounds = LatLngBounds( @@ -289,20 +272,14 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { southwest: LatLng.fromJson(latLngData['southwest'])!, ); - final List markerIds = - (arguments['markerIds']! as List) - .map((dynamic markerId) => MarkerId(markerId as String)) - .toList(); + final List markerIds = (arguments['markerIds']! as List) + .map((dynamic markerId) => MarkerId(markerId as String)) + .toList(); _mapEventStreamController.add( ClusterTapEvent( mapId, - Cluster( - clusterManagerId, - markerIds, - position: position, - bounds: bounds, - ), + Cluster(clusterManagerId, markerIds, position: position, bounds: bounds), ), ); default: @@ -319,60 +296,34 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { } @override - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) { - return channel(mapId).invokeMethod('map#update', { - 'options': optionsUpdate, - }); + Future updateMapOptions(Map optionsUpdate, {required int mapId}) { + return channel( + mapId, + ).invokeMethod('map#update', {'options': optionsUpdate}); } @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) { - return channel( - mapId, - ).invokeMethod('markers#update', markerUpdates.toJson()); + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) { + return channel(mapId).invokeMethod('markers#update', markerUpdates.toJson()); } @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) { - return channel( - mapId, - ).invokeMethod('polygons#update', polygonUpdates.toJson()); + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) { + return channel(mapId).invokeMethod('polygons#update', polygonUpdates.toJson()); } @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) { - return channel( - mapId, - ).invokeMethod('polylines#update', polylineUpdates.toJson()); + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) { + return channel(mapId).invokeMethod('polylines#update', polylineUpdates.toJson()); } @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) { - return channel( - mapId, - ).invokeMethod('circles#update', circleUpdates.toJson()); + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) { + return channel(mapId).invokeMethod('circles#update', circleUpdates.toJson()); } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) { return channel(mapId).invokeMethod( 'heatmaps#update', serializeMapsObjectUpdates(heatmapUpdates, serializeHeatmap), @@ -380,20 +331,14 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { } @override - Future updateTileOverlays({ - required Set newTileOverlays, - required int mapId, - }) { - final Map? currentTileOverlays = - _tileOverlays[mapId]; + Future updateTileOverlays({required Set newTileOverlays, required int mapId}) { + final Map? currentTileOverlays = _tileOverlays[mapId]; final Set previousSet = currentTileOverlays != null ? currentTileOverlays.values.toSet() : {}; final updates = TileOverlayUpdates.from(previousSet, newTileOverlays); _tileOverlays[mapId] = keyTileOverlayId(newTileOverlays); - return channel( - mapId, - ).invokeMethod('tileOverlays#update', updates.toJson()); + return channel(mapId).invokeMethod('tileOverlays#update', updates.toJson()); } @override @@ -401,35 +346,30 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { ClusterManagerUpdates clusterManagerUpdates, { required int mapId, }) { - return channel(mapId).invokeMethod( - 'clusterManagers#update', - clusterManagerUpdates.toJson(), - ); + return channel( + mapId, + ).invokeMethod('clusterManagers#update', clusterManagerUpdates.toJson()); } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) { - return channel(mapId).invokeMethod( - 'tileOverlays#clearTileCache', - {'tileOverlayId': tileOverlayId.value}, - ); + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) { + return channel(mapId).invokeMethod('tileOverlays#clearTileCache', { + 'tileOverlayId': tileOverlayId.value, + }); } @override Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) { - return channel(mapId).invokeMethod('camera#animate', { - 'cameraUpdate': cameraUpdate.toJson(), - }); + return channel( + mapId, + ).invokeMethod('camera#animate', {'cameraUpdate': cameraUpdate.toJson()}); } @override Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) { - return channel(mapId).invokeMethod('camera#move', { - 'cameraUpdate': cameraUpdate.toJson(), - }); + return channel( + mapId, + ).invokeMethod('camera#move', {'cameraUpdate': cameraUpdate.toJson()}); } @override @@ -455,24 +395,16 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { } @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) async { - final Map point = (await channel(mapId) - .invokeMapMethod( - 'map#getScreenCoordinate', - latLng.toJson(), - ))!; + Future getScreenCoordinate(LatLng latLng, {required int mapId}) async { + final Map point = (await channel( + mapId, + ).invokeMapMethod('map#getScreenCoordinate', latLng.toJson()))!; return ScreenCoordinate(x: point['x']!, y: point['y']!); } @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) async { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) async { final List latLng = (await channel( mapId, ).invokeMethod>('map#getLatLng', screenCoordinate.toJson()))!; @@ -481,29 +413,23 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { @override Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) { - return channel(mapId).invokeMethod( - 'markers#showInfoWindow', - {'markerId': markerId.value}, - ); + return channel( + mapId, + ).invokeMethod('markers#showInfoWindow', {'markerId': markerId.value}); } @override Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) { - return channel(mapId).invokeMethod( - 'markers#hideInfoWindow', - {'markerId': markerId.value}, - ); + return channel( + mapId, + ).invokeMethod('markers#hideInfoWindow', {'markerId': markerId.value}); } @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { - return (await channel(mapId).invokeMethod( - 'markers#isInfoWindowShown', - {'markerId': markerId.value}, - ))!; + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { + return (await channel(mapId).invokeMethod('markers#isInfoWindowShown', { + 'markerId': markerId.value, + }))!; } @override @@ -538,8 +464,7 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { Map mapOptions = const {}, }) { final creationParams = { - 'initialCameraPosition': widgetConfiguration.initialCameraPosition - .toMap(), + 'initialCameraPosition': widgetConfiguration.initialCameraPosition.toMap(), 'options': mapOptions, 'markersToAdd': serializeMarkerSet(mapObjects.markers), 'polygonsToAdd': serializePolygonSet(mapObjects.polygons), @@ -553,14 +478,13 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { if (useAndroidViewSurface) { return PlatformViewLink( viewType: 'plugins.flutter.io/google_maps', - surfaceFactory: - (BuildContext context, PlatformViewController controller) { - return AndroidViewSurface( - controller: controller as AndroidViewController, - gestureRecognizers: widgetConfiguration.gestureRecognizers, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - ); - }, + surfaceFactory: (BuildContext context, PlatformViewController controller) { + return AndroidViewSurface( + controller: controller as AndroidViewController, + gestureRecognizers: widgetConfiguration.gestureRecognizers, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + ); + }, onCreatePlatformView: (PlatformViewCreationParams params) { final SurfaceAndroidViewController controller = PlatformViewsService.initSurfaceAndroidView( @@ -571,9 +495,7 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { creationParamsCodec: const StandardMessageCodec(), onFocus: () => params.onFocusChanged(true), ); - controller.addOnPlatformViewCreatedListener( - params.onPlatformViewCreated, - ); + controller.addOnPlatformViewCreatedListener(params.onPlatformViewCreated); controller.addOnPlatformViewCreatedListener(onPlatformViewCreated); controller.create(); @@ -599,9 +521,7 @@ class MethodChannelGoogleMapsFlutter extends GoogleMapsFlutterPlatform { ); } - return Text( - '$defaultTargetPlatform is not yet supported by the maps plugin', - ); + return Text('$defaultTargetPlatform is not yet supported by the maps plugin'); } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart index 8b3b6317b4e6..204b9150b967 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/method_channel/serialization.dart @@ -47,9 +47,7 @@ Object serializeMapsObjectUpdates>( _addIfNonNull( json, _objectIdsToRemoveKey(updates.objectName), - updates.objectIdsToRemove - .map((MapsObjectId m) => m.value) - .toList(), + updates.objectIdsToRemove.map((MapsObjectId m) => m.value).toList(), ); return json; @@ -60,34 +58,18 @@ Object serializeHeatmap(Heatmap heatmap) { final json = {}; _addIfNonNull(json, _heatmapIdKey, heatmap.heatmapId.value); - _addIfNonNull( - json, - _heatmapDataKey, - heatmap.data.map(serializeWeightedLatLng).toList(), - ); + _addIfNonNull(json, _heatmapDataKey, heatmap.data.map(serializeWeightedLatLng).toList()); _addIfNonNull(json, _heatmapDissipatingKey, heatmap.dissipating); final HeatmapGradient? gradient = heatmap.gradient; if (gradient != null) { - _addIfNonNull( - json, - _heatmapGradientKey, - serializeHeatmapGradient(gradient), - ); + _addIfNonNull(json, _heatmapGradientKey, serializeHeatmapGradient(gradient)); } _addIfNonNull(json, _heatmapMaxIntensityKey, heatmap.maxIntensity); _addIfNonNull(json, _heatmapOpacityKey, heatmap.opacity); _addIfNonNull(json, _heatmapRadiusKey, heatmap.radius.radius); - _addIfNonNull( - json, - _heatmapMinimumZoomIntensityKey, - heatmap.minimumZoomIntensity, - ); - _addIfNonNull( - json, - _heatmapMaximumZoomIntensityKey, - heatmap.maximumZoomIntensity, - ); + _addIfNonNull(json, _heatmapMinimumZoomIntensityKey, heatmap.minimumZoomIntensity); + _addIfNonNull(json, _heatmapMaximumZoomIntensityKey, heatmap.maximumZoomIntensity); return json; } @@ -130,9 +112,7 @@ Object serializeHeatmapGradient(HeatmapGradient gradient) { _addIfNonNull( json, _heatmapGradientColorsKey, - gradient.colors - .map((HeatmapGradientColor e) => e.color.toARGB32()) - .toList(), + gradient.colors.map((HeatmapGradientColor e) => e.color.toARGB32()).toList(), ); _addIfNonNull( json, @@ -155,10 +135,9 @@ HeatmapGradient? deserializeHeatmapGradient(Object? json) { .whereType() .map((int e) => Color(e)) .toList(); - final List startPoints = - (map[_heatmapGradientStartPointsKey]! as List) - .whereType() - .toList(); + final List startPoints = (map[_heatmapGradientStartPointsKey]! as List) + .whereType() + .toList(); final gradientColors = []; for (var i = 0; i < colors.length; i++) { gradientColors.add(HeatmapGradientColor(colors[i], startPoints[i])); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_flutter_platform.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_flutter_platform.dart index 06920d3ea741..4ca64f66a8c6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_flutter_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_flutter_platform.dart @@ -56,10 +56,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// /// The returned [Future] completes after listeners have been notified. @Deprecated('Use updateMapConfiguration instead.') - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) { + Future updateMapOptions(Map optionsUpdate, {required int mapId}) { throw UnimplementedError('updateMapOptions() has not been implemented.'); } @@ -69,14 +66,8 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future updateMapConfiguration( - MapConfiguration configuration, { - required int mapId, - }) { - return updateMapOptions( - jsonForMapConfiguration(configuration), - mapId: mapId, - ); + Future updateMapConfiguration(MapConfiguration configuration, {required int mapId}) { + return updateMapOptions(jsonForMapConfiguration(configuration), mapId: mapId); } /// Updates marker configuration. @@ -85,10 +76,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) { throw UnimplementedError('updateMarkers() has not been implemented.'); } @@ -98,10 +86,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) { throw UnimplementedError('updatePolygons() has not been implemented.'); } @@ -111,10 +96,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) { throw UnimplementedError('updatePolylines() has not been implemented.'); } @@ -124,10 +106,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) { throw UnimplementedError('updateCircles() has not been implemented.'); } @@ -137,10 +116,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) { throw UnimplementedError('updateHeatmaps() has not been implemented.'); } @@ -150,10 +126,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// platform side. /// /// The returned [Future] completes after listeners have been notified. - Future updateTileOverlays({ - required Set newTileOverlays, - required int mapId, - }) { + Future updateTileOverlays({required Set newTileOverlays, required int mapId}) { throw UnimplementedError('updateTileOverlays() has not been implemented.'); } @@ -167,9 +140,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { ClusterManagerUpdates clusterManagerUpdates, { required int mapId, }) { - throw UnimplementedError( - 'updateClusterManagers() has not been implemented.', - ); + throw UnimplementedError('updateClusterManagers() has not been implemented.'); } /// Updates ground overlay configuration. @@ -180,9 +151,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { GroundOverlayUpdates groundOverlayUpdates, { required int mapId, }) { - throw UnimplementedError( - 'updateGroundOverlays() has not been implemented.', - ); + throw UnimplementedError('updateGroundOverlays() has not been implemented.'); } /// Clears the tile cache so that all tiles will be requested again from the @@ -192,10 +161,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// cleared from the map after calling this method. The Google Maps SDK maintains a small /// in-memory cache of tiles. If you want to cache tiles for longer, you /// should implement an on-disk cache. - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) { throw UnimplementedError('clearTileCache() has not been implemented.'); } @@ -252,10 +218,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// A projection is used to translate between on screen location and geographic coordinates. /// Screen location is in screen pixels (not display pixels) with respect to the top left corner /// of the map, not necessarily of the whole screen. - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) { throw UnimplementedError('getScreenCoordinate() has not been implemented.'); } @@ -264,10 +227,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// A projection is used to translate between on screen location and geographic coordinates. /// Screen location is in screen pixels (not display pixels) with respect to the top left corner /// of the map, not necessarily of the whole screen. - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) { throw UnimplementedError('getLatLng() has not been implemented.'); } @@ -280,9 +240,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// * [hideMarkerInfoWindow] to hide the Info Window. /// * [isMarkerInfoWindowShown] to check if the Info Window is showing. Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) { - throw UnimplementedError( - 'showMarkerInfoWindow() has not been implemented.', - ); + throw UnimplementedError('showMarkerInfoWindow() has not been implemented.'); } /// Programmatically hide the Info Window for a [Marker]. @@ -294,9 +252,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// * [showMarkerInfoWindow] to show the Info Window. /// * [isMarkerInfoWindowShown] to check if the Info Window is showing. Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) { - throw UnimplementedError( - 'hideMarkerInfoWindow() has not been implemented.', - ); + throw UnimplementedError('hideMarkerInfoWindow() has not been implemented.'); } /// Returns `true` when the [InfoWindow] is showing, `false` otherwise. @@ -307,10 +263,7 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// * See also: /// * [showMarkerInfoWindow] to show the Info Window. /// * [hideMarkerInfoWindow] to hide the Info Window. - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) { throw UnimplementedError('updateMapOptions() has not been implemented.'); } @@ -504,8 +457,6 @@ abstract class GoogleMapsFlutterPlatform extends PlatformInterface { /// inspecting the platform map state. @visibleForTesting void enableDebugInspection() { - throw UnimplementedError( - 'enableDebugInspection() has not been implemented.', - ); + throw UnimplementedError('enableDebugInspection() has not been implemented.'); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart index 49dd73ec5a24..827b6295d560 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/platform_interface/google_maps_inspector_platform.dart @@ -61,9 +61,7 @@ abstract class GoogleMapsInspectorPlatform extends PlatformInterface { /// Returns true if the "my location" button is enabled. Future isMyLocationButtonEnabled({required int mapId}) { - throw UnimplementedError( - 'isMyLocationButtonEnabled() has not been implemented.', - ); + throw UnimplementedError('isMyLocationButtonEnabled() has not been implemented.'); } /// Returns true if the traffic overlay is enabled. @@ -78,37 +76,27 @@ abstract class GoogleMapsInspectorPlatform extends PlatformInterface { /// Returns true if rotate gestures are enabled. Future areRotateGesturesEnabled({required int mapId}) { - throw UnimplementedError( - 'areRotateGesturesEnabled() has not been implemented.', - ); + throw UnimplementedError('areRotateGesturesEnabled() has not been implemented.'); } /// Returns true if scroll gestures are enabled. Future areScrollGesturesEnabled({required int mapId}) { - throw UnimplementedError( - 'areScrollGesturesEnabled() has not been implemented.', - ); + throw UnimplementedError('areScrollGesturesEnabled() has not been implemented.'); } /// Returns true if tilt gestures are enabled. Future areTiltGesturesEnabled({required int mapId}) { - throw UnimplementedError( - 'areTiltGesturesEnabled() has not been implemented.', - ); + throw UnimplementedError('areTiltGesturesEnabled() has not been implemented.'); } /// Returns true if zoom controls are enabled. Future areZoomControlsEnabled({required int mapId}) { - throw UnimplementedError( - 'areZoomControlsEnabled() has not been implemented.', - ); + throw UnimplementedError('areZoomControlsEnabled() has not been implemented.'); } /// Returns true if zoom gestures are enabled. Future areZoomGesturesEnabled({required int mapId}) { - throw UnimplementedError( - 'areZoomGesturesEnabled() has not been implemented.', - ); + throw UnimplementedError('areZoomGesturesEnabled() has not been implemented.'); } /// Returns information about the tile overlay with the given ID. @@ -117,10 +105,7 @@ abstract class GoogleMapsInspectorPlatform extends PlatformInterface { /// be the same Dart object as the original [TileOverlay] provided to the /// platform interface with that ID, and not all fields (e.g., /// [TileOverlay.tileProvider]) will be populated. - Future getTileOverlayInfo( - TileOverlayId tileOverlayId, { - required int mapId, - }) { + Future getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) { throw UnimplementedError('getTileOverlayInfo() has not been implemented.'); } @@ -148,9 +133,7 @@ abstract class GoogleMapsInspectorPlatform extends PlatformInterface { GroundOverlayId groundOverlayId, { required int mapId, }) { - throw UnimplementedError( - 'getGroundOverlayInfo() has not been implemented.', - ); + throw UnimplementedError('getGroundOverlayInfo() has not been implemented.'); } /// Returns current clusters from [ClusterManager]. diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/advanced_marker.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/advanced_marker.dart index 7f818e9ebc77..278093c88139 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/advanced_marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/advanced_marker.dart @@ -109,8 +109,7 @@ class AdvancedMarker extends Marker { 'zIndex': zIndex, 'collisionBehavior': collisionBehavior.index, 'anchor': _offsetToJson(anchor), - if (clusterManagerIdValue != null) - 'clusterManagerId': clusterManagerIdValue, + if (clusterManagerIdValue != null) 'clusterManagerId': clusterManagerIdValue, }; } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart index 84aeaa6212d3..b483b9f5a683 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/bitmap.dart @@ -87,10 +87,7 @@ abstract class BitmapDescriptor { if (jsonList.length == 3) { assert(jsonList[2] != null && jsonList[2] is String); assert((jsonList[2] as String).isNotEmpty); - return AssetBitmap( - name: jsonList[1] as String, - package: jsonList[2] as String, - ); + return AssetBitmap(name: jsonList[1] as String, package: jsonList[2] as String); } return AssetBitmap(name: jsonList[1] as String); case _fromAssetImage: @@ -105,16 +102,10 @@ abstract class BitmapDescriptor { return AssetImageBitmap( name: jsonList[1] as String, scale: jsonList[2] as double, - size: Size( - (sizeList[0] as num).toDouble(), - (sizeList[1] as num).toDouble(), - ), + size: Size((sizeList[0] as num).toDouble(), (sizeList[1] as num).toDouble()), ); } - return AssetImageBitmap( - name: jsonList[1] as String, - scale: jsonList[2] as double, - ); + return AssetImageBitmap(name: jsonList[1] as String, scale: jsonList[2] as double); case AssetMapBitmap.type: assert(jsonList.length == 2); assert(jsonList[1] != null && jsonList[1] is Map); @@ -127,17 +118,11 @@ abstract class BitmapDescriptor { assert(jsonMap['imagePixelRatio'] is double); assert(!jsonMap.containsKey('width') || jsonMap['width'] is double); assert(!jsonMap.containsKey('height') || jsonMap['height'] is double); - final double? width = jsonMap.containsKey('width') - ? jsonMap['width'] as double - : null; - final double? height = jsonMap.containsKey('height') - ? jsonMap['height'] as double - : null; + final double? width = jsonMap.containsKey('width') ? jsonMap['width'] as double : null; + final double? height = jsonMap.containsKey('height') ? jsonMap['height'] as double : null; return AssetMapBitmap( jsonMap['assetName'] as String, - bitmapScaling: mapBitmapScalingFromString( - jsonMap['bitmapScaling'] as String, - ), + bitmapScaling: mapBitmapScalingFromString(jsonMap['bitmapScaling'] as String), imagePixelRatio: jsonMap['imagePixelRatio'] as double, width: width, height: height, @@ -154,17 +139,11 @@ abstract class BitmapDescriptor { assert(jsonMap['imagePixelRatio'] is double); assert(!jsonMap.containsKey('width') || jsonMap['width'] is double); assert(!jsonMap.containsKey('height') || jsonMap['height'] is double); - final double? width = jsonMap.containsKey('width') - ? jsonMap['width'] as double - : null; - final double? height = jsonMap.containsKey('height') - ? jsonMap['height'] as double - : null; + final double? width = jsonMap.containsKey('width') ? jsonMap['width'] as double : null; + final double? height = jsonMap.containsKey('height') ? jsonMap['height'] as double : null; return BytesMapBitmap( jsonMap['byteData'] as Uint8List, - bitmapScaling: mapBitmapScalingFromString( - jsonMap['bitmapScaling'] as String, - ), + bitmapScaling: mapBitmapScalingFromString(jsonMap['bitmapScaling'] as String), width: width, height: height, imagePixelRatio: jsonMap['imagePixelRatio'] as double, @@ -255,9 +234,7 @@ abstract class BitmapDescriptor { return AssetImageBitmap(name: assetName, scale: devicePixelRatio); } final assetImage = AssetImage(assetName, package: package, bundle: bundle); - final AssetBundleImageKey assetBundleImageKey = await assetImage.obtainKey( - configuration, - ); + final AssetBundleImageKey assetBundleImageKey = await assetImage.obtainKey(configuration); final Size? size = kIsWeb ? configuration.size : null; return AssetImageBitmap( name: assetBundleImageKey.name, @@ -274,10 +251,7 @@ abstract class BitmapDescriptor { /// `size` is not required (and ignored, if passed) in other platforms. @Deprecated('Use BitmapDescriptor.bytes method instead.') static BitmapDescriptor fromBytes(Uint8List byteData, {Size? size}) { - assert( - byteData.isNotEmpty, - 'Cannot create BitmapDescriptor with empty byteData', - ); + assert(byteData.isNotEmpty, 'Cannot create BitmapDescriptor with empty byteData'); return BytesBitmap(byteData: byteData, size: size); } @@ -374,11 +348,7 @@ abstract class BitmapDescriptor { Color? borderColor, AdvancedMarkerGlyph? glyph, }) { - return PinConfig( - backgroundColor: backgroundColor, - borderColor: borderColor, - glyph: glyph, - ); + return PinConfig(backgroundColor: backgroundColor, borderColor: borderColor, glyph: glyph); } /// Convert the object to a Json format. @@ -440,11 +410,7 @@ class AssetBitmap extends BitmapDescriptor { final String? package; @override - Object toJson() => [ - BitmapDescriptor._fromAsset, - name, - if (package != null) package!, - ]; + Object toJson() => [BitmapDescriptor._fromAsset, name, if (package != null) package!]; } /// A [BitmapDescriptor] from an asset image. @@ -456,8 +422,7 @@ class AssetImageBitmap extends BitmapDescriptor { /// This method takes into consideration various asset resolutions /// and scales the images to the right resolution depending on the dpi. @Deprecated('Use AssetMapBitmap instead') - const AssetImageBitmap({required this.name, required this.scale, this.size}) - : super._(); + const AssetImageBitmap({required this.name, required this.scale, this.size}) : super._(); /// Name of the image asset. final String name; @@ -504,12 +469,8 @@ class AssetImageBitmap extends BitmapDescriptor { /// ratio. These cases are similar to [BoxFit.fitWidth] and /// [BoxFit.fitHeight], respectively. abstract class MapBitmap extends BitmapDescriptor { - MapBitmap._({ - required this.bitmapScaling, - required this.imagePixelRatio, - this.width, - this.height, - }) : super._(); + MapBitmap._({required this.bitmapScaling, required this.imagePixelRatio, this.width, this.height}) + : super._(); /// The scaling method of the bitmap. final MapBitmapScaling bitmapScaling; @@ -703,10 +664,7 @@ class AssetMapBitmap extends MapBitmap { super.width, super.height, }) : assert(assetName.isNotEmpty, 'The asset name must not be empty.'), - assert( - imagePixelRatio > 0.0, - 'The imagePixelRatio must be greater than 0.', - ), + assert(imagePixelRatio > 0.0, 'The imagePixelRatio must be greater than 0.'), assert( bitmapScaling != MapBitmapScaling.none || width == null, 'If bitmapScaling is set to MapBitmapScaling.none, width parameter cannot be used.', @@ -811,9 +769,7 @@ class AssetMapBitmap extends MapBitmap { }) async { assert(assetName.isNotEmpty, 'The asset name must not be empty.'); final assetImage = AssetImage(assetName, package: package, bundle: bundle); - final AssetBundleImageKey assetBundleImageKey = await assetImage.obtainKey( - configuration, - ); + final AssetBundleImageKey assetBundleImageKey = await assetImage.obtainKey(configuration); return AssetMapBitmap._( assetName: assetBundleImageKey.name, @@ -983,10 +939,7 @@ class BytesMapBitmap extends MapBitmap { super.width, super.height, double? imagePixelRatio, - }) : assert( - byteData.isNotEmpty, - 'Cannot create BitmapDescriptor with empty byteData.', - ), + }) : assert(byteData.isNotEmpty, 'Cannot create BitmapDescriptor with empty byteData.'), assert( bitmapScaling != MapBitmapScaling.none || imagePixelRatio == null, 'If bitmapScaling is set to MapBitmapScaling.none, imagePixelRatio parameter cannot be used.', @@ -1111,8 +1064,7 @@ class PinConfig extends BitmapDescriptor { Object toJson() => [ type, { - if (backgroundColor != null) - 'backgroundColor': backgroundColor?.toARGB32(), + if (backgroundColor != null) 'backgroundColor': backgroundColor?.toARGB32(), if (borderColor != null) 'borderColor': borderColor?.toARGB32(), if (glyph != null) 'glyph': glyph?.toJson(), }, @@ -1147,10 +1099,7 @@ class BitmapGlyph extends AdvancedMarkerGlyph { /// [bitmap] is the image to be displayed in the center of the glyph. Must not /// be an [AdvancedMarkerGlyph]. const BitmapGlyph({required this.bitmap}) - : assert( - bitmap is! AdvancedMarkerGlyph, - 'BitmapDescriptor cannot be an AdvancedMarkerGlyph.', - ), + : assert(bitmap is! AdvancedMarkerGlyph, 'BitmapDescriptor cannot be an AdvancedMarkerGlyph.'), super._(); /// Bitmap image to be displayed in the center of the glyph. @@ -1178,10 +1127,7 @@ class TextGlyph extends AdvancedMarkerGlyph { Object toJson() { return [ 'textGlyph', - { - 'text': text, - if (textColor != null) 'textColor': textColor!.toARGB32(), - }, + {'text': text, if (textColor != null) 'textColor': textColor!.toARGB32()}, ]; } } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart index af6c5d0e45e1..b7c303103b8d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/camera.dart @@ -230,8 +230,7 @@ class CameraUpdateNewCameraPosition extends CameraUpdate { /// Defines a camera move to a latitude and longitude. class CameraUpdateNewLatLng extends CameraUpdate { /// Creates a camera move to latitude and longitude. - const CameraUpdateNewLatLng(this.latLng) - : super._(CameraUpdateType.newLatLng); + const CameraUpdateNewLatLng(this.latLng) : super._(CameraUpdateType.newLatLng); /// New latitude and longitude of the camera.. final LatLng latLng; @@ -257,8 +256,7 @@ class CameraUpdateNewLatLngBounds extends CameraUpdate { /// Defines a camera move to new coordinates with a zoom level. class CameraUpdateNewLatLngZoom extends CameraUpdate { /// Creates a camera move with coordinates and zoom level. - const CameraUpdateNewLatLngZoom(this.latLng, this.zoom) - : super._(CameraUpdateType.newLatLngZoom); + const CameraUpdateNewLatLngZoom(this.latLng, this.zoom) : super._(CameraUpdateType.newLatLngZoom); /// New coordinates of the camera. final LatLng latLng; @@ -272,8 +270,7 @@ class CameraUpdateNewLatLngZoom extends CameraUpdate { /// Defines a camera scroll by a certain delta. class CameraUpdateScrollBy extends CameraUpdate { /// Creates a camera scroll. - const CameraUpdateScrollBy(this.dx, this.dy) - : super._(CameraUpdateType.scrollBy); + const CameraUpdateScrollBy(this.dx, this.dy) : super._(CameraUpdateType.scrollBy); /// Scroll delta x. final double dx; @@ -287,8 +284,7 @@ class CameraUpdateScrollBy extends CameraUpdate { /// Defines a relative camera zoom. class CameraUpdateZoomBy extends CameraUpdate { /// Creates a relative camera zoom. - const CameraUpdateZoomBy(this.amount, [this.focus]) - : super._(CameraUpdateType.zoomBy); + const CameraUpdateZoomBy(this.amount, [this.focus]) : super._(CameraUpdateType.zoomBy); /// Change in camera zoom amount. final double amount; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cap.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cap.dart index 78402a1ea4f3..aeaa3bc32a3c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cap.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cap.dart @@ -68,10 +68,7 @@ class Cap { /// [refWidth] is the reference stroke width (in pixels) - the stroke width for which /// the cap bitmap at its native dimension is designed. Must be positive. Default value /// is 10 pixels. - static Cap customCapFromBitmap( - BitmapDescriptor bitmapDescriptor, { - double refWidth = 10, - }) { + static Cap customCapFromBitmap(BitmapDescriptor bitmapDescriptor, {double refWidth = 10}) { assert(refWidth > 0.0); return CustomCap(bitmapDescriptor, refWidth: refWidth); } @@ -93,8 +90,7 @@ class CustomCap extends Cap { /// [refWidth] is the reference stroke width (in pixels) - the stroke width for which /// the cap bitmap at its native dimension is designed. Must be positive. Default value /// is 10 pixels. - const CustomCap(this.bitmapDescriptor, {this.refWidth = 10}) - : super._(CapType.custom); + const CustomCap(this.bitmapDescriptor, {this.refWidth = 10}) : super._(CapType.custom); /// Bitmap overlay centered at the start or end vertex of a [Polyline]. final BitmapDescriptor bitmapDescriptor; @@ -104,9 +100,5 @@ class CustomCap extends Cap { final double refWidth; @override - Object toJson() => [ - _capTypeToJson(type), - bitmapDescriptor.toJson(), - refWidth, - ]; + Object toJson() => [_capTypeToJson(type), bitmapDescriptor.toJson(), refWidth]; } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart index a6d21835ca05..848dd07e0885 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/circle_updates.dart @@ -10,8 +10,7 @@ import 'types.dart'; // (Do not re-export) class CircleUpdates extends MapsObjectUpdates { /// Computes [CircleUpdates] given previous and current [Circle]s. - CircleUpdates.from(super.previous, super.current) - : super.from(objectName: 'circle'); + CircleUpdates.from(super.previous, super.current) : super.from(objectName: 'circle'); /// Set of Circles to be added in this update. Set get circlesToAdd => objectsToAdd; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster.dart index 6402d9304ebe..c34cc8d7fe81 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster.dart @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/foundation.dart' - show immutable, listEquals, objectRuntimeType; +import 'package:flutter/foundation.dart' show immutable, listEquals, objectRuntimeType; import 'types.dart'; /// A cluster containing multiple markers. @@ -47,6 +46,5 @@ class Cluster { } @override - int get hashCode => - Object.hash(clusterManagerId, position, bounds, markerIds); + int get hashCode => Object.hash(clusterManagerId, position, bounds, markerIds); } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager.dart index db6cc0e455e8..c283d14d0317 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager.dart @@ -63,8 +63,7 @@ class ClusterManager implements MapsObject { if (other.runtimeType != runtimeType) { return false; } - return other is ClusterManager && - clusterManagerId == other.clusterManagerId; + return other is ClusterManager && clusterManagerId == other.clusterManagerId; } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager_updates.dart index 9a83b5dab080..3cdf3a3ea78d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster_manager_updates.dart @@ -17,8 +17,7 @@ class ClusterManagerUpdates extends MapsObjectUpdates { Set get clusterManagersToAdd => objectsToAdd; /// Set of ClusterManagerIds to be removed in this update. - Set get clusterManagerIdsToRemove => - objectIdsToRemove.cast(); + Set get clusterManagerIdsToRemove => objectIdsToRemove.cast(); /// Set of Clusters to be changed in this update. Set get clusterManagersToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay.dart index 62d77a98c25e..b1c4bb4883b8 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay.dart @@ -324,10 +324,7 @@ class GroundOverlay implements MapsObject { addIfPresent('bounds', bounds?.toJson()); addIfPresent('width', width); addIfPresent('height', height); - addIfPresent( - 'anchor', - anchor != null ? [anchor!.dx, anchor!.dy] : null, - ); + addIfPresent('anchor', anchor != null ? [anchor!.dx, anchor!.dy] : null); addIfPresent('bearing', bearing); addIfPresent('transparency', transparency); addIfPresent('zIndex', zIndex); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay_updates.dart index fcb814083e73..7ee8f08aa40b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ground_overlay_updates.dart @@ -14,8 +14,7 @@ class GroundOverlayUpdates extends MapsObjectUpdates { Set get groundOverlaysToAdd => objectsToAdd; /// Set of GroundOverlayIds to be removed in this update. - Set get groundOverlayIdsToRemove => - objectIdsToRemove.cast(); + Set get groundOverlayIdsToRemove => objectIdsToRemove.cast(); /// Set of GroundOverlays to be changed in this update. Set get groundOverlaysToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap.dart index 88f33b8ab82e..06b94f3683f2 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap.dart @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/foundation.dart' - show immutable, listEquals, objectRuntimeType; +import 'package:flutter/foundation.dart' show immutable, listEquals, objectRuntimeType; import 'package:flutter/material.dart' show Color; import 'types.dart'; @@ -158,10 +157,8 @@ class Heatmap implements MapsObject { /// Creates a new [Heatmap] object whose values are the same as this /// instance. @override - Heatmap clone() => copyWith( - dataParam: List.of(data), - gradientParam: gradient?.clone(), - ); + Heatmap clone() => + copyWith(dataParam: List.of(data), gradientParam: gradient?.clone()); /// Converts this object to something serializable in JSON. @override @@ -237,9 +234,7 @@ class WeightedLatLng { @override bool operator ==(Object other) { - return other is WeightedLatLng && - other.point == point && - other.weight == weight; + return other is WeightedLatLng && other.point == point && other.weight == weight; } @override @@ -266,20 +261,13 @@ class HeatmapGradient { /// Creates a new [HeatmapGradient] object whose values are the same as this /// instance, unless overwritten by the specified parameters. - HeatmapGradient copyWith({ - List? colorsParam, - int? colorMapSizeParam, - }) { - return HeatmapGradient( - colorsParam ?? colors, - colorMapSize: colorMapSizeParam ?? colorMapSize, - ); + HeatmapGradient copyWith({List? colorsParam, int? colorMapSizeParam}) { + return HeatmapGradient(colorsParam ?? colors, colorMapSize: colorMapSizeParam ?? colorMapSize); } /// Creates a new [HeatmapGradient] object whose values are the same as this /// instance. - HeatmapGradient clone() => - copyWith(colorsParam: List.of(colors)); + HeatmapGradient clone() => copyWith(colorsParam: List.of(colors)); /// Converts this object to something serializable in JSON. Object toJson() { @@ -291,14 +279,8 @@ class HeatmapGradient { } } - addIfPresent( - 'colors', - colors.map((HeatmapGradientColor e) => e.color.toARGB32()).toList(), - ); - addIfPresent( - 'startPoints', - colors.map((HeatmapGradientColor e) => e.startPoint).toList(), - ); + addIfPresent('colors', colors.map((HeatmapGradientColor e) => e.color.toARGB32()).toList()); + addIfPresent('startPoints', colors.map((HeatmapGradientColor e) => e.startPoint).toList()); addIfPresent('colorMapSize', colorMapSize); return json; @@ -336,10 +318,7 @@ class HeatmapGradientColor { /// Creates a new [HeatmapGradientColor] object whose values are the same as /// this instance, unless overwritten by the specified parameters. HeatmapGradientColor copyWith({Color? colorParam, double? startPointParam}) { - return HeatmapGradientColor( - colorParam ?? color, - startPointParam ?? startPoint, - ); + return HeatmapGradientColor(colorParam ?? color, startPointParam ?? startPoint); } /// Creates a new [HeatmapGradientColor] object whose values are the same as @@ -354,9 +333,7 @@ class HeatmapGradientColor { if (other.runtimeType != runtimeType) { return false; } - return other is HeatmapGradientColor && - color == other.color && - startPoint == other.startPoint; + return other is HeatmapGradientColor && color == other.color && startPoint == other.startPoint; } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap_updates.dart index 1b288888f927..0bd745bcb2ee 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/heatmap_updates.dart @@ -10,8 +10,7 @@ import 'types.dart'; // (Do not re-export) class HeatmapUpdates extends MapsObjectUpdates { /// Computes [HeatmapUpdates] given previous and current [Heatmap]s. - HeatmapUpdates.from(super.previous, super.current) - : super.from(objectName: 'heatmap'); + HeatmapUpdates.from(super.previous, super.current) : super.from(objectName: 'heatmap'); /// Set of Heatmaps to be added in this update. Set get heatmapsToAdd => objectsToAdd; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart index 9c193950a3ac..a17492decf8a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/location.dart @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/foundation.dart' - show immutable, objectRuntimeType, visibleForTesting; +import 'package:flutter/foundation.dart' show immutable, objectRuntimeType, visibleForTesting; /// A pair of latitude and longitude coordinates, stored as degrees. @immutable @@ -44,14 +43,11 @@ class LatLng { } @override - String toString() => - '${objectRuntimeType(this, 'LatLng')}($latitude, $longitude)'; + String toString() => '${objectRuntimeType(this, 'LatLng')}($latitude, $longitude)'; @override bool operator ==(Object other) { - return other is LatLng && - other.latitude == latitude && - other.longitude == longitude; + return other is LatLng && other.latitude == latitude && other.longitude == longitude; } @override @@ -88,8 +84,7 @@ class LatLngBounds { /// Returns whether this rectangle contains the given [LatLng]. bool contains(LatLng point) { - return _containsLatitude(point.latitude) && - _containsLongitude(point.longitude); + return _containsLatitude(point.latitude) && _containsLongitude(point.longitude); } bool _containsLatitude(double lat) { @@ -112,10 +107,7 @@ class LatLngBounds { } assert(json is List && json.length == 2); final list = json as List; - return LatLngBounds( - southwest: LatLng.fromJson(list[0])!, - northeast: LatLng.fromJson(list[1])!, - ); + return LatLngBounds(southwest: LatLng.fromJson(list[0])!, northeast: LatLng.fromJson(list[1])!); } @override @@ -125,9 +117,7 @@ class LatLngBounds { @override bool operator ==(Object other) { - return other is LatLngBounds && - other.southwest == southwest && - other.northeast == northeast; + return other is LatLngBounds && other.southwest == southwest && other.northeast == northeast; } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart index c8d178575484..b1b13ec4a73d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart @@ -38,8 +38,7 @@ class MapConfiguration { this.trafficEnabled, this.buildingsEnabled, String? mapId, - @Deprecated('cloudMapId is deprecated. Use mapId instead.') - String? cloudMapId, + @Deprecated('cloudMapId is deprecated. Use mapId instead.') String? cloudMapId, this.style, this.markerType, this.colorScheme, @@ -162,23 +161,17 @@ class MapConfiguration { /// that are different from [other]. MapConfiguration diffFrom(MapConfiguration other) { return MapConfiguration( - webCameraControlPosition: - webCameraControlPosition != other.webCameraControlPosition + webCameraControlPosition: webCameraControlPosition != other.webCameraControlPosition ? webCameraControlPosition : null, - webCameraControlEnabled: - webCameraControlEnabled != other.webCameraControlEnabled + webCameraControlEnabled: webCameraControlEnabled != other.webCameraControlEnabled ? webCameraControlEnabled : null, webGestureHandling: webGestureHandling != other.webGestureHandling ? webGestureHandling : null, - compassEnabled: compassEnabled != other.compassEnabled - ? compassEnabled - : null, - mapToolbarEnabled: mapToolbarEnabled != other.mapToolbarEnabled - ? mapToolbarEnabled - : null, + compassEnabled: compassEnabled != other.compassEnabled ? compassEnabled : null, + mapToolbarEnabled: mapToolbarEnabled != other.mapToolbarEnabled ? mapToolbarEnabled : null, cameraTargetBounds: cameraTargetBounds != other.cameraTargetBounds ? cameraTargetBounds : null, @@ -186,12 +179,10 @@ class MapConfiguration { minMaxZoomPreference: minMaxZoomPreference != other.minMaxZoomPreference ? minMaxZoomPreference : null, - rotateGesturesEnabled: - rotateGesturesEnabled != other.rotateGesturesEnabled + rotateGesturesEnabled: rotateGesturesEnabled != other.rotateGesturesEnabled ? rotateGesturesEnabled : null, - scrollGesturesEnabled: - scrollGesturesEnabled != other.scrollGesturesEnabled + scrollGesturesEnabled: scrollGesturesEnabled != other.scrollGesturesEnabled ? scrollGesturesEnabled : null, tiltGesturesEnabled: tiltGesturesEnabled != other.tiltGesturesEnabled @@ -210,26 +201,15 @@ class MapConfiguration { zoomGesturesEnabled: zoomGesturesEnabled != other.zoomGesturesEnabled ? zoomGesturesEnabled : null, - liteModeEnabled: liteModeEnabled != other.liteModeEnabled - ? liteModeEnabled - : null, - myLocationEnabled: myLocationEnabled != other.myLocationEnabled - ? myLocationEnabled - : null, - myLocationButtonEnabled: - myLocationButtonEnabled != other.myLocationButtonEnabled + liteModeEnabled: liteModeEnabled != other.liteModeEnabled ? liteModeEnabled : null, + myLocationEnabled: myLocationEnabled != other.myLocationEnabled ? myLocationEnabled : null, + myLocationButtonEnabled: myLocationButtonEnabled != other.myLocationButtonEnabled ? myLocationButtonEnabled : null, padding: padding != other.padding ? padding : null, - indoorViewEnabled: indoorViewEnabled != other.indoorViewEnabled - ? indoorViewEnabled - : null, - trafficEnabled: trafficEnabled != other.trafficEnabled - ? trafficEnabled - : null, - buildingsEnabled: buildingsEnabled != other.buildingsEnabled - ? buildingsEnabled - : null, + indoorViewEnabled: indoorViewEnabled != other.indoorViewEnabled ? indoorViewEnabled : null, + trafficEnabled: trafficEnabled != other.trafficEnabled ? trafficEnabled : null, + buildingsEnabled: buildingsEnabled != other.buildingsEnabled ? buildingsEnabled : null, mapId: mapId != other.mapId ? mapId : null, style: style != other.style ? style : null, markerType: markerType != other.markerType ? markerType : null, @@ -241,20 +221,16 @@ class MapConfiguration { /// replacing the previous values. MapConfiguration applyDiff(MapConfiguration diff) { return MapConfiguration( - webCameraControlPosition: - diff.webCameraControlPosition ?? webCameraControlPosition, - webCameraControlEnabled: - diff.webCameraControlEnabled ?? webCameraControlEnabled, + webCameraControlPosition: diff.webCameraControlPosition ?? webCameraControlPosition, + webCameraControlEnabled: diff.webCameraControlEnabled ?? webCameraControlEnabled, webGestureHandling: diff.webGestureHandling ?? webGestureHandling, compassEnabled: diff.compassEnabled ?? compassEnabled, mapToolbarEnabled: diff.mapToolbarEnabled ?? mapToolbarEnabled, cameraTargetBounds: diff.cameraTargetBounds ?? cameraTargetBounds, mapType: diff.mapType ?? mapType, minMaxZoomPreference: diff.minMaxZoomPreference ?? minMaxZoomPreference, - rotateGesturesEnabled: - diff.rotateGesturesEnabled ?? rotateGesturesEnabled, - scrollGesturesEnabled: - diff.scrollGesturesEnabled ?? scrollGesturesEnabled, + rotateGesturesEnabled: diff.rotateGesturesEnabled ?? rotateGesturesEnabled, + scrollGesturesEnabled: diff.scrollGesturesEnabled ?? scrollGesturesEnabled, tiltGesturesEnabled: diff.tiltGesturesEnabled ?? tiltGesturesEnabled, fortyFiveDegreeImageryEnabled: diff.fortyFiveDegreeImageryEnabled ?? fortyFiveDegreeImageryEnabled, @@ -263,8 +239,7 @@ class MapConfiguration { zoomGesturesEnabled: diff.zoomGesturesEnabled ?? zoomGesturesEnabled, liteModeEnabled: diff.liteModeEnabled ?? liteModeEnabled, myLocationEnabled: diff.myLocationEnabled ?? myLocationEnabled, - myLocationButtonEnabled: - diff.myLocationButtonEnabled ?? myLocationButtonEnabled, + myLocationButtonEnabled: diff.myLocationButtonEnabled ?? myLocationButtonEnabled, padding: diff.padding ?? padding, indoorViewEnabled: diff.indoorViewEnabled ?? indoorViewEnabled, trafficEnabled: diff.trafficEnabled ?? trafficEnabled, diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart index 33bf6efdc7ea..132f0fc2f55e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/foundation.dart' - show immutable, objectRuntimeType, setEquals; +import 'package:flutter/foundation.dart' show immutable, objectRuntimeType, setEquals; import 'maps_object.dart'; import 'utils/maps_object.dart'; @@ -16,11 +15,7 @@ class MapsObjectUpdates> { /// [objectName] is the prefix to use when serializing the updates into a JSON /// dictionary. E.g., 'circle' will give 'circlesToAdd', 'circlesToUpdate', /// 'circleIdsToRemove'. - MapsObjectUpdates.from( - Set previous, - Set current, { - required this.objectName, - }) { + MapsObjectUpdates.from(Set previous, Set current, {required this.objectName}) { final Map, T> previousObjects = keyByMapsObjectId(previous); final Map, T> currentObjects = keyByMapsObjectId(current); @@ -37,10 +32,7 @@ class MapsObjectUpdates> { _objectIdsToRemove = previousObjectIds.difference(currentObjectIds); - _objectsToAdd = currentObjectIds - .difference(previousObjectIds) - .map(idToCurrentObject) - .toSet(); + _objectsToAdd = currentObjectIds.difference(previousObjectIds).map(idToCurrentObject).toSet(); // Returns `true` if [current] is not equals to previous one with the // same id. @@ -91,10 +83,7 @@ class MapsObjectUpdates> { } addIfNonNull('${objectName}sToAdd', serializeMapsObjectSet(_objectsToAdd)); - addIfNonNull( - '${objectName}sToChange', - serializeMapsObjectSet(_objectsToChange), - ); + addIfNonNull('${objectName}sToChange', serializeMapsObjectSet(_objectsToChange)); addIfNonNull( '${objectName}IdsToRemove', _objectIdsToRemove.map((MapsObjectId m) => m.value).toList(), diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker.dart index 7756ce422955..a36bf69dda7b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker.dart @@ -4,8 +4,7 @@ import 'dart:ui' show Offset; -import 'package:flutter/foundation.dart' - show ValueChanged, VoidCallback, immutable; +import 'package:flutter/foundation.dart' show ValueChanged, VoidCallback, immutable; import 'types.dart'; @@ -17,12 +16,7 @@ Object _offsetToJson(Offset offset) { @immutable class InfoWindow { /// Creates an immutable representation of a label on for [Marker]. - const InfoWindow({ - this.title, - this.snippet, - this.anchor = const Offset(0.5, 0.0), - this.onTap, - }); + const InfoWindow({this.title, this.snippet, this.anchor = const Offset(0.5, 0.0), this.onTap}); /// Text labels specifying that no text is to be displayed. static const InfoWindow noText = InfoWindow(); @@ -165,10 +159,7 @@ class Marker implements MapsObject { this.onDragStart, this.onDragEnd, }) : assert(0.0 <= alpha && alpha <= 1.0), - assert( - zIndex == 0.0 || zIndexInt == 0, - 'Only one of zIndex and zIndexInt can be provided', - ), + assert(zIndex == 0.0 || zIndexInt == 0, 'Only one of zIndex and zIndexInt can be provided'), _zIndexNum = zIndexInt == 0 ? zIndex : zIndexInt; /// Uniquely identifies a [Marker]. diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker_updates.dart index ee8d74baf949..433bfffa0249 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/marker_updates.dart @@ -10,8 +10,7 @@ import 'types.dart'; // (Do not re-export) class MarkerUpdates extends MapsObjectUpdates { /// Computes [MarkerUpdates] given previous and current [Marker]s. - MarkerUpdates.from(super.previous, super.current) - : super.from(objectName: 'marker'); + MarkerUpdates.from(super.previous, super.current) : super.from(objectName: 'marker'); /// Set of Markers to be added in this update. Set get markersToAdd => objectsToAdd; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/pattern_item.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/pattern_item.dart index 98f7a29543fd..72270cb6cd4e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/pattern_item.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/pattern_item.dart @@ -35,10 +35,7 @@ class PatternItem { /// [length] has to be non-negative. static PatternItem dash(double length) { assert(length >= 0.0); - return VariableLengthPatternItem._( - patternItemType: PatternItemType.dash, - length: length, - ); + return VariableLengthPatternItem._(patternItemType: PatternItemType.dash, length: length); } /// A gap used in the stroke pattern for a [Polyline]. @@ -46,10 +43,7 @@ class PatternItem { /// [length] has to be non-negative. static PatternItem gap(double length) { assert(length >= 0.0); - return VariableLengthPatternItem._( - patternItemType: PatternItemType.gap, - length: length, - ); + return VariableLengthPatternItem._(patternItemType: PatternItemType.gap, length: length); } /// The type of rendering used for an item in a pattern. diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon.dart index 9d84e1317c51..ecc249202f95 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon.dart @@ -3,8 +3,7 @@ // found in the LICENSE file. import 'package:collection/collection.dart'; -import 'package:flutter/foundation.dart' - show VoidCallback, immutable, listEquals; +import 'package:flutter/foundation.dart' show VoidCallback, immutable, listEquals; import 'package:flutter/material.dart' show Color, Colors; import 'types.dart'; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon_updates.dart index f51cb1b6d6b5..42435b27bbc6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polygon_updates.dart @@ -10,8 +10,7 @@ import 'types.dart'; // (Do not re-export) class PolygonUpdates extends MapsObjectUpdates { /// Computes [PolygonUpdates] given previous and current [Polygon]s. - PolygonUpdates.from(super.previous, super.current) - : super.from(objectName: 'polygon'); + PolygonUpdates.from(super.previous, super.current) : super.from(objectName: 'polygon'); /// Set of Polygons to be added in this update. Set get polygonsToAdd => objectsToAdd; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline.dart index 970ffdb35a2c..71656d80fd0c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline.dart @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/foundation.dart' - show VoidCallback, immutable, listEquals; +import 'package:flutter/foundation.dart' show VoidCallback, immutable, listEquals; import 'package:flutter/material.dart' show Color, Colors; import 'types.dart'; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart index edda9c6f09d1..a77dda113f8c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart @@ -10,15 +10,13 @@ import 'types.dart'; // (Do not re-export) class PolylineUpdates extends MapsObjectUpdates { /// Computes [PolylineUpdates] given previous and current [Polyline]s. - PolylineUpdates.from(super.previous, super.current) - : super.from(objectName: 'polyline'); + PolylineUpdates.from(super.previous, super.current) : super.from(objectName: 'polyline'); /// Set of Polylines to be added in this update. Set get polylinesToAdd => objectsToAdd; /// Set of PolylineIds to be removed in this update. - Set get polylineIdsToRemove => - objectIdsToRemove.cast(); + Set get polylineIdsToRemove => objectIdsToRemove.cast(); /// Set of Polylines to be changed in this update. Set get polylinesToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay.dart index 7732b841306b..5b303b780e44 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay.dart @@ -146,13 +146,6 @@ class TileOverlay implements MapsObject { } @override - int get hashCode => Object.hash( - tileOverlayId, - fadeIn, - tileProvider, - transparency, - zIndex, - visible, - tileSize, - ); + int get hashCode => + Object.hash(tileOverlayId, fadeIn, tileProvider, transparency, zIndex, visible, tileSize); } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay_updates.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay_updates.dart index 1ae44dce02c9..fe90d788798c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay_updates.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_overlay_updates.dart @@ -7,15 +7,13 @@ import 'types.dart'; /// Update specification for a set of [TileOverlay]s. class TileOverlayUpdates extends MapsObjectUpdates { /// Computes [TileOverlayUpdates] given previous and current [TileOverlay]s. - TileOverlayUpdates.from(super.previous, super.current) - : super.from(objectName: 'tileOverlay'); + TileOverlayUpdates.from(super.previous, super.current) : super.from(objectName: 'tileOverlay'); /// Set of TileOverlays to be added in this update. Set get tileOverlaysToAdd => objectsToAdd; /// Set of TileOverlayIds to be removed in this update. - Set get tileOverlayIdsToRemove => - objectIdsToRemove.cast(); + Set get tileOverlayIdsToRemove => objectIdsToRemove.cast(); /// Set of TileOverlays to be changed in this update. Set get tileOverlaysToChange => objectsToChange; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ui.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ui.dart index 9e037f82d7f1..31de4420936a 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ui.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/ui.dart @@ -87,10 +87,7 @@ class MinMaxZoomPreference { final double? maxZoom; /// Unbounded zooming. - static const MinMaxZoomPreference unbounded = MinMaxZoomPreference( - null, - null, - ); + static const MinMaxZoomPreference unbounded = MinMaxZoomPreference(null, null); /// Converts this object to something serializable in JSON. Object toJson() => [minZoom, maxZoom]; @@ -103,9 +100,7 @@ class MinMaxZoomPreference { if (runtimeType != other.runtimeType) { return false; } - return other is MinMaxZoomPreference && - minZoom == other.minZoom && - maxZoom == other.maxZoom; + return other is MinMaxZoomPreference && minZoom == other.minZoom && maxZoom == other.maxZoom; } @override diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/ground_overlay.dart index 8a8f5b6c5cdf..2e0f7a31b307 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/ground_overlay.dart @@ -6,10 +6,6 @@ import '../types.dart'; import 'maps_object.dart'; /// Converts an [Iterable] of GroundOverlay to a Map of GroundOverlayId -> GroundOverlay. -Map keyByGroundOverlayId( - Iterable groundOverlays, -) { - return keyByMapsObjectId( - groundOverlays, - ).cast(); +Map keyByGroundOverlayId(Iterable groundOverlays) { + return keyByMapsObjectId(groundOverlays).cast(); } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart index ebb8d2fadcc1..15927c14758c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/map_configuration_serialization.dart @@ -21,8 +21,7 @@ Map jsonForMapConfiguration(MapConfiguration config) { final EdgeInsets? padding = config.padding; return { if (config.compassEnabled != null) 'compassEnabled': config.compassEnabled!, - if (config.mapToolbarEnabled != null) - 'mapToolbarEnabled': config.mapToolbarEnabled!, + if (config.mapToolbarEnabled != null) 'mapToolbarEnabled': config.mapToolbarEnabled!, if (config.cameraTargetBounds != null) 'cameraTargetBounds': config.cameraTargetBounds!.toJson(), if (config.mapType != null) 'mapType': config.mapType!.index, @@ -32,32 +31,19 @@ Map jsonForMapConfiguration(MapConfiguration config) { 'rotateGesturesEnabled': config.rotateGesturesEnabled!, if (config.scrollGesturesEnabled != null) 'scrollGesturesEnabled': config.scrollGesturesEnabled!, - if (config.tiltGesturesEnabled != null) - 'tiltGesturesEnabled': config.tiltGesturesEnabled!, - if (config.zoomControlsEnabled != null) - 'zoomControlsEnabled': config.zoomControlsEnabled!, - if (config.zoomGesturesEnabled != null) - 'zoomGesturesEnabled': config.zoomGesturesEnabled!, - if (config.liteModeEnabled != null) - 'liteModeEnabled': config.liteModeEnabled!, - if (config.trackCameraPosition != null) - 'trackCameraPosition': config.trackCameraPosition!, - if (config.myLocationEnabled != null) - 'myLocationEnabled': config.myLocationEnabled!, + if (config.tiltGesturesEnabled != null) 'tiltGesturesEnabled': config.tiltGesturesEnabled!, + if (config.zoomControlsEnabled != null) 'zoomControlsEnabled': config.zoomControlsEnabled!, + if (config.zoomGesturesEnabled != null) 'zoomGesturesEnabled': config.zoomGesturesEnabled!, + if (config.liteModeEnabled != null) 'liteModeEnabled': config.liteModeEnabled!, + if (config.trackCameraPosition != null) 'trackCameraPosition': config.trackCameraPosition!, + if (config.myLocationEnabled != null) 'myLocationEnabled': config.myLocationEnabled!, if (config.myLocationButtonEnabled != null) 'myLocationButtonEnabled': config.myLocationButtonEnabled!, if (padding != null) - 'padding': [ - padding.top, - padding.left, - padding.bottom, - padding.right, - ], - if (config.indoorViewEnabled != null) - 'indoorEnabled': config.indoorViewEnabled!, + 'padding': [padding.top, padding.left, padding.bottom, padding.right], + if (config.indoorViewEnabled != null) 'indoorEnabled': config.indoorViewEnabled!, if (config.trafficEnabled != null) 'trafficEnabled': config.trafficEnabled!, - if (config.buildingsEnabled != null) - 'buildingsEnabled': config.buildingsEnabled!, + if (config.buildingsEnabled != null) 'buildingsEnabled': config.buildingsEnabled!, if (config.cloudMapId != null) 'cloudMapId': config.cloudMapId!, if (config.mapId != null) 'mapId': config.mapId!, if (config.style != null) 'style': config.style!, diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/maps_object.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/maps_object.dart index 37de3d9f7d93..fb737abc8bbb 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/maps_object.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/maps_object.dart @@ -5,13 +5,9 @@ import '../maps_object.dart'; /// Converts an [Iterable] of [MapsObject]s in a Map of [MapObjectId] -> [MapObject]. -Map, T> keyByMapsObjectId>( - Iterable objects, -) { +Map, T> keyByMapsObjectId>(Iterable objects) { return Map, T>.fromEntries( - objects.map( - (T object) => MapEntry, T>(object.mapsId, object.clone()), - ), + objects.map((T object) => MapEntry, T>(object.mapsId, object.clone())), ); } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/tile_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/tile_overlay.dart index 7094a4c50eeb..e0576a7174bf 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/tile_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/tile_overlay.dart @@ -6,12 +6,8 @@ import '../types.dart'; import 'maps_object.dart'; /// Converts an [Iterable] of TileOverlay in a Map of TileOverlayId -> TileOverlay. -Map keyTileOverlayId( - Iterable tileOverlays, -) { - return keyByMapsObjectId( - tileOverlays, - ).cast(); +Map keyTileOverlayId(Iterable tileOverlays) { + return keyByMapsObjectId(tileOverlays).cast(); } /// Converts a Set of TileOverlays into something serializable in JSON. diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/method_channel/method_channel_google_maps_flutter_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/method_channel/method_channel_google_maps_flutter_test.dart index 83d9adfe247d..d181508fa569 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/method_channel/method_channel_google_maps_flutter_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/method_channel/method_channel_google_maps_flutter_test.dart @@ -25,27 +25,24 @@ void main() { required Future? Function(MethodCall call) handler, }) { final MethodChannel channel = maps.ensureChannelInitialized(mapId); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (MethodCall methodCall) { - log.add(methodCall.method); - return handler(methodCall); - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (MethodCall methodCall) { + log.add(methodCall.method); + return handler(methodCall); + }, + ); } - Future sendPlatformMessage( - int mapId, - String method, - Map data, - ) async { + Future sendPlatformMessage(int mapId, String method, Map data) async { final ByteData byteData = const StandardMethodCodec().encodeMethodCall( MethodCall(method, data), ); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - 'plugins.flutter.io/google_maps_$mapId', - byteData, - (ByteData? data) {}, - ); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'plugins.flutter.io/google_maps_$mapId', + byteData, + (ByteData? data) {}, + ); } // Calls each method that uses invokeMethod with a return type other than @@ -109,34 +106,18 @@ void main() { final markerDragStartStream = StreamQueue( maps.onMarkerDragStart(mapId: mapId), ); - final markerDragStream = StreamQueue( - maps.onMarkerDrag(mapId: mapId), - ); + final markerDragStream = StreamQueue(maps.onMarkerDrag(mapId: mapId)); final markerDragEndStream = StreamQueue( maps.onMarkerDragEnd(mapId: mapId), ); - await sendPlatformMessage( - mapId, - 'marker#onDragStart', - jsonMarkerDragStartEvent, - ); + await sendPlatformMessage(mapId, 'marker#onDragStart', jsonMarkerDragStartEvent); await sendPlatformMessage(mapId, 'marker#onDrag', jsonMarkerDragEvent); - await sendPlatformMessage( - mapId, - 'marker#onDragEnd', - jsonMarkerDragEndEvent, - ); + await sendPlatformMessage(mapId, 'marker#onDragEnd', jsonMarkerDragEndEvent); - expect( - (await markerDragStartStream.next).value.value, - equals('drag-start-marker'), - ); + expect((await markerDragStartStream.next).value.value, equals('drag-start-marker')); expect((await markerDragStream.next).value.value, equals('drag-marker')); - expect( - (await markerDragEndStream.next).value.value, - equals('drag-end-marker'), - ); + expect((await markerDragEndStream.next).value.value, equals('drag-end-marker')); }); }); } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_flutter_platform_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_flutter_platform_test.dart index 1f72413a9485..2254a30780a9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_flutter_platform_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_flutter_platform_test.dart @@ -15,8 +15,7 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Store the initial instance before any tests change it. - final GoogleMapsFlutterPlatform initialInstance = - GoogleMapsFlutterPlatform.instance; + final GoogleMapsFlutterPlatform initialInstance = GoogleMapsFlutterPlatform.instance; group('$GoogleMapsFlutterPlatform', () { test('$MethodChannelGoogleMapsFlutter() is the default instance', () { @@ -25,8 +24,7 @@ void main() { test('Cannot be implemented with `implements`', () { expect(() { - GoogleMapsFlutterPlatform.instance = - ImplementsGoogleMapsFlutterPlatform(); + GoogleMapsFlutterPlatform.instance = ImplementsGoogleMapsFlutterPlatform(); // In versions of `package:plugin_platform_interface` prior to fixing // https://github.com/flutter/flutter/issues/109339, an attempt to // implement a platform interface using `implements` would sometimes @@ -46,30 +44,23 @@ void main() { GoogleMapsFlutterPlatform.instance = ExtendsGoogleMapsFlutterPlatform(); }); - test( - 'default implementation of `buildViewWithTextDirection` delegates to `buildView`', - () { - final GoogleMapsFlutterPlatform platform = - BuildViewGoogleMapsFlutterPlatform(); - expect( - platform.buildViewWithTextDirection( - 0, - (_) {}, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), - textDirection: TextDirection.ltr, - ), - isA(), - ); - }, - ); + test('default implementation of `buildViewWithTextDirection` delegates to `buildView`', () { + final GoogleMapsFlutterPlatform platform = BuildViewGoogleMapsFlutterPlatform(); + expect( + platform.buildViewWithTextDirection( + 0, + (_) {}, + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), + textDirection: TextDirection.ltr, + ), + isA(), + ); + }); test( 'default implementation of `buildViewWithConfiguration` delegates to `buildViewWithTextDirection`', () { - final GoogleMapsFlutterPlatform platform = - BuildViewGoogleMapsFlutterPlatform(); + final GoogleMapsFlutterPlatform platform = BuildViewGoogleMapsFlutterPlatform(); expect( platform.buildViewWithConfiguration( 0, @@ -88,12 +79,8 @@ void main() { expect( () => BuildViewGoogleMapsFlutterPlatform().updateClusterManagers( ClusterManagerUpdates.from( - { - const ClusterManager(clusterManagerId: ClusterManagerId('123')), - }, - { - const ClusterManager(clusterManagerId: ClusterManagerId('456')), - }, + {const ClusterManager(clusterManagerId: ClusterManagerId('123'))}, + {const ClusterManager(clusterManagerId: ClusterManagerId('456'))}, ), mapId: 0, ), @@ -109,40 +96,28 @@ void main() { }); test('default implementation of `getStyleError` returns null', () async { - final GoogleMapsFlutterPlatform platform = - BuildViewGoogleMapsFlutterPlatform(); + final GoogleMapsFlutterPlatform platform = BuildViewGoogleMapsFlutterPlatform(); expect(await platform.getStyleError(mapId: 0), null); }); - test( - 'default implementation of isAdvancedMarkersAvailable returns false', - () async { - final GoogleMapsFlutterPlatform platform = - BuildViewGoogleMapsFlutterPlatform(); - expect(await platform.isAdvancedMarkersAvailable(mapId: 0), isFalse); - }, - ); + test('default implementation of isAdvancedMarkersAvailable returns false', () async { + final GoogleMapsFlutterPlatform platform = BuildViewGoogleMapsFlutterPlatform(); + expect(await platform.isAdvancedMarkersAvailable(mapId: 0), isFalse); + }); test( 'default implementation of `animateCameraWithConfiguration` delegates to `animateCamera`', () { - final GoogleMapsFlutterPlatform platform = - ExtendsGoogleMapsFlutterPlatform(); + final GoogleMapsFlutterPlatform platform = ExtendsGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; - const animationConfig = CameraUpdateAnimationConfiguration( - duration: Duration(seconds: 2), - ); + const animationConfig = CameraUpdateAnimationConfiguration(duration: Duration(seconds: 2)); final CameraUpdate cameraUpdate = CameraUpdate.newCameraPosition( const CameraPosition(target: LatLng(10.0, 15.0)), ); expect( - () => platform.animateCameraWithConfiguration( - cameraUpdate, - animationConfig, - mapId: 0, - ), + () => platform.animateCameraWithConfiguration(cameraUpdate, animationConfig, mapId: 0), throwsA( isA().having( (UnimplementedError e) => e.message, @@ -160,8 +135,7 @@ class GoogleMapsFlutterPlatformMock extends Mock with MockPlatformInterfaceMixin implements GoogleMapsFlutterPlatform {} -class ImplementsGoogleMapsFlutterPlatform extends Mock - implements GoogleMapsFlutterPlatform {} +class ImplementsGoogleMapsFlutterPlatform extends Mock implements GoogleMapsFlutterPlatform {} class ExtendsGoogleMapsFlutterPlatform extends GoogleMapsFlutterPlatform {} diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart index 9a457b761aca..bb19c4eb8aac 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/platform_interface/google_maps_inspector_platform_test.dart @@ -8,8 +8,7 @@ import 'package:mockito/mockito.dart'; void main() { // Store the initial instance before any tests change it. - final GoogleMapsInspectorPlatform? initialInstance = - GoogleMapsInspectorPlatform.instance; + final GoogleMapsInspectorPlatform? initialInstance = GoogleMapsInspectorPlatform.instance; test('default instance is null', () { expect(initialInstance, isNull); @@ -17,8 +16,7 @@ void main() { test('cannot be implemented with `implements`', () { expect(() { - GoogleMapsInspectorPlatform.instance = - ImplementsGoogleMapsInspectorPlatform(); + GoogleMapsInspectorPlatform.instance = ImplementsGoogleMapsInspectorPlatform(); }, throwsA(isInstanceOf())); }); @@ -27,7 +25,6 @@ void main() { }); } -class ImplementsGoogleMapsInspectorPlatform extends Mock - implements GoogleMapsInspectorPlatform {} +class ImplementsGoogleMapsInspectorPlatform extends Mock implements GoogleMapsInspectorPlatform {} class ExtendsGoogleMapsInspectorPlatform extends GoogleMapsInspectorPlatform {} diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/advanced_marker_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/advanced_marker_test.dart index 1db90a8dd14d..7b7bdd6ae5f1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/advanced_marker_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/advanced_marker_test.dart @@ -42,8 +42,9 @@ void main() { }); test('toJson', () { - final BitmapDescriptor testDescriptor = - BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan); + final BitmapDescriptor testDescriptor = BitmapDescriptor.defaultMarkerWithHue( + BitmapDescriptor.hueCyan, + ); final marker = AdvancedMarker( markerId: const MarkerId('ABC123'), alpha: 0.12345, @@ -87,8 +88,7 @@ void main() { 'rotation': 100.0, 'visible': false, 'zIndex': 100.0, - 'collisionBehavior': - MarkerCollisionBehavior.requiredAndHidesOptional.index, + 'collisionBehavior': MarkerCollisionBehavior.requiredAndHidesOptional.index, }); }); @@ -105,8 +105,9 @@ void main() { const markerId = MarkerId('ABC123'); final marker = AdvancedMarker(markerId: markerId); - final BitmapDescriptor testDescriptor = - BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan); + final BitmapDescriptor testDescriptor = BitmapDescriptor.defaultMarkerWithHue( + BitmapDescriptor.hueCyan, + ); const testAlphaParam = 0.12345; const testAnchorParam = Offset(100, 100); final bool testConsumeTapEventsParam = !marker.consumeTapEvents; @@ -180,30 +181,21 @@ void main() { }); test('zIndex param', () { - final marker = AdvancedMarker( - markerId: const MarkerId('ABC123'), - zIndex: 5, - ); + final marker = AdvancedMarker(markerId: const MarkerId('ABC123'), zIndex: 5); expect(marker.zIndexInt, 5); expect(marker.zIndex, 5.00); }); test('zIndexInt param copyWith', () { - final marker = AdvancedMarker( - markerId: const MarkerId('ABC123'), - zIndex: 5, - ); + final marker = AdvancedMarker(markerId: const MarkerId('ABC123'), zIndex: 5); final AdvancedMarker copy = marker.copyWith(zIndexIntParam: 10); expect(copy.zIndexInt, 10); expect(copy.zIndex, 10.0); }); test('zIndex param copyWith', () { - final marker = AdvancedMarker( - markerId: const MarkerId('ABC123'), - zIndex: 5, - ); + final marker = AdvancedMarker(markerId: const MarkerId('ABC123'), zIndex: 5); final AdvancedMarker copy = marker.copyWith(zIndexParam: 10.0); expect(copy.zIndexInt, 10); expect(copy.zIndex, 10.0); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart index 815476f37973..c2235398198d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart @@ -18,9 +18,7 @@ void main() { final Object json = descriptor.toJson(); // Rehydrate a new bitmap descriptor... - final BitmapDescriptor descriptorFromJson = BitmapDescriptor.fromJson( - json, - ); + final BitmapDescriptor descriptorFromJson = BitmapDescriptor.fromJson(json); expect(descriptorFromJson, isNot(descriptor)); // New instance expect(descriptorFromJson.toJson(), json); @@ -97,10 +95,7 @@ void main() { group('fromJson validation', () { group('type validation', () { test('correct type', () { - expect( - BitmapDescriptor.fromJson(['defaultMarker']), - isA(), - ); + expect(BitmapDescriptor.fromJson(['defaultMarker']), isA()); }); test('wrong type', () { @@ -111,17 +106,11 @@ void main() { }); group('defaultMarker', () { test('hue is null', () { - expect( - BitmapDescriptor.fromJson(['defaultMarker']), - isA(), - ); + expect(BitmapDescriptor.fromJson(['defaultMarker']), isA()); }); test('hue is number', () { - expect( - BitmapDescriptor.fromJson(['defaultMarker', 158]), - isA(), - ); + expect(BitmapDescriptor.fromJson(['defaultMarker', 158]), isA()); }); test('hue is not number', () { @@ -178,40 +167,24 @@ void main() { test('package is passed', () { expect( - BitmapDescriptor.fromJson([ - 'fromAsset', - 'some/path.png', - 'some_package', - ]), + BitmapDescriptor.fromJson(['fromAsset', 'some/path.png', 'some_package']), isA(), ); }); test('package cannot be null or empty', () { expect(() { - BitmapDescriptor.fromJson([ - 'fromAsset', - 'some/path.png', - null, - ]); + BitmapDescriptor.fromJson(['fromAsset', 'some/path.png', null]); }, throwsAssertionError); expect(() { - BitmapDescriptor.fromJson([ - 'fromAsset', - 'some/path.png', - '', - ]); + BitmapDescriptor.fromJson(['fromAsset', 'some/path.png', '']); }, throwsAssertionError); }); }); group('fromAssetImage', () { test('name and dpi passed', () { expect( - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - 1.0, - ]), + BitmapDescriptor.fromJson(['fromAssetImage', 'some/path.png', 1.0]), isA(), ); }); @@ -225,12 +198,11 @@ void main() { imageConfiguration, 'red_square.png', ); - final BitmapDescriptor scaled = - await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'red_square.png', - mipmaps: false, - ); + final BitmapDescriptor scaled = await BitmapDescriptor.fromAssetImage( + imageConfiguration, + 'red_square.png', + mipmaps: false, + ); expect((mip.toJson() as List)[2], 1); expect((scaled.toJson() as List)[2], 3); @@ -250,18 +222,10 @@ void main() { test('dpi must be number', () { expect(() { - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - null, - ]); + BitmapDescriptor.fromJson(['fromAssetImage', 'some/path.png', null]); }, throwsAssertionError); expect(() { - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - 'one', - ]); + BitmapDescriptor.fromJson(['fromAssetImage', 'some/path.png', 'one']); }, throwsAssertionError); }); @@ -277,35 +241,27 @@ void main() { ); }); - test( - 'optional [width, height] List cannot be null or not contain 2 elements', - () { - expect(() { - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - 1.0, - null, - ]); - }, throwsAssertionError); - expect(() { - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - 1.0, - [], - ]); - }, throwsAssertionError); - expect(() { - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - 1.0, - [640, 480, 1024], - ]); - }, throwsAssertionError); - }, - ); + test('optional [width, height] List cannot be null or not contain 2 elements', () { + expect(() { + BitmapDescriptor.fromJson(['fromAssetImage', 'some/path.png', 1.0, null]); + }, throwsAssertionError); + expect(() { + BitmapDescriptor.fromJson([ + 'fromAssetImage', + 'some/path.png', + 1.0, + [], + ]); + }, throwsAssertionError); + expect(() { + BitmapDescriptor.fromJson([ + 'fromAssetImage', + 'some/path.png', + 1.0, + [640, 480, 1024], + ]); + }, throwsAssertionError); + }); }); group('bytes', () { @@ -327,20 +283,10 @@ void main() { test('without bytes', () { expect(() { - BitmapDescriptor.fromJson([ - BytesMapBitmap.type, - null, - 'auto', - 3.0, - ]); + BitmapDescriptor.fromJson([BytesMapBitmap.type, null, 'auto', 3.0]); }, throwsAssertionError); expect(() { - BitmapDescriptor.fromJson([ - BytesMapBitmap.type, - [], - 'auto', - 3.0, - ]); + BitmapDescriptor.fromJson([BytesMapBitmap.type, [], 'auto', 3.0]); }, throwsAssertionError); }); }); @@ -362,20 +308,10 @@ void main() { test('name cannot be null or empty', () { expect(() { - BitmapDescriptor.fromJson([ - AssetMapBitmap.type, - null, - 'auto', - 1.0, - ]); + BitmapDescriptor.fromJson([AssetMapBitmap.type, null, 'auto', 1.0]); }, throwsAssertionError); expect(() { - BitmapDescriptor.fromJson([ - AssetMapBitmap.type, - '', - 'auto', - 1.0, - ]); + BitmapDescriptor.fromJson([AssetMapBitmap.type, '', 'auto', 1.0]); }, throwsAssertionError); }); @@ -418,67 +354,64 @@ void main() { ); }); - test( - 'optional width and height parameters must be in proper format', - () { - expect(() { - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - 'auto', - 1.0, - null, - ]); - }, throwsAssertionError); - expect(() { - BitmapDescriptor.fromJson([ - 'fromAssetImage', - 'some/path.png', - 'auto', - 1.0, - [], - ]); - }, throwsAssertionError); - expect(() { - BitmapDescriptor.fromJson([ - AssetMapBitmap.type, - 'some/path.png', - { - 'assetName': 'red_square.png', - 'bitmapScaling': MapBitmapScaling.auto.name, - 'imagePixelRatio': null, - 'width': null, - 'height': 1.0, - }, - ]); - }, throwsAssertionError); - expect(() { - BitmapDescriptor.fromJson([ - AssetMapBitmap.type, - 'some/path.png', - { - 'assetName': 'red_square.png', - 'bitmapScaling': MapBitmapScaling.auto.name, - 'imagePixelRatio': null, - 'width': 1.0, - 'height': null, - }, - ]); - }, throwsAssertionError); - expect(() { - BitmapDescriptor.fromJson([ - AssetMapBitmap.type, - 'some/path.png', - { - 'assetName': 'red_square.png', - 'bitmapScaling': MapBitmapScaling.auto.name, - 'imagePixelRatio': null, - 'width': '1.0', - }, - ]); - }, throwsAssertionError); - }, - ); + test('optional width and height parameters must be in proper format', () { + expect(() { + BitmapDescriptor.fromJson([ + 'fromAssetImage', + 'some/path.png', + 'auto', + 1.0, + null, + ]); + }, throwsAssertionError); + expect(() { + BitmapDescriptor.fromJson([ + 'fromAssetImage', + 'some/path.png', + 'auto', + 1.0, + [], + ]); + }, throwsAssertionError); + expect(() { + BitmapDescriptor.fromJson([ + AssetMapBitmap.type, + 'some/path.png', + { + 'assetName': 'red_square.png', + 'bitmapScaling': MapBitmapScaling.auto.name, + 'imagePixelRatio': null, + 'width': null, + 'height': 1.0, + }, + ]); + }, throwsAssertionError); + expect(() { + BitmapDescriptor.fromJson([ + AssetMapBitmap.type, + 'some/path.png', + { + 'assetName': 'red_square.png', + 'bitmapScaling': MapBitmapScaling.auto.name, + 'imagePixelRatio': null, + 'width': 1.0, + 'height': null, + }, + ]); + }, throwsAssertionError); + expect(() { + BitmapDescriptor.fromJson([ + AssetMapBitmap.type, + 'some/path.png', + { + 'assetName': 'red_square.png', + 'bitmapScaling': MapBitmapScaling.auto.name, + 'imagePixelRatio': null, + 'width': '1.0', + }, + ]); + }, throwsAssertionError); + }); }); }); }); @@ -534,10 +467,7 @@ void main() { test('construct with width', () async { const double width = 100; - final BitmapDescriptor descriptor = AssetMapBitmap( - 'red_square.png', - width: width, - ); + final BitmapDescriptor descriptor = AssetMapBitmap('red_square.png', width: width); expect(descriptor, isA()); expect(descriptor, isA()); @@ -690,9 +620,7 @@ void main() { }); test('construct', () { - final BitmapDescriptor descriptor = BytesMapBitmap( - Uint8List.fromList([1, 2, 3]), - ); + final BitmapDescriptor descriptor = BytesMapBitmap(Uint8List.fromList([1, 2, 3])); expect(descriptor, isA()); expect(descriptor, isA()); expect( @@ -770,10 +698,7 @@ void main() { }); test('construct', () { - const pinConfig = PinConfig( - backgroundColor: Colors.green, - borderColor: Colors.blue, - ); + const pinConfig = PinConfig(backgroundColor: Colors.green, borderColor: Colors.blue); expect(pinConfig, isA()); expect(pinConfig.backgroundColor, Colors.green); expect(pinConfig.borderColor, Colors.blue); @@ -802,10 +727,7 @@ void main() { 'borderColor': Colors.blue.toARGB32(), 'glyph': [ 'textGlyph', - { - 'text': 'Hello', - 'textColor': Colors.red.toARGB32(), - }, + {'text': 'Hello', 'textColor': Colors.red.toARGB32()}, ], }, ]); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/camera_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/camera_test.dart index 0ecb775e2cf9..0e5cd408a0ea 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/camera_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/camera_test.dart @@ -17,9 +17,8 @@ void main() { ); // Cast to to ensure that recreating from JSON, where // type information will have likely been lost, still works. - final Map json = - (cameraPosition.toMap() as Map) - .cast(); + final Map json = (cameraPosition.toMap() as Map) + .cast(); final CameraPosition? cameraPositionFromJson = CameraPosition.fromMap(json); expect(cameraPosition, cameraPositionFromJson); @@ -32,9 +31,7 @@ void main() { tilt: 30.0, zoom: 1.5, ); - final CameraUpdate cameraUpdate = CameraUpdate.newCameraPosition( - cameraPosition, - ); + final CameraUpdate cameraUpdate = CameraUpdate.newCameraPosition(cameraPosition); expect(cameraUpdate.runtimeType, CameraUpdateNewCameraPosition); expect(cameraUpdate.updateType, CameraUpdateType.newCameraPosition); cameraUpdate as CameraUpdateNewCameraPosition; @@ -60,10 +57,7 @@ void main() { southwest: const LatLng(-2.0, -3.0), ); const padding = 1.0; - final CameraUpdate cameraUpdate = CameraUpdate.newLatLngBounds( - latLngBounds, - padding, - ); + final CameraUpdate cameraUpdate = CameraUpdate.newLatLngBounds(latLngBounds, padding); expect(cameraUpdate.runtimeType, CameraUpdateNewLatLngBounds); expect(cameraUpdate.updateType, CameraUpdateType.newLatLngBounds); cameraUpdate as CameraUpdateNewLatLngBounds; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cap_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cap_test.dart index 0a2084f6ba16..c78325474122 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cap_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cap_test.dart @@ -36,10 +36,7 @@ void main() { }); test('customCapWithWidth', () { - final Cap cap = Cap.customCapFromBitmap( - BitmapDescriptor.defaultMarker, - refWidth: 100, - ); + final Cap cap = Cap.customCapFromBitmap(BitmapDescriptor.defaultMarker, refWidth: 100); expect( cap.toJson(), equals([ diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_manager_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_manager_test.dart index a842eed38dfa..f1a2ae64f12e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_manager_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_manager_test.dart @@ -11,35 +11,27 @@ void main() { group('$ClusterManager', () { test('constructor defaults', () { - const manager = ClusterManager( - clusterManagerId: ClusterManagerId('1234'), - ); + const manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); expect(manager.clusterManagerId, const ClusterManagerId('1234')); }); test('toJson', () { - const manager = ClusterManager( - clusterManagerId: ClusterManagerId('1234'), - ); + const manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); final json = manager.toJson() as Map; expect(json, {'clusterManagerId': '1234'}); }); test('clone', () { - const manager = ClusterManager( - clusterManagerId: ClusterManagerId('1234'), - ); + const manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); final ClusterManager clone = manager.clone(); expect(identical(clone, manager), isFalse); expect(clone, equals(manager)); }); test('copyWith', () { - const manager = ClusterManager( - clusterManagerId: ClusterManagerId('1234'), - ); + const manager = ClusterManager(clusterManagerId: ClusterManagerId('1234')); final log = []; final ClusterManager copy = manager.copyWith( diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_test.dart index 8641cb5fc854..7530cf7c3968 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/cluster_test.dart @@ -26,10 +26,7 @@ void main() { expect(cluster.position, equals(const LatLng(55.0, 66.0))); expect( cluster.bounds, - LatLngBounds( - northeast: const LatLng(88.0, 22.0), - southwest: const LatLng(11.0, 99.0), - ), + LatLngBounds(northeast: const LatLng(88.0, 22.0), southwest: const LatLng(11.0, 99.0)), ); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart index f93e4d27e6ae..c89b2232fd49 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/heatmap_test.dart @@ -140,11 +140,7 @@ void main() { const radius = HeatmapRadius.fromPixels(10); const heatmap1 = Heatmap(heatmapId: id, data: data, radius: radius); const heatmap2 = Heatmap(heatmapId: id, data: data, radius: radius); - const heatmap3 = Heatmap( - heatmapId: id, - data: data, - radius: HeatmapRadius.fromPixels(20), - ); + const heatmap3 = Heatmap(heatmapId: id, data: data, radius: HeatmapRadius.fromPixels(20)); expect(heatmap1, heatmap2); expect(heatmap1, isNot(heatmap3)); @@ -221,9 +217,7 @@ void main() { group('$HeatmapGradient', () { test('constructor defaults', () { - const colors = [ - HeatmapGradientColor(Colors.red, 0.0), - ]; + const colors = [HeatmapGradientColor(Colors.red, 0.0)]; const gradient = HeatmapGradient(colors); expect(gradient.colors, colors); @@ -231,9 +225,7 @@ void main() { }); test('construct with values', () { - const colors = [ - HeatmapGradientColor(Colors.red, 0.0), - ]; + const colors = [HeatmapGradientColor(Colors.red, 0.0)]; const colorMapSize = 512; const gradient = HeatmapGradient(colors, colorMapSize: colorMapSize); @@ -246,9 +238,7 @@ void main() { HeatmapGradientColor(Colors.red, 0.0), ]); - const colors = [ - HeatmapGradientColor(Colors.blue, 0.0), - ]; + const colors = [HeatmapGradientColor(Colors.blue, 0.0)]; const colorMapSize = 512; final HeatmapGradient gradient2 = gradient1.copyWith( colorsParam: colors, @@ -269,27 +259,19 @@ void main() { }); test('toJson', () { - const colors = [ - HeatmapGradientColor(Colors.red, 0.0), - ]; + const colors = [HeatmapGradientColor(Colors.red, 0.0)]; const colorMapSize = 512; const gradient = HeatmapGradient(colors, colorMapSize: colorMapSize); expect(gradient.toJson(), { - 'colors': colors - .map((HeatmapGradientColor e) => e.color.toARGB32()) - .toList(), - 'startPoints': colors - .map((HeatmapGradientColor e) => e.startPoint) - .toList(), + 'colors': colors.map((HeatmapGradientColor e) => e.color.toARGB32()).toList(), + 'startPoints': colors.map((HeatmapGradientColor e) => e.startPoint).toList(), 'colorMapSize': colorMapSize, }); }); test('==', () { - const colors = [ - HeatmapGradientColor(Colors.red, 0.0), - ]; + const colors = [HeatmapGradientColor(Colors.red, 0.0)]; const gradient1 = HeatmapGradient(colors); const gradient2 = HeatmapGradient(colors); const gradient3 = HeatmapGradient([ @@ -301,9 +283,7 @@ void main() { }); test('hashCode', () { - const colors = [ - HeatmapGradientColor(Colors.red, 0.0), - ]; + const colors = [HeatmapGradientColor(Colors.red, 0.0)]; const colorMapSize = 512; const gradient = HeatmapGradient(colors, colorMapSize: colorMapSize); @@ -354,10 +334,7 @@ void main() { test('hashCode', () { const gradientColor = HeatmapGradientColor(Colors.red, 0.0); - expect( - gradientColor.hashCode, - Object.hash(gradientColor.color, gradientColor.startPoint), - ); + expect(gradientColor.hashCode, Object.hash(gradientColor.color, gradientColor.startPoint)); }); test('toString', () { diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart index e8564565457f..5ed9e487b360 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/map_configuration_test.dart @@ -18,10 +18,7 @@ void main() { compassEnabled: false, mapToolbarEnabled: false, cameraTargetBounds: CameraTargetBounds( - LatLngBounds( - northeast: const LatLng(30, 20), - southwest: const LatLng(10, 40), - ), + LatLngBounds(northeast: const LatLng(30, 20), southwest: const LatLng(10, 40)), ), mapType: MapType.normal, minMaxZoomPreference: const MinMaxZoomPreference(1.0, 10.0), @@ -70,9 +67,7 @@ void main() { }); test('handle webGestureHandling', () async { - const diff = MapConfiguration( - webGestureHandling: WebGestureHandling.none, - ); + const diff = MapConfiguration(webGestureHandling: WebGestureHandling.none); const empty = MapConfiguration(); final MapConfiguration updated = diffBase.applyDiff(diff); @@ -100,10 +95,7 @@ void main() { // The diff from empty options should be the diff itself. expect(diff.diffFrom(empty), diff); // A diff applied to non-empty options should update that field. - expect( - updated.webCameraControlPosition, - WebCameraControlPosition.blockEndInlineEnd, - ); + expect(updated.webCameraControlPosition, WebCameraControlPosition.blockEndInlineEnd); // The hash code should change. expect(empty.hashCode, isNot(diff.hashCode)); }); @@ -158,10 +150,7 @@ void main() { test('handle cameraTargetBounds', () async { final newBounds = CameraTargetBounds( - LatLngBounds( - northeast: const LatLng(55, 15), - southwest: const LatLng(5, 15), - ), + LatLngBounds(northeast: const LatLng(55, 15), southwest: const LatLng(5, 15)), ); final diff = MapConfiguration(cameraTargetBounds: newBounds); @@ -538,10 +527,7 @@ void main() { test('is false with cameraTargetBounds', () async { final newBounds = CameraTargetBounds( - LatLngBounds( - northeast: const LatLng(55, 15), - southwest: const LatLng(5, 15), - ), + LatLngBounds(northeast: const LatLng(55, 15), southwest: const LatLng(5, 15)), ); final diff = MapConfiguration(cameraTargetBounds: newBounds); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_test.dart index 4dadb84ef9f4..a888f03cd8b1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_test.dart @@ -20,11 +20,7 @@ void main() { const object3 = TestMapsObject(id3); expect( keyByMapsObjectId({object1, object2, object3}), - , TestMapsObject>{ - id1: object1, - id2: object2, - id3: object3, - }, + , TestMapsObject>{id1: object1, id2: object2, id3: object3}, ); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart index 8b70c2f22ec0..d71afca6da15 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/maps_object_updates_test.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter_platform_interface/src/types/utils/maps_obje import 'test_maps_object.dart'; class TestMapsObjectUpdate extends MapsObjectUpdates { - TestMapsObjectUpdate.from(super.previous, super.current) - : super.from(objectName: 'testObject'); + TestMapsObjectUpdate.from(super.previous, super.current) : super.from(objectName: 'testObject'); } void main() { @@ -22,18 +21,13 @@ void main() { const to1 = TestMapsObject(MapsObjectId('id1')); const to2 = TestMapsObject(MapsObjectId('id2')); const to3 = TestMapsObject(MapsObjectId('id3')); - const to3Changed = TestMapsObject( - MapsObjectId('id3'), - data: 2, - ); + const to3Changed = TestMapsObject(MapsObjectId('id3'), data: 2); const to4 = TestMapsObject(MapsObjectId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; final updates = TestMapsObjectUpdate.from(previous, current); - final toRemove = >{ - const MapsObjectId('id1'), - }; + final toRemove = >{const MapsObjectId('id1')}; expect(updates.objectIdsToRemove, toRemove); final toAdd = {to4}; @@ -47,10 +41,7 @@ void main() { const to1 = TestMapsObject(MapsObjectId('id1')); const to2 = TestMapsObject(MapsObjectId('id2')); const to3 = TestMapsObject(MapsObjectId('id3')); - const to3Changed = TestMapsObject( - MapsObjectId('id3'), - data: 2, - ); + const to3Changed = TestMapsObject(MapsObjectId('id3'), data: 2); const to4 = TestMapsObject(MapsObjectId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; @@ -70,10 +61,7 @@ void main() { const to1 = TestMapsObject(MapsObjectId('id1')); const to2 = TestMapsObject(MapsObjectId('id2')); const to3 = TestMapsObject(MapsObjectId('id3')); - const to3Changed = TestMapsObject( - MapsObjectId('id3'), - data: 2, - ); + const to3Changed = TestMapsObject(MapsObjectId('id3'), data: 2); const to4 = TestMapsObject(MapsObjectId('id4')); final previous = {to1, to2, to3}; final current1 = {to2, to3Changed, to4}; @@ -90,10 +78,7 @@ void main() { const to1 = TestMapsObject(MapsObjectId('id1')); const to2 = TestMapsObject(MapsObjectId('id2')); const to3 = TestMapsObject(MapsObjectId('id3')); - const to3Changed = TestMapsObject( - MapsObjectId('id3'), - data: 2, - ); + const to3Changed = TestMapsObject(MapsObjectId('id3'), data: 2); const to4 = TestMapsObject(MapsObjectId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; @@ -112,10 +97,7 @@ void main() { const to1 = TestMapsObject(MapsObjectId('id1')); const to2 = TestMapsObject(MapsObjectId('id2')); const to3 = TestMapsObject(MapsObjectId('id3')); - const to3Changed = TestMapsObject( - MapsObjectId('id3'), - data: 2, - ); + const to3Changed = TestMapsObject(MapsObjectId('id3'), data: 2); const to4 = TestMapsObject(MapsObjectId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/marker_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/marker_test.dart index 9b684bc6fa31..d3e4c44c489e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/marker_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/marker_test.dart @@ -42,8 +42,9 @@ void main() { }); test('toJson', () { - final BitmapDescriptor testDescriptor = - BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan); + final BitmapDescriptor testDescriptor = BitmapDescriptor.defaultMarkerWithHue( + BitmapDescriptor.hueCyan, + ); final marker = Marker( markerId: const MarkerId('ABC123'), alpha: 0.12345, @@ -100,8 +101,9 @@ void main() { const markerId = MarkerId('ABC123'); const marker = Marker(markerId: markerId); - final BitmapDescriptor testDescriptor = - BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan); + final BitmapDescriptor testDescriptor = BitmapDescriptor.defaultMarkerWithHue( + BitmapDescriptor.hueCyan, + ); const testAlphaParam = 0.12345; const testAnchorParam = Offset(100, 100); final bool testConsumeTapEventsParam = !marker.consumeTapEvents; @@ -172,11 +174,7 @@ void main() { test("Assert that both zIndex and zIndex int aren't passed in", () { expect( - () => Marker( - markerId: const MarkerId('ABC123'), - zIndex: 5, - zIndexInt: 10, - ), + () => Marker(markerId: const MarkerId('ABC123'), zIndex: 5, zIndexInt: 10), throwsAssertionError, ); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart index f6d5b6027b00..bce80dafaaf8 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/test_maps_object.dart @@ -31,9 +31,7 @@ class TestMapsObject implements MapsObject { if (other.runtimeType != runtimeType) { return false; } - return other is TestMapsObject && - mapsId == other.mapsId && - data == other.data; + return other is TestMapsObject && mapsId == other.mapsId && data == other.data; } @override @@ -41,6 +39,5 @@ class TestMapsObject implements MapsObject { } class TestMapsObjectUpdate extends MapsObjectUpdates { - TestMapsObjectUpdate.from(super.previous, super.current) - : super.from(objectName: 'testObject'); + TestMapsObjectUpdate.from(super.previous, super.current) : super.from(objectName: 'testObject'); } diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart index e4092ac385ea..863b122723f1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_test.dart @@ -53,17 +53,11 @@ void main() { test('invalid transparency throws', () async { expect( - () => TileOverlay( - tileOverlayId: const TileOverlayId('id1'), - transparency: -0.1, - ), + () => TileOverlay(tileOverlayId: const TileOverlayId('id1'), transparency: -0.1), throwsAssertionError, ); expect( - () => TileOverlay( - tileOverlayId: const TileOverlayId('id2'), - transparency: 1.2, - ), + () => TileOverlay(tileOverlayId: const TileOverlayId('id2'), transparency: 1.2), throwsAssertionError, ); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart index 3811a865a85a..159a095bcf33 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart @@ -15,10 +15,7 @@ void main() { const to1 = TileOverlay(tileOverlayId: TileOverlayId('id1')); const to2 = TileOverlay(tileOverlayId: TileOverlayId('id2')); const to3 = TileOverlay(tileOverlayId: TileOverlayId('id3')); - const to3Changed = TileOverlay( - tileOverlayId: TileOverlayId('id3'), - transparency: 0.5, - ); + const to3Changed = TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5); const to4 = TileOverlay(tileOverlayId: TileOverlayId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; @@ -38,10 +35,7 @@ void main() { const to1 = TileOverlay(tileOverlayId: TileOverlayId('id1')); const to2 = TileOverlay(tileOverlayId: TileOverlayId('id2')); const to3 = TileOverlay(tileOverlayId: TileOverlayId('id3')); - const to3Changed = TileOverlay( - tileOverlayId: TileOverlayId('id3'), - transparency: 0.5, - ); + const to3Changed = TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5); const to4 = TileOverlay(tileOverlayId: TileOverlayId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; @@ -50,9 +44,7 @@ void main() { final Object json = updates.toJson(); expect(json, { 'tileOverlaysToAdd': serializeTileOverlaySet(updates.tileOverlaysToAdd), - 'tileOverlaysToChange': serializeTileOverlaySet( - updates.tileOverlaysToChange, - ), + 'tileOverlaysToChange': serializeTileOverlaySet(updates.tileOverlaysToChange), 'tileOverlayIdsToRemove': updates.tileOverlayIdsToRemove .map((TileOverlayId m) => m.value) .toList(), @@ -63,10 +55,7 @@ void main() { const to1 = TileOverlay(tileOverlayId: TileOverlayId('id1')); const to2 = TileOverlay(tileOverlayId: TileOverlayId('id2')); const to3 = TileOverlay(tileOverlayId: TileOverlayId('id3')); - const to3Changed = TileOverlay( - tileOverlayId: TileOverlayId('id3'), - transparency: 0.5, - ); + const to3Changed = TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5); const to4 = TileOverlay(tileOverlayId: TileOverlayId('id4')); final previous = {to1, to2, to3}; final current1 = {to2, to3Changed, to4}; @@ -83,10 +72,7 @@ void main() { const to1 = TileOverlay(tileOverlayId: TileOverlayId('id1')); const to2 = TileOverlay(tileOverlayId: TileOverlayId('id2')); const to3 = TileOverlay(tileOverlayId: TileOverlayId('id3')); - const to3Changed = TileOverlay( - tileOverlayId: TileOverlayId('id3'), - transparency: 0.5, - ); + const to3Changed = TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5); const to4 = TileOverlay(tileOverlayId: TileOverlayId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; @@ -105,10 +91,7 @@ void main() { const to1 = TileOverlay(tileOverlayId: TileOverlayId('id1')); const to2 = TileOverlay(tileOverlayId: TileOverlayId('id2')); const to3 = TileOverlay(tileOverlayId: TileOverlayId('id3')); - const to3Changed = TileOverlay( - tileOverlayId: TileOverlayId('id3'), - transparency: 0.5, - ); + const to3Changed = TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5); const to4 = TileOverlay(tileOverlayId: TileOverlayId('id4')); final previous = {to1, to2, to3}; final current = {to2, to3Changed, to4}; diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/cluster_manager_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/cluster_manager_test.dart index 4bb0d908feb3..70cb77545e45 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/cluster_manager_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/cluster_manager_test.dart @@ -18,8 +18,7 @@ void main() { const ClusterManager(clusterManagerId: id3), ]; - final Map result = - keyByClusterManagerId(clusterManagers); + final Map result = keyByClusterManagerId(clusterManagers); expect(result, isA>()); expect(result[id1], equals(clusterManagers[0])); diff --git a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/map_configuration_serialization_test.dart b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/map_configuration_serialization_test.dart index 7777f2399fe2..85100905a9e1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/map_configuration_serialization_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/utils/map_configuration_serialization_test.dart @@ -23,10 +23,7 @@ void main() { compassEnabled: false, mapToolbarEnabled: false, cameraTargetBounds: CameraTargetBounds( - LatLngBounds( - northeast: const LatLng(30, 20), - southwest: const LatLng(10, 40), - ), + LatLngBounds(northeast: const LatLng(30, 20), southwest: const LatLng(10, 40)), ), mapType: MapType.normal, minMaxZoomPreference: const MinMaxZoomPreference(1.0, 10.0), @@ -84,10 +81,7 @@ void main() { }); test('mapId preferred over cloudMapId', () { - const config = MapConfiguration( - mapId: 'map-id', - cloudMapId: 'cloud-map-id', - ); + const config = MapConfiguration(mapId: 'map-id', cloudMapId: 'cloud-map-id'); final Map json = jsonForMapConfiguration(config); expect(json, {'mapId': 'map-id', 'cloudMapId': 'map-id'}); }); @@ -95,9 +89,6 @@ void main() { test('mapId falls back to cloudMapId', () { const config = MapConfiguration(cloudMapId: 'cloud-map-id'); final Map json = jsonForMapConfiguration(config); - expect(json, { - 'mapId': 'cloud-map-id', - 'cloudMapId': 'cloud-map-id', - }); + expect(json, {'mapId': 'cloud-map-id', 'cloudMapId': 'cloud-map-id'}); }); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_marker_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_marker_test.dart index 5b464df10a83..fb6bd43835c1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_marker_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_marker_test.dart @@ -66,11 +66,7 @@ void main() { AdvancedMarkerController(marker: marker, onDragStart: onDragStart); // Trigger a drag end event... - gmaps.event.trigger( - marker, - 'dragstart', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(marker, 'dragstart', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); expect(await methodCalled, isTrue); }); @@ -79,11 +75,7 @@ void main() { AdvancedMarkerController(marker: marker, onDrag: onDrag); // Trigger a drag end event... - gmaps.event.trigger( - marker, - 'drag', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(marker, 'drag', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); expect(await methodCalled, isTrue); }); @@ -92,11 +84,7 @@ void main() { AdvancedMarkerController(marker: marker, onDragEnd: onDragEnd); // Trigger a drag end event... - gmaps.event.trigger( - marker, - 'dragend', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(marker, 'dragend', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); expect(await methodCalled, isTrue); }); @@ -104,8 +92,7 @@ void main() { testWidgets('update', (WidgetTester tester) async { final controller = AdvancedMarkerController(marker: marker); final options = gmaps.AdvancedMarkerElementOptions() - ..collisionBehavior = - gmaps.CollisionBehavior.OPTIONAL_AND_HIDES_LOWER_PRIORITY + ..collisionBehavior = gmaps.CollisionBehavior.OPTIONAL_AND_HIDES_LOWER_PRIORITY ..gmpDraggable = true ..position = gmaps.LatLng(42, 54); @@ -115,10 +102,7 @@ void main() { controller.update(options); expect(marker.gmpDraggable, isTrue); - expect( - marker.collisionBehavior, - gmaps.CollisionBehavior.OPTIONAL_AND_HIDES_LOWER_PRIORITY, - ); + expect(marker.collisionBehavior, gmaps.CollisionBehavior.OPTIONAL_AND_HIDES_LOWER_PRIORITY); final JSAny? position = marker.position; expect(position, isNotNull); expect(position is gmaps.LatLngLiteral, isTrue); @@ -126,9 +110,7 @@ void main() { expect((position as gmaps.LatLngLiteral).lng, equals(54)); }); - testWidgets('infoWindow null, showInfoWindow.', ( - WidgetTester tester, - ) async { + testWidgets('infoWindow null, showInfoWindow.', (WidgetTester tester) async { final controller = AdvancedMarkerController(marker: marker); controller.showInfoWindow(); @@ -140,10 +122,7 @@ void main() { final infoWindow = gmaps.InfoWindow(); final map = gmaps.Map(createDivElement()); marker.map = map; - final controller = AdvancedMarkerController( - marker: marker, - infoWindow: infoWindow, - ); + final controller = AdvancedMarkerController(marker: marker, infoWindow: infoWindow); controller.showInfoWindow(); @@ -155,10 +134,7 @@ void main() { final infoWindow = gmaps.InfoWindow(); final map = gmaps.Map(createDivElement()); marker.map = map; - final controller = AdvancedMarkerController( - marker: marker, - infoWindow: infoWindow, - ); + final controller = AdvancedMarkerController(marker: marker, infoWindow: infoWindow); controller.hideInfoWindow(); @@ -173,10 +149,7 @@ void main() { final infoWindow = gmaps.InfoWindow(); final map = gmaps.Map(createDivElement()); marker.map = map; - controller = AdvancedMarkerController( - marker: marker, - infoWindow: infoWindow, - ); + controller = AdvancedMarkerController(marker: marker, infoWindow: infoWindow); }); testWidgets('drops gmaps instance', (WidgetTester tester) async { @@ -185,11 +158,8 @@ void main() { expect(controller.marker, isNull); }); - testWidgets('cannot call update after remove', ( - WidgetTester tester, - ) async { - final options = gmaps.AdvancedMarkerElementOptions() - ..gmpDraggable = true; + testWidgets('cannot call update after remove', (WidgetTester tester) async { + final options = gmaps.AdvancedMarkerElementOptions()..gmpDraggable = true; controller.remove(); @@ -198,9 +168,7 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot call showInfoWindow after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call showInfoWindow after remove', (WidgetTester tester) async { controller.remove(); expect(() { @@ -208,9 +176,7 @@ void main() { }, throwsStateError); }); - testWidgets('cannot call hideInfoWindow after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call hideInfoWindow after remove', (WidgetTester tester) async { controller.remove(); expect(() { diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_markers_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_markers_test.dart index 11b7b9df35ef..c3868cd5ac6d 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_markers_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/advanced_markers_test.dart @@ -26,22 +26,17 @@ void main() { group('MarkersController', () { late StreamController> events; - late MarkersController< - gmaps.AdvancedMarkerElement, - gmaps.AdvancedMarkerElementOptions - > + late MarkersController controller; - late ClusterManagersController - clusterManagersController; + late ClusterManagersController clusterManagersController; late gmaps.Map map; setUp(() { events = StreamController>(); - clusterManagersController = - ClusterManagersController( - stream: events, - ); + clusterManagersController = ClusterManagersController( + stream: events, + ); controller = AdvancedMarkersController( stream: events, clusterManagersController: clusterManagersController, @@ -69,9 +64,7 @@ void main() { gmaps.AdvancedMarkerElement? marker; gmaps.LatLngLiteral? position; - final markers = { - AdvancedMarker(markerId: const MarkerId('1')), - }; + final markers = {AdvancedMarker(markerId: const MarkerId('1'))}; await controller.addMarkers(markers); marker = controller.markers[const MarkerId('1')]?.marker; @@ -105,46 +98,42 @@ void main() { expect(position.lng, equals(54)); }); - testWidgets( - 'changeMarkers resets marker position if not passed when updating!', - (WidgetTester tester) async { - gmaps.AdvancedMarkerElement? marker; - gmaps.LatLngLiteral? position; + testWidgets('changeMarkers resets marker position if not passed when updating!', ( + WidgetTester tester, + ) async { + gmaps.AdvancedMarkerElement? marker; + gmaps.LatLngLiteral? position; + + final markers = { + AdvancedMarker(markerId: const MarkerId('1'), position: const LatLng(42, 54)), + }; + await controller.addMarkers(markers); - final markers = { - AdvancedMarker( - markerId: const MarkerId('1'), - position: const LatLng(42, 54), - ), - }; - await controller.addMarkers(markers); - - marker = controller.markers[const MarkerId('1')]?.marker; - expect(marker, isNotNull); - expect(marker!.gmpDraggable, isFalse); - - position = marker.position! as gmaps.LatLngLiteral; - expect(position, isNotNull); - expect(position.lat, equals(42)); - expect(position.lng, equals(54)); - - // Update the marker without position. - final updatedMarkers = { - AdvancedMarker(markerId: const MarkerId('1'), draggable: true), - }; - await controller.changeMarkers(updatedMarkers); - expect(controller.markers.length, 1); - - marker = controller.markers[const MarkerId('1')]?.marker; - expect(marker, isNotNull); - expect(marker!.gmpDraggable, isTrue); - - position = marker.position! as gmaps.LatLngLiteral; - expect(position, isNotNull); - expect(position.lat, equals(0)); - expect(position.lng, equals(0)); - }, - ); + marker = controller.markers[const MarkerId('1')]?.marker; + expect(marker, isNotNull); + expect(marker!.gmpDraggable, isFalse); + + position = marker.position! as gmaps.LatLngLiteral; + expect(position, isNotNull); + expect(position.lat, equals(42)); + expect(position.lng, equals(54)); + + // Update the marker without position. + final updatedMarkers = { + AdvancedMarker(markerId: const MarkerId('1'), draggable: true), + }; + await controller.changeMarkers(updatedMarkers); + expect(controller.markers.length, 1); + + marker = controller.markers[const MarkerId('1')]?.marker; + expect(marker, isNotNull); + expect(marker!.gmpDraggable, isTrue); + + position = marker.position! as gmaps.LatLngLiteral; + expect(position, isNotNull); + expect(position.lat, equals(0)); + expect(position.lng, equals(0)); + }); testWidgets('removeMarkers', (WidgetTester tester) async { final markers = { @@ -158,10 +147,7 @@ void main() { expect(controller.markers.length, 3); // Remove some markers. - final markerIdsToRemove = { - const MarkerId('1'), - const MarkerId('3'), - }; + final markerIdsToRemove = {const MarkerId('1'), const MarkerId('3')}; controller.removeMarkers(markerIdsToRemove); @@ -192,9 +178,7 @@ void main() { expect(controller.markers[const MarkerId('1')]?.infoWindowShown, isFalse); }); - testWidgets('only single InfoWindow is visible', ( - WidgetTester tester, - ) async { + testWidgets('only single InfoWindow is visible', (WidgetTester tester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), @@ -221,9 +205,7 @@ void main() { expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isTrue); }); - testWidgets('markers with custom asset icon work', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom asset icon work', (WidgetTester tester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), @@ -234,9 +216,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLImageElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLImageElement?; expect(icon, isNotNull); final String assetUrl = icon!.src; @@ -247,9 +227,7 @@ void main() { expect(icon.style.height, '48px'); }); - testWidgets('markers with custom asset icon and pixel ratio work', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom asset icon and pixel ratio work', (WidgetTester tester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), @@ -260,9 +238,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLImageElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLImageElement?; expect(icon, isNotNull); final String assetUrl = icon!.src; @@ -292,9 +268,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLImageElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLImageElement?; expect(icon, isNotNull); final String assetUrl = icon!.src; @@ -306,25 +280,18 @@ void main() { expect(icon.style.height, '64px'); }); - testWidgets('markers with missing asset icon should not set size', ( - WidgetTester tester, - ) async { + testWidgets('markers with missing asset icon should not set size', (WidgetTester tester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), - icon: AssetMapBitmap( - 'assets/broken_asset_name.png', - imagePixelRatio: 2.0, - ), + icon: AssetMapBitmap('assets/broken_asset_name.png', imagePixelRatio: 2.0), ), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLImageElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLImageElement?; expect(icon, isNotNull); final String assetUrl = icon!.src; @@ -335,26 +302,19 @@ void main() { expect(icon.style.height, isEmpty); }); - testWidgets('markers with custom bitmap icon work', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom bitmap icon work', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); final markers = { AdvancedMarker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLImageElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLImageElement?; expect(icon, isNotNull); final String blobUrl = icon!.src; @@ -364,8 +324,7 @@ void main() { expect( response.bodyBytes, bytes, - reason: - 'Bytes from the Icon blob must match bytes used to create AdvancedMarker', + reason: 'Bytes from the Icon blob must match bytes used to create AdvancedMarker', ); // Icon size is 16x16 pixels, this should be automatically read from the @@ -390,9 +349,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLImageElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLImageElement?; expect(icon, isNotNull); // Icon size is 16x16 pixels, this should be automatically read from the @@ -402,9 +359,7 @@ void main() { expect(icon.style.height, '16px'); }); - testWidgets('markers with custom bitmap icon pass size to sdk', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom bitmap icon pass size to sdk', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); final markers = { AdvancedMarker( @@ -416,17 +371,13 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLImageElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLImageElement?; expect(icon, isNotNull); expect(icon!.style.width, '20px'); expect(icon.style.height, '30px'); }); - testWidgets('markers created with text glyph work', ( - WidgetTester widgetTester, - ) async { + testWidgets('markers created with text glyph work', (WidgetTester widgetTester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), @@ -440,9 +391,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLDivElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLDivElement?; expect(icon, isNotNull); // Query pin nodes and find text element. This is a bit fragile as it @@ -462,9 +411,7 @@ void main() { expect(paragraphElement!.innerHTML.toString(), 'Hey'); }); - testWidgets('markers created with bitmap glyph work', ( - WidgetTester widgetTester, - ) async { + testWidgets('markers created with bitmap glyph work', (WidgetTester widgetTester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), @@ -483,9 +430,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.content - as HTMLDivElement?; + final icon = controller.markers[const MarkerId('1')]?.marker?.content as HTMLDivElement?; expect(icon, isNotNull); // Query pin nodes and find text element. This is a bit fragile as it @@ -506,9 +451,7 @@ void main() { expect(imgElement!.src, endsWith('assets/red_square.png')); }); - testWidgets('InfoWindow snippet can have links', ( - WidgetTester tester, - ) async { + testWidgets('InfoWindow snippet can have links', (WidgetTester tester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), @@ -522,38 +465,26 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final content = - controller.markers[const MarkerId('1')]?.infoWindow?.content - as HTMLElement?; + final content = controller.markers[const MarkerId('1')]?.infoWindow?.content as HTMLElement?; expect(content, isNotNull); final String innerHtml = (content!.innerHTML as JSString).toDart; expect(innerHtml, contains('title for test')); - expect( - innerHtml, - contains( - 'Go to Google >>>', - ), - ); + expect(innerHtml, contains('Go to Google >>>')); }); testWidgets('InfoWindow content is clickable', (WidgetTester tester) async { final markers = { AdvancedMarker( markerId: const MarkerId('1'), - infoWindow: const InfoWindow( - title: 'title for test', - snippet: 'some snippet', - ), + infoWindow: const InfoWindow(title: 'title for test', snippet: 'some snippet'), ), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final content = - controller.markers[const MarkerId('1')]?.infoWindow?.content - as HTMLElement?; + final content = controller.markers[const MarkerId('1')]?.infoWindow?.content as HTMLElement?; content?.click(); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/cloud_map_styles_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/cloud_map_styles_test.dart index 9fd38622c105..7de829345ce6 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/cloud_map_styles_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/cloud_map_styles_test.dart @@ -3,19 +3,12 @@ // found in the LICENSE file. import 'dart:async'; -import 'package:flutter/widgets.dart' - show Directionality, SizedBox, TextDirection; +import 'package:flutter/widgets.dart' show Directionality, SizedBox, TextDirection; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart' - show - CameraPosition, - LatLng, - MapConfiguration, - MapEvent, - MapWidgetConfiguration; -import 'package:google_maps_flutter_web/google_maps_flutter_web.dart' - show GoogleMapController; + show CameraPosition, LatLng, MapConfiguration, MapEvent, MapWidgetConfiguration; +import 'package:google_maps_flutter_web/google_maps_flutter_web.dart' show GoogleMapController; import 'package:integration_test/integration_test.dart'; void main() { @@ -26,9 +19,7 @@ void main() { textDirection: TextDirection.ltr, ); - testWidgets('cloud mapId present => mapId set & styles omitted', ( - WidgetTester tester, - ) async { + testWidgets('cloud mapId present => mapId set & styles omitted', (WidgetTester tester) async { const testMapConfig = MapConfiguration(mapId: 'test-cloud-map-id'); await tester.pumpWidget( @@ -125,9 +116,7 @@ void main() { controller.dispose(); }); - testWidgets('empty cloud mapId is treated as no mapId', ( - WidgetTester tester, - ) async { + testWidgets('empty cloud mapId is treated as no mapId', (WidgetTester tester) async { await tester.pumpWidget( const Directionality(textDirection: TextDirection.ltr, child: SizedBox()), ); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart index 931465c7b950..cf9b9f24a3d9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.dart @@ -23,27 +23,15 @@ const String _kMapId = '000000000000000'; // Dummy map ID. gmaps.Map mapShim() => throw UnimplementedError(); @GenerateNiceMocks(>[ - MockSpec( - fallbackGenerators: {#googleMap: mapShim}, - ), - MockSpec( - fallbackGenerators: {#googleMap: mapShim}, - ), - MockSpec( - fallbackGenerators: {#googleMap: mapShim}, - ), - MockSpec( - fallbackGenerators: {#googleMap: mapShim}, - ), + MockSpec(fallbackGenerators: {#googleMap: mapShim}), + MockSpec(fallbackGenerators: {#googleMap: mapShim}), + MockSpec(fallbackGenerators: {#googleMap: mapShim}), + MockSpec(fallbackGenerators: {#googleMap: mapShim}), MockSpec>( fallbackGenerators: {#googleMap: mapShim}, ), - MockSpec( - fallbackGenerators: {#googleMap: mapShim}, - ), - MockSpec( - fallbackGenerators: {#googleMap: mapShim}, - ), + MockSpec(fallbackGenerators: {#googleMap: mapShim}), + MockSpec(fallbackGenerators: {#googleMap: mapShim}), ]) /// Test Google Map Controller void main() { @@ -56,9 +44,7 @@ void main() { // Creates a controller with the default mapId and stream controller, and any `options` needed. GoogleMapController createController({ - CameraPosition initialCameraPosition = const CameraPosition( - target: LatLng(0, 0), - ), + CameraPosition initialCameraPosition = const CameraPosition(target: LatLng(0, 0)), MapObjects mapObjects = const MapObjects(), MapConfiguration mapConfiguration = const MapConfiguration(), }) { @@ -86,10 +72,7 @@ void main() { testWidgets('constructor creates widget', (WidgetTester tester) async { expect(controller.widget, isNotNull); expect(controller.widget, isA()); - expect( - (controller.widget! as HtmlElementView).viewType, - endsWith('$mapId'), - ); + expect((controller.widget! as HtmlElementView).viewType, endsWith('$mapId')); }); testWidgets('widget is cached when reused', (WidgetTester tester) async { @@ -99,18 +82,14 @@ void main() { }); group('dispose', () { - testWidgets('closes the stream and removes the widget', ( - WidgetTester tester, - ) async { + testWidgets('closes the stream and removes the widget', (WidgetTester tester) async { controller.dispose(); expect(stream.isClosed, isTrue); expect(controller.widget, isNull); }); - testWidgets('cannot call getVisibleRegion after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot call getVisibleRegion after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { @@ -118,21 +97,15 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot call getScreenCoordinate after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot call getScreenCoordinate after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { - await controller.getScreenCoordinate( - const LatLng(43.3072465, -5.6918241), - ); + await controller.getScreenCoordinate(const LatLng(43.3072465, -5.6918241)); }, throwsAssertionError); }); - testWidgets('cannot call getLatLng after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot call getLatLng after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { @@ -140,9 +113,7 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot call moveCamera after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot call moveCamera after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { @@ -150,9 +121,7 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot call getZoomLevel after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot call getZoomLevel after dispose', (WidgetTester tester) async { controller.dispose(); expect(() async { @@ -160,45 +129,31 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot updateCircles after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot updateCircles after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { - controller.updateCircles( - CircleUpdates.from(const {}, const {}), - ); + controller.updateCircles(CircleUpdates.from(const {}, const {})); }, throwsAssertionError); }); - testWidgets('cannot updateHeatmaps after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot updateHeatmaps after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { - controller.updateHeatmaps( - HeatmapUpdates.from(const {}, const {}), - ); + controller.updateHeatmaps(HeatmapUpdates.from(const {}, const {})); }, throwsAssertionError); }); - testWidgets('cannot updatePolygons after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot updatePolygons after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { - controller.updatePolygons( - PolygonUpdates.from(const {}, const {}), - ); + controller.updatePolygons(PolygonUpdates.from(const {}, const {})); }, throwsAssertionError); }); - testWidgets('cannot updatePolylines after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot updatePolylines after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { @@ -208,15 +163,11 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot updateMarkers after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot updateMarkers after dispose', (WidgetTester tester) async { controller.dispose(); await expectLater( - controller.updateMarkers( - MarkerUpdates.from(const {}, const {}), - ), + controller.updateMarkers(MarkerUpdates.from(const {}, const {})), throwsAssertionError, ); @@ -229,9 +180,7 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot updateTileOverlays after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot updateTileOverlays after dispose', (WidgetTester tester) async { controller.dispose(); expect(() { @@ -239,9 +188,7 @@ void main() { }, throwsAssertionError); }); - testWidgets('isInfoWindowShown defaults to false', ( - WidgetTester tester, - ) async { + testWidgets('isInfoWindowShown defaults to false', (WidgetTester tester) async { controller.dispose(); expect(controller.isInfoWindowShown(const MarkerId('any')), false); @@ -286,16 +233,8 @@ void main() { // Trigger events on the map, and verify they've been broadcast to the stream final Stream> capturedEvents = stream.stream.take(5); - gmaps.event.trigger( - map, - 'click', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); - gmaps.event.trigger( - map, - 'rightclick', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(map, 'click', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); + gmaps.event.trigger(map, 'rightclick', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); // The following line causes 2 events gmaps.event.trigger(map, 'bounds_changed'); gmaps.event.trigger(map, 'idle'); @@ -309,9 +248,7 @@ void main() { expect(events[4], isA()); }); - testWidgets('stops listening to map events once disposed', ( - WidgetTester tester, - ) async { + testWidgets('stops listening to map events once disposed', (WidgetTester tester) async { controller = createController() ..debugSetOverrides( createMap: (_, __) => map, @@ -329,16 +266,8 @@ void main() { // Trigger events on the map, and verify they've been broadcast to the stream final Stream> capturedEvents = stream.stream.take(5); - gmaps.event.trigger( - map, - 'click', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); - gmaps.event.trigger( - map, - 'rightclick', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(map, 'click', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); + gmaps.event.trigger(map, 'rightclick', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); // The following line causes 2 events gmaps.event.trigger(map, 'bounds_changed'); gmaps.event.trigger(map, 'idle'); @@ -348,9 +277,7 @@ void main() { expect(events, isEmpty); }); - testWidgets("binds geometry controllers to map's", ( - WidgetTester tester, - ) async { + testWidgets("binds geometry controllers to map's", (WidgetTester tester) async { controller = createController() ..debugSetOverrides( createMap: (_, __) => map, @@ -375,9 +302,7 @@ void main() { testWidgets('renders initial geometry', (WidgetTester tester) async { final mapObjects = MapObjects( - circles: { - const Circle(circleId: CircleId('circle-1'), zIndex: 1234), - }, + circles: {const Circle(circleId: CircleId('circle-1'), zIndex: 1234)}, heatmaps: { const Heatmap( heatmapId: HeatmapId('heatmap-1'), @@ -393,10 +318,7 @@ void main() { markers: { const Marker( markerId: MarkerId('marker-1'), - infoWindow: InfoWindow( - title: 'title for test', - snippet: 'snippet for test', - ), + infoWindow: InfoWindow(title: 'title for test', snippet: 'snippet for test'), ), }, polygons: { @@ -437,9 +359,7 @@ void main() { ], ), }, - tileOverlays: { - const TileOverlay(tileOverlayId: TileOverlayId('overlay-1')), - }, + tileOverlays: {const TileOverlay(tileOverlayId: TileOverlayId('overlay-1'))}, groundOverlays: { GroundOverlay.fromBounds( groundOverlayId: const GroundOverlayId('bounds_1'), @@ -513,9 +433,7 @@ void main() { expect(capturedOptions!.tilt, 0); }); - testWidgets('translates fortyFiveDegreeImageryEnabled option', ( - WidgetTester tester, - ) async { + testWidgets('translates fortyFiveDegreeImageryEnabled option', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( @@ -537,9 +455,7 @@ void main() { expect(capturedOptions!.tilt, isNull); }); - testWidgets('translates webGestureHandling option', ( - WidgetTester tester, - ) async { + testWidgets('translates webGestureHandling option', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( @@ -560,9 +476,7 @@ void main() { expect(capturedOptions!.gestureHandling, 'greedy'); }); - testWidgets('translates webCameraControlEnabled option', ( - WidgetTester tester, - ) async { + testWidgets('translates webCameraControlEnabled option', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( @@ -583,9 +497,7 @@ void main() { expect(capturedOptions!.cameraControl, isTrue); }); - testWidgets('translates webCameraControlPosition option', ( - WidgetTester tester, - ) async { + testWidgets('translates webCameraControlPosition option', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( @@ -611,9 +523,7 @@ void main() { ); }); - testWidgets('translates cameraTargetBounds option', ( - WidgetTester tester, - ) async { + testWidgets('translates cameraTargetBounds option', (WidgetTester tester) async { final mockLatLngBounds = LatLngBounds( southwest: const LatLng(20, 30), northeast: const LatLng(25, 35), @@ -644,9 +554,7 @@ void main() { expect(capturedBounds.west, mockLatLngBounds.southwest.longitude); }); - testWidgets('sets initial position when passed', ( - WidgetTester tester, - ) async { + testWidgets('sets initial position when passed', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( @@ -676,9 +584,7 @@ void main() { "elementType": "labels.text.fill", "stylers": [{"color": "#6b9a76"}] }]'''; - controller = createController( - mapConfiguration: const MapConfiguration(style: style), - ); + controller = createController(mapConfiguration: const MapConfiguration(style: style)); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { capturedOptions = options; @@ -692,9 +598,7 @@ void main() { expect(capturedOptions!.styles?.length, 1); }); - testWidgets('stores style errors for later querying', ( - WidgetTester tester, - ) async { + testWidgets('stores style errors for later querying', (WidgetTester tester) async { gmaps.MapOptions? capturedOptions; controller = createController( mapConfiguration: const MapConfiguration( @@ -717,9 +621,7 @@ void main() { expect(capturedOptions!.zoomControl, true); }); - testWidgets('setting invalid style leaves previous style', ( - WidgetTester tester, - ) async { + testWidgets('setting invalid style leaves previous style', (WidgetTester tester) async { gmaps.MapOptions? initialCapturedOptions; gmaps.MapOptions? updatedCapturedOptions; const style = ''' @@ -728,9 +630,7 @@ void main() { "elementType": "labels.text.fill", "stylers": [{"color": "#6b9a76"}] }]'''; - controller = createController( - mapConfiguration: const MapConfiguration(style: style), - ); + controller = createController(mapConfiguration: const MapConfiguration(style: style)); controller.debugSetOverrides( createMap: (_, gmaps.MapOptions options) { initialCapturedOptions = options; @@ -742,17 +642,12 @@ void main() { ); controller.init(); - controller.updateMapConfiguration( - const MapConfiguration(style: '[[invalid style'), - ); + controller.updateMapConfiguration(const MapConfiguration(style: '[[invalid style')); expect(initialCapturedOptions, isNotNull); expect(initialCapturedOptions!.styles?.length, 1); // The styles should not have changed. - expect( - updatedCapturedOptions!.styles, - initialCapturedOptions!.styles, - ); + expect(updatedCapturedOptions!.styles, initialCapturedOptions!.styles); }); }); @@ -762,15 +657,9 @@ void main() { expect(controller.trafficLayer, isNull); }); - testWidgets('initializes with traffic layer', ( - WidgetTester tester, - ) async { + testWidgets('initializes with traffic layer', (WidgetTester tester) async { controller = - createController( - mapConfiguration: const MapConfiguration( - trafficEnabled: true, - ), - ) + createController(mapConfiguration: const MapConfiguration(trafficEnabled: true)) ..debugSetOverrides(createMap: (_, __) => map) ..init(); expect(controller.trafficLayer, isNotNull); @@ -796,9 +685,7 @@ void main() { group('updateMapConfiguration', () { testWidgets('can update `options`', (WidgetTester tester) async { - controller.updateMapConfiguration( - const MapConfiguration(mapType: MapType.satellite), - ); + controller.updateMapConfiguration(const MapConfiguration(mapType: MapType.satellite)); expect(map.mapTypeId, gmaps.MapTypeId.SATELLITE); }); @@ -806,15 +693,11 @@ void main() { testWidgets('can turn on/off traffic', (WidgetTester tester) async { expect(controller.trafficLayer, isNull); - controller.updateMapConfiguration( - const MapConfiguration(trafficEnabled: true), - ); + controller.updateMapConfiguration(const MapConfiguration(trafficEnabled: true)); expect(controller.trafficLayer, isNotNull); - controller.updateMapConfiguration( - const MapConfiguration(trafficEnabled: false), - ); + controller.updateMapConfiguration(const MapConfiguration(trafficEnabled: false)); expect(controller.trafficLayer, isNull); }); @@ -826,17 +709,13 @@ void main() { "elementType": "labels.text.fill", "stylers": [{"color": "#6b9a76"}] }]'''; - controller.updateMapConfiguration( - const MapConfiguration(style: style), - ); + controller.updateMapConfiguration(const MapConfiguration(style: style)); expect(controller.styles.length, 1); }); testWidgets('can update style', (WidgetTester tester) async { - controller.updateMapConfiguration( - const MapConfiguration(style: '[[[invalid style'), - ); + controller.updateMapConfiguration(const MapConfiguration(style: '[[[invalid style')); expect(controller.styles, isEmpty); expect(controller.lastStyleError, isNotNull); @@ -846,18 +725,14 @@ void main() { group('viewport getters', () { testWidgets('getVisibleRegion', (WidgetTester tester) async { final gmaps.LatLng gmCenter = map.center; - final center = LatLng( - gmCenter.lat.toDouble(), - gmCenter.lng.toDouble(), - ); + final center = LatLng(gmCenter.lat.toDouble(), gmCenter.lng.toDouble()); final LatLngBounds bounds = await controller.getVisibleRegion(); expect( bounds.contains(center), isTrue, - reason: - 'The computed visible region must contain the center of the created map.', + reason: 'The computed visible region must contain the center of the created map.', ); }); @@ -894,11 +769,7 @@ void main() { controller.updateCircles(CircleUpdates.from(previous, current)); verify(mock.removeCircles({const CircleId('to-be-removed')})); - verify( - mock.addCircles({ - const Circle(circleId: CircleId('to-be-added')), - }), - ); + verify(mock.addCircles({const Circle(circleId: CircleId('to-be-added'))})); verify( mock.changeCircles({ const Circle(circleId: CircleId('to-be-updated'), visible: false), @@ -956,9 +827,7 @@ void main() { controller.updateHeatmaps(HeatmapUpdates.from(previous, current)); - verify( - mock.removeHeatmaps({const HeatmapId('to-be-removed')}), - ); + verify(mock.removeHeatmaps({const HeatmapId('to-be-removed')})); verify( mock.addHeatmaps({ const Heatmap( @@ -997,11 +866,7 @@ void main() { await controller.updateMarkers(MarkerUpdates.from(previous, current)); verify(mock.removeMarkers({const MarkerId('to-be-removed')})); - verify( - mock.addMarkers({ - const Marker(markerId: MarkerId('to-be-added')), - }), - ); + verify(mock.addMarkers({const Marker(markerId: MarkerId('to-be-added'))})); verify( mock.changeMarkers({ const Marker(markerId: MarkerId('to-be-updated'), visible: false), @@ -1025,20 +890,11 @@ void main() { controller.updatePolygons(PolygonUpdates.from(previous, current)); - verify( - mock.removePolygons({const PolygonId('to-be-removed')}), - ); - verify( - mock.addPolygons({ - const Polygon(polygonId: PolygonId('to-be-added')), - }), - ); + verify(mock.removePolygons({const PolygonId('to-be-removed')})); + verify(mock.addPolygons({const Polygon(polygonId: PolygonId('to-be-added'))})); verify( mock.changePolygons({ - const Polygon( - polygonId: PolygonId('to-be-updated'), - visible: false, - ), + const Polygon(polygonId: PolygonId('to-be-updated'), visible: false), }), ); }); @@ -1053,29 +909,19 @@ void main() { }; final current = { - const Polyline( - polylineId: PolylineId('to-be-updated'), - visible: false, - ), + const Polyline(polylineId: PolylineId('to-be-updated'), visible: false), const Polyline(polylineId: PolylineId('to-be-added')), }; controller.updatePolylines(PolylineUpdates.from(previous, current)); + verify(mock.removePolylines({const PolylineId('to-be-removed')})); verify( - mock.removePolylines({const PolylineId('to-be-removed')}), - ); - verify( - mock.addPolylines({ - const Polyline(polylineId: PolylineId('to-be-added')), - }), + mock.addPolylines({const Polyline(polylineId: PolylineId('to-be-added'))}), ); verify( mock.changePolylines({ - const Polyline( - polylineId: PolylineId('to-be-updated'), - visible: false, - ), + const Polyline(polylineId: PolylineId('to-be-updated'), visible: false), }), ); }); @@ -1092,18 +938,11 @@ void main() { )..debugSetOverrides(tileOverlays: mock); controller.updateTileOverlays({ - const TileOverlay( - tileOverlayId: TileOverlayId('to-be-updated'), - visible: false, - ), + const TileOverlay(tileOverlayId: TileOverlayId('to-be-updated'), visible: false), const TileOverlay(tileOverlayId: TileOverlayId('to-be-added')), }); - verify( - mock.removeTileOverlays({ - const TileOverlayId('to-be-removed'), - }), - ); + verify(mock.removeTileOverlays({const TileOverlayId('to-be-removed')})); verify( mock.addTileOverlays({ const TileOverlay(tileOverlayId: TileOverlayId('to-be-added')), @@ -1111,18 +950,14 @@ void main() { ); verify( mock.changeTileOverlays({ - const TileOverlay( - tileOverlayId: TileOverlayId('to-be-updated'), - visible: false, - ), + const TileOverlay(tileOverlayId: TileOverlayId('to-be-updated'), visible: false), }), ); }); testWidgets('updateGroundOverlays', (WidgetTester tester) async { final mock = MockGroundOverlaysController(); - controller = createController() - ..debugSetOverrides(groundOverlays: mock); + controller = createController()..debugSetOverrides(groundOverlays: mock); final bounds = LatLngBounds( northeast: const LatLng(100, 0), @@ -1151,24 +986,17 @@ void main() { position: position, ); - final previous = { - groundOverlayToBeUpdated, - groundOverlayToBeRemoved, - }; + final previous = {groundOverlayToBeUpdated, groundOverlayToBeRemoved}; final current = { groundOverlayToBeUpdated.copyWith(visibleParam: false), groundOverlayToBeAdded, }; - controller.updateGroundOverlays( - GroundOverlayUpdates.from(previous, current), - ); + controller.updateGroundOverlays(GroundOverlayUpdates.from(previous, current)); verify( - mock.removeGroundOverlays({ - groundOverlayToBeRemoved.groundOverlayId, - }), + mock.removeGroundOverlays({groundOverlayToBeRemoved.groundOverlayId}), ); verify(mock.addGroundOverlays({groundOverlayToBeAdded})); verify( diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.mocks.dart index c08034d58f1e..ca94f9a80994 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_controller_test.mocks.dart @@ -28,8 +28,7 @@ import 'google_maps_controller_test.dart' as _i5; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeMarkerController_0 extends _i1.SmartFake - implements _i2.MarkerController { +class _FakeMarkerController_0 extends _i1.SmartFake implements _i2.MarkerController { _FakeMarkerController_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -39,43 +38,31 @@ class _FakeMarkerController_0 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockCirclesController extends _i1.Mock implements _i2.CirclesController { @override - Map<_i3.CircleId, _i2.CircleController> get circles => - (super.noSuchMethod( - Invocation.getter(#circles), - returnValue: <_i3.CircleId, _i2.CircleController>{}, - returnValueForMissingStub: <_i3.CircleId, _i2.CircleController>{}, - ) - as Map<_i3.CircleId, _i2.CircleController>); + Map<_i3.CircleId, _i2.CircleController> get circles => (super.noSuchMethod( + Invocation.getter(#circles), + returnValue: <_i3.CircleId, _i2.CircleController>{}, + returnValueForMissingStub: <_i3.CircleId, _i2.CircleController>{}, + ) as Map<_i3.CircleId, _i2.CircleController>); @override - _i4.Map get googleMap => - (super.noSuchMethod( - Invocation.getter(#googleMap), - returnValue: _i5.mapShim(), - returnValueForMissingStub: _i5.mapShim(), - ) - as _i4.Map); + _i4.Map get googleMap => (super.noSuchMethod( + Invocation.getter(#googleMap), + returnValue: _i5.mapShim(), + returnValueForMissingStub: _i5.mapShim(), + ) as _i4.Map); @override int get mapId => - (super.noSuchMethod( - Invocation.getter(#mapId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#mapId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - set googleMap(_i4.Map? value) => super.noSuchMethod( - Invocation.setter(#googleMap, value), - returnValueForMissingStub: null, - ); + set googleMap(_i4.Map? value) => + super.noSuchMethod(Invocation.setter(#googleMap, value), returnValueForMissingStub: null); @override - set mapId(int? value) => super.noSuchMethod( - Invocation.setter(#mapId, value), - returnValueForMissingStub: null, - ); + set mapId(int? value) => + super.noSuchMethod(Invocation.setter(#mapId, value), returnValueForMissingStub: null); @override void addCircles(Set<_i3.Circle>? circlesToAdd) => super.noSuchMethod( @@ -90,11 +77,10 @@ class MockCirclesController extends _i1.Mock implements _i2.CirclesController { ); @override - void removeCircles(Set<_i3.CircleId>? circleIdsToRemove) => - super.noSuchMethod( - Invocation.method(#removeCircles, [circleIdsToRemove]), - returnValueForMissingStub: null, - ); + void removeCircles(Set<_i3.CircleId>? circleIdsToRemove) => super.noSuchMethod( + Invocation.method(#removeCircles, [circleIdsToRemove]), + returnValueForMissingStub: null, + ); @override void bindToMap(int? mapId, _i4.Map? googleMap) => super.noSuchMethod( @@ -106,46 +92,33 @@ class MockCirclesController extends _i1.Mock implements _i2.CirclesController { /// A class which mocks [HeatmapsController]. /// /// See the documentation for Mockito's code generation for more information. -class MockHeatmapsController extends _i1.Mock - implements _i2.HeatmapsController { +class MockHeatmapsController extends _i1.Mock implements _i2.HeatmapsController { @override - Map<_i3.HeatmapId, _i2.HeatmapController> get heatmaps => - (super.noSuchMethod( - Invocation.getter(#heatmaps), - returnValue: <_i3.HeatmapId, _i2.HeatmapController>{}, - returnValueForMissingStub: <_i3.HeatmapId, _i2.HeatmapController>{}, - ) - as Map<_i3.HeatmapId, _i2.HeatmapController>); + Map<_i3.HeatmapId, _i2.HeatmapController> get heatmaps => (super.noSuchMethod( + Invocation.getter(#heatmaps), + returnValue: <_i3.HeatmapId, _i2.HeatmapController>{}, + returnValueForMissingStub: <_i3.HeatmapId, _i2.HeatmapController>{}, + ) as Map<_i3.HeatmapId, _i2.HeatmapController>); @override - _i4.Map get googleMap => - (super.noSuchMethod( - Invocation.getter(#googleMap), - returnValue: _i5.mapShim(), - returnValueForMissingStub: _i5.mapShim(), - ) - as _i4.Map); + _i4.Map get googleMap => (super.noSuchMethod( + Invocation.getter(#googleMap), + returnValue: _i5.mapShim(), + returnValueForMissingStub: _i5.mapShim(), + ) as _i4.Map); @override int get mapId => - (super.noSuchMethod( - Invocation.getter(#mapId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#mapId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - set googleMap(_i4.Map? value) => super.noSuchMethod( - Invocation.setter(#googleMap, value), - returnValueForMissingStub: null, - ); + set googleMap(_i4.Map? value) => + super.noSuchMethod(Invocation.setter(#googleMap, value), returnValueForMissingStub: null); @override - set mapId(int? value) => super.noSuchMethod( - Invocation.setter(#mapId, value), - returnValueForMissingStub: null, - ); + set mapId(int? value) => + super.noSuchMethod(Invocation.setter(#mapId, value), returnValueForMissingStub: null); @override void addHeatmaps(Set<_i3.Heatmap>? heatmapsToAdd) => super.noSuchMethod( @@ -160,11 +133,10 @@ class MockHeatmapsController extends _i1.Mock ); @override - void removeHeatmaps(Set<_i3.HeatmapId>? heatmapIdsToRemove) => - super.noSuchMethod( - Invocation.method(#removeHeatmaps, [heatmapIdsToRemove]), - returnValueForMissingStub: null, - ); + void removeHeatmaps(Set<_i3.HeatmapId>? heatmapIdsToRemove) => super.noSuchMethod( + Invocation.method(#removeHeatmaps, [heatmapIdsToRemove]), + returnValueForMissingStub: null, + ); @override void bindToMap(int? mapId, _i4.Map? googleMap) => super.noSuchMethod( @@ -176,46 +148,33 @@ class MockHeatmapsController extends _i1.Mock /// A class which mocks [PolygonsController]. /// /// See the documentation for Mockito's code generation for more information. -class MockPolygonsController extends _i1.Mock - implements _i2.PolygonsController { +class MockPolygonsController extends _i1.Mock implements _i2.PolygonsController { @override - Map<_i3.PolygonId, _i2.PolygonController> get polygons => - (super.noSuchMethod( - Invocation.getter(#polygons), - returnValue: <_i3.PolygonId, _i2.PolygonController>{}, - returnValueForMissingStub: <_i3.PolygonId, _i2.PolygonController>{}, - ) - as Map<_i3.PolygonId, _i2.PolygonController>); + Map<_i3.PolygonId, _i2.PolygonController> get polygons => (super.noSuchMethod( + Invocation.getter(#polygons), + returnValue: <_i3.PolygonId, _i2.PolygonController>{}, + returnValueForMissingStub: <_i3.PolygonId, _i2.PolygonController>{}, + ) as Map<_i3.PolygonId, _i2.PolygonController>); @override - _i4.Map get googleMap => - (super.noSuchMethod( - Invocation.getter(#googleMap), - returnValue: _i5.mapShim(), - returnValueForMissingStub: _i5.mapShim(), - ) - as _i4.Map); + _i4.Map get googleMap => (super.noSuchMethod( + Invocation.getter(#googleMap), + returnValue: _i5.mapShim(), + returnValueForMissingStub: _i5.mapShim(), + ) as _i4.Map); @override int get mapId => - (super.noSuchMethod( - Invocation.getter(#mapId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#mapId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - set googleMap(_i4.Map? value) => super.noSuchMethod( - Invocation.setter(#googleMap, value), - returnValueForMissingStub: null, - ); + set googleMap(_i4.Map? value) => + super.noSuchMethod(Invocation.setter(#googleMap, value), returnValueForMissingStub: null); @override - set mapId(int? value) => super.noSuchMethod( - Invocation.setter(#mapId, value), - returnValueForMissingStub: null, - ); + set mapId(int? value) => + super.noSuchMethod(Invocation.setter(#mapId, value), returnValueForMissingStub: null); @override void addPolygons(Set<_i3.Polygon>? polygonsToAdd) => super.noSuchMethod( @@ -230,11 +189,10 @@ class MockPolygonsController extends _i1.Mock ); @override - void removePolygons(Set<_i3.PolygonId>? polygonIdsToRemove) => - super.noSuchMethod( - Invocation.method(#removePolygons, [polygonIdsToRemove]), - returnValueForMissingStub: null, - ); + void removePolygons(Set<_i3.PolygonId>? polygonIdsToRemove) => super.noSuchMethod( + Invocation.method(#removePolygons, [polygonIdsToRemove]), + returnValueForMissingStub: null, + ); @override void bindToMap(int? mapId, _i4.Map? googleMap) => super.noSuchMethod( @@ -246,47 +204,33 @@ class MockPolygonsController extends _i1.Mock /// A class which mocks [PolylinesController]. /// /// See the documentation for Mockito's code generation for more information. -class MockPolylinesController extends _i1.Mock - implements _i2.PolylinesController { +class MockPolylinesController extends _i1.Mock implements _i2.PolylinesController { @override - Map<_i3.PolylineId, _i2.PolylineController> get lines => - (super.noSuchMethod( - Invocation.getter(#lines), - returnValue: <_i3.PolylineId, _i2.PolylineController>{}, - returnValueForMissingStub: - <_i3.PolylineId, _i2.PolylineController>{}, - ) - as Map<_i3.PolylineId, _i2.PolylineController>); + Map<_i3.PolylineId, _i2.PolylineController> get lines => (super.noSuchMethod( + Invocation.getter(#lines), + returnValue: <_i3.PolylineId, _i2.PolylineController>{}, + returnValueForMissingStub: <_i3.PolylineId, _i2.PolylineController>{}, + ) as Map<_i3.PolylineId, _i2.PolylineController>); @override - _i4.Map get googleMap => - (super.noSuchMethod( - Invocation.getter(#googleMap), - returnValue: _i5.mapShim(), - returnValueForMissingStub: _i5.mapShim(), - ) - as _i4.Map); + _i4.Map get googleMap => (super.noSuchMethod( + Invocation.getter(#googleMap), + returnValue: _i5.mapShim(), + returnValueForMissingStub: _i5.mapShim(), + ) as _i4.Map); @override int get mapId => - (super.noSuchMethod( - Invocation.getter(#mapId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#mapId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - set googleMap(_i4.Map? value) => super.noSuchMethod( - Invocation.setter(#googleMap, value), - returnValueForMissingStub: null, - ); + set googleMap(_i4.Map? value) => + super.noSuchMethod(Invocation.setter(#googleMap, value), returnValueForMissingStub: null); @override - set mapId(int? value) => super.noSuchMethod( - Invocation.setter(#mapId, value), - returnValueForMissingStub: null, - ); + set mapId(int? value) => + super.noSuchMethod(Invocation.setter(#mapId, value), returnValueForMissingStub: null); @override void addPolylines(Set<_i3.Polyline>? polylinesToAdd) => super.noSuchMethod( @@ -295,18 +239,16 @@ class MockPolylinesController extends _i1.Mock ); @override - void changePolylines(Set<_i3.Polyline>? polylinesToChange) => - super.noSuchMethod( - Invocation.method(#changePolylines, [polylinesToChange]), - returnValueForMissingStub: null, - ); + void changePolylines(Set<_i3.Polyline>? polylinesToChange) => super.noSuchMethod( + Invocation.method(#changePolylines, [polylinesToChange]), + returnValueForMissingStub: null, + ); @override - void removePolylines(Set<_i3.PolylineId>? polylineIdsToRemove) => - super.noSuchMethod( - Invocation.method(#removePolylines, [polylineIdsToRemove]), - returnValueForMissingStub: null, - ); + void removePolylines(Set<_i3.PolylineId>? polylineIdsToRemove) => super.noSuchMethod( + Invocation.method(#removePolylines, [polylineIdsToRemove]), + returnValueForMissingStub: null, + ); @override void bindToMap(int? mapId, _i4.Map? googleMap) => super.noSuchMethod( @@ -318,108 +260,74 @@ class MockPolylinesController extends _i1.Mock /// A class which mocks [MarkersController]. /// /// See the documentation for Mockito's code generation for more information. -class MockMarkersController extends _i1.Mock - implements _i2.MarkersController { +class MockMarkersController extends _i1.Mock implements _i2.MarkersController { @override - Map<_i3.MarkerId, _i2.MarkerController> get markers => - (super.noSuchMethod( - Invocation.getter(#markers), - returnValue: <_i3.MarkerId, _i2.MarkerController>{}, - returnValueForMissingStub: - <_i3.MarkerId, _i2.MarkerController>{}, - ) - as Map<_i3.MarkerId, _i2.MarkerController>); + Map<_i3.MarkerId, _i2.MarkerController> get markers => (super.noSuchMethod( + Invocation.getter(#markers), + returnValue: <_i3.MarkerId, _i2.MarkerController>{}, + returnValueForMissingStub: <_i3.MarkerId, _i2.MarkerController>{}, + ) as Map<_i3.MarkerId, _i2.MarkerController>); @override - _i4.Map get googleMap => - (super.noSuchMethod( - Invocation.getter(#googleMap), - returnValue: _i5.mapShim(), - returnValueForMissingStub: _i5.mapShim(), - ) - as _i4.Map); + _i4.Map get googleMap => (super.noSuchMethod( + Invocation.getter(#googleMap), + returnValue: _i5.mapShim(), + returnValueForMissingStub: _i5.mapShim(), + ) as _i4.Map); @override int get mapId => - (super.noSuchMethod( - Invocation.getter(#mapId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#mapId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - set googleMap(_i4.Map? value) => super.noSuchMethod( - Invocation.setter(#googleMap, value), - returnValueForMissingStub: null, - ); + set googleMap(_i4.Map? value) => + super.noSuchMethod(Invocation.setter(#googleMap, value), returnValueForMissingStub: null); @override - set mapId(int? value) => super.noSuchMethod( - Invocation.setter(#mapId, value), - returnValueForMissingStub: null, - ); + set mapId(int? value) => + super.noSuchMethod(Invocation.setter(#mapId, value), returnValueForMissingStub: null); @override - _i6.Future addMarkers(Set<_i3.Marker>? markersToAdd) => - (super.noSuchMethod( - Invocation.method(#addMarkers, [markersToAdd]), - returnValue: _i6.Future.value(), - returnValueForMissingStub: _i6.Future.value(), - ) - as _i6.Future); + _i6.Future addMarkers(Set<_i3.Marker>? markersToAdd) => (super.noSuchMethod( + Invocation.method(#addMarkers, [markersToAdd]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) as _i6.Future); @override _i6.Future<_i2.MarkerController> createMarkerController( _i3.Marker? marker, Object? markerOptions, _i4.InfoWindow? gmInfoWindow, - ) => - (super.noSuchMethod( - Invocation.method(#createMarkerController, [ - marker, - markerOptions, - gmInfoWindow, - ]), - returnValue: _i6.Future<_i2.MarkerController>.value( - _FakeMarkerController_0( - this, - Invocation.method(#createMarkerController, [ - marker, - markerOptions, - gmInfoWindow, - ]), - ), - ), - returnValueForMissingStub: - _i6.Future<_i2.MarkerController>.value( - _FakeMarkerController_0( - this, - Invocation.method(#createMarkerController, [ - marker, - markerOptions, - gmInfoWindow, - ]), - ), - ), - ) - as _i6.Future<_i2.MarkerController>); - - @override - _i6.Future changeMarkers(Set<_i3.Marker>? markersToChange) => - (super.noSuchMethod( - Invocation.method(#changeMarkers, [markersToChange]), - returnValue: _i6.Future.value(), - returnValueForMissingStub: _i6.Future.value(), - ) - as _i6.Future); - - @override - void removeMarkers(Set<_i3.MarkerId>? markerIdsToRemove) => - super.noSuchMethod( - Invocation.method(#removeMarkers, [markerIdsToRemove]), - returnValueForMissingStub: null, - ); + ) => (super.noSuchMethod( + Invocation.method(#createMarkerController, [marker, markerOptions, gmInfoWindow]), + returnValue: _i6.Future<_i2.MarkerController>.value( + _FakeMarkerController_0( + this, + Invocation.method(#createMarkerController, [marker, markerOptions, gmInfoWindow]), + ), + ), + returnValueForMissingStub: _i6.Future<_i2.MarkerController>.value( + _FakeMarkerController_0( + this, + Invocation.method(#createMarkerController, [marker, markerOptions, gmInfoWindow]), + ), + ), + ) as _i6.Future<_i2.MarkerController>); + + @override + _i6.Future changeMarkers(Set<_i3.Marker>? markersToChange) => (super.noSuchMethod( + Invocation.method(#changeMarkers, [markersToChange]), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) as _i6.Future); + + @override + void removeMarkers(Set<_i3.MarkerId>? markerIdsToRemove) => super.noSuchMethod( + Invocation.method(#removeMarkers, [markerIdsToRemove]), + returnValueForMissingStub: null, + ); @override void showMarkerInfoWindow(_i3.MarkerId? markerId) => super.noSuchMethod( @@ -434,13 +342,11 @@ class MockMarkersController extends _i1.Mock ); @override - bool isInfoWindowShown(_i3.MarkerId? markerId) => - (super.noSuchMethod( - Invocation.method(#isInfoWindowShown, [markerId]), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool isInfoWindowShown(_i3.MarkerId? markerId) => (super.noSuchMethod( + Invocation.method(#isInfoWindowShown, [markerId]), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override void bindToMap(int? mapId, _i4.Map? googleMap) => super.noSuchMethod( @@ -452,58 +358,44 @@ class MockMarkersController extends _i1.Mock /// A class which mocks [TileOverlaysController]. /// /// See the documentation for Mockito's code generation for more information. -class MockTileOverlaysController extends _i1.Mock - implements _i2.TileOverlaysController { +class MockTileOverlaysController extends _i1.Mock implements _i2.TileOverlaysController { @override - _i4.Map get googleMap => - (super.noSuchMethod( - Invocation.getter(#googleMap), - returnValue: _i5.mapShim(), - returnValueForMissingStub: _i5.mapShim(), - ) - as _i4.Map); + _i4.Map get googleMap => (super.noSuchMethod( + Invocation.getter(#googleMap), + returnValue: _i5.mapShim(), + returnValueForMissingStub: _i5.mapShim(), + ) as _i4.Map); @override int get mapId => - (super.noSuchMethod( - Invocation.getter(#mapId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#mapId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - set googleMap(_i4.Map? value) => super.noSuchMethod( - Invocation.setter(#googleMap, value), - returnValueForMissingStub: null, - ); + set googleMap(_i4.Map? value) => + super.noSuchMethod(Invocation.setter(#googleMap, value), returnValueForMissingStub: null); @override - set mapId(int? value) => super.noSuchMethod( - Invocation.setter(#mapId, value), - returnValueForMissingStub: null, - ); + set mapId(int? value) => + super.noSuchMethod(Invocation.setter(#mapId, value), returnValueForMissingStub: null); @override - void addTileOverlays(Set<_i3.TileOverlay>? tileOverlaysToAdd) => - super.noSuchMethod( - Invocation.method(#addTileOverlays, [tileOverlaysToAdd]), - returnValueForMissingStub: null, - ); + void addTileOverlays(Set<_i3.TileOverlay>? tileOverlaysToAdd) => super.noSuchMethod( + Invocation.method(#addTileOverlays, [tileOverlaysToAdd]), + returnValueForMissingStub: null, + ); @override - void changeTileOverlays(Set<_i3.TileOverlay>? tileOverlays) => - super.noSuchMethod( - Invocation.method(#changeTileOverlays, [tileOverlays]), - returnValueForMissingStub: null, - ); + void changeTileOverlays(Set<_i3.TileOverlay>? tileOverlays) => super.noSuchMethod( + Invocation.method(#changeTileOverlays, [tileOverlays]), + returnValueForMissingStub: null, + ); @override - void removeTileOverlays(Set<_i3.TileOverlayId>? tileOverlayIds) => - super.noSuchMethod( - Invocation.method(#removeTileOverlays, [tileOverlayIds]), - returnValueForMissingStub: null, - ); + void removeTileOverlays(Set<_i3.TileOverlayId>? tileOverlayIds) => super.noSuchMethod( + Invocation.method(#removeTileOverlays, [tileOverlayIds]), + returnValueForMissingStub: null, + ); @override void clearTileCache(_i3.TileOverlayId? tileOverlayId) => super.noSuchMethod( @@ -521,66 +413,50 @@ class MockTileOverlaysController extends _i1.Mock /// A class which mocks [GroundOverlaysController]. /// /// See the documentation for Mockito's code generation for more information. -class MockGroundOverlaysController extends _i1.Mock - implements _i2.GroundOverlaysController { +class MockGroundOverlaysController extends _i1.Mock implements _i2.GroundOverlaysController { @override - _i4.Map get googleMap => - (super.noSuchMethod( - Invocation.getter(#googleMap), - returnValue: _i5.mapShim(), - returnValueForMissingStub: _i5.mapShim(), - ) - as _i4.Map); + _i4.Map get googleMap => (super.noSuchMethod( + Invocation.getter(#googleMap), + returnValue: _i5.mapShim(), + returnValueForMissingStub: _i5.mapShim(), + ) as _i4.Map); @override int get mapId => - (super.noSuchMethod( - Invocation.getter(#mapId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#mapId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - set googleMap(_i4.Map? value) => super.noSuchMethod( - Invocation.setter(#googleMap, value), - returnValueForMissingStub: null, - ); + set googleMap(_i4.Map? value) => + super.noSuchMethod(Invocation.setter(#googleMap, value), returnValueForMissingStub: null); @override - set mapId(int? value) => super.noSuchMethod( - Invocation.setter(#mapId, value), - returnValueForMissingStub: null, - ); + set mapId(int? value) => + super.noSuchMethod(Invocation.setter(#mapId, value), returnValueForMissingStub: null); @override - void addGroundOverlays(Set<_i3.GroundOverlay>? groundOverlaysToAdd) => - super.noSuchMethod( - Invocation.method(#addGroundOverlays, [groundOverlaysToAdd]), - returnValueForMissingStub: null, - ); + void addGroundOverlays(Set<_i3.GroundOverlay>? groundOverlaysToAdd) => super.noSuchMethod( + Invocation.method(#addGroundOverlays, [groundOverlaysToAdd]), + returnValueForMissingStub: null, + ); @override - void changeGroundOverlays(Set<_i3.GroundOverlay>? groundOverlays) => - super.noSuchMethod( - Invocation.method(#changeGroundOverlays, [groundOverlays]), - returnValueForMissingStub: null, - ); + void changeGroundOverlays(Set<_i3.GroundOverlay>? groundOverlays) => super.noSuchMethod( + Invocation.method(#changeGroundOverlays, [groundOverlays]), + returnValueForMissingStub: null, + ); @override - void removeGroundOverlays(Set<_i3.GroundOverlayId>? groundOverlayIds) => - super.noSuchMethod( - Invocation.method(#removeGroundOverlays, [groundOverlayIds]), - returnValueForMissingStub: null, - ); + void removeGroundOverlays(Set<_i3.GroundOverlayId>? groundOverlayIds) => super.noSuchMethod( + Invocation.method(#removeGroundOverlays, [groundOverlayIds]), + returnValueForMissingStub: null, + ); @override - _i4.GroundOverlay? getGroundOverlay(_i3.GroundOverlayId? groundOverlayId) => - (super.noSuchMethod( - Invocation.method(#getGroundOverlay, [groundOverlayId]), - returnValueForMissingStub: null, - ) - as _i4.GroundOverlay?); + _i4.GroundOverlay? getGroundOverlay(_i3.GroundOverlayId? groundOverlayId) => (super.noSuchMethod( + Invocation.method(#getGroundOverlay, [groundOverlayId]), + returnValueForMissingStub: null, + ) as _i4.GroundOverlay?); @override void bindToMap(int? mapId, _i4.Map? googleMap) => super.noSuchMethod( diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart index 24cec1d5c3a7..ca1cde5334d9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.dart @@ -51,9 +51,7 @@ void main() { plugin.debugSetMapById({0: controller}); }); - testWidgets('cannot call methods after dispose', ( - WidgetTester tester, - ) async { + testWidgets('cannot call methods after dispose', (WidgetTester tester) async { plugin.dispose(mapId: 0); verify(controller.dispose()); @@ -70,50 +68,40 @@ void main() { const testMapId = 33930; const initialCameraPosition = CameraPosition(target: LatLng(0, 0)); - testWidgets( - 'returns an HtmlElementView and caches the controller for later', - (WidgetTester tester) async { - final cache = {}; - plugin.debugSetMapById(cache); - - final Widget widget = plugin.buildViewWithConfiguration( - testMapId, - onPlatformViewCreated, - widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: initialCameraPosition, - textDirection: TextDirection.ltr, - ), - ); - - expect(widget, isA()); - expect( - (widget as HtmlElementView).viewType, - contains('$testMapId'), - reason: - 'view type should contain the mapId passed when creating the map.', - ); - expect(cache, contains(testMapId)); - expect( - cache[testMapId], - isNotNull, - reason: 'cached controller cannot be null.', - ); - expect( - cache[testMapId]!.isInitialized, - isTrue, - reason: 'buildView calls init on the controller', - ); - }, - ); - - testWidgets('returns cached instance if it already exists', ( + testWidgets('returns an HtmlElementView and caches the controller for later', ( WidgetTester tester, ) async { + final cache = {}; + plugin.debugSetMapById(cache); + + final Widget widget = plugin.buildViewWithConfiguration( + testMapId, + onPlatformViewCreated, + widgetConfiguration: const MapWidgetConfiguration( + initialCameraPosition: initialCameraPosition, + textDirection: TextDirection.ltr, + ), + ); + + expect(widget, isA()); + expect( + (widget as HtmlElementView).viewType, + contains('$testMapId'), + reason: 'view type should contain the mapId passed when creating the map.', + ); + expect(cache, contains(testMapId)); + expect(cache[testMapId], isNotNull, reason: 'cached controller cannot be null.'); + expect( + cache[testMapId]!.isInitialized, + isTrue, + reason: 'buildView calls init on the controller', + ); + }); + + testWidgets('returns cached instance if it already exists', (WidgetTester tester) async { const expected = HtmlElementView(viewType: 'only-for-testing'); when(controller.widget).thenReturn(expected); - plugin.debugSetMapById({ - testMapId: controller, - }); + plugin.debugSetMapById({testMapId: controller}); final Widget widget = plugin.buildViewWithConfiguration( testMapId, @@ -127,45 +115,43 @@ void main() { expect(widget, equals(expected)); }); - testWidgets( - 'asynchronously reports onPlatformViewCreated the first time it happens', - (WidgetTester tester) async { - final cache = {}; - plugin.debugSetMapById(cache); + testWidgets('asynchronously reports onPlatformViewCreated the first time it happens', ( + WidgetTester tester, + ) async { + final cache = {}; + plugin.debugSetMapById(cache); - plugin.buildViewWithConfiguration( - testMapId, - onPlatformViewCreated, - widgetConfiguration: const MapWidgetConfiguration( - initialCameraPosition: initialCameraPosition, - textDirection: TextDirection.ltr, - ), - ); + plugin.buildViewWithConfiguration( + testMapId, + onPlatformViewCreated, + widgetConfiguration: const MapWidgetConfiguration( + initialCameraPosition: initialCameraPosition, + textDirection: TextDirection.ltr, + ), + ); - // Simulate Google Maps JS SDK being "ready" - cache[testMapId]!.stream.add(WebMapReadyEvent(testMapId)); + // Simulate Google Maps JS SDK being "ready" + cache[testMapId]!.stream.add(WebMapReadyEvent(testMapId)); - expect( - cache[testMapId]!.isInitialized, - isTrue, - reason: 'buildView calls init on the controller', - ); - expect( - await reportedMapIdCompleter.future, - testMapId, - reason: 'Should call onPlatformViewCreated with the mapId', - ); + expect( + cache[testMapId]!.isInitialized, + isTrue, + reason: 'buildView calls init on the controller', + ); + expect( + await reportedMapIdCompleter.future, + testMapId, + reason: 'Should call onPlatformViewCreated with the mapId', + ); - // Fire repeated event again... - cache[testMapId]!.stream.add(WebMapReadyEvent(testMapId)); - expect( - numberOnPlatformViewCreatedCalls, - equals(1), - reason: - 'Should not call onPlatformViewCreated for the same controller multiple times', - ); - }, - ); + // Fire repeated event again... + cache[testMapId]!.stream.add(WebMapReadyEvent(testMapId)); + expect( + numberOnPlatformViewCreatedCalls, + equals(1), + reason: 'Should not call onPlatformViewCreated for the same controller multiple times', + ); + }); }); group('setMapStyles', () { @@ -176,16 +162,12 @@ void main() { "stylers": [{"color": "#6b9a76"}] }]'''; - testWidgets('translates styles for controller', ( - WidgetTester tester, - ) async { + testWidgets('translates styles for controller', (WidgetTester tester) async { plugin.debugSetMapById({0: controller}); await plugin.setMapStyle(mapStyle, mapId: 0); - final dynamic captured = verify( - controller.updateStyles(captureThat(isList)), - ).captured[0]; + final dynamic captured = verify(controller.updateStyles(captureThat(isList))).captured[0]; final styles = captured as List; expect(styles.length, 1); @@ -197,9 +179,7 @@ void main() { expect((style.stylers[0]['color']! as JSString).toDart, '#6b9a76'); }); - testWidgets('throws MapStyleException for invalid styles', ( - WidgetTester tester, - ) async { + testWidgets('throws MapStyleException for invalid styles', (WidgetTester tester) async { plugin.debugSetMapById({0: controller}); expect(() async { @@ -225,50 +205,35 @@ void main() { }); // Geometry testWidgets('updateMarkers', (WidgetTester tester) async { - final expectedUpdates = MarkerUpdates.from( - const {}, - const {}, - ); + final expectedUpdates = MarkerUpdates.from(const {}, const {}); await plugin.updateMarkers(expectedUpdates, mapId: mapId); verify(controller.updateMarkers(expectedUpdates)); }); testWidgets('updatePolygons', (WidgetTester tester) async { - final expectedUpdates = PolygonUpdates.from( - const {}, - const {}, - ); + final expectedUpdates = PolygonUpdates.from(const {}, const {}); await plugin.updatePolygons(expectedUpdates, mapId: mapId); verify(controller.updatePolygons(expectedUpdates)); }); testWidgets('updatePolylines', (WidgetTester tester) async { - final expectedUpdates = PolylineUpdates.from( - const {}, - const {}, - ); + final expectedUpdates = PolylineUpdates.from(const {}, const {}); await plugin.updatePolylines(expectedUpdates, mapId: mapId); verify(controller.updatePolylines(expectedUpdates)); }); testWidgets('updateCircles', (WidgetTester tester) async { - final expectedUpdates = CircleUpdates.from( - const {}, - const {}, - ); + final expectedUpdates = CircleUpdates.from(const {}, const {}); await plugin.updateCircles(expectedUpdates, mapId: mapId); verify(controller.updateCircles(expectedUpdates)); }); testWidgets('updateHeatmaps', (WidgetTester tester) async { - final expectedUpdates = HeatmapUpdates.from( - const {}, - const {}, - ); + final expectedUpdates = HeatmapUpdates.from(const {}, const {}); await plugin.updateHeatmaps(expectedUpdates, mapId: mapId); @@ -280,10 +245,7 @@ void main() { const TileOverlay(tileOverlayId: TileOverlayId('overlay')), }; - await plugin.updateTileOverlays( - newTileOverlays: expectedOverlays, - mapId: mapId, - ); + await plugin.updateTileOverlays(newTileOverlays: expectedOverlays, mapId: mapId); verify(controller.updateTileOverlays(expectedOverlays)); }); @@ -296,18 +258,14 @@ void main() { }); // Camera testWidgets('animateCamera', (WidgetTester tester) async { - final CameraUpdate expectedUpdates = CameraUpdate.newLatLng( - const LatLng(43.3626, -5.8433), - ); + final CameraUpdate expectedUpdates = CameraUpdate.newLatLng(const LatLng(43.3626, -5.8433)); await plugin.animateCamera(expectedUpdates, mapId: mapId); verify(controller.moveCamera(expectedUpdates)); }); testWidgets('moveCamera', (WidgetTester tester) async { - final CameraUpdate expectedUpdates = CameraUpdate.newLatLng( - const LatLng(43.3628, -5.8478), - ); + final CameraUpdate expectedUpdates = CameraUpdate.newLatLng(const LatLng(43.3628, -5.8478)); await plugin.moveCamera(expectedUpdates, mapId: mapId); @@ -392,9 +350,7 @@ void main() { late StreamController> streamController; setUp(() { streamController = StreamController>.broadcast(); - when( - controller.events, - ).thenAnswer((Invocation realInvocation) => streamController.stream); + when(controller.events).thenAnswer((Invocation realInvocation) => streamController.stream); plugin.debugSetMapById({mapId: controller}); }); @@ -420,8 +376,7 @@ void main() { testWidgets('onCameraMoveStarted', (WidgetTester tester) async { final event = CameraMoveStartedEvent(mapId); - final Stream stream = plugin - .onCameraMoveStarted(mapId: mapId); + final Stream stream = plugin.onCameraMoveStarted(mapId: mapId); await testStreamFiltering(stream, event); }); @@ -431,18 +386,14 @@ void main() { const CameraPosition(target: LatLng(43.3790, -5.8660)), ); - final Stream stream = plugin.onCameraMove( - mapId: mapId, - ); + final Stream stream = plugin.onCameraMove(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onCameraIdle', (WidgetTester tester) async { final event = CameraIdleEvent(mapId); - final Stream stream = plugin.onCameraIdle( - mapId: mapId, - ); + final Stream stream = plugin.onCameraIdle(mapId: mapId); await testStreamFiltering(stream, event); }); @@ -457,9 +408,7 @@ void main() { testWidgets('onInfoWindowTap', (WidgetTester tester) async { final event = InfoWindowTapEvent(mapId, const MarkerId('test-123')); - final Stream stream = plugin.onInfoWindowTap( - mapId: mapId, - ); + final Stream stream = plugin.onInfoWindowTap(mapId: mapId); await testStreamFiltering(stream, event); }); @@ -470,9 +419,7 @@ void main() { const MarkerId('test-123'), ); - final Stream stream = plugin.onMarkerDragStart( - mapId: mapId, - ); + final Stream stream = plugin.onMarkerDragStart(mapId: mapId); await testStreamFiltering(stream, event); }); @@ -483,9 +430,7 @@ void main() { const MarkerId('test-123'), ); - final Stream stream = plugin.onMarkerDrag( - mapId: mapId, - ); + final Stream stream = plugin.onMarkerDrag(mapId: mapId); await testStreamFiltering(stream, event); }); @@ -496,9 +441,7 @@ void main() { const MarkerId('test-123'), ); - final Stream stream = plugin.onMarkerDragEnd( - mapId: mapId, - ); + final Stream stream = plugin.onMarkerDragEnd(mapId: mapId); await testStreamFiltering(stream, event); }); @@ -506,18 +449,14 @@ void main() { testWidgets('onPolygonTap', (WidgetTester tester) async { final event = PolygonTapEvent(mapId, const PolygonId('test-123')); - final Stream stream = plugin.onPolygonTap( - mapId: mapId, - ); + final Stream stream = plugin.onPolygonTap(mapId: mapId); await testStreamFiltering(stream, event); }); testWidgets('onPolylineTap', (WidgetTester tester) async { final event = PolylineTapEvent(mapId, const PolylineId('test-123')); - final Stream stream = plugin.onPolylineTap( - mapId: mapId, - ); + final Stream stream = plugin.onPolylineTap(mapId: mapId); await testStreamFiltering(stream, event); }); @@ -539,9 +478,7 @@ void main() { testWidgets('onLongPress', (WidgetTester tester) async { final event = MapLongPressEvent(mapId, const LatLng(43.3608, -5.8425)); - final Stream stream = plugin.onLongPress( - mapId: mapId, - ); + final Stream stream = plugin.onLongPress(mapId: mapId); await testStreamFiltering(stream, event); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart index 4a8fa105c250..489ceef04dd8 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/google_maps_plugin_test.mocks.dart @@ -27,97 +27,70 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeMapConfiguration_0 extends _i1.SmartFake - implements _i2.MapConfiguration { +class _FakeMapConfiguration_0 extends _i1.SmartFake implements _i2.MapConfiguration { _FakeMapConfiguration_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeStreamController_1 extends _i1.SmartFake - implements _i3.StreamController { +class _FakeStreamController_1 extends _i1.SmartFake implements _i3.StreamController { _FakeStreamController_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeLatLngBounds_2 extends _i1.SmartFake implements _i2.LatLngBounds { - _FakeLatLngBounds_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeLatLngBounds_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeScreenCoordinate_3 extends _i1.SmartFake - implements _i2.ScreenCoordinate { +class _FakeScreenCoordinate_3 extends _i1.SmartFake implements _i2.ScreenCoordinate { _FakeScreenCoordinate_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeLatLng_4 extends _i1.SmartFake implements _i2.LatLng { - _FakeLatLng_4(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeLatLng_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [GoogleMapController]. /// /// See the documentation for Mockito's code generation for more information. -class MockGoogleMapController extends _i1.Mock - implements _i4.GoogleMapController { +class MockGoogleMapController extends _i1.Mock implements _i4.GoogleMapController { @override - _i2.MapConfiguration get configuration => - (super.noSuchMethod( - Invocation.getter(#configuration), - returnValue: _FakeMapConfiguration_0( - this, - Invocation.getter(#configuration), - ), - returnValueForMissingStub: _FakeMapConfiguration_0( - this, - Invocation.getter(#configuration), - ), - ) - as _i2.MapConfiguration); + _i2.MapConfiguration get configuration => (super.noSuchMethod( + Invocation.getter(#configuration), + returnValue: _FakeMapConfiguration_0(this, Invocation.getter(#configuration)), + returnValueForMissingStub: _FakeMapConfiguration_0(this, Invocation.getter(#configuration)), + ) as _i2.MapConfiguration); @override - _i3.StreamController<_i2.MapEvent> get stream => - (super.noSuchMethod( - Invocation.getter(#stream), - returnValue: _FakeStreamController_1<_i2.MapEvent>( - this, - Invocation.getter(#stream), - ), - returnValueForMissingStub: - _FakeStreamController_1<_i2.MapEvent>( - this, - Invocation.getter(#stream), - ), - ) - as _i3.StreamController<_i2.MapEvent>); + _i3.StreamController<_i2.MapEvent> get stream => (super.noSuchMethod( + Invocation.getter(#stream), + returnValue: _FakeStreamController_1<_i2.MapEvent>(this, Invocation.getter(#stream)), + returnValueForMissingStub: _FakeStreamController_1<_i2.MapEvent>( + this, + Invocation.getter(#stream), + ), + ) as _i3.StreamController<_i2.MapEvent>); @override - _i3.Stream<_i2.MapEvent> get events => - (super.noSuchMethod( - Invocation.getter(#events), - returnValue: _i3.Stream<_i2.MapEvent>.empty(), - returnValueForMissingStub: - _i3.Stream<_i2.MapEvent>.empty(), - ) - as _i3.Stream<_i2.MapEvent>); + _i3.Stream<_i2.MapEvent> get events => (super.noSuchMethod( + Invocation.getter(#events), + returnValue: _i3.Stream<_i2.MapEvent>.empty(), + returnValueForMissingStub: _i3.Stream<_i2.MapEvent>.empty(), + ) as _i3.Stream<_i2.MapEvent>); @override - bool get isInitialized => - (super.noSuchMethod( - Invocation.getter(#isInitialized), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isInitialized => (super.noSuchMethod( + Invocation.getter(#isInitialized), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - List<_i5.MapTypeStyle> get styles => - (super.noSuchMethod( - Invocation.getter(#styles), - returnValue: <_i5.MapTypeStyle>[], - returnValueForMissingStub: <_i5.MapTypeStyle>[], - ) - as List<_i5.MapTypeStyle>); + List<_i5.MapTypeStyle> get styles => (super.noSuchMethod( + Invocation.getter(#styles), + returnValue: <_i5.MapTypeStyle>[], + returnValueForMissingStub: <_i5.MapTypeStyle>[], + ) as List<_i5.MapTypeStyle>); @override void debugSetOverrides({ @@ -148,17 +121,13 @@ class MockGoogleMapController extends _i1.Mock ); @override - void init() => super.noSuchMethod( - Invocation.method(#init, []), - returnValueForMissingStub: null, - ); + void init() => super.noSuchMethod(Invocation.method(#init, []), returnValueForMissingStub: null); @override - void updateMapConfiguration(_i2.MapConfiguration? update) => - super.noSuchMethod( - Invocation.method(#updateMapConfiguration, [update]), - returnValueForMissingStub: null, - ); + void updateMapConfiguration(_i2.MapConfiguration? update) => super.noSuchMethod( + Invocation.method(#updateMapConfiguration, [update]), + returnValueForMissingStub: null, + ); @override void updateStyles(List<_i5.MapTypeStyle>? styles) => super.noSuchMethod( @@ -167,79 +136,51 @@ class MockGoogleMapController extends _i1.Mock ); @override - _i3.Future<_i2.LatLngBounds> getVisibleRegion() => - (super.noSuchMethod( - Invocation.method(#getVisibleRegion, []), - returnValue: _i3.Future<_i2.LatLngBounds>.value( - _FakeLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.LatLngBounds>.value( - _FakeLatLngBounds_2( - this, - Invocation.method(#getVisibleRegion, []), - ), - ), - ) - as _i3.Future<_i2.LatLngBounds>); + _i3.Future<_i2.LatLngBounds> getVisibleRegion() => (super.noSuchMethod( + Invocation.method(#getVisibleRegion, []), + returnValue: _i3.Future<_i2.LatLngBounds>.value( + _FakeLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.LatLngBounds>.value( + _FakeLatLngBounds_2(this, Invocation.method(#getVisibleRegion, [])), + ), + ) as _i3.Future<_i2.LatLngBounds>); @override - _i3.Future<_i2.ScreenCoordinate> getScreenCoordinate(_i2.LatLng? latLng) => - (super.noSuchMethod( - Invocation.method(#getScreenCoordinate, [latLng]), - returnValue: _i3.Future<_i2.ScreenCoordinate>.value( - _FakeScreenCoordinate_3( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.ScreenCoordinate>.value( - _FakeScreenCoordinate_3( - this, - Invocation.method(#getScreenCoordinate, [latLng]), - ), - ), - ) - as _i3.Future<_i2.ScreenCoordinate>); + _i3.Future<_i2.ScreenCoordinate> getScreenCoordinate(_i2.LatLng? latLng) => (super.noSuchMethod( + Invocation.method(#getScreenCoordinate, [latLng]), + returnValue: _i3.Future<_i2.ScreenCoordinate>.value( + _FakeScreenCoordinate_3(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + returnValueForMissingStub: _i3.Future<_i2.ScreenCoordinate>.value( + _FakeScreenCoordinate_3(this, Invocation.method(#getScreenCoordinate, [latLng])), + ), + ) as _i3.Future<_i2.ScreenCoordinate>); @override - _i3.Future<_i2.LatLng> getLatLng(_i2.ScreenCoordinate? screenCoordinate) => - (super.noSuchMethod( - Invocation.method(#getLatLng, [screenCoordinate]), - returnValue: _i3.Future<_i2.LatLng>.value( - _FakeLatLng_4( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.LatLng>.value( - _FakeLatLng_4( - this, - Invocation.method(#getLatLng, [screenCoordinate]), - ), - ), - ) - as _i3.Future<_i2.LatLng>); + _i3.Future<_i2.LatLng> getLatLng(_i2.ScreenCoordinate? screenCoordinate) => (super.noSuchMethod( + Invocation.method(#getLatLng, [screenCoordinate]), + returnValue: _i3.Future<_i2.LatLng>.value( + _FakeLatLng_4(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + returnValueForMissingStub: _i3.Future<_i2.LatLng>.value( + _FakeLatLng_4(this, Invocation.method(#getLatLng, [screenCoordinate])), + ), + ) as _i3.Future<_i2.LatLng>); @override - _i3.Future moveCamera(_i2.CameraUpdate? cameraUpdate) => - (super.noSuchMethod( - Invocation.method(#moveCamera, [cameraUpdate]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future moveCamera(_i2.CameraUpdate? cameraUpdate) => (super.noSuchMethod( + Invocation.method(#moveCamera, [cameraUpdate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future getZoomLevel() => - (super.noSuchMethod( - Invocation.method(#getZoomLevel, []), - returnValue: _i3.Future.value(0.0), - returnValueForMissingStub: _i3.Future.value(0.0), - ) - as _i3.Future); + _i3.Future getZoomLevel() => (super.noSuchMethod( + Invocation.method(#getZoomLevel, []), + returnValue: _i3.Future.value(0.0), + returnValueForMissingStub: _i3.Future.value(0.0), + ) as _i3.Future); @override void updateCircles(_i2.CircleUpdates? updates) => super.noSuchMethod( @@ -266,41 +207,34 @@ class MockGoogleMapController extends _i1.Mock ); @override - _i3.Future updateMarkers(_i2.MarkerUpdates? updates) => - (super.noSuchMethod( - Invocation.method(#updateMarkers, [updates]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); - - @override - void updateClusterManagers(_i2.ClusterManagerUpdates? updates) => - super.noSuchMethod( - Invocation.method(#updateClusterManagers, [updates]), - returnValueForMissingStub: null, - ); + _i3.Future updateMarkers(_i2.MarkerUpdates? updates) => (super.noSuchMethod( + Invocation.method(#updateMarkers, [updates]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - void updateGroundOverlays(_i2.GroundOverlayUpdates? updates) => - super.noSuchMethod( - Invocation.method(#updateGroundOverlays, [updates]), - returnValueForMissingStub: null, - ); + void updateClusterManagers(_i2.ClusterManagerUpdates? updates) => super.noSuchMethod( + Invocation.method(#updateClusterManagers, [updates]), + returnValueForMissingStub: null, + ); @override - void updateTileOverlays(Set<_i2.TileOverlay>? newOverlays) => - super.noSuchMethod( - Invocation.method(#updateTileOverlays, [newOverlays]), - returnValueForMissingStub: null, - ); + void updateGroundOverlays(_i2.GroundOverlayUpdates? updates) => super.noSuchMethod( + Invocation.method(#updateGroundOverlays, [updates]), + returnValueForMissingStub: null, + ); @override - void clearTileCache(_i2.TileOverlayId? id) => super.noSuchMethod( - Invocation.method(#clearTileCache, [id]), + void updateTileOverlays(Set<_i2.TileOverlay>? newOverlays) => super.noSuchMethod( + Invocation.method(#updateTileOverlays, [newOverlays]), returnValueForMissingStub: null, ); + @override + void clearTileCache(_i2.TileOverlayId? id) => + super.noSuchMethod(Invocation.method(#clearTileCache, [id]), returnValueForMissingStub: null); + @override void showInfoWindow(_i2.MarkerId? markerId) => super.noSuchMethod( Invocation.method(#showInfoWindow, [markerId]), @@ -314,26 +248,20 @@ class MockGoogleMapController extends _i1.Mock ); @override - bool isInfoWindowShown(_i2.MarkerId? markerId) => - (super.noSuchMethod( - Invocation.method(#isInfoWindowShown, [markerId]), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool isInfoWindowShown(_i2.MarkerId? markerId) => (super.noSuchMethod( + Invocation.method(#isInfoWindowShown, [markerId]), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - bool isAdvancedMarkersAvailable() => - (super.noSuchMethod( - Invocation.method(#isAdvancedMarkersAvailable, []), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool isAdvancedMarkersAvailable() => (super.noSuchMethod( + Invocation.method(#isAdvancedMarkersAvailable, []), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); + void dispose() => + super.noSuchMethod(Invocation.method(#dispose, []), returnValueForMissingStub: null); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart index 5cc202d21fc6..3db47dc988a4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_clustering_test.dart @@ -18,8 +18,7 @@ void main() { GoogleMapsFlutterPlatform.instance.enableDebugInspection(); final GoogleMapsFlutterPlatform plugin = GoogleMapsFlutterPlatform.instance; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; const mapCenter = LatLng(20, 20); const initialCameraPosition = CameraPosition(target: mapCenter); @@ -58,10 +57,7 @@ void main() { initialCameraPosition: initialCameraPosition, textDirection: TextDirection.ltr, ), - mapObjects: MapObjects( - clusterManagers: clusterManagers, - markers: initialMarkers, - ), + mapObjects: MapObjects(clusterManagers: clusterManagers, markers: initialMarkers), ), ); @@ -71,10 +67,7 @@ void main() { final List clusters = await waitForValueMatchingPredicate>( tester, - () async => inspector.getClusters( - mapId: mapId, - clusterManagerId: clusterManagerId, - ), + () async => inspector.getClusters(mapId: mapId, clusterManagerId: clusterManagerId), (List clusters) => clusters.isNotEmpty, ) ?? []; @@ -84,9 +77,7 @@ void main() { // Copy only the first marker with null clusterManagerId. // This means that both markers should be removed from the cluster. - final updatedMarkers = { - _copyMarkerWithClusterManagerId(initialMarkers.first, null), - }; + final updatedMarkers = {_copyMarkerWithClusterManagerId(initialMarkers.first, null)}; final markerUpdates = MarkerUpdates.from(initialMarkers, updatedMarkers); await plugin.updateMarkers(markerUpdates, mapId: mapId); @@ -94,10 +85,7 @@ void main() { final List updatedClusters = await waitForValueMatchingPredicate>( tester, - () async => inspector.getClusters( - mapId: mapId, - clusterManagerId: clusterManagerId, - ), + () async => inspector.getClusters(mapId: mapId, clusterManagerId: clusterManagerId), (List clusters) => clusters.isNotEmpty, ) ?? []; @@ -105,9 +93,7 @@ void main() { expect(updatedClusters.length, 0); }); - testWidgets('clusters render once per batched add', ( - WidgetTester tester, - ) async { + testWidgets('clusters render once per batched add', (WidgetTester tester) async { const clusterManagerId = ClusterManagerId('cluster 1'); final clusterManagers = { @@ -142,10 +128,7 @@ void main() { (int id) async { final StreamSubscription? subscription = (inspector as GoogleMapsInspectorWeb) - .getClusteringEvents( - mapId: testMapId, - clusterManagerId: clusterManagerId, - ) + .getClusteringEvents(mapId: testMapId, clusterManagerId: clusterManagerId) ?.listen(events.add); await plugin.updateMarkers( @@ -161,10 +144,7 @@ void main() { initialCameraPosition: initialCameraPosition, textDirection: TextDirection.ltr, ), - mapObjects: MapObjects( - clusterManagers: clusterManagers, - markers: initialMarkers, - ), + mapObjects: MapObjects(clusterManagers: clusterManagers, markers: initialMarkers), ), ); @@ -209,10 +189,7 @@ Future waitForValueMatchingPredicate( return null; } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, @@ -236,11 +213,7 @@ Marker _copyMarkerWithClusterManagerId( } /// Pumps a [map] widget in [tester] of a certain [size], then waits until it settles. -Future _pumpMap( - WidgetTester tester, - Widget map, [ - Size size = const Size.square(200), -]) async { +Future _pumpMap(WidgetTester tester, Widget map, [Size size = const Size.square(200)]) async { await tester.pumpWidget(_wrapMap(map, size)); await tester.pumpAndSettle(); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart index f2bc3e69bda6..5da1235a71e1 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/marker_test.dart @@ -66,11 +66,7 @@ void main() { LegacyMarkerController(marker: marker, onDragStart: onDragStart); // Trigger a drag end event... - gmaps.event.trigger( - marker, - 'dragstart', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(marker, 'dragstart', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); expect(await methodCalled, isTrue); }); @@ -79,11 +75,7 @@ void main() { LegacyMarkerController(marker: marker, onDrag: onDrag); // Trigger a drag end event... - gmaps.event.trigger( - marker, - 'drag', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(marker, 'drag', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); expect(await methodCalled, isTrue); }); @@ -92,11 +84,7 @@ void main() { LegacyMarkerController(marker: marker, onDragEnd: onDragEnd); // Trigger a drag end event... - gmaps.event.trigger( - marker, - 'dragend', - gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0), - ); + gmaps.event.trigger(marker, 'dragend', gmaps.MapMouseEvent()..latLng = gmaps.LatLng(0, 0)); expect(await methodCalled, isTrue); }); @@ -116,9 +104,7 @@ void main() { expect(marker.position?.lng, equals(54)); }); - testWidgets('infoWindow null, showInfoWindow.', ( - WidgetTester tester, - ) async { + testWidgets('infoWindow null, showInfoWindow.', (WidgetTester tester) async { final controller = LegacyMarkerController(marker: marker); controller.showInfoWindow(); @@ -130,10 +116,7 @@ void main() { final infoWindow = gmaps.InfoWindow(); final map = gmaps.Map(createDivElement()); marker.set('map', map); - final controller = LegacyMarkerController( - marker: marker, - infoWindow: infoWindow, - ); + final controller = LegacyMarkerController(marker: marker, infoWindow: infoWindow); controller.showInfoWindow(); @@ -145,10 +128,7 @@ void main() { final infoWindow = gmaps.InfoWindow(); final map = gmaps.Map(createDivElement()); marker.set('map', map); - final controller = LegacyMarkerController( - marker: marker, - infoWindow: infoWindow, - ); + final controller = LegacyMarkerController(marker: marker, infoWindow: infoWindow); controller.hideInfoWindow(); @@ -163,10 +143,7 @@ void main() { final infoWindow = gmaps.InfoWindow(); final map = gmaps.Map(createDivElement()); marker.set('map', map); - controller = LegacyMarkerController( - marker: marker, - infoWindow: infoWindow, - ); + controller = LegacyMarkerController(marker: marker, infoWindow: infoWindow); }); testWidgets('drops gmaps instance', (WidgetTester tester) async { @@ -175,9 +152,7 @@ void main() { expect(controller.marker, isNull); }); - testWidgets('cannot call update after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call update after remove', (WidgetTester tester) async { final options = gmaps.MarkerOptions()..draggable = true; controller.remove(); @@ -187,9 +162,7 @@ void main() { }, throwsAssertionError); }); - testWidgets('cannot call showInfoWindow after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call showInfoWindow after remove', (WidgetTester tester) async { controller.remove(); expect(() { @@ -197,9 +170,7 @@ void main() { }, throwsStateError); }); - testWidgets('cannot call hideInfoWindow after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call hideInfoWindow after remove', (WidgetTester tester) async { controller.remove(); expect(() { diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart index 4c1be3ce22c7..01a65425d913 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/markers_test.dart @@ -32,9 +32,7 @@ void main() { setUp(() { events = StreamController>(); - clusterManagersController = ClusterManagersController( - stream: events, - ); + clusterManagersController = ClusterManagersController(stream: events); controller = LegacyMarkersController( stream: events, clusterManagersController: clusterManagersController, @@ -77,11 +75,7 @@ void main() { // Update the marker with draggable and position final updatedMarkers = { - const Marker( - markerId: MarkerId('1'), - draggable: true, - position: LatLng(42, 54), - ), + const Marker(markerId: MarkerId('1'), draggable: true, position: LatLng(42, 54)), }; await controller.changeMarkers(updatedMarkers); expect(controller.markers.length, 1); @@ -96,43 +90,38 @@ void main() { expect(position.lng, equals(54)); }); - testWidgets( - 'changeMarkers resets marker position if not passed when updating!', - (WidgetTester tester) async { - gmaps.Marker? marker; - gmaps.LatLng? position; - - final markers = { - const Marker(markerId: MarkerId('1'), position: LatLng(42, 54)), - }; - await controller.addMarkers(markers); - - marker = controller.markers[const MarkerId('1')]?.marker; - expect(marker, isNotNull); - expect(marker!.draggable, isFalse); - - position = marker.position; - expect(position, isNotNull); - expect(position!.lat, equals(42)); - expect(position.lng, equals(54)); - - // Update the marker without position - final updatedMarkers = { - const Marker(markerId: MarkerId('1'), draggable: true), - }; - await controller.changeMarkers(updatedMarkers); - expect(controller.markers.length, 1); - - marker = controller.markers[const MarkerId('1')]?.marker; - expect(marker, isNotNull); - expect(marker!.draggable, isTrue); - - position = marker.position; - expect(position, isNotNull); - expect(position!.lat, equals(0)); - expect(position.lng, equals(0)); - }, - ); + testWidgets('changeMarkers resets marker position if not passed when updating!', ( + WidgetTester tester, + ) async { + gmaps.Marker? marker; + gmaps.LatLng? position; + + final markers = {const Marker(markerId: MarkerId('1'), position: LatLng(42, 54))}; + await controller.addMarkers(markers); + + marker = controller.markers[const MarkerId('1')]?.marker; + expect(marker, isNotNull); + expect(marker!.draggable, isFalse); + + position = marker.position; + expect(position, isNotNull); + expect(position!.lat, equals(42)); + expect(position.lng, equals(54)); + + // Update the marker without position + final updatedMarkers = {const Marker(markerId: MarkerId('1'), draggable: true)}; + await controller.changeMarkers(updatedMarkers); + expect(controller.markers.length, 1); + + marker = controller.markers[const MarkerId('1')]?.marker; + expect(marker, isNotNull); + expect(marker!.draggable, isTrue); + + position = marker.position; + expect(position, isNotNull); + expect(position!.lat, equals(0)); + expect(position.lng, equals(0)); + }); testWidgets('removeMarkers', (WidgetTester tester) async { final markers = { @@ -146,10 +135,7 @@ void main() { expect(controller.markers.length, 3); // Remove some markers... - final markerIdsToRemove = { - const MarkerId('1'), - const MarkerId('3'), - }; + final markerIdsToRemove = {const MarkerId('1'), const MarkerId('3')}; controller.removeMarkers(markerIdsToRemove); @@ -181,9 +167,7 @@ void main() { }); // https://github.com/flutter/flutter/issues/67380 - testWidgets('only single InfoWindow is visible', ( - WidgetTester tester, - ) async { + testWidgets('only single InfoWindow is visible', (WidgetTester tester) async { final markers = { const Marker( markerId: MarkerId('1'), @@ -210,9 +194,7 @@ void main() { expect(controller.markers[const MarkerId('2')]?.infoWindowShown, isTrue); }); - testWidgets('markers with custom asset icon work', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom asset icon work', (WidgetTester tester) async { final markers = { Marker( markerId: const MarkerId('1'), @@ -223,8 +205,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final String assetUrl = icon!.url; @@ -240,9 +221,7 @@ void main() { expect(scaledSize.height, 48); }); - testWidgets('markers with custom asset icon and pixelratio work', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom asset icon and pixelratio work', (WidgetTester tester) async { final markers = { Marker( markerId: const MarkerId('1'), @@ -253,8 +232,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final String assetUrl = icon!.url; @@ -288,8 +266,7 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final String assetUrl = icon!.url; @@ -306,24 +283,18 @@ void main() { expect(scaledSize.height, 64); }); - testWidgets('markers with missing asset icon should not set size', ( - WidgetTester tester, - ) async { + testWidgets('markers with missing asset icon should not set size', (WidgetTester tester) async { final markers = { Marker( markerId: const MarkerId('1'), - icon: AssetMapBitmap( - 'assets/broken_asset_name.png', - imagePixelRatio: 2.0, - ), + icon: AssetMapBitmap('assets/broken_asset_name.png', imagePixelRatio: 2.0), ), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final String assetUrl = icon!.url; @@ -335,25 +306,19 @@ void main() { }); // https://github.com/flutter/flutter/issues/66622 - testWidgets('markers with custom bitmap icon work', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom bitmap icon work', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final String blobUrl = icon!.url; @@ -363,8 +328,7 @@ void main() { expect( response.bodyBytes, bytes, - reason: - 'Bytes from the Icon blob must match bytes used to create Marker', + reason: 'Bytes from the Icon blob must match bytes used to create Marker', ); final gmaps.Size size = icon.size!; @@ -380,22 +344,16 @@ void main() { expect(scaledSize.height, expectedSize); }); - testWidgets('markers with custom bitmap icon and pixelratio work', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom bitmap icon and pixelratio work', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); final markers = { - Marker( - markerId: const MarkerId('1'), - icon: BytesMapBitmap(bytes, imagePixelRatio: 1), - ), + Marker(markerId: const MarkerId('1'), icon: BytesMapBitmap(bytes, imagePixelRatio: 1)), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final gmaps.Size size = icon!.size!; @@ -411,22 +369,16 @@ void main() { }); // https://github.com/flutter/flutter/issues/73789 - testWidgets('markers with custom bitmap icon pass size to sdk', ( - WidgetTester tester, - ) async { + testWidgets('markers with custom bitmap icon pass size to sdk', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); final markers = { - Marker( - markerId: const MarkerId('1'), - icon: BytesMapBitmap(bytes, width: 20, height: 30), - ), + Marker(markerId: const MarkerId('1'), icon: BytesMapBitmap(bytes, width: 20, height: 30)), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final icon = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon, isNotNull); final gmaps.Size size = icon!.size!; @@ -439,9 +391,7 @@ void main() { }); // https://github.com/flutter/flutter/issues/67854 - testWidgets('InfoWindow snippet can have links', ( - WidgetTester tester, - ) async { + testWidgets('InfoWindow snippet can have links', (WidgetTester tester) async { final markers = { const Marker( markerId: MarkerId('1'), @@ -455,19 +405,12 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 1); - final content = - controller.markers[const MarkerId('1')]?.infoWindow?.content - as HTMLElement?; + final content = controller.markers[const MarkerId('1')]?.infoWindow?.content as HTMLElement?; expect(content, isNotNull); final String innerHtml = (content!.innerHTML as JSString).toDart; expect(innerHtml, contains('title for test')); - expect( - innerHtml, - contains( - 'Go to Google >>>', - ), - ); + expect(innerHtml, contains('Go to Google >>>')); }); // https://github.com/flutter/flutter/issues/67289 @@ -475,19 +418,14 @@ void main() { final markers = { const Marker( markerId: MarkerId('1'), - infoWindow: InfoWindow( - title: 'title for test', - snippet: 'some snippet', - ), + infoWindow: InfoWindow(title: 'title for test', snippet: 'some snippet'), ), }; await controller.addMarkers(markers); expect(controller.markers.length, 1); - final content = - controller.markers[const MarkerId('1')]?.infoWindow?.content - as HTMLElement?; + final content = controller.markers[const MarkerId('1')]?.infoWindow?.content as HTMLElement?; content?.click(); @@ -517,11 +455,9 @@ void main() { await controller.addMarkers(markers); expect(controller.markers.length, 2); - final icon1 = - controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; + final icon1 = controller.markers[const MarkerId('1')]?.marker?.icon as gmaps.Icon?; expect(icon1, isNotNull); - final icon2 = - controller.markers[const MarkerId('2')]?.marker?.icon as gmaps.Icon?; + final icon2 = controller.markers[const MarkerId('2')]?.marker?.icon as gmaps.Icon?; expect(icon2, isNotNull); expect(icon1!.anchor, isNotNull); @@ -532,9 +468,7 @@ void main() { expect(icon2.anchor!.y, height * anchorOffset.dy); }); - testWidgets('interpret correct zIndex in convertsion', ( - WidgetTester tester, - ) async { + testWidgets('interpret correct zIndex in convertsion', (WidgetTester tester) async { const markerId = MarkerId('1'); final markers = {const Marker(markerId: markerId, zIndexInt: 4)}; diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart index 16a42d85b03c..dfefc8e69aa3 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart @@ -37,30 +37,20 @@ void main() { const id = TileOverlayId(''); testWidgets('minimal initialization', (WidgetTester tester) async { - final controller = TileOverlayController( - tileOverlay: const TileOverlay(tileOverlayId: id), - ); + final controller = TileOverlayController(tileOverlay: const TileOverlay(tileOverlayId: id)); final gmaps.Size? size = controller.gmMapType.tileSize; expect(size?.width, TileOverlayController.logicalTileSize); expect(size?.height, TileOverlayController.logicalTileSize); - expect( - controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document), - null, - ); + expect(controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document), null); }); testWidgets('produces image tiles', (WidgetTester tester) async { final controller = TileOverlayController( - tileOverlay: const TileOverlay( - tileOverlayId: id, - tileProvider: TestTileProvider(), - ), + tileOverlay: const TileOverlay(tileOverlayId: id, tileProvider: TestTileProvider()), ); - final img = - controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document)! - as HTMLImageElement; + final img = controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document)! as HTMLImageElement; expect(img.naturalWidth, 0); expect(img.naturalHeight, 0); expect((img.hidden! as JSBoolean).toDart, true); @@ -76,38 +66,23 @@ void main() { testWidgets('update', (WidgetTester tester) async { final controller = TileOverlayController( - tileOverlay: const TileOverlay( - tileOverlayId: id, - tileProvider: NoTileProvider(), - ), + tileOverlay: const TileOverlay(tileOverlayId: id, tileProvider: NoTileProvider()), ); { final img = - controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document)! - as HTMLImageElement; + controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document)! as HTMLImageElement; await null; // let `getTile` `then` complete - expect( - img.src, - isEmpty, - reason: 'The NoTileProvider never updates the img src', - ); + expect(img.src, isEmpty, reason: 'The NoTileProvider never updates the img src'); } - controller.update( - const TileOverlay(tileOverlayId: id, tileProvider: TestTileProvider()), - ); + controller.update(const TileOverlay(tileOverlayId: id, tileProvider: TestTileProvider())); { final img = - controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document)! - as HTMLImageElement; + controller.gmMapType.getTile(gmaps.Point(0, 0), 0, document)! as HTMLImageElement; await img.onLoad.first; - expect( - img.src, - isNotEmpty, - reason: 'The img `src` should eventually become the Blob URL.', - ); + expect(img.src, isNotEmpty, reason: 'The img `src` should eventually become the Blob URL.'); } controller.update(const TileOverlay(tileOverlayId: id)); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.dart index 6a1f23833b58..5e2f961abf0e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.dart @@ -9,8 +9,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps/google_maps.dart' as gmaps; import 'package:google_maps_flutter/google_maps_flutter.dart'; -import 'package:google_maps_flutter_web/google_maps_flutter_web.dart' - hide GoogleMapController; +import 'package:google_maps_flutter_web/google_maps_flutter_web.dart' hide GoogleMapController; // ignore: implementation_imports import 'package:google_maps_flutter_web/src/utils.dart'; import 'package:integration_test/integration_test.dart'; @@ -23,9 +22,7 @@ import 'overlays_test.mocks.dart'; MockTileProvider neverTileProvider() { final tileProvider = MockTileProvider(); - when( - tileProvider.getTile(any, any, any), - ).thenAnswer((_) => Completer().future); + when(tileProvider.getTile(any, any, any)).thenAnswer((_) => Completer().future); return tileProvider; } @@ -51,9 +48,7 @@ void main() { map = gmaps.Map(createDivElement()); controller.googleMap = map; - tileProviders = [ - for (int i = 0; i < 3; ++i) neverTileProvider(), - ]; + tileProviders = [for (int i = 0; i < 3; ++i) neverTileProvider()]; tileOverlays = [ for (int i = 0; i < 3; ++i) @@ -99,9 +94,7 @@ void main() { verifyNoMoreInteractions(tileProviders[2]); // Re-enable overlay 0. - controller.changeTileOverlays({ - tileOverlays[0].copyWith(visibleParam: true), - }); + controller.changeTileOverlays({tileOverlays[0].copyWith(visibleParam: true)}); probeTiles(); @@ -115,19 +108,18 @@ void main() { verifyNoMoreInteractions(tileProviders[2]); }); - testWidgets( - 'updating the z index of a hidden layer does not make it visible', - (WidgetTester tester) async { - controller.addTileOverlays({...tileOverlays}); + testWidgets('updating the z index of a hidden layer does not make it visible', ( + WidgetTester tester, + ) async { + controller.addTileOverlays({...tileOverlays}); - controller.changeTileOverlays({ - tileOverlays[0].copyWith(zIndexParam: -1, visibleParam: false), - }); + controller.changeTileOverlays({ + tileOverlays[0].copyWith(zIndexParam: -1, visibleParam: false), + }); - probeTiles(); - verifyZeroInteractions(tileProviders[0]); - }, - ); + probeTiles(); + verifyZeroInteractions(tileProviders[0]); + }); testWidgets('removeTileOverlays', (WidgetTester tester) async { controller.addTileOverlays({...tileOverlays}); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.mocks.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.mocks.dart index 6abd4a780e62..2a497c7fc3ad 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.mocks.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlays_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:google_maps_flutter_platform_interface/src/types/types.dart' - as _i2; +import 'package:google_maps_flutter_platform_interface/src/types/types.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -25,8 +24,7 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: invalid_use_of_internal_member class _FakeTile_0 extends _i1.SmartFake implements _i2.Tile { - _FakeTile_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeTile_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [TileProvider]. @@ -34,15 +32,13 @@ class _FakeTile_0 extends _i1.SmartFake implements _i2.Tile { /// See the documentation for Mockito's code generation for more information. class MockTileProvider extends _i1.Mock implements _i2.TileProvider { @override - _i3.Future<_i2.Tile> getTile(int? x, int? y, int? zoom) => - (super.noSuchMethod( - Invocation.method(#getTile, [x, y, zoom]), - returnValue: _i3.Future<_i2.Tile>.value( - _FakeTile_0(this, Invocation.method(#getTile, [x, y, zoom])), - ), - returnValueForMissingStub: _i3.Future<_i2.Tile>.value( - _FakeTile_0(this, Invocation.method(#getTile, [x, y, zoom])), - ), - ) - as _i3.Future<_i2.Tile>); + _i3.Future<_i2.Tile> getTile(int? x, int? y, int? zoom) => (super.noSuchMethod( + Invocation.method(#getTile, [x, y, zoom]), + returnValue: _i3.Future<_i2.Tile>.value( + _FakeTile_0(this, Invocation.method(#getTile, [x, y, zoom])), + ), + returnValueForMissingStub: _i3.Future<_i2.Tile>.value( + _FakeTile_0(this, Invocation.method(#getTile, [x, y, zoom])), + ), + ) as _i3.Future<_i2.Tile>); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart index 8a8529379fa0..9dae1527cb00 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/projection_test.dart @@ -11,8 +11,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:google_maps_flutter/google_maps_flutter.dart' - show GoogleMap, GoogleMapController; +import 'package:google_maps_flutter/google_maps_flutter.dart' show GoogleMap, GoogleMapController; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'package:integration_test/integration_test.dart'; @@ -53,12 +52,9 @@ void main() { onMapCreated: onMapCreated, ); - final GoogleMapController controller = - await controllerCompleter.future; + final GoogleMapController controller = await controllerCompleter.future; - await controller.moveCamera( - CameraUpdate.newLatLngZoom(const LatLng(19, 26), 12), - ); + await controller.moveCamera(CameraUpdate.newLatLngZoom(const LatLng(19, 26), 12)); final LatLng coords = await controller.getLatLng( ScreenCoordinate(x: size.width ~/ 2, y: size.height ~/ 2), @@ -97,8 +93,7 @@ void main() { final GoogleMapController controller = await controllerCompleter.future; - final LatLngBounds firstVisibleRegion = await controller - .getVisibleRegion(); + final LatLngBounds firstVisibleRegion = await controller.getVisibleRegion(); expect(firstVisibleRegion, isNotNull); expect(firstVisibleRegion.southwest, isNotNull); @@ -107,33 +102,22 @@ void main() { expect(firstVisibleRegion.contains(initialMapCenter), isTrue); const padding = 0.1; - await controller.moveCamera( - CameraUpdate.newLatLngBounds(firstVisibleRegion, padding), - ); + await controller.moveCamera(CameraUpdate.newLatLngBounds(firstVisibleRegion, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await controller - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await controller.getVisibleRegion(); expect(secondVisibleRegion, isNotNull); expect(secondVisibleRegion, isNot(zeroLatLngBounds)); expect(secondVisibleRegion, isNot(firstVisibleRegion)); expect(secondVisibleRegion.contains(initialMapCenter), isTrue); - expect( - secondVisibleRegion.contains(firstVisibleRegion.northeast), - isTrue, - ); - expect( - secondVisibleRegion.contains(firstVisibleRegion.southwest), - isTrue, - ); + expect(secondVisibleRegion.contains(firstVisibleRegion.northeast), isTrue); + expect(secondVisibleRegion.contains(firstVisibleRegion.southwest), isTrue); }); }); group('getScreenCoordinate', () { - testWidgets('target of map is in center of widget', ( - WidgetTester tester, - ) async { + testWidgets('target of map is in center of widget', (WidgetTester tester) async { await pumpCenteredMap( tester, initialCamera: initialCamera, @@ -143,17 +127,10 @@ void main() { final GoogleMapController controller = await controllerCompleter.future; - final ScreenCoordinate screenPosition = await controller - .getScreenCoordinate(center); + final ScreenCoordinate screenPosition = await controller.getScreenCoordinate(center); - expect( - screenPosition.x, - closeTo(size.width / 2, _acceptablePixelDelta), - ); - expect( - screenPosition.y, - closeTo(size.height / 2, _acceptablePixelDelta), - ); + expect(screenPosition.x, closeTo(size.width / 2, _acceptablePixelDelta)); + expect(screenPosition.y, closeTo(size.height / 2, _acceptablePixelDelta)); }); testWidgets('NorthWest of visible region corresponds to x:0, y:0', ( @@ -168,49 +145,37 @@ void main() { final GoogleMapController controller = await controllerCompleter.future; final LatLngBounds bounds = await controller.getVisibleRegion(); - final northWest = LatLng( - bounds.northeast.latitude, - bounds.southwest.longitude, - ); + final northWest = LatLng(bounds.northeast.latitude, bounds.southwest.longitude); - final ScreenCoordinate screenPosition = await controller - .getScreenCoordinate(northWest); + final ScreenCoordinate screenPosition = await controller.getScreenCoordinate(northWest); expect(screenPosition.x, closeTo(0, _acceptablePixelDelta)); expect(screenPosition.y, closeTo(0, _acceptablePixelDelta)); }); - testWidgets( - 'SouthEast of visible region corresponds to x:size.width, y:size.height', - (WidgetTester tester) async { - await pumpCenteredMap( - tester, - initialCamera: initialCamera, - size: size, - onMapCreated: onMapCreated, - ); - final GoogleMapController controller = - await controllerCompleter.future; + testWidgets('SouthEast of visible region corresponds to x:size.width, y:size.height', ( + WidgetTester tester, + ) async { + await pumpCenteredMap( + tester, + initialCamera: initialCamera, + size: size, + onMapCreated: onMapCreated, + ); + final GoogleMapController controller = await controllerCompleter.future; - final LatLngBounds bounds = await controller.getVisibleRegion(); - final southEast = LatLng( - bounds.southwest.latitude, - bounds.northeast.longitude, - ); + final LatLngBounds bounds = await controller.getVisibleRegion(); + final southEast = LatLng(bounds.southwest.latitude, bounds.northeast.longitude); - final ScreenCoordinate screenPosition = await controller - .getScreenCoordinate(southEast); + final ScreenCoordinate screenPosition = await controller.getScreenCoordinate(southEast); - expect(screenPosition.x, closeTo(size.width, _acceptablePixelDelta)); - expect(screenPosition.y, closeTo(size.height, _acceptablePixelDelta)); - }, - ); + expect(screenPosition.x, closeTo(size.width, _acceptablePixelDelta)); + expect(screenPosition.y, closeTo(size.height, _acceptablePixelDelta)); + }); }); group('getLatLng', () { - testWidgets('Center of widget is the target of map', ( - WidgetTester tester, - ) async { + testWidgets('Center of widget is the target of map', (WidgetTester tester) async { await pumpCenteredMap( tester, initialCamera: initialCamera, @@ -224,19 +189,11 @@ void main() { ScreenCoordinate(x: size.width ~/ 2, y: size.height ~/ 2), ); - expect( - coords.latitude, - closeTo(center.latitude, _acceptableLatLngDelta), - ); - expect( - coords.longitude, - closeTo(center.longitude, _acceptableLatLngDelta), - ); + expect(coords.latitude, closeTo(center.latitude, _acceptableLatLngDelta)); + expect(coords.longitude, closeTo(center.longitude, _acceptableLatLngDelta)); }); - testWidgets('Top-left of widget is NorthWest bound of map', ( - WidgetTester tester, - ) async { + testWidgets('Top-left of widget is NorthWest bound of map', (WidgetTester tester) async { await pumpCenteredMap( tester, initialCamera: initialCamera, @@ -246,28 +203,15 @@ void main() { final GoogleMapController controller = await controllerCompleter.future; final LatLngBounds bounds = await controller.getVisibleRegion(); - final northWest = LatLng( - bounds.northeast.latitude, - bounds.southwest.longitude, - ); + final northWest = LatLng(bounds.northeast.latitude, bounds.southwest.longitude); - final LatLng coords = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); + final LatLng coords = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); - expect( - coords.latitude, - closeTo(northWest.latitude, _acceptableLatLngDelta), - ); - expect( - coords.longitude, - closeTo(northWest.longitude, _acceptableLatLngDelta), - ); + expect(coords.latitude, closeTo(northWest.latitude, _acceptableLatLngDelta)); + expect(coords.longitude, closeTo(northWest.longitude, _acceptableLatLngDelta)); }); - testWidgets('Bottom-right of widget is SouthWest bound of map', ( - WidgetTester tester, - ) async { + testWidgets('Bottom-right of widget is SouthWest bound of map', (WidgetTester tester) async { await pumpCenteredMap( tester, initialCamera: initialCamera, @@ -277,23 +221,14 @@ void main() { final GoogleMapController controller = await controllerCompleter.future; final LatLngBounds bounds = await controller.getVisibleRegion(); - final southEast = LatLng( - bounds.southwest.latitude, - bounds.northeast.longitude, - ); + final southEast = LatLng(bounds.southwest.latitude, bounds.northeast.longitude); final LatLng coords = await controller.getLatLng( ScreenCoordinate(x: size.width.toInt(), y: size.height.toInt()), ); - expect( - coords.latitude, - closeTo(southEast.latitude, _acceptableLatLngDelta), - ); - expect( - coords.longitude, - closeTo(southEast.longitude, _acceptableLatLngDelta), - ); + expect(coords.latitude, closeTo(southEast.latitude, _acceptableLatLngDelta)); + expect(coords.longitude, closeTo(southEast.longitude, _acceptableLatLngDelta)); }); }); }); @@ -344,10 +279,7 @@ class CenteredMap extends StatelessWidget { body: Center( child: SizedBox.fromSize( size: size, - child: GoogleMap( - initialCameraPosition: initialCamera, - onMapCreated: onMapCreated, - ), + child: GoogleMap(initialCameraPosition: initialCamera, onMapCreated: onMapCreated), ), ), ), diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart index c8f7f610d67c..0db9ab62d318 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shape_test.dart @@ -74,9 +74,7 @@ void main() { expect(controller.circle, isNull); }); - testWidgets('cannot call update after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call update after remove', (WidgetTester tester) async { final options = gmaps.CircleOptions()..draggable = true; controller.remove(); @@ -129,9 +127,7 @@ void main() { expect(controller.polygon, isNull); }); - testWidgets('cannot call update after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call update after remove', (WidgetTester tester) async { final options = gmaps.PolygonOptions()..draggable = true; controller.remove(); @@ -151,11 +147,7 @@ void main() { }); testWidgets('onTap gets called', (WidgetTester tester) async { - PolylineController( - polyline: polyline, - consumeTapEvents: true, - onTap: onTap, - ); + PolylineController(polyline: polyline, consumeTapEvents: true, onTap: onTap); // Trigger a click event... gmaps.event.trigger(polyline, 'click', gmaps.MapMouseEvent()); @@ -188,9 +180,7 @@ void main() { expect(controller.line, isNull); }); - testWidgets('cannot call update after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call update after remove', (WidgetTester tester) async { final options = gmaps.PolylineOptions()..draggable = true; controller.remove(); @@ -234,9 +224,7 @@ void main() { expect(controller.heatmap, isNull); }); - testWidgets('cannot call update after remove', ( - WidgetTester tester, - ) async { + testWidgets('cannot call update after remove', (WidgetTester tester) async { final options = visualization.HeatmapLayerOptions()..dissipating = true; controller.remove(); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart index 62630275bae8..3bc5e8759bb4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/shapes_test.dart @@ -65,9 +65,7 @@ void main() { expect(controller.circles[const CircleId('1')]?.circle?.visible, isTrue); - final updatedCircles = { - const Circle(circleId: CircleId('1'), visible: false), - }; + final updatedCircles = {const Circle(circleId: CircleId('1'), visible: false)}; controller.changeCircles(updatedCircles); expect(controller.circles.length, 1); @@ -86,10 +84,7 @@ void main() { expect(controller.circles.length, 3); // Remove some circles... - final circleIdsToRemove = { - const CircleId('1'), - const CircleId('3'), - }; + final circleIdsToRemove = {const CircleId('1'), const CircleId('3')}; controller.removeCircles(circleIdsToRemove); @@ -113,15 +108,9 @@ void main() { final gmaps.Circle circle = controller.circles.values.first.circle!; expect((circle.get('fillColor')! as JSString).toDart, '#fabada'); - expect( - (circle.get('fillOpacity')! as JSNumber).toDartDouble, - closeTo(0.5, _acceptableDelta), - ); + expect((circle.get('fillOpacity')! as JSNumber).toDartDouble, closeTo(0.5, _acceptableDelta)); expect((circle.get('strokeColor')! as JSString).toDart, '#c0ffee'); - expect( - (circle.get('strokeOpacity')! as JSNumber).toDartDouble, - closeTo(1, _acceptableDelta), - ); + expect((circle.get('strokeOpacity')! as JSNumber).toDartDouble, closeTo(1, _acceptableDelta)); }); testWidgets('addCircles sets clickable according to consumeTapEvents', ( @@ -134,15 +123,11 @@ void main() { controller.addCircles(circles); - final CircleController? circle1Controller = - controller.circles[const CircleId('1')]; - final CircleController? circle2Controller = - controller.circles[const CircleId('2')]; + final CircleController? circle1Controller = controller.circles[const CircleId('1')]; + final CircleController? circle2Controller = controller.circles[const CircleId('2')]; - final bool circle1Clickable = - (circle1Controller!.circle! as JSObject).clickable; - final bool circle2Clickable = - (circle2Controller!.circle! as JSObject).clickable; + final bool circle1Clickable = (circle1Controller!.circle! as JSObject).clickable; + final bool circle2Clickable = (circle2Controller!.circle! as JSObject).clickable; expect(circle1Clickable, true); expect(circle2Clickable, false); @@ -177,22 +162,14 @@ void main() { final polygons = {const Polygon(polygonId: PolygonId('1'))}; controller.addPolygons(polygons); - expect( - controller.polygons[const PolygonId('1')]?.polygon?.visible, - isTrue, - ); + expect(controller.polygons[const PolygonId('1')]?.polygon?.visible, isTrue); // Update the polygon - final updatedPolygons = { - const Polygon(polygonId: PolygonId('1'), visible: false), - }; + final updatedPolygons = {const Polygon(polygonId: PolygonId('1'), visible: false)}; controller.changePolygons(updatedPolygons); expect(controller.polygons.length, 1); - expect( - controller.polygons[const PolygonId('1')]?.polygon?.visible, - isFalse, - ); + expect(controller.polygons[const PolygonId('1')]?.polygon?.visible, isFalse); }); testWidgets('removePolygons', (WidgetTester tester) async { @@ -207,10 +184,7 @@ void main() { expect(controller.polygons.length, 3); // Remove some polygons... - final polygonIdsToRemove = { - const PolygonId('1'), - const PolygonId('3'), - }; + final polygonIdsToRemove = {const PolygonId('1'), const PolygonId('3')}; controller.removePolygons(polygonIdsToRemove); @@ -255,11 +229,7 @@ void main() { LatLng(32.321, -64.757), ], holes: >[ - [ - LatLng(28.745, -70.579), - LatLng(29.57, -67.514), - LatLng(27.339, -66.668), - ], + [LatLng(28.745, -70.579), LatLng(29.57, -67.514), LatLng(27.339, -66.668)], ], ), }; @@ -281,11 +251,7 @@ void main() { LatLng(32.321, -64.757), ], holes: >[ - [ - LatLng(28.745, -70.579), - LatLng(29.57, -67.514), - LatLng(27.339, -66.668), - ], + [LatLng(28.745, -70.579), LatLng(29.57, -67.514), LatLng(27.339, -66.668)], ], ), }; @@ -298,9 +264,7 @@ void main() { expect(geometry.poly.containsLocation(pointInHole, polygon!), false); }); - testWidgets('Hole Path gets reversed to display correctly', ( - WidgetTester tester, - ) async { + testWidgets('Hole Path gets reversed to display correctly', (WidgetTester tester) async { final polygons = { const Polygon( polygonId: PolygonId('BermudaTriangle'), @@ -310,11 +274,7 @@ void main() { LatLng(32.321, -64.757), ], holes: >[ - [ - LatLng(27.339, -66.668), - LatLng(29.57, -67.514), - LatLng(28.745, -70.579), - ], + [LatLng(27.339, -66.668), LatLng(29.57, -67.514), LatLng(28.745, -70.579)], ], ), }; @@ -339,15 +299,11 @@ void main() { controller.addPolygons(polygons); - final PolygonController? polygon1Controller = - controller.polygons[const PolygonId('1')]; - final PolygonController? polygon2Controller = - controller.polygons[const PolygonId('2')]; + final PolygonController? polygon1Controller = controller.polygons[const PolygonId('1')]; + final PolygonController? polygon2Controller = controller.polygons[const PolygonId('2')]; - final bool polygon1Clickable = - (polygon1Controller!.polygon! as JSObject).clickable; - final bool polygon2Clickable = - (polygon2Controller!.polygon! as JSObject).clickable; + final bool polygon1Clickable = (polygon1Controller!.polygon! as JSObject).clickable; + final bool polygon2Clickable = (polygon2Controller!.polygon! as JSObject).clickable; expect(polygon1Clickable, true); expect(polygon2Clickable, false); @@ -405,10 +361,7 @@ void main() { expect(controller.lines.length, 3); // Remove some polylines... - final polylineIdsToRemove = { - const PolylineId('1'), - const PolylineId('3'), - }; + final polylineIdsToRemove = {const PolylineId('1'), const PolylineId('3')}; controller.removePolylines(polylineIdsToRemove); @@ -428,10 +381,7 @@ void main() { final gmaps.Polyline line = controller.lines.values.first.line!; expect((line.get('strokeColor')! as JSString).toDart, '#fabada'); - expect( - (line.get('strokeOpacity')! as JSNumber).toDartDouble, - closeTo(0.5, _acceptableDelta), - ); + expect((line.get('strokeOpacity')! as JSNumber).toDartDouble, closeTo(0.5, _acceptableDelta)); }); testWidgets('addPolylines sets clickable according to consumeTapEvents', ( @@ -444,15 +394,11 @@ void main() { controller.addPolylines(polylines); - final PolylineController? polyline1Controller = - controller.lines[const PolylineId('1')]; - final PolylineController? polyline2Controller = - controller.lines[const PolylineId('2')]; + final PolylineController? polyline1Controller = controller.lines[const PolylineId('1')]; + final PolylineController? polyline2Controller = controller.lines[const PolylineId('2')]; - final bool polyline1Clickable = - (polyline1Controller!.line! as JSObject).clickable; - final bool polyline2Clickable = - (polyline2Controller!.line! as JSObject).clickable; + final bool polyline1Clickable = (polyline1Controller!.line! as JSObject).clickable; + final bool polyline2Clickable = (polyline2Controller!.line! as JSObject).clickable; expect(polyline1Clickable, true); expect(polyline2Clickable, false); @@ -516,10 +462,7 @@ void main() { }; controller.addHeatmaps(heatmaps); - expect( - controller.heatmaps[const HeatmapId('1')]!.heatmap!.data.array.toDart, - hasLength(0), - ); + expect(controller.heatmaps[const HeatmapId('1')]!.heatmap!.data.array.toDart, hasLength(0)); final updatedHeatmaps = { const Heatmap( @@ -531,10 +474,7 @@ void main() { controller.changeHeatmaps(updatedHeatmaps); expect(controller.heatmaps.length, 1); - expect( - controller.heatmaps[const HeatmapId('1')]!.heatmap!.data.array.toDart, - hasLength(1), - ); + expect(controller.heatmaps[const HeatmapId('1')]!.heatmap!.data.array.toDart, hasLength(1)); }); testWidgets('removeHeatmaps', (WidgetTester tester) async { @@ -561,10 +501,7 @@ void main() { expect(controller.heatmaps.length, 3); // Remove some polylines... - final heatmapIdsToRemove = { - const HeatmapId('1'), - const HeatmapId('3'), - }; + final heatmapIdsToRemove = {const HeatmapId('1'), const HeatmapId('3')}; controller.removeHeatmaps(heatmapIdsToRemove); @@ -588,8 +525,7 @@ void main() { controller.addHeatmaps(heatmaps); - final visualization.HeatmapLayer heatmap = - controller.heatmaps.values.first.heatmap!; + final visualization.HeatmapLayer heatmap = controller.heatmaps.values.first.heatmap!; expect( (heatmap.get('gradient')! as JSArray).toDart.map( diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circles.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circles.dart index aa94f0adb240..b0307ef33208 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circles.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/circles.dart @@ -47,8 +47,7 @@ class CirclesController extends GeometryController { } void _changeCircle(Circle circle) { - final CircleController? circleController = - _circleIdToController[circle.circleId]; + final CircleController? circleController = _circleIdToController[circle.circleId]; circleController?.update(_circleOptionsFromCircle(circle)); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart index c778ed3ce687..c887b9af5b9b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/convert.dart @@ -16,8 +16,7 @@ web.TrustedTypePolicy? _gmapsTrustedTypePolicy; // A cache for image size Futures to reduce redundant image fetch requests. // This cache should be always cleaned up after marker updates are processed. -final Map> _bitmapSizeFutureCache = - >{}; +final Map> _bitmapSizeFutureCache = >{}; // A cache for blob URLs of bitmaps to avoid creating a new blob URL for the // same bitmap instances. This cache should be always cleaned up after marker @@ -68,16 +67,14 @@ gmaps.MapOptions _configurationAndStyleToGmapsOptions( options.mapTypeId = _gmapTypeIDForPluginType(configuration.mapType!); } - final MinMaxZoomPreference? zoomPreference = - configuration.minMaxZoomPreference; + final MinMaxZoomPreference? zoomPreference = configuration.minMaxZoomPreference; if (zoomPreference != null) { options ..minZoom = zoomPreference.minZoom ..maxZoom = zoomPreference.maxZoom; } - final LatLngBounds? cameraTargetLatLngBounds = - configuration.cameraTargetBounds?.bounds; + final LatLngBounds? cameraTargetLatLngBounds = configuration.cameraTargetBounds?.bounds; if (cameraTargetLatLngBounds != null) { options.restriction = gmaps.MapRestriction( latLngBounds: latLngBoundsToGmlatLngBounds(cameraTargetLatLngBounds), @@ -108,9 +105,7 @@ gmaps.MapOptions _configurationAndStyleToGmapsOptions( ); if (controlPosition != null) { - options.cameraControlOptions = gmaps.CameraControlOptions( - position: controlPosition, - ); + options.cameraControlOptions = gmaps.CameraControlOptions(position: controlPosition); } } @@ -187,25 +182,15 @@ gmaps.ColorScheme? _gmapTypeColorSchemeForPluginColor(MapColorScheme? scheme) { return null; } -gmaps.MapOptions _applyInitialPosition( - CameraPosition initialPosition, - gmaps.MapOptions options, -) { +gmaps.MapOptions _applyInitialPosition(CameraPosition initialPosition, gmaps.MapOptions options) { // Adjust the initial position, if passed... options.zoom = initialPosition.zoom; - options.center = gmaps.LatLng( - initialPosition.target.latitude, - initialPosition.target.longitude, - ); + options.center = gmaps.LatLng(initialPosition.target.latitude, initialPosition.target.longitude); return options; } // The keys we'd expect to see in a serialized MapTypeStyle JSON object. -final Set _mapStyleKeys = { - 'elementType', - 'featureType', - 'stylers', -}; +final Set _mapStyleKeys = {'elementType', 'featureType', 'stylers'}; // Checks if the passed in Map contains some of the _mapStyleKeys. bool _isJsonMapStyle(Map value) { @@ -219,26 +204,24 @@ List _mapStyles(String? mapStyleJson) { try { styles = (json.decode( - mapStyleJson, - reviver: (Object? key, Object? value) { - if (value is Map && - _isJsonMapStyle(value as Map)) { - var stylers = []; - if (value['stylers'] != null) { - stylers = (value['stylers']! as List) - .whereType>() - .map(MapStyler.fromJson) - .toList(); - } - return gmaps.MapTypeStyle() - ..elementType = value['elementType'] as String? - ..featureType = value['featureType'] as String? - ..stylers = stylers; - } - return value; - }, - ) - as List) + mapStyleJson, + reviver: (Object? key, Object? value) { + if (value is Map && _isJsonMapStyle(value as Map)) { + var stylers = []; + if (value['stylers'] != null) { + stylers = (value['stylers']! as List) + .whereType>() + .map(MapStyler.fromJson) + .toList(); + } + return gmaps.MapTypeStyle() + ..elementType = value['elementType'] as String? + ..featureType = value['featureType'] as String? + ..stylers = stylers; + } + return value; + }, + ) as List) .where((Object? element) => element != null) .cast() .toList(); @@ -277,9 +260,7 @@ gmaps.LatLngBounds latLngBoundsToGmlatLngBounds(LatLngBounds latLngBounds) { CameraPosition _gmViewportToCameraPosition(gmaps.Map map) { return CameraPosition( - target: gmLatLngToLatLng( - map.isCenterDefined() ? map.center : _nullGmapsLatLng, - ), + target: gmLatLngToLatLng(map.isCenterDefined() ? map.center : _nullGmapsLatLng), bearing: map.isHeadingDefined() ? map.heading.toDouble() : 0, tilt: map.isTiltDefined() ? map.tilt.toDouble() : 0, zoom: map.isZoomDefined() ? map.zoom.toDouble() : 0, @@ -311,8 +292,7 @@ gmaps.InfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { container.appendChild(title); } if (markerSnippet.isNotEmpty) { - final web.HTMLElement snippet = createDivElement() - ..className = 'infowindow-snippet'; + final web.HTMLElement snippet = createDivElement()..className = 'infowindow-snippet'; // Firefox and Safari don't support Trusted Types yet. // See https://developer.mozilla.org/en-US/docs/Web/API/TrustedTypePolicyFactory#browser_compatibility @@ -326,9 +306,7 @@ gmaps.InfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { ), ); - snippet.trustedInnerHTML = _gmapsTrustedTypePolicy!.createHTMLNoArgs( - markerSnippet, - ); + snippet.trustedInnerHTML = _gmapsTrustedTypePolicy!.createHTMLNoArgs(markerSnippet); } else { // `sanitizeHtml` is used to clean the (potential) user input from (potential) // XSS attacks through the contents of the marker InfoWindow. @@ -383,15 +361,8 @@ void _setIconStyle({ } } -void _setIconAnchor({ - required gmaps.Size size, - required Offset anchor, - required gmaps.Icon icon, -}) { - final gmapsAnchor = gmaps.Point( - size.width * anchor.dx, - size.height * anchor.dy, - ); +void _setIconAnchor({required gmaps.Size size, required Offset anchor, required gmaps.Icon icon}) { + final gmapsAnchor = gmaps.Point(size.width * anchor.dx, size.height * anchor.dy); icon.anchor = gmapsAnchor; } @@ -416,10 +387,7 @@ Future _getBitmapSize(MapBitmap mapBitmap, String url) async { // If both, width and height are set, return the provided dimensions. return gmaps.Size(width, height); } else { - assert( - url.isNotEmpty, - 'URL must not be empty when calculating dimensions.', - ); + assert(url.isNotEmpty, 'URL must not be empty when calculating dimensions.'); final Size? bitmapSize = await _bitmapSizeFutureCache.putIfAbsent(url, () { return _fetchBitmapSize(url); @@ -456,10 +424,7 @@ Future _fetchBitmapSize(String url) async { final image = web.HTMLImageElement()..src = url; // Wait for the onLoad or onError event. - await Future.any(>[ - image.onLoad.first, - image.onError.first, - ]); + await Future.any(>[image.onLoad.first, image.onError.first]); if (image.width == 0 || image.height == 0) { // Complete with null for invalid images. @@ -487,12 +452,8 @@ Future _advancedMarkerIconFromPinConfig( required double rotation, }) async { final options = gmaps.PinElementOptions() - ..background = config.backgroundColor != null - ? _getCssColor(config.backgroundColor!) - : null - ..borderColor = config.borderColor != null - ? _getCssColor(config.borderColor!) - : null; + ..background = config.backgroundColor != null ? _getCssColor(config.backgroundColor!) : null + ..borderColor = config.borderColor != null ? _getCssColor(config.borderColor!) : null; final AdvancedMarkerGlyph? glyph = config.glyph; switch (glyph) { @@ -506,8 +467,7 @@ Future _advancedMarkerIconFromPinConfig( } options.glyph = element; case final BitmapGlyph bitmapGlyph: - final web.Node? - glyphBitmap = await _advancedMarkerIconFromBitmapDescriptor( + final web.Node? glyphBitmap = await _advancedMarkerIconFromBitmapDescriptor( bitmapGlyph.bitmap, // Always opaque, opacity is handled by the parent marker. opacity: 1.0, @@ -539,9 +499,7 @@ Future _advancedMarkerIconFromMapBitmap( (final BytesMapBitmap bytesMapBitmap) => _bitmapBlobUrlCache.putIfAbsent( bytesMapBitmap.byteData.hashCode, () { - final blob = web.Blob( - [bytesMapBitmap.byteData.toJS].toJS, - ); + final blob = web.Blob([bytesMapBitmap.byteData.toJS].toJS); return web.URL.createObjectURL(blob as JSObject); }, ), @@ -590,17 +548,13 @@ Future _advancedMarkerIconFromBytes( // Create a Blob from bytes, but let the browser figure out the encoding. final web.Blob blob; - assert( - bytes is Uint8List, - 'The bytes for a BitmapDescriptor icon must be a Uint8List', - ); + assert(bytes is Uint8List, 'The bytes for a BitmapDescriptor icon must be a Uint8List'); // TODO(ditman): Improve this conversion // See https://github.com/dart-lang/web/issues/180 blob = web.Blob([(bytes as Uint8List).toJS].toJS); - final icon = web.HTMLImageElement() - ..src = web.URL.createObjectURL(blob as JSObject); + final icon = web.HTMLImageElement()..src = web.URL.createObjectURL(blob as JSObject); final gmaps.Size? size = _gmSizeFromIconConfig(iconConfig, 2); _setIconStyle(size: size, icon: icon, opacity: opacity, isVisible: isVisible); @@ -669,9 +623,7 @@ Future _gmIconFromBitmapDescriptor( () { // TODO(ditman): Improve this conversion // See https://github.com/dart-lang/web/issues/180 - final blob = web.Blob( - [bytesMapBitmap.byteData.toJS].toJS, - ); + final blob = web.Blob([bytesMapBitmap.byteData.toJS].toJS); return web.URL.createObjectURL(blob as JSObject); }, ), @@ -704,8 +656,7 @@ Future _gmIconFromBitmapDescriptor( assert(iconConfig.length >= 2); // iconConfig[2] contains the DPIs of the screen, but that information is // already encoded in the iconConfig[1] - icon = gmaps.Icon() - ..url = ui_web.assetManager.getAssetUrl(iconConfig[1]! as String); + icon = gmaps.Icon()..url = ui_web.assetManager.getAssetUrl(iconConfig[1]! as String); final gmaps.Size? size = _gmSizeFromIconConfig(iconConfig, 3); if (size != null) { @@ -719,10 +670,7 @@ Future _gmIconFromBitmapDescriptor( // Create a Blob from bytes, but let the browser figure out the encoding final web.Blob blob; - assert( - bytes is Uint8List, - 'The bytes for a BitmapDescriptor icon must be a Uint8List', - ); + assert(bytes is Uint8List, 'The bytes for a BitmapDescriptor icon must be a Uint8List'); // TODO(ditman): Improve this conversion // See https://github.com/dart-lang/web/issues/180 @@ -742,35 +690,24 @@ Future _gmIconFromBitmapDescriptor( // Computes the options for a new [gmaps.Marker] from an incoming set of options // [marker], and the existing marker registered with the map: [currentMarker]. -Future _markerOptionsFromMarker( - Marker marker, - T? currentMarker, -) async { +Future _markerOptionsFromMarker(Marker marker, T? currentMarker) async { if (marker is AdvancedMarker) { final options = gmaps.AdvancedMarkerElementOptions() - ..collisionBehavior = _markerCollisionBehaviorToGmCollisionBehavior( - marker.collisionBehavior, - ) + ..collisionBehavior = _markerCollisionBehaviorToGmCollisionBehavior(marker.collisionBehavior) ..content = await _advancedMarkerIconFromBitmapDescriptor( marker.icon, opacity: marker.alpha, isVisible: marker.visible, rotation: marker.rotation, ) - ..position = gmaps.LatLng( - marker.position.latitude, - marker.position.longitude, - ) + ..position = gmaps.LatLng(marker.position.latitude, marker.position.longitude) ..title = sanitizeHtml(marker.infoWindow.title ?? '') ..zIndex = marker.zIndex ..gmpDraggable = marker.draggable; return options as O; } else { final options = gmaps.MarkerOptions() - ..position = gmaps.LatLng( - marker.position.latitude, - marker.position.longitude, - ) + ..position = gmaps.LatLng(marker.position.latitude, marker.position.longitude) ..icon = await _gmIconFromBitmapDescriptor(marker.icon, marker.anchor) ..title = sanitizeHtml(marker.infoWindow.title ?? '') ..zIndex = marker.zIndex @@ -795,9 +732,7 @@ MarkerId getMarkerId(Object marker) { final element = marker as gmaps.AdvancedMarkerElement; return MarkerId(element.id); } else { - throw ArgumentError( - 'Must be either a gmaps.Marker or a gmaps.AdvancedMarkerElement', - ); + throw ArgumentError('Must be either a gmaps.Marker or a gmaps.AdvancedMarkerElement'); } } @@ -843,14 +778,9 @@ visualization.HeatmapLayerOptions _heatmapOptionsFromHeatmap(Heatmap heatmap) { return heatmapOptions; } -gmaps.PolygonOptions _polygonOptionsFromPolygon( - gmaps.Map googleMap, - Polygon polygon, -) { +gmaps.PolygonOptions _polygonOptionsFromPolygon(gmaps.Map googleMap, Polygon polygon) { // Convert all points to GmLatLng - final List path = polygon.points - .map(_latLngToGmLatLng) - .toList(); + final List path = polygon.points.map(_latLngToGmLatLng).toList(); final bool isClockwisePolygon = _isPolygonClockwise(path); @@ -925,13 +855,8 @@ bool _isPolygonClockwise(List path) { return direction >= 0; } -gmaps.PolylineOptions _polylineOptionsFromPolyline( - gmaps.Map googleMap, - Polyline polyline, -) { - final List paths = polyline.points - .map(_latLngToGmLatLng) - .toList(); +gmaps.PolylineOptions _polylineOptionsFromPolyline(gmaps.Map googleMap, Polyline polyline) { + final List paths = polyline.points.map(_latLngToGmLatLng).toList(); return gmaps.PolylineOptions() ..path = paths.toJS @@ -996,18 +921,12 @@ void _applyCameraUpdate(gmaps.Map map, CameraUpdate update) { gmaps.LatLng? focusLatLng; final double zoomDelta = json[1] as double? ?? 0; // Web only supports integer changes... - final int newZoomDelta = zoomDelta < 0 - ? zoomDelta.floor() - : zoomDelta.ceil(); + final int newZoomDelta = zoomDelta < 0 ? zoomDelta.floor() : zoomDelta.ceil(); if (json.length == 3) { final List latLng = asJsonList(json[2]); // With focus try { - focusLatLng = _pixelToLatLng( - map, - latLng[0]! as int, - latLng[1]! as int, - ); + focusLatLng = _pixelToLatLng(map, latLng[0]! as int, latLng[1]! as int); } catch (e) { // https://github.com/a14n/dart-google-maps/issues/87 // print('Error computing new focus LatLng. JS Error: ' + e.toString()); @@ -1034,18 +953,14 @@ String urlFromMapBitmap(MapBitmap mapBitmap) { (final BytesMapBitmap bytesMapBitmap) => _bitmapBlobUrlCache.putIfAbsent( bytesMapBitmap.byteData.hashCode, () { - final blob = web.Blob( - [bytesMapBitmap.byteData.toJS].toJS, - ); + final blob = web.Blob([bytesMapBitmap.byteData.toJS].toJS); return web.URL.createObjectURL(blob as JSObject); }, ), (final AssetMapBitmap assetMapBitmap) => ui_web.assetManager.getAssetUrl( assetMapBitmap.assetName, ), - _ => throw UnimplementedError( - 'Only BytesMapBitmap and AssetMapBitmap are supported.', - ), + _ => throw UnimplementedError('Only BytesMapBitmap and AssetMapBitmap are supported.'), }; } @@ -1054,18 +969,9 @@ gmaps.LatLng _pixelToLatLng(gmaps.Map map, int x, int y) { final gmaps.LatLngBounds? bounds = map.bounds; final gmaps.Projection? projection = map.projection; - assert( - bounds != null, - 'Map Bounds required to compute LatLng of screen x/y.', - ); - assert( - projection != null, - 'Map Projection required to compute LatLng of screen x/y', - ); - assert( - map.isZoomDefined(), - 'Current map zoom level required to compute LatLng of screen x/y', - ); + assert(bounds != null, 'Map Bounds required to compute LatLng of screen x/y.'); + assert(projection != null, 'Map Projection required to compute LatLng of screen x/y'); + assert(map.isZoomDefined(), 'Current map zoom level required to compute LatLng of screen x/y'); final num zoom = map.zoom; @@ -1077,18 +983,13 @@ gmaps.LatLng _pixelToLatLng(gmaps.Map map, int x, int y) { final int scale = 1 << (zoom.toInt()); // 2 ^ zoom - final point = gmaps.Point( - (x / scale) + bottomLeft.x, - (y / scale) + topRight.y, - ); + final point = gmaps.Point((x / scale) + bottomLeft.x, (y / scale) + topRight.y); return projection.fromPointToLatLng(point)!; } /// Converts a [WebCameraControlPosition] to [gmaps.ControlPosition]. -gmaps.ControlPosition? _toControlPosition( - WebCameraControlPosition webCameraControlPosition, -) { +gmaps.ControlPosition? _toControlPosition(WebCameraControlPosition webCameraControlPosition) { switch (webCameraControlPosition) { case WebCameraControlPosition.blockEndInlineCenter: return gmaps.ControlPosition.BLOCK_END_INLINE_CENTER; diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart index bb8a5c624340..13e9054d9c7c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_controller.dart @@ -6,8 +6,7 @@ part of '../google_maps_flutter_web.dart'; /// Type used when passing an override to the _createMap function. @visibleForTesting -typedef DebugCreateMapFunction = - gmaps.Map Function(web.HTMLElement div, gmaps.MapOptions options); +typedef DebugCreateMapFunction = gmaps.Map Function(web.HTMLElement div, gmaps.MapOptions options); /// Type used when passing an override to the _setOptions function. @visibleForTesting @@ -41,9 +40,7 @@ class GoogleMapController { // Check if all markers are of the same type. Mixing marker types is not // allowed. - final Set markerTypes = _markers - .map((Marker e) => e.runtimeType) - .toSet(); + final Set markerTypes = _markers.map((Marker e) => e.runtimeType).toSet(); if (markerTypes.isNotEmpty) { assert(markerTypes.length == 1, 'All markers must be of the same type.'); @@ -67,33 +64,27 @@ class GoogleMapController { // Advanced and legacy markers are handled differently so markers controller // and cluster manager need be initialized with the correct marker type. _clusterManagersController = switch (mapConfiguration.markerType) { - null || MarkerType.marker => ClusterManagersController( + null || + MarkerType.marker => ClusterManagersController(stream: _streamController), + MarkerType.advancedMarker => ClusterManagersController( stream: _streamController, ), - MarkerType.advancedMarker => - ClusterManagersController( - stream: _streamController, - ), }; _markersController = switch (mapConfiguration.markerType) { null || MarkerType.marker => LegacyMarkersController( stream: stream, clusterManagersController: - _clusterManagersController! - as ClusterManagersController, + _clusterManagersController! as ClusterManagersController, ), MarkerType.advancedMarker => AdvancedMarkersController( stream: stream, clusterManagersController: - _clusterManagersController! - as ClusterManagersController, + _clusterManagersController! as ClusterManagersController, ), }; _tileOverlaysController = TileOverlaysController(); - _groundOverlaysController = GroundOverlaysController( - stream: _streamController, - ); + _groundOverlaysController = GroundOverlaysController(stream: _streamController); _updateStylesFromConfiguration(mapConfiguration); // Register the view factory that will hold the `_div` that holds the map in the DOM. @@ -104,10 +95,7 @@ class GoogleMapController { ..style.width = '100%' ..style.height = '100%'; - ui_web.platformViewRegistry.registerViewFactory( - _getViewType(mapId), - (int viewId) => _div, - ); + ui_web.platformViewRegistry.registerViewFactory(_getViewType(mapId), (int viewId) => _div); } // The internal ID of the map. Used to broadcast events, DOM IDs and everything where a unique ID is needed. @@ -196,13 +184,11 @@ class GoogleMapController { /// The ClusterManagersController of this Map. Only for integration testing. @visibleForTesting - ClusterManagersController? get clusterManagersController => - _clusterManagersController; + ClusterManagersController? get clusterManagersController => _clusterManagersController; /// The GroundOverlaysController of this Map. Only for integration testing. @visibleForTesting - GroundOverlaysController? get groundOverlayController => - _groundOverlaysController; + GroundOverlaysController? get groundOverlayController => _groundOverlaysController; /// Overrides certain properties to install mocks defined during testing. @visibleForTesting @@ -300,24 +286,16 @@ class GoogleMapController { _streamController.add(WebMapReadyEvent(_mapId)); } }); - _onClickSubscription = map.onClick.listen(( - gmaps.MapMouseEventOrIconMouseEvent event, - ) { + _onClickSubscription = map.onClick.listen((gmaps.MapMouseEventOrIconMouseEvent event) { assert(event.latLng != null); if (!_streamController.isClosed) { - _streamController.add( - MapTapEvent(_mapId, gmLatLngToLatLng(event.latLng!)), - ); + _streamController.add(MapTapEvent(_mapId, gmLatLngToLatLng(event.latLng!))); } }); - _onRightClickSubscription = map.onRightclick.listen(( - gmaps.MapMouseEvent event, - ) { + _onRightClickSubscription = map.onRightclick.listen((gmaps.MapMouseEvent event) { assert(event.latLng != null); if (!_streamController.isClosed) { - _streamController.add( - MapLongPressEvent(_mapId, gmLatLngToLatLng(event.latLng!)), - ); + _streamController.add(MapLongPressEvent(_mapId, gmLatLngToLatLng(event.latLng!))); } }); _onBoundsChangedSubscription = map.onBoundsChanged.listen((void _) { @@ -328,9 +306,7 @@ class GoogleMapController { } } if (!_streamController.isClosed) { - _streamController.add( - CameraMoveEvent(_mapId, _gmViewportToCameraPosition(map)), - ); + _streamController.add(CameraMoveEvent(_mapId, _gmViewportToCameraPosition(map))); } }); _onIdleSubscription = map.onIdle.listen((void _) { @@ -349,10 +325,7 @@ class GoogleMapController { // These controllers are either created in the constructor of this class, or // overriden (for testing) by the [debugSetOverrides] method. They can't be // null. - assert( - _circlesController != null, - 'Cannot attach a map to a null CirclesController instance.', - ); + assert(_circlesController != null, 'Cannot attach a map to a null CirclesController instance.'); assert( _heatmapsController != null, 'Cannot attach a map to a null HeatmapsController instance.', @@ -365,10 +338,7 @@ class GoogleMapController { _polylinesController != null, 'Cannot attach a map to a null PolylinesController instance.', ); - assert( - _markersController != null, - 'Cannot attach a map to a null MarkersController instance.', - ); + assert(_markersController != null, 'Cannot attach a map to a null MarkersController instance.'); assert( _clusterManagersController != null, 'Cannot attach a map to a null ClusterManagersController instance.', @@ -430,9 +400,7 @@ class GoogleMapController { // TODO(stuartmorgan): Refactor so that _lastMapConfiguration.style is the // source of truth for style info. Currently it's tracked and handled // separately since style didn't used to be part of the configuration. - List _updateStylesFromConfiguration( - MapConfiguration update, - ) { + List _updateStylesFromConfiguration(MapConfiguration update) { if (update.style != null) { // Provide async access to the error rather than throwing, to match the // behavior of other platforms where there's no mechanism to return errors @@ -453,9 +421,7 @@ class GoogleMapController { void updateMapConfiguration(MapConfiguration update) { assert(_googleMap != null, 'Cannot update options on a null map.'); - final List styles = _updateStylesFromConfiguration( - update, - ); + final List styles = _updateStylesFromConfiguration(update); final MapConfiguration newConfiguration = _mergeConfigurations(update); final gmaps.MapOptions newOptions = _configurationAndStyleToGmapsOptions( newConfiguration, @@ -469,9 +435,7 @@ class GoogleMapController { /// Updates the map options with a new list of [styles]. void updateStyles(List styles) { _lastStyles = styles; - _setOptions( - _configurationAndStyleToGmapsOptions(_lastMapConfiguration, styles), - ); + _setOptions(_configurationAndStyleToGmapsOptions(_lastMapConfiguration, styles)); } /// A getter for the current styles. Only for tests. @@ -509,39 +473,25 @@ class GoogleMapController { assert(_googleMap != null, 'Cannot get the visible region of a null map.'); final gmaps.LatLngBounds bounds = - await Future.value(_googleMap!.bounds) ?? - _nullGmapsLatLngBounds; + await Future.value(_googleMap!.bounds) ?? _nullGmapsLatLngBounds; return gmLatLngBoundsToLatLngBounds(bounds); } /// Returns the [ScreenCoordinate] for a given viewport [LatLng]. Future getScreenCoordinate(LatLng latLng) async { - assert( - _googleMap != null, - 'Cannot get the screen coordinates with a null map.', - ); + assert(_googleMap != null, 'Cannot get the screen coordinates with a null map.'); - final gmaps.Point point = toScreenLocation( - _googleMap!, - _latLngToGmLatLng(latLng), - ); + final gmaps.Point point = toScreenLocation(_googleMap!, _latLngToGmLatLng(latLng)); return ScreenCoordinate(x: point.x.toInt(), y: point.y.toInt()); } /// Returns the [LatLng] for a `screenCoordinate` (in pixels) of the viewport. Future getLatLng(ScreenCoordinate screenCoordinate) async { - assert( - _googleMap != null, - 'Cannot get the lat, lng of a screen coordinate with a null map.', - ); + assert(_googleMap != null, 'Cannot get the lat, lng of a screen coordinate with a null map.'); - final gmaps.LatLng latLng = _pixelToLatLng( - _googleMap!, - screenCoordinate.x, - screenCoordinate.y, - ); + final gmaps.LatLng latLng = _pixelToLatLng(_googleMap!, screenCoordinate.x, screenCoordinate.y); return gmLatLngToLatLng(latLng); } @@ -567,10 +517,7 @@ class GoogleMapController { /// Applies [CircleUpdates] to the currently managed circles. void updateCircles(CircleUpdates updates) { - assert( - _circlesController != null, - 'Cannot update circles after dispose().', - ); + assert(_circlesController != null, 'Cannot update circles after dispose().'); _circlesController?.addCircles(updates.circlesToAdd); _circlesController?.changeCircles(updates.circlesToChange); _circlesController?.removeCircles(updates.circleIdsToRemove); @@ -578,10 +525,7 @@ class GoogleMapController { /// Applies [HeatmapUpdates] to the currently managed heatmaps. void updateHeatmaps(HeatmapUpdates updates) { - assert( - _heatmapsController != null, - 'Cannot update heatmaps after dispose().', - ); + assert(_heatmapsController != null, 'Cannot update heatmaps after dispose().'); _heatmapsController?.addHeatmaps(updates.heatmapsToAdd); _heatmapsController?.changeHeatmaps(updates.heatmapsToChange); _heatmapsController?.removeHeatmaps(updates.heatmapIdsToRemove); @@ -589,10 +533,7 @@ class GoogleMapController { /// Applies [PolygonUpdates] to the currently managed polygons. void updatePolygons(PolygonUpdates updates) { - assert( - _polygonsController != null, - 'Cannot update polygons after dispose().', - ); + assert(_polygonsController != null, 'Cannot update polygons after dispose().'); _polygonsController?.addPolygons(updates.polygonsToAdd); _polygonsController?.changePolygons(updates.polygonsToChange); _polygonsController?.removePolygons(updates.polygonIdsToRemove); @@ -600,10 +541,7 @@ class GoogleMapController { /// Applies [PolylineUpdates] to the currently managed lines. void updatePolylines(PolylineUpdates updates) { - assert( - _polylinesController != null, - 'Cannot update polylines after dispose().', - ); + assert(_polylinesController != null, 'Cannot update polylines after dispose().'); _polylinesController?.addPolylines(updates.polylinesToAdd); _polylinesController?.changePolylines(updates.polylinesToChange); _polylinesController?.removePolylines(updates.polylineIdsToRemove); @@ -611,10 +549,7 @@ class GoogleMapController { /// Applies [MarkerUpdates] to the currently managed markers. Future updateMarkers(MarkerUpdates updates) async { - assert( - _markersController != null, - 'Cannot update markers after dispose().', - ); + assert(_markersController != null, 'Cannot update markers after dispose().'); await _markersController?.addMarkers(updates.markersToAdd); await _markersController?.changeMarkers(updates.markersToChange); _markersController?.removeMarkers(updates.markerIdsToRemove); @@ -623,24 +558,14 @@ class GoogleMapController { /// Applies [ClusterManagerUpdates] to the currently managed cluster managers. void updateClusterManagers(ClusterManagerUpdates updates) { - assert( - _clusterManagersController != null, - 'Cannot update markers after dispose().', - ); - _clusterManagersController?.addClusterManagers( - updates.clusterManagersToAdd, - ); - _clusterManagersController?.removeClusterManagers( - updates.clusterManagerIdsToRemove, - ); + assert(_clusterManagersController != null, 'Cannot update markers after dispose().'); + _clusterManagersController?.addClusterManagers(updates.clusterManagersToAdd); + _clusterManagersController?.removeClusterManagers(updates.clusterManagerIdsToRemove); } /// Updates the set of [GroundOverlay]s. void updateGroundOverlays(GroundOverlayUpdates updates) { - assert( - _groundOverlaysController != null, - 'Cannot update tile overlays after dispose().', - ); + assert(_groundOverlaysController != null, 'Cannot update tile overlays after dispose().'); _groundOverlaysController?.addGroundOverlays(updates.objectsToAdd); _groundOverlaysController?.changeGroundOverlays(updates.objectsToChange); _groundOverlaysController?.removeGroundOverlays( @@ -655,15 +580,10 @@ class GoogleMapController { newOverlays, objectName: 'tileOverlay', ); - assert( - _tileOverlaysController != null, - 'Cannot update tile overlays after dispose().', - ); + assert(_tileOverlaysController != null, 'Cannot update tile overlays after dispose().'); _tileOverlaysController?.addTileOverlays(updates.objectsToAdd); _tileOverlaysController?.changeTileOverlays(updates.objectsToChange); - _tileOverlaysController?.removeTileOverlays( - updates.objectIdsToRemove.cast(), - ); + _tileOverlaysController?.removeTileOverlays(updates.objectIdsToRemove.cast()); _tileOverlays = newOverlays; } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart index 04982b8d75e4..9e1ce02285d9 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_flutter_web.dart @@ -29,10 +29,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// Retrieve a map controller by its mapId. GoogleMapController _map(int mapId) { final GoogleMapController? controller = _mapById[mapId]; - assert( - controller != null, - 'Maps cannot be retrieved before calling buildView!', - ); + assert(controller != null, 'Maps cannot be retrieved before calling buildView!'); return controller!; } @@ -49,55 +46,37 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// This attempts to merge the new `optionsUpdate` passed in, with the previous /// options passed to the map (in other updates, or when creating it). @override - Future updateMapConfiguration( - MapConfiguration update, { - required int mapId, - }) async { + Future updateMapConfiguration(MapConfiguration update, {required int mapId}) async { _map(mapId).updateMapConfiguration(update); } /// Applies the passed in `markerUpdates` to the `mapId`. @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { await _map(mapId).updateMarkers(markerUpdates); } /// Applies the passed in `polygonUpdates` to the `mapId`. @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { _map(mapId).updatePolygons(polygonUpdates); } /// Applies the passed in `polylineUpdates` to the `mapId`. @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { _map(mapId).updatePolylines(polylineUpdates); } /// Applies the passed in `circleUpdates` to the `mapId`. @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { _map(mapId).updateCircles(circleUpdates); } /// Applies the passed in `heatmapUpdates` to the `mapId`. @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) async { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) async { _map(mapId).updateHeatmaps(heatmapUpdates); } @@ -126,28 +105,19 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async { _map(mapId).clearTileCache(tileOverlayId); } /// Applies the given `cameraUpdate` to the current viewport (with animation). @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async { + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async { return moveCamera(cameraUpdate, mapId: mapId); } /// Applies the given `cameraUpdate` to the current viewport. @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async { + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async { return _map(mapId).moveCamera(cameraUpdate); } @@ -170,19 +140,13 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// Returns the screen coordinate (in pixels) of a given `latLng`. @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) { return _map(mapId).getScreenCoordinate(latLng); } /// Returns the [LatLng] of a [ScreenCoordinate] of the viewport. @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) { return _map(mapId).getLatLng(screenCoordinate); } @@ -192,10 +156,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// * [hideMarkerInfoWindow] to hide the info window. /// * [isMarkerInfoWindowShown] to check if the info window is visible/hidden. @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async { + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async { _map(mapId).showInfoWindow(markerId); } @@ -205,10 +166,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// * [showMarkerInfoWindow] to show the info window. /// * [isMarkerInfoWindowShown] to check if the info window is shown. @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async { + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async { _map(mapId).hideInfoWindow(markerId); } @@ -218,10 +176,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// * [showMarkerInfoWindow] to show the info window. /// * [hideMarkerInfoWindow] to hide the info window. @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return _map(mapId).isInfoWindowShown(markerId); } @@ -352,13 +307,8 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { _mapById[creationId] = mapController; - mapController.events.whereType().first.then(( - WebMapReadyEvent event, - ) { - assert( - creationId == event.mapId, - 'Received WebMapReadyEvent for the wrong map', - ); + mapController.events.whereType().first.then((WebMapReadyEvent event) { + assert(creationId == event.mapId, 'Received WebMapReadyEvent for the wrong map'); // Notify the plugin now that there's a fully initialized controller. onPlatformViewCreated.call(event.mapId); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_inspector_web.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_inspector_web.dart index 714c03811641..863dcfad514c 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_inspector_web.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/google_maps_inspector_web.dart @@ -16,12 +16,10 @@ import 'marker_clustering.dart'; typedef ConfigurationProvider = MapConfiguration Function(int mapId); /// Function that gets the [ClusterManagersController] for a given `mapId`. -typedef ClusterManagersControllerProvider = - ClusterManagersController? Function(int mapId); +typedef ClusterManagersControllerProvider = ClusterManagersController? Function(int mapId); /// Function that gets the [GroundOverlaysController] for a given `mapId`. -typedef GroundOverlaysControllerProvider = - GroundOverlaysController? Function(int mapId); +typedef GroundOverlaysControllerProvider = GroundOverlaysController? Function(int mapId); /// This platform implementation allows inspecting the running maps. class GoogleMapsInspectorWeb extends GoogleMapsInspectorPlatform { @@ -77,10 +75,7 @@ class GoogleMapsInspectorWeb extends GoogleMapsInspectorPlatform { } @override - Future getTileOverlayInfo( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future getTileOverlayInfo(TileOverlayId tileOverlayId, {required int mapId}) async { return null; // Custom tiles not supported on the web } @@ -92,10 +87,9 @@ class GoogleMapsInspectorWeb extends GoogleMapsInspectorPlatform { GroundOverlayId groundOverlayId, { required int mapId, }) async { - final gmaps.GroundOverlay? groundOverlay = - _groundOverlaysControllerProvider( - mapId, - )!.getGroundOverlay(groundOverlayId); + final gmaps.GroundOverlay? groundOverlay = _groundOverlaysControllerProvider( + mapId, + )!.getGroundOverlay(groundOverlayId); if (groundOverlay == null) { return null; @@ -105,10 +99,7 @@ class GoogleMapsInspectorWeb extends GoogleMapsInspectorPlatform { return GroundOverlay.fromBounds( groundOverlayId: groundOverlayId, - image: BytesMapBitmap( - Uint8List.fromList([0]), - bitmapScaling: MapBitmapScaling.none, - ), + image: BytesMapBitmap(Uint8List.fromList([0]), bitmapScaling: MapBitmapScaling.none), bounds: gmLatLngBoundsToLatLngBounds(groundOverlay.bounds), transparency: 1.0 - groundOverlay.opacity, visible: groundOverlay.map != null, @@ -146,10 +137,7 @@ class GoogleMapsInspectorWeb extends GoogleMapsInspectorPlatform { required int mapId, required ClusterManagerId clusterManagerId, }) async { - return _clusterManagersControllerProvider( - mapId, - )?.getClusters(clusterManagerId) ?? - []; + return _clusterManagersControllerProvider(mapId)?.getClusters(clusterManagerId) ?? []; } /// Returns the stream of clustering events for a given [ClusterManager]. @@ -158,8 +146,6 @@ class GoogleMapsInspectorWeb extends GoogleMapsInspectorPlatform { required int mapId, required ClusterManagerId clusterManagerId, }) { - return _clusterManagersControllerProvider( - mapId, - )?.getClustererEvents(clusterManagerId); + return _clusterManagersControllerProvider(mapId)?.getClustererEvents(clusterManagerId); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlay.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlay.dart index 1a3b0090481b..36182e558374 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlay.dart @@ -8,10 +8,8 @@ part of '../google_maps_flutter_web.dart'; class GroundOverlayController { /// Creates a [GroundOverlayController] that wraps a /// [gmaps.GroundOverlay] object. - GroundOverlayController({ - required gmaps.GroundOverlay groundOverlay, - required VoidCallback onTap, - }) : _groundOverlay = groundOverlay { + GroundOverlayController({required gmaps.GroundOverlay groundOverlay, required VoidCallback onTap}) + : _groundOverlay = groundOverlay { groundOverlay.onClick.listen((gmaps.MapMouseEvent event) { onTap.call(); }); diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlays.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlays.dart index ef22a05adccb..ede0ddaf4e98 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlays.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/ground_overlays.dart @@ -10,14 +10,11 @@ class GroundOverlaysController extends GeometryController { /// /// The [stream] parameter is a required [StreamController] used for /// emitting ground overlay tap events. - GroundOverlaysController({ - required StreamController> stream, - }) : _streamController = stream, - _groundOverlayIdToController = - {}; + GroundOverlaysController({required StreamController> stream}) + : _streamController = stream, + _groundOverlayIdToController = {}; - final Map - _groundOverlayIdToController; + final Map _groundOverlayIdToController; // The stream over which ground overlays broadcast their events final StreamController> _streamController; @@ -35,9 +32,7 @@ class GroundOverlaysController extends GeometryController { 'On Web platform, bounds must be provided for GroundOverlay', ); - final gmaps.LatLngBounds bounds = latLngBoundsToGmlatLngBounds( - groundOverlay.bounds!, - ); + final gmaps.LatLngBounds bounds = latLngBoundsToGmlatLngBounds(groundOverlay.bounds!); final groundOverlayOptions = gmaps.GroundOverlayOptions() ..opacity = 1.0 - groundOverlay.transparency @@ -89,8 +84,9 @@ class GroundOverlaysController extends GeometryController { } void _removeGroundOverlay(GroundOverlayId groundOverlayId) { - final GroundOverlayController? controller = _groundOverlayIdToController - .remove(groundOverlayId); + final GroundOverlayController? controller = _groundOverlayIdToController.remove( + groundOverlayId, + ); if (controller != null) { controller.remove(); } @@ -103,8 +99,9 @@ class GroundOverlaysController extends GeometryController { /// Returns the [GroundOverlay] with the given [GroundOverlayId]. /// Only used for testing. gmaps.GroundOverlay? getGroundOverlay(GroundOverlayId groundOverlayId) { - final GroundOverlayController? controller = _groundOverlayIdToController - .remove(groundOverlayId); + final GroundOverlayController? controller = _groundOverlayIdToController.remove( + groundOverlayId, + ); return controller?.groundOverlay; } } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmap.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmap.dart index c55e7ea7fd8f..d6feccc00a9b 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmap.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmap.dart @@ -7,8 +7,7 @@ part of '../google_maps_flutter_web.dart'; /// The `HeatmapController` class wraps a [visualization.HeatmapLayer] and its `onTap` behavior. class HeatmapController { /// Creates a `HeatmapController`, which wraps a [visualization.HeatmapLayer] object and its `onTap` behavior. - HeatmapController({required visualization.HeatmapLayer heatmap}) - : _heatmap = heatmap; + HeatmapController({required visualization.HeatmapLayer heatmap}) : _heatmap = heatmap; visualization.HeatmapLayer? _heatmap; diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmaps.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmaps.dart index 105c2fb1a0c0..fb3eeeffdee4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmaps.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/heatmaps.dart @@ -7,8 +7,7 @@ part of '../google_maps_flutter_web.dart'; /// This class manages all the [HeatmapController]s associated to a [GoogleMapController]. class HeatmapsController extends GeometryController { /// Initialize the cache - HeatmapsController() - : _heatmapIdToController = {}; + HeatmapsController() : _heatmapIdToController = {}; // A cache of [HeatmapController]s indexed by their [HeatmapId]. final Map _heatmapIdToController; @@ -25,8 +24,7 @@ class HeatmapsController extends GeometryController { } void _addHeatmap(Heatmap heatmap) { - final visualization.HeatmapLayerOptions heatmapOptions = - _heatmapOptionsFromHeatmap(heatmap); + final visualization.HeatmapLayerOptions heatmapOptions = _heatmapOptionsFromHeatmap(heatmap); final gmHeatmap = visualization.HeatmapLayer(heatmapOptions); gmHeatmap.map = googleMap; final controller = HeatmapController(heatmap: gmHeatmap); @@ -39,16 +37,14 @@ class HeatmapsController extends GeometryController { } void _changeHeatmap(Heatmap heatmap) { - final HeatmapController? heatmapController = - _heatmapIdToController[heatmap.heatmapId]; + final HeatmapController? heatmapController = _heatmapIdToController[heatmap.heatmapId]; heatmapController?.update(_heatmapOptionsFromHeatmap(heatmap)); } /// Removes a set of [HeatmapId]s from the cache. void removeHeatmaps(Set heatmapIdsToRemove) { for (final heatmapId in heatmapIdsToRemove) { - final HeatmapController? heatmapController = - _heatmapIdToController[heatmapId]; + final HeatmapController? heatmapController = _heatmapIdToController[heatmapId]; heatmapController?.remove(); _heatmapIdToController.remove(heatmapId); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker.dart index ca443c4b8441..d905b01eab3e 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker.dart @@ -105,8 +105,7 @@ abstract class MarkerController { /// /// [gmaps.Marker] is a legacy class that is being replaced /// by [gmaps.AdvancedMarkerElement]. -class LegacyMarkerController - extends MarkerController { +class LegacyMarkerController extends MarkerController { /// Creates a `LegacyMarkerController`, which wraps a [gmaps.Marker] object. LegacyMarkerController({ required super.marker, @@ -124,8 +123,7 @@ class LegacyMarkerController /// This list keeps track of all event subscriptions created for the marker, /// including taps and different drag events. /// These subscriptions should be disposed when the controller is disposed. - final List> _subscriptions = - >[]; + final List> _subscriptions = >[]; @override void addMarkerListener({ @@ -195,10 +193,7 @@ class LegacyMarkerController } @override - void update( - gmaps.MarkerOptions options, { - web.HTMLElement? newInfoWindowContent, - }) { + void update(gmaps.MarkerOptions options, {web.HTMLElement? newInfoWindowContent}) { assert(_marker != null, 'Cannot `update` Marker after calling `remove`.'); _marker!.options = options; @@ -216,11 +211,7 @@ class LegacyMarkerController /// [gmaps.AdvancedMarkerElement] is a new class that is /// replacing [gmaps.Marker]. class AdvancedMarkerController - extends - MarkerController< - gmaps.AdvancedMarkerElement, - gmaps.AdvancedMarkerElementOptions - > { + extends MarkerController { /// Creates a `AdvancedMarkerController`, which wraps /// a [gmaps.AdvancedMarkerElement] object. AdvancedMarkerController({ @@ -239,8 +230,7 @@ class AdvancedMarkerController /// This list keeps track of all event subscriptions created for the marker, /// including taps and different drag events. /// These subscriptions should be disposed when the controller is disposed. - final List> _subscriptions = - >[]; + final List> _subscriptions = >[]; @override void addMarkerListener({ @@ -312,10 +302,7 @@ class AdvancedMarkerController } @override - void update( - gmaps.AdvancedMarkerElementOptions options, { - web.HTMLElement? newInfoWindowContent, - }) { + void update(gmaps.AdvancedMarkerElementOptions options, {web.HTMLElement? newInfoWindowContent}) { assert(_marker != null, 'Cannot `update` Marker after calling `remove`.'); final gmaps.AdvancedMarkerElement marker = _marker!; diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart index 8fb0e57e8ae4..7185882831a4 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering.dart @@ -35,18 +35,15 @@ class ClusterManagersController extends GeometryController { /// /// The [stream] parameter is a required [StreamController] used for /// emitting map events. - ClusterManagersController({ - required StreamController> stream, - }) : _streamController = stream, - _clusterManagerIdToMarkerClusterer = - >{}; + ClusterManagersController({required StreamController> stream}) + : _streamController = stream, + _clusterManagerIdToMarkerClusterer = >{}; // The stream over which cluster managers broadcast their events final StreamController> _streamController; // A cache of [MarkerClusterer]s indexed by their [ClusterManagerId]. - final Map> - _clusterManagerIdToMarkerClusterer; + final Map> _clusterManagerIdToMarkerClusterer; /// Adds a set of [ClusterManager] objects to the cache. void addClusterManagers(Set clusterManagersToAdd) { @@ -56,16 +53,11 @@ class ClusterManagersController extends GeometryController { void _addClusterManager(ClusterManager clusterManager) { final MarkerClusterer markerClusterer = createMarkerClusterer( googleMap, - ( - gmaps.MapMouseEvent event, - MarkerClustererCluster cluster, - gmaps.Map map, - ) => + (gmaps.MapMouseEvent event, MarkerClustererCluster cluster, gmaps.Map map) => _clusterClicked(clusterManager.clusterManagerId, event, cluster, map), ); - _clusterManagerIdToMarkerClusterer[clusterManager.clusterManagerId] = - markerClusterer; + _clusterManagerIdToMarkerClusterer[clusterManager.clusterManagerId] = markerClusterer; markerClusterer.onAdd(); } @@ -138,21 +130,15 @@ class ClusterManagersController extends GeometryController { _clusterManagerIdToMarkerClusterer[clusterManagerId]; if (markerClusterer != null) { return markerClusterer.clusters - .map( - (MarkerClustererCluster cluster) => - _convertCluster(clusterManagerId, cluster), - ) + .map((MarkerClustererCluster cluster) => _convertCluster(clusterManagerId, cluster)) .toList(); } return []; } /// Returns the stream of clustering lifecycle events for the given manager. - Stream? getClustererEvents( - ClusterManagerId clusterManagerId, - ) => interop.getClustererEvents( - _clusterManagerIdToMarkerClusterer[clusterManagerId]!, - ); + Stream? getClustererEvents(ClusterManagerId clusterManagerId) => + interop.getClustererEvents(_clusterManagerIdToMarkerClusterer[clusterManagerId]!); void _clusterClicked( ClusterManagerId clusterManagerId, @@ -160,12 +146,8 @@ class ClusterManagersController extends GeometryController { MarkerClustererCluster markerClustererCluster, gmaps.Map map, ) { - if (markerClustererCluster.count > 0 && - markerClustererCluster.bounds != null) { - final Cluster cluster = _convertCluster( - clusterManagerId, - markerClustererCluster, - ); + if (markerClustererCluster.count > 0 && markerClustererCluster.bounds != null) { + final Cluster cluster = _convertCluster(clusterManagerId, markerClustererCluster); _streamController.add(ClusterTapEvent(mapId, cluster)); } } @@ -176,18 +158,11 @@ class ClusterManagersController extends GeometryController { MarkerClustererCluster markerClustererCluster, ) { final LatLng position = gmLatLngToLatLng(markerClustererCluster.position); - final LatLngBounds bounds = gmLatLngBoundsToLatLngBounds( - markerClustererCluster.bounds!, - ); + final LatLngBounds bounds = gmLatLngBoundsToLatLngBounds(markerClustererCluster.bounds!); final List markerIds = markerClustererCluster.markers .map(getMarkerId) .toList(); - return Cluster( - clusterManagerId, - markerIds, - position: position, - bounds: bounds, - ); + return Cluster(clusterManagerId, markerIds, position: position, bounds: bounds); } } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart index 1fa5a697f8bf..ae00416808ac 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/marker_clustering_js_interop.dart @@ -16,8 +16,11 @@ import 'package:google_maps/google_maps.dart' as gmaps; import 'marker_clustering.dart'; /// A typedef representing a callback function for handling cluster tap events. -typedef ClusterClickHandler = - void Function(gmaps.MapMouseEvent, MarkerClustererCluster, gmaps.Map); +typedef ClusterClickHandler = void Function( + gmaps.MapMouseEvent, + MarkerClustererCluster, + gmaps.Map, +); /// The [MarkerClustererOptions] object used to initialize [MarkerClusterer]. /// @@ -34,13 +37,11 @@ extension type MarkerClustererOptions._(JSObject _) implements JSObject { map: map as JSAny?, markers: markers?.cast().toJS ?? JSArray(), onClusterClick: onClusterClick != null - ? ((JSAny event, MarkerClustererCluster cluster, JSAny map) => - onClusterClick( - event as gmaps.MapMouseEvent, - cluster, - map as gmaps.Map, - )) - .toJS + ? ((JSAny event, MarkerClustererCluster cluster, JSAny map) => onClusterClick( + event as gmaps.MapMouseEvent, + cluster, + map as gmaps.Map, + )).toJS : null, ); @@ -61,18 +62,13 @@ extension type MarkerClustererOptions._(JSObject _) implements JSObject { external JSArray? get _markers; /// Returns the onClusterClick handler. - ClusterClickHandler? get onClusterClick => - _onClusterClick?.toDart as ClusterClickHandler?; + ClusterClickHandler? get onClusterClick => _onClusterClick?.toDart as ClusterClickHandler?; @JS('onClusterClick') external JSExportedDartFunction? get _onClusterClick; } @JS('google.maps.event.addListener') -external JSAny _gmapsAddListener( - JSAny instance, - String eventName, - JSFunction handler, -); +external JSAny _gmapsAddListener(JSAny instance, String eventName, JSFunction handler); @JS('google.maps.event.removeListener') external void _gmapsRemoveListener(JSAny listenerHandle); @@ -135,8 +131,7 @@ extension type MarkerClusterer._(JSObject _) implements JSObject { external void _addMarkers(JSArray? markers, bool? noDraw); /// Removes a marker from the [MarkerClusterer]. - bool removeMarker(T marker, bool? noDraw) => - _removeMarker(marker as JSAny, noDraw); + bool removeMarker(T marker, bool? noDraw) => _removeMarker(marker as JSAny, noDraw); @JS('removeMarker') external bool _removeMarker(JSAny marker, bool? noDraw); @@ -171,10 +166,7 @@ MarkerClusterer createMarkerClusterer( gmaps.Map map, ClusterClickHandler onClusterClickHandler, ) { - final options = MarkerClustererOptions( - map: map, - onClusterClick: onClusterClickHandler, - ); + final options = MarkerClustererOptions(map: map, onClusterClick: onClusterClickHandler); return MarkerClusterer(options); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart index 4ded27038e5f..fc89042b00dd 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/markers.dart @@ -18,8 +18,7 @@ part of '../google_maps_flutter_web.dart'; /// /// [T] must extend [JSObject]. It's not specified in code because our mocking /// framework does not support mocking JSObjects. -abstract class MarkersController - extends GeometryController { +abstract class MarkersController extends GeometryController { /// Initialize the cache. The [StreamController] comes from the [GoogleMapController], and is shared with other controllers. MarkersController({ required StreamController> stream, @@ -44,11 +43,11 @@ abstract class MarkersController /// /// Wraps each [Marker] into its corresponding [MarkerController]. Future addMarkers(Set markersToAdd) async { - final Map> markersByClusters = markersToAdd - .groupListsBy((Marker marker) => marker.clusterManagerId); + final Map> markersByClusters = markersToAdd.groupListsBy( + (Marker marker) => marker.clusterManagerId, + ); - for (final MapEntry> entry - in markersByClusters.entries) { + for (final MapEntry> entry in markersByClusters.entries) { final List> markerControllers = await Future.wait( entry.value.map(_createMarker), ); @@ -57,10 +56,7 @@ abstract class MarkersController if (clusterManagerId != null) { _clusterManagersController.addItems( clusterManagerId, - markerControllers - .map((controller) => controller.marker) - .whereType() - .toList(), + markerControllers.map((controller) => controller.marker).whereType().toList(), ); } else { for (final controller in markerControllers) { @@ -82,16 +78,14 @@ abstract class MarkersController } Future> _createMarker(Marker marker) async { - final gmaps.InfoWindowOptions? infoWindowOptions = - _infoWindowOptionsFromMarker(marker); + final gmaps.InfoWindowOptions? infoWindowOptions = _infoWindowOptionsFromMarker(marker); gmaps.InfoWindow? gmInfoWindow; if (infoWindowOptions != null) { gmInfoWindow = gmaps.InfoWindow(infoWindowOptions); // Google Maps' JS SDK does not have a click event on the InfoWindow, so // we make one... - if (infoWindowOptions.content != null && - infoWindowOptions.content is web.HTMLElement) { + if (infoWindowOptions.content != null && infoWindowOptions.content is web.HTMLElement) { final content = infoWindowOptions.content! as web.HTMLElement; content.onclick = (JSAny? _) { @@ -100,13 +94,9 @@ abstract class MarkersController } } - final MarkerController? markerController = - _markerIdToController[marker.markerId]; + final MarkerController? markerController = _markerIdToController[marker.markerId]; final T? currentMarker = markerController?.marker; - final O markerOptions = await _markerOptionsFromMarker( - marker, - currentMarker, - ); + final O markerOptions = await _markerOptionsFromMarker(marker, currentMarker); final MarkerController controller = await createMarkerController( marker, markerOptions, @@ -136,11 +126,9 @@ abstract class MarkersController } Future _changeMarker(Marker marker) async { - final MarkerController? markerController = - _markerIdToController[marker.markerId]; + final MarkerController? markerController = _markerIdToController[marker.markerId]; if (markerController != null) { - final ClusterManagerId? oldClusterManagerId = - markerController.clusterManagerId; + final ClusterManagerId? oldClusterManagerId = markerController.clusterManagerId; final ClusterManagerId? newClusterManagerId = marker.clusterManagerId; if (oldClusterManagerId != newClusterManagerId) { @@ -148,12 +136,8 @@ abstract class MarkersController _removeMarker(marker.markerId); await _addMarker(marker); } else { - final O markerOptions = await _markerOptionsFromMarker( - marker, - markerController.marker, - ); - final gmaps.InfoWindowOptions? infoWindow = - _infoWindowOptionsFromMarker(marker); + final O markerOptions = await _markerOptionsFromMarker(marker, markerController.marker); + final gmaps.InfoWindowOptions? infoWindow = _infoWindowOptionsFromMarker(marker); markerController.update( markerOptions, newInfoWindowContent: infoWindow?.content as web.HTMLElement?, @@ -164,41 +148,32 @@ abstract class MarkersController /// Removes a set of [MarkerId]s from the cache. void removeMarkers(Set markerIdsToRemove) { - final List?>> markersControllers = - markerIdsToRemove - .map( - (MarkerId markerId) => - MapEntry?>( - markerId, - _markerIdToController[markerId], - ), - ) - .toList(); - - final Map> controllersByCluster = - markersControllers - .groupListsBy( - (MapEntry?> markerControler) => - markerControler.value?._clusterManagerId, - ) - .map( - ( - ClusterManagerId? key, - List?>> value, - ) => MapEntry>( + final List?>> markersControllers = markerIdsToRemove + .map( + (MarkerId markerId) => MapEntry?>( + markerId, + _markerIdToController[markerId], + ), + ) + .toList(); + + final Map> controllersByCluster = markersControllers + .groupListsBy( + (MapEntry?> markerControler) => + markerControler.value?._clusterManagerId, + ) + .map( + (ClusterManagerId? key, List?>> value) => + MapEntry>( key, value - .map( - (MapEntry?> x) => - x.value?.marker, - ) + .map((MapEntry?> x) => x.value?.marker) .whereType() .toList(), ), - ); + ); - for (final MapEntry> entry - in controllersByCluster.entries) { + for (final MapEntry> entry in controllersByCluster.entries) { if (entry.key != null) { _clusterManagersController.removeItems(entry.key!, entry.value); } @@ -211,8 +186,7 @@ abstract class MarkersController } void _removeMarker(MarkerId markerId) { - final MarkerController? markerController = - _markerIdToController[markerId]; + final MarkerController? markerController = _markerIdToController[markerId]; if (markerController?.clusterManagerId != null) { _clusterManagersController.removeItem( markerController!.clusterManagerId!, @@ -230,8 +204,7 @@ abstract class MarkersController /// See also [hideMarkerInfoWindow] and [isInfoWindowShown]. void showMarkerInfoWindow(MarkerId markerId) { _hideAllMarkerInfoWindow(); - final MarkerController? markerController = - _markerIdToController[markerId]; + final MarkerController? markerController = _markerIdToController[markerId]; markerController?.showInfoWindow(); } @@ -239,8 +212,7 @@ abstract class MarkersController /// /// See also [showMarkerInfoWindow] and [isInfoWindowShown]. void hideMarkerInfoWindow(MarkerId markerId) { - final MarkerController? markerController = - _markerIdToController[markerId]; + final MarkerController? markerController = _markerIdToController[markerId]; markerController?.hideInfoWindow(); } @@ -248,8 +220,7 @@ abstract class MarkersController /// /// See also [showMarkerInfoWindow] and [hideMarkerInfoWindow]. bool isInfoWindowShown(MarkerId markerId) { - final MarkerController? markerController = - _markerIdToController[markerId]; + final MarkerController? markerController = _markerIdToController[markerId]; return markerController?.infoWindowShown ?? false; } @@ -267,29 +238,20 @@ abstract class MarkersController } void _onMarkerDragStart(MarkerId markerId, gmaps.LatLng latLng) { - _streamController.add( - MarkerDragStartEvent(mapId, gmLatLngToLatLng(latLng), markerId), - ); + _streamController.add(MarkerDragStartEvent(mapId, gmLatLngToLatLng(latLng), markerId)); } void _onMarkerDrag(MarkerId markerId, gmaps.LatLng latLng) { - _streamController.add( - MarkerDragEvent(mapId, gmLatLngToLatLng(latLng), markerId), - ); + _streamController.add(MarkerDragEvent(mapId, gmLatLngToLatLng(latLng), markerId)); } void _onMarkerDragEnd(MarkerId markerId, gmaps.LatLng latLng) { - _streamController.add( - MarkerDragEndEvent(mapId, gmLatLngToLatLng(latLng), markerId), - ); + _streamController.add(MarkerDragEndEvent(mapId, gmLatLngToLatLng(latLng), markerId)); } void _hideAllMarkerInfoWindow() { _markerIdToController.values - .where( - (MarkerController? controller) => - controller?.infoWindowShown ?? false, - ) + .where((MarkerController? controller) => controller?.infoWindowShown ?? false) .forEach((MarkerController controller) { controller.hideInfoWindow(); }); @@ -297,13 +259,9 @@ abstract class MarkersController } /// A [MarkersController] for the legacy [gmaps.Marker] class. -class LegacyMarkersController - extends MarkersController { +class LegacyMarkersController extends MarkersController { /// Initialize the markers controller for the legacy [gmaps.Marker] class. - LegacyMarkersController({ - required super.stream, - required super.clusterManagersController, - }); + LegacyMarkersController({required super.stream, required super.clusterManagersController}); @override Future createMarkerController( @@ -338,17 +296,10 @@ class LegacyMarkersController /// A [MarkersController] for the advanced [gmaps.AdvancedMarkerElement] class. class AdvancedMarkersController - extends - MarkersController< - gmaps.AdvancedMarkerElement, - gmaps.AdvancedMarkerElementOptions - > { + extends MarkersController { /// Initialize the markers controller for advanced markers /// ([gmaps.AdvancedMarkerElement]). - AdvancedMarkersController({ - required super.stream, - required super.clusterManagersController, - }); + AdvancedMarkersController({required super.stream, required super.clusterManagersController}); @override Future createMarkerController( diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart index c8054cd49112..7cf41e25a0ba 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlay.dart @@ -31,11 +31,7 @@ class TileOverlayController { } /// Renders a Tile for gmaps; delegating to the configured [TileProvider]. - web.HTMLElement? _getTile( - gmaps.Point? tileCoord, - num? zoom, - web.Document? ownerDocument, - ) { + web.HTMLElement? _getTile(gmaps.Point? tileCoord, num? zoom, web.Document? ownerDocument) { if (_tileOverlay.tileProvider == null) { return null; } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlays.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlays.dart index b8b9cea80959..8dc826b7bc7f 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlays.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/overlays.dart @@ -8,8 +8,7 @@ part of '../google_maps_flutter_web.dart'; class TileOverlaysController extends GeometryController { final Map _tileOverlays = {}; - final List _visibleTileOverlays = - []; + final List _visibleTileOverlays = []; // Inserts `tileOverlayController` into the list of visible overlays, and the current [googleMap]. // @@ -57,8 +56,7 @@ class TileOverlaysController extends GeometryController { } void _changeTileOverlay(TileOverlay tileOverlay) { - final TileOverlayController controller = - _tileOverlays[tileOverlay.tileOverlayId]!; + final TileOverlayController controller = _tileOverlays[tileOverlay.tileOverlayId]!; final bool wasVisible = controller.tileOverlay.visible; final bool isVisible = tileOverlay.visible; @@ -79,9 +77,7 @@ class TileOverlaysController extends GeometryController { } void _removeTileOverlay(TileOverlayId tileOverlayId) { - final TileOverlayController? controller = _tileOverlays.remove( - tileOverlayId, - ); + final TileOverlayController? controller = _tileOverlays.remove(tileOverlayId); if (controller != null) { _remove(controller); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygons.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygons.dart index d79d1adf5a0a..86bfbf943c29 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygons.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polygons.dart @@ -29,10 +29,7 @@ class PolygonsController extends GeometryController { } void _addPolygon(Polygon polygon) { - final gmaps.PolygonOptions polygonOptions = _polygonOptionsFromPolygon( - googleMap, - polygon, - ); + final gmaps.PolygonOptions polygonOptions = _polygonOptionsFromPolygon(googleMap, polygon); final gmPolygon = gmaps.Polygon(polygonOptions)..map = googleMap; final controller = PolygonController( polygon: gmPolygon, @@ -50,8 +47,7 @@ class PolygonsController extends GeometryController { } void _changePolygon(Polygon polygon) { - final PolygonController? polygonController = - _polygonIdToController[polygon.polygonId]; + final PolygonController? polygonController = _polygonIdToController[polygon.polygonId]; polygonController?.update(_polygonOptionsFromPolygon(googleMap, polygon)); } @@ -62,8 +58,7 @@ class PolygonsController extends GeometryController { // Removes a polygon and its controller by its [PolygonId]. void _removePolygon(PolygonId polygonId) { - final PolygonController? polygonController = - _polygonIdToController[polygonId]; + final PolygonController? polygonController = _polygonIdToController[polygonId]; polygonController?.remove(); _polygonIdToController.remove(polygonId); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polyline.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polyline.dart index 5f46732d968e..ef3430371e26 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polyline.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polyline.dart @@ -35,10 +35,7 @@ class PolylineController { /// /// This cannot be called after [remove]. void update(gmaps.PolylineOptions options) { - assert( - _polyline != null, - 'Cannot `update` Polyline after calling `remove`.', - ); + assert(_polyline != null, 'Cannot `update` Polyline after calling `remove`.'); _polyline!.options = options; } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polylines.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polylines.dart index 4263a92b5a72..1afd553b3c54 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polylines.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/polylines.dart @@ -29,10 +29,7 @@ class PolylinesController extends GeometryController { } void _addPolyline(Polyline polyline) { - final gmaps.PolylineOptions polylineOptions = _polylineOptionsFromPolyline( - googleMap, - polyline, - ); + final gmaps.PolylineOptions polylineOptions = _polylineOptionsFromPolyline(googleMap, polyline); final gmPolyline = gmaps.Polyline(polylineOptions)..map = googleMap; final controller = PolylineController( polyline: gmPolyline, @@ -50,11 +47,8 @@ class PolylinesController extends GeometryController { } void _changePolyline(Polyline polyline) { - final PolylineController? polylineController = - _polylineIdToController[polyline.polylineId]; - polylineController?.update( - _polylineOptionsFromPolyline(googleMap, polyline), - ); + final PolylineController? polylineController = _polylineIdToController[polyline.polylineId]; + polylineController?.update(_polylineOptionsFromPolyline(googleMap, polyline)); } /// Removes a set of [PolylineId]s from the cache. @@ -64,8 +58,7 @@ class PolylinesController extends GeometryController { // Removes a polyline and its controller by its [PolylineId]. void _removePolyline(PolylineId polylineId) { - final PolylineController? polylineController = - _polylineIdToController[polylineId]; + final PolylineController? polylineController = _polylineIdToController[polylineId]; polylineController?.remove(); _polylineIdToController.remove(polylineId); } diff --git a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/to_screen_location.dart b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/to_screen_location.dart index da923e792156..e0da0787bf85 100644 --- a/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/to_screen_location.dart +++ b/packages/google_maps_flutter/google_maps_flutter_web/lib/src/third_party/to_screen_location/to_screen_location.dart @@ -29,18 +29,9 @@ import 'package:google_maps/google_maps.dart' as gmaps; /// /// See: https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/Projection#public-point-toscreenlocation-latlng-location gmaps.Point toScreenLocation(gmaps.Map map, gmaps.LatLng coords) { - assert( - map.bounds != null, - 'Map Bounds required to compute screen x/y of LatLng.', - ); - assert( - map.projection != null, - 'Map Projection required to compute screen x/y of LatLng.', - ); - assert( - map.isZoomDefined(), - 'Current map zoom level required to compute screen x/y of LatLng.', - ); + assert(map.bounds != null, 'Map Bounds required to compute screen x/y of LatLng.'); + assert(map.projection != null, 'Map Projection required to compute screen x/y of LatLng.'); + assert(map.isZoomDefined(), 'Current map zoom level required to compute screen x/y of LatLng.'); final gmaps.LatLngBounds bounds = map.bounds!; final gmaps.Projection projection = map.projection!; diff --git a/packages/google_sign_in/google_sign_in/example/lib/main.dart b/packages/google_sign_in/google_sign_in/example/lib/main.dart index 8d9e19c159dc..c03b45219952 100644 --- a/packages/google_sign_in/google_sign_in/example/lib/main.dart +++ b/packages/google_sign_in/google_sign_in/example/lib/main.dart @@ -24,9 +24,7 @@ String? serverClientId; /// The scopes required by this application. // #docregion CheckAuthorization -const List scopes = [ - 'https://www.googleapis.com/auth/contacts.readonly', -]; +const List scopes = ['https://www.googleapis.com/auth/contacts.readonly']; // #enddocregion CheckAuthorization void main() { @@ -56,9 +54,7 @@ class _SignInDemoState extends State { // #docregion Setup final GoogleSignIn signIn = GoogleSignIn.instance; unawaited( - signIn.initialize(clientId: clientId, serverClientId: serverClientId).then(( - _, - ) { + signIn.initialize(clientId: clientId, serverClientId: serverClientId).then((_) { signIn.authenticationEvents .listen(_handleAuthenticationEvent) .onError(_handleAuthenticationError); @@ -72,9 +68,7 @@ class _SignInDemoState extends State { // #enddocregion Setup } - Future _handleAuthenticationEvent( - GoogleSignInAuthenticationEvent event, - ) async { + Future _handleAuthenticationEvent(GoogleSignInAuthenticationEvent event) async { // #docregion CheckAuthorization final GoogleSignInAccount? user = // ... // #enddocregion CheckAuthorization @@ -85,8 +79,7 @@ class _SignInDemoState extends State { // Check for existing authorization. // #docregion CheckAuthorization - final GoogleSignInClientAuthorization? authorization = await user - ?.authorizationClient + final GoogleSignInClientAuthorization? authorization = await user?.authorizationClient .authorizationForScopes(scopes); // #enddocregion CheckAuthorization @@ -118,8 +111,9 @@ class _SignInDemoState extends State { setState(() { _contactText = 'Loading contact info...'; }); - final Map? headers = await user.authorizationClient - .authorizationHeaders(scopes); + final Map? headers = await user.authorizationClient.authorizationHeaders( + scopes, + ); if (headers == null) { setState(() { _contactText = ''; @@ -165,22 +159,16 @@ class _SignInDemoState extends State { String? _pickFirstNamedContact(Map data) { final connections = data['connections'] as List?; - final contact = - connections?.firstWhere( - (dynamic contact) => - (contact as Map)['names'] != null, - orElse: () => null, - ) - as Map?; + final contact = connections?.firstWhere( + (dynamic contact) => (contact as Map)['names'] != null, + orElse: () => null, + ) as Map?; if (contact != null) { final names = contact['names'] as List; - final name = - names.firstWhere( - (dynamic name) => - (name as Map)['displayName'] != null, - orElse: () => null, - ) - as Map?; + final name = names.firstWhere( + (dynamic name) => (name as Map)['displayName'] != null, + orElse: () => null, + ) as Map?; if (name != null) { return name['displayName'] as String?; } @@ -196,8 +184,7 @@ class _SignInDemoState extends State { Future _handleAuthorizeScopes(GoogleSignInAccount user) async { try { // #docregion RequestScopes - final GoogleSignInClientAuthorization authorization = await user - .authorizationClient + final GoogleSignInClientAuthorization authorization = await user.authorizationClient .authorizeScopes(scopes); // #enddocregion RequestScopes @@ -228,8 +215,7 @@ class _SignInDemoState extends State { Future _handleGetAuthCode(GoogleSignInAccount user) async { try { // #docregion RequestServerAuth - final GoogleSignInServerAuthorization? serverAuth = await user - .authorizationClient + final GoogleSignInServerAuthorization? serverAuth = await user.authorizationClient .authorizeServer(scopes); // #enddocregion RequestServerAuth @@ -274,10 +260,7 @@ class _SignInDemoState extends State { if (_isAuthorized) ...[ // The user has Authorized all required scopes. if (_contactText.isNotEmpty) Text(_contactText), - ElevatedButton( - child: const Text('REFRESH'), - onPressed: () => _handleGetContact(user), - ), + ElevatedButton(child: const Text('REFRESH'), onPressed: () => _handleGetContact(user)), if (_serverAuthCode.isEmpty) ElevatedButton( child: const Text('REQUEST SERVER CODE'), @@ -320,9 +303,7 @@ class _SignInDemoState extends State { web.renderButton() // #enddocregion ExplicitSignIn else - const Text( - 'This platform does not have a known authentication method', - ), + const Text('This platform does not have a known authentication method'), // #docregion ExplicitSignIn ], // #enddocregion ExplicitSignIn @@ -333,10 +314,7 @@ class _SignInDemoState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Google Sign In')), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - ), + body: ConstrainedBox(constraints: const BoxConstraints.expand(), child: _buildBody()), ); } diff --git a/packages/google_sign_in/google_sign_in/example/lib/src/web_wrapper.dart b/packages/google_sign_in/google_sign_in/example/lib/src/web_wrapper.dart index 6b157ae4059e..ba8fe415e990 100644 --- a/packages/google_sign_in/google_sign_in/example/lib/src/web_wrapper.dart +++ b/packages/google_sign_in/google_sign_in/example/lib/src/web_wrapper.dart @@ -2,5 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -export 'web_wrapper_stub.dart' - if (dart.library.js_interop) 'web_wrapper_web.dart'; +export 'web_wrapper_stub.dart' if (dart.library.js_interop) 'web_wrapper_web.dart'; diff --git a/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart b/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart index 4f647fee6af6..2d1c18a1af8f 100644 --- a/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart +++ b/packages/google_sign_in/google_sign_in/lib/google_sign_in.dart @@ -28,10 +28,8 @@ export 'widgets.dart'; /// new [GoogleSignInAccount] instance until after a call to [signOut]. @immutable class GoogleSignInAccount implements GoogleIdentity { - GoogleSignInAccount._( - GoogleSignInUserData userData, - AuthenticationTokenData tokenData, - ) : displayName = userData.displayName, + GoogleSignInAccount._(GoogleSignInUserData userData, AuthenticationTokenData tokenData) + : displayName = userData.displayName, email = userData.email, id = userData.id, photoUrl = userData.photoUrl, @@ -82,18 +80,11 @@ class GoogleSignInAccount implements GoogleIdentity { email == otherAccount.email && id == otherAccount.id && photoUrl == otherAccount.photoUrl && - _authenticationTokens.idToken == - otherAccount._authenticationTokens.idToken; + _authenticationTokens.idToken == otherAccount._authenticationTokens.idToken; } @override - int get hashCode => Object.hash( - displayName, - email, - id, - photoUrl, - _authenticationTokens.idToken, - ); + int get hashCode => Object.hash(displayName, email, id, photoUrl, _authenticationTokens.idToken); @override String toString() { @@ -139,9 +130,7 @@ class GoogleSignInAuthorizationClient { /// /// In rare cases, this can return tokens that are no longer valid. See /// [clearAuthorizationToken] for details. - Future authorizationForScopes( - List scopes, - ) async { + Future authorizationForScopes(List scopes) async { return _authorizeClient(scopes, promptIfUnauthorized: false); } @@ -156,9 +145,7 @@ class GoogleSignInAuthorizationClient { /// /// In rare cases, this can return tokens that are no longer valid. See /// [clearAuthorizationToken] for details. - Future authorizeScopes( - List scopes, - ) async { + Future authorizeScopes(List scopes) async { final GoogleSignInClientAuthorization? authz = await _authorizeClient( scopes, promptIfUnauthorized: true, @@ -195,10 +182,7 @@ class GoogleSignInAuthorizationClient { if (authz == null) { return null; } - return { - 'Authorization': 'Bearer ${authz.accessToken}', - 'X-Goog-AuthUser': '0', - }; + return {'Authorization': 'Bearer ${authz.accessToken}', 'X-Goog-AuthUser': '0'}; } /// Requests that the user authorize the given scopes for server use. @@ -218,11 +202,8 @@ class GoogleSignInAuthorizationClient { /// /// In rare cases, this can return tokens that are no longer valid. See /// [clearAuthorizationToken] for details. - Future authorizeServer( - List scopes, - ) async { - final ServerAuthorizationTokenData? tokens = await GoogleSignInPlatform - .instance + Future authorizeServer(List scopes) async { + final ServerAuthorizationTokenData? tokens = await GoogleSignInPlatform.instance .serverAuthorizationTokensForScopes( ServerAuthorizationTokensForScopesParameters( request: AuthorizationRequestDetails( @@ -235,9 +216,7 @@ class GoogleSignInAuthorizationClient { ); return tokens == null ? null - : GoogleSignInServerAuthorization( - serverAuthCode: tokens.serverAuthCode, - ); + : GoogleSignInServerAuthorization(serverAuthCode: tokens.serverAuthCode); } /// Removes the given [accessToken] from any local authorization caches. @@ -258,8 +237,7 @@ class GoogleSignInAuthorizationClient { List scopes, { required bool promptIfUnauthorized, }) async { - final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform - .instance + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform.instance .clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( request: AuthorizationRequestDetails( @@ -270,9 +248,7 @@ class GoogleSignInAuthorizationClient { ), ), ); - return tokens == null - ? null - : GoogleSignInClientAuthorization(accessToken: tokens.accessToken); + return tokens == null ? null : GoogleSignInClientAuthorization(accessToken: tokens.accessToken); } } @@ -353,9 +329,7 @@ class GoogleSignIn { ), ); case AuthenticationEventSignOut(): - _authenticationStreamController.add( - GoogleSignInAuthenticationEventSignOut(), - ); + _authenticationStreamController.add(GoogleSignInAuthenticationEventSignOut()); case AuthenticationEventException(): _authenticationStreamController.addError(event.exception); } @@ -367,8 +341,7 @@ class GoogleSignIn { return _authenticationStreamController.stream; } - final StreamController - _authenticationStreamController = + final StreamController _authenticationStreamController = StreamController.broadcast(); // Whether this package is responsible for creating stream events from @@ -415,11 +388,8 @@ class GoogleSignIn { bool reportAllExceptions = false, }) { try { - final Future? future = GoogleSignInPlatform - .instance - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + final Future? future = GoogleSignInPlatform.instance + .attemptLightweightAuthentication(const AttemptLightweightAuthenticationParameters()); if (future == null) { return null; } @@ -461,14 +431,9 @@ class GoogleSignIn { return null; } - final account = GoogleSignInAccount._( - result.user, - result.authenticationTokens, - ); + final account = GoogleSignInAccount._(result.user, result.authenticationTokens); if (_createAuthenticationStreamEvents) { - _authenticationStreamController.add( - GoogleSignInAuthenticationEventSignIn(user: account), - ); + _authenticationStreamController.add(GoogleSignInAuthenticationEventSignIn(user: account)); } return account; } on GoogleSignInException catch (e, stack) { @@ -512,8 +477,7 @@ class GoogleSignIn { /// determine how authentication is handled. For instance, the platform may /// provide platform-controlled sign-in UI elements that must be used instead /// of application-specific UI. - bool supportsAuthenticate() => - GoogleSignInPlatform.instance.supportsAuthenticate(); + bool supportsAuthenticate() => GoogleSignInPlatform.instance.supportsAuthenticate(); /// Whether or not authorization calls that could show UI must be called from /// a user interaction, such as a button press, on the current platform. @@ -538,20 +502,14 @@ class GoogleSignIn { /// that do not will ignore [scopeHint]. You should always assume that /// [GoogleSignInAuthorizationClient.authorizationForScopes] could return null /// even if you pass a [scopeHint] here. - Future authenticate({ - List scopeHint = const [], - }) async { + Future authenticate({List scopeHint = const []}) async { try { - final AuthenticationResults result = await GoogleSignInPlatform.instance - .authenticate(AuthenticateParameters(scopeHint: scopeHint)); - final account = GoogleSignInAccount._( - result.user, - result.authenticationTokens, + final AuthenticationResults result = await GoogleSignInPlatform.instance.authenticate( + AuthenticateParameters(scopeHint: scopeHint), ); + final account = GoogleSignInAccount._(result.user, result.authenticationTokens); if (_createAuthenticationStreamEvents) { - _authenticationStreamController.add( - GoogleSignInAuthenticationEventSignIn(user: account), - ); + _authenticationStreamController.add(GoogleSignInAuthenticationEventSignIn(user: account)); } return account; } on GoogleSignInException catch (e, stack) { @@ -578,9 +536,7 @@ class GoogleSignIn { /// Signs out any currently signed in user(s). Future signOut() { if (_createAuthenticationStreamEvents) { - _authenticationStreamController.add( - GoogleSignInAuthenticationEventSignOut(), - ); + _authenticationStreamController.add(GoogleSignInAuthenticationEventSignOut()); } return GoogleSignInPlatform.instance.signOut(const SignOutParams()); } @@ -590,9 +546,7 @@ class GoogleSignIn { Future disconnect() async { // Disconnecting also signs out, so synthesize a sign-out if necessary. if (_createAuthenticationStreamEvents) { - _authenticationStreamController.add( - GoogleSignInAuthenticationEventSignOut(), - ); + _authenticationStreamController.add(GoogleSignInAuthenticationEventSignOut()); } // TODO(stuartmorgan): Consider making a per-user disconnect option once // the Android implementation is available so that we can see how it is diff --git a/packages/google_sign_in/google_sign_in/lib/src/event_types.dart b/packages/google_sign_in/google_sign_in/lib/src/event_types.dart index 42f63fdbaf17..a80b04c2798d 100644 --- a/packages/google_sign_in/google_sign_in/lib/src/event_types.dart +++ b/packages/google_sign_in/google_sign_in/lib/src/event_types.dart @@ -18,8 +18,7 @@ sealed class GoogleSignInAuthenticationEvent { /// A sign-in event, corresponding to an authentication flow completing /// successfully. @immutable -class GoogleSignInAuthenticationEventSignIn - extends GoogleSignInAuthenticationEvent { +class GoogleSignInAuthenticationEventSignIn extends GoogleSignInAuthenticationEvent { /// Creates an event for a successful sign in. const GoogleSignInAuthenticationEventSignIn({required this.user}); @@ -32,5 +31,4 @@ class GoogleSignInAuthenticationEventSignIn /// Implicit sign-outs (for example, due to server-side authentication /// revocation, or timeouts) are not guaranteed to send events. @immutable -class GoogleSignInAuthenticationEventSignOut - extends GoogleSignInAuthenticationEvent {} +class GoogleSignInAuthenticationEventSignOut extends GoogleSignInAuthenticationEvent {} diff --git a/packages/google_sign_in/google_sign_in/lib/testing.dart b/packages/google_sign_in/google_sign_in/lib/testing.dart index 85b3f9872d59..0616a46bafbe 100644 --- a/packages/google_sign_in/google_sign_in/lib/testing.dart +++ b/packages/google_sign_in/google_sign_in/lib/testing.dart @@ -42,10 +42,7 @@ class FakeSignInBackend { // do nothing return null; case 'getTokens': - return { - 'idToken': user.idToken, - 'accessToken': user.accessToken, - }; + return {'idToken': user.idToken, 'accessToken': user.accessToken}; case 'signIn': return user._asMap; case 'signInSilently': diff --git a/packages/google_sign_in/google_sign_in/lib/widgets.dart b/packages/google_sign_in/google_sign_in/lib/widgets.dart index a0a3cd1f1e18..54d6ea64a652 100644 --- a/packages/google_sign_in/google_sign_in/lib/widgets.dart +++ b/packages/google_sign_in/google_sign_in/lib/widgets.dart @@ -74,18 +74,12 @@ class GoogleUserCircleAvatar extends StatelessWidget { // Placeholder to use when there is no photo URL, and while the photo is // loading. Uses the first character of the display name (if it has one), // or the first letter of the email address if it does not. - final placeholderCharSources = [ - identity.displayName, - identity.email, - '-', - ]; + final placeholderCharSources = [identity.displayName, identity.email, '-']; final String placeholderChar = placeholderCharSources .firstWhere((String? str) => str != null && str.trimLeft().isNotEmpty)! .trimLeft()[0] .toUpperCase(); - final Widget placeholder = Center( - child: Text(placeholderChar, textAlign: TextAlign.center), - ); + final Widget placeholder = Center(child: Text(placeholderChar, textAlign: TextAlign.center)); final String? photoUrl = identity.photoUrl ?? placeholderPhotoUrl; if (photoUrl == null) { @@ -93,8 +87,7 @@ class GoogleUserCircleAvatar extends StatelessWidget { } // Add a sizing directive to the profile photo URL. - final double size = - MediaQuery.of(context).devicePixelRatio * constraints.maxWidth; + final double size = MediaQuery.of(context).devicePixelRatio * constraints.maxWidth; final String sizedPhotoUrl = fife.addSizeDirectiveToUrl(photoUrl, size); // Fade the photo in over the top of the placeholder. diff --git a/packages/google_sign_in/google_sign_in/test/fife_test.dart b/packages/google_sign_in/google_sign_in/test/fife_test.dart index a4000242fa8f..675bacee4438 100644 --- a/packages/google_sign_in/google_sign_in/test/fife_test.dart +++ b/packages/google_sign_in/google_sign_in/test/fife_test.dart @@ -55,14 +55,11 @@ void main() { expect(addSizeDirectiveToUrl(url, size), expected); }); - test( - 'many directives, sets size and crop, preserves other directives', - () { - const url = '$base=s120-c-fSoften=1,50,0'; - const expected = '$base=c-fSoften=1,50,0-s20'; - expect(addSizeDirectiveToUrl(url, size), expected); - }, - ); + test('many directives, sets size and crop, preserves other directives', () { + const url = '$base=s120-c-fSoften=1,50,0'; + const expected = '$base=c-fSoften=1,50,0-s20'; + expect(addSizeDirectiveToUrl(url, size), expected); + }); }); }); } diff --git a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart index c1a83c2986a9..227ad4aaec40 100644 --- a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart +++ b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.dart @@ -45,9 +45,7 @@ void main() { await googleSignIn.initialize(); - final VerificationResult verification = verify( - mockPlatform.init(captureAny), - ); + final VerificationResult verification = verify(mockPlatform.init(captureAny)); final params = verification.captured[0] as InitParameters; expect(params.clientId, null); expect(params.serverClientId, null); @@ -69,9 +67,7 @@ void main() { hostedDomain: hostedDomain, ); - final VerificationResult verification = verify( - mockPlatform.init(captureAny), - ); + final VerificationResult verification = verify(mockPlatform.init(captureAny)); final params = verification.captured[0] as InitParameters; expect(params.clientId, clientId); expect(params.serverClientId, serverClientId); @@ -104,59 +100,47 @@ void main() { expect(signIn.user.authentication.idToken, idToken); }); - test( - 'reports sync exceptions from attemptLightweightAuthentication', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; + test('reports sync exceptions from attemptLightweightAuthentication', () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.interrupted, - ); - when( - mockPlatform.attemptLightweightAuthentication(any), - ).thenThrow(exception); - - final errorCompleter = Completer(); - final StreamSubscription subscription = - googleSignIn.authenticationEvents - .handleError((Object e) => errorCompleter.complete(e)) - .listen((_) => fail('The only event should be an error')); - await googleSignIn.initialize(); - // This doesn't throw, since reportAllExceptions is false. - await googleSignIn.attemptLightweightAuthentication(); - - final Object e = await errorCompleter.future; - expect(e, exception); - await subscription.cancel(); - }, - ); - - test( - 'reports async exceptions from attemptLightweightAuthentication', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; + const exception = GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); + when(mockPlatform.attemptLightweightAuthentication(any)).thenThrow(exception); + + final errorCompleter = Completer(); + final StreamSubscription subscription = googleSignIn + .authenticationEvents + .handleError((Object e) => errorCompleter.complete(e)) + .listen((_) => fail('The only event should be an error')); + await googleSignIn.initialize(); + // This doesn't throw, since reportAllExceptions is false. + await googleSignIn.attemptLightweightAuthentication(); - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.interrupted, - ); - when( - mockPlatform.attemptLightweightAuthentication(any), - ).thenAnswer((_) async => throw exception); - - final errorCompleter = Completer(); - final StreamSubscription subscription = - googleSignIn.authenticationEvents - .handleError((Object e) => errorCompleter.complete(e)) - .listen((_) => fail('The only event should be an error')); - await googleSignIn.initialize(); - // This doesn't throw, since reportAllExceptions is false. - await googleSignIn.attemptLightweightAuthentication(); - - final Object e = await errorCompleter.future; - expect(e, exception); - await subscription.cancel(); - }, - ); + final Object e = await errorCompleter.future; + expect(e, exception); + await subscription.cancel(); + }); + + test('reports async exceptions from attemptLightweightAuthentication', () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; + + const exception = GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenAnswer((_) async => throw exception); + + final errorCompleter = Completer(); + final StreamSubscription subscription = googleSignIn + .authenticationEvents + .handleError((Object e) => errorCompleter.complete(e)) + .listen((_) => fail('The only event should be an error')); + await googleSignIn.initialize(); + // This doesn't throw, since reportAllExceptions is false. + await googleSignIn.attemptLightweightAuthentication(); + + final Object e = await errorCompleter.future; + expect(e, exception); + await subscription.cancel(); + }); test('reports success from authenticate', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; @@ -184,21 +168,16 @@ void main() { test('reports sync exceptions from authenticate', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.interrupted, - ); + const exception = GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); when(mockPlatform.authenticate(any)).thenThrow(exception); final errorCompleter = Completer(); - final StreamSubscription subscription = - googleSignIn.authenticationEvents - .handleError((Object e) => errorCompleter.complete(e)) - .listen((_) => fail('The only event should be an error')); + final StreamSubscription subscription = googleSignIn + .authenticationEvents + .handleError((Object e) => errorCompleter.complete(e)) + .listen((_) => fail('The only event should be an error')); await googleSignIn.initialize(); - await expectLater( - googleSignIn.authenticate(), - throwsA(isA()), - ); + await expectLater(googleSignIn.authenticate(), throwsA(isA())); final Object e = await errorCompleter.future; expect(e, exception); @@ -208,23 +187,16 @@ void main() { test('reports async exceptions from authenticate', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.interrupted, - ); - when( - mockPlatform.authenticate(any), - ).thenAnswer((_) async => throw exception); + const exception = GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); + when(mockPlatform.authenticate(any)).thenAnswer((_) async => throw exception); final errorCompleter = Completer(); - final StreamSubscription subscription = - googleSignIn.authenticationEvents - .handleError((Object e) => errorCompleter.complete(e)) - .listen((_) => fail('The only event should be an error')); + final StreamSubscription subscription = googleSignIn + .authenticationEvents + .handleError((Object e) => errorCompleter.complete(e)) + .listen((_) => fail('The only event should be an error')); await googleSignIn.initialize(); - await expectLater( - googleSignIn.authenticate(), - throwsA(isA()), - ); + await expectLater(googleSignIn.authenticate(), throwsA(isA())); final Object e = await errorCompleter.future; expect(e, exception); @@ -273,9 +245,7 @@ void main() { test('reports $support from platform', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when( - mockPlatform.authorizationRequiresUserInteraction(), - ).thenReturn(support); + when(mockPlatform.authorizationRequiresUserInteraction()).thenReturn(support); expect(googleSignIn.authorizationRequiresUserInteraction(), support); }); @@ -308,18 +278,12 @@ void main() { test('reports all exceptions when requested - sync', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.canceled, - ); - when( - mockPlatform.attemptLightweightAuthentication(any), - ).thenThrow(exception); + const exception = GoogleSignInException(code: GoogleSignInExceptionCode.canceled); + when(mockPlatform.attemptLightweightAuthentication(any)).thenThrow(exception); await googleSignIn.initialize(); expect( - googleSignIn.attemptLightweightAuthentication( - reportAllExceptions: true, - ), + googleSignIn.attemptLightweightAuthentication(reportAllExceptions: true), throwsA( isA().having( (GoogleSignInException e) => e.code, @@ -330,47 +294,38 @@ void main() { ); }); - test( - 'reports serious exceptions even when all exceptions are not requested - sync', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; + test('reports serious exceptions even when all exceptions are not requested - sync', () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; + + const exception = GoogleSignInException( + code: GoogleSignInExceptionCode.clientConfigurationError, + ); + when(mockPlatform.attemptLightweightAuthentication(any)).thenThrow(exception); - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.clientConfigurationError, - ); - when( - mockPlatform.attemptLightweightAuthentication(any), - ).thenThrow(exception); - - await googleSignIn.initialize(); - expect( - googleSignIn.attemptLightweightAuthentication(), - throwsA( - isA().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.clientConfigurationError, - ), + await googleSignIn.initialize(); + expect( + googleSignIn.attemptLightweightAuthentication(), + throwsA( + isA().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.clientConfigurationError, ), - ); - }, - ); + ), + ); + }); test('reports all exceptions when requested - async', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.canceled, - ); + const exception = GoogleSignInException(code: GoogleSignInExceptionCode.canceled); when( mockPlatform.attemptLightweightAuthentication(any), ).thenAnswer((_) async => throw exception); await googleSignIn.initialize(); expect( - googleSignIn.attemptLightweightAuthentication( - reportAllExceptions: true, - ), + googleSignIn.attemptLightweightAuthentication(reportAllExceptions: true), throwsA( isA().having( (GoogleSignInException e) => e.code, @@ -381,31 +336,28 @@ void main() { ); }); - test( - 'reports serious exceptions even when all exceptions are not requested - async', - () async { - final GoogleSignIn googleSignIn = GoogleSignIn.instance; + test('reports serious exceptions even when all exceptions are not requested - async', () async { + final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.clientConfigurationError, - ); - when( - mockPlatform.attemptLightweightAuthentication(any), - ).thenAnswer((_) async => throw exception); - - await googleSignIn.initialize(); - expect( - googleSignIn.attemptLightweightAuthentication(), - throwsA( - isA().having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.clientConfigurationError, - ), + const exception = GoogleSignInException( + code: GoogleSignInExceptionCode.clientConfigurationError, + ); + when( + mockPlatform.attemptLightweightAuthentication(any), + ).thenAnswer((_) async => throw exception); + + await googleSignIn.initialize(); + expect( + googleSignIn.attemptLightweightAuthentication(), + throwsA( + isA().having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.clientConfigurationError, ), - ); - }, - ); + ), + ); + }); test('returns a null future from the platform', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; @@ -420,9 +372,7 @@ void main() { test('returns a future that resolves to null from the platform', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when( - mockPlatform.attemptLightweightAuthentication(any), - ).thenAnswer((_) async => null); + when(mockPlatform.attemptLightweightAuthentication(any)).thenAnswer((_) async => null); final Future? signInFuture = googleSignIn .attemptLightweightAuthentication(); @@ -447,9 +397,7 @@ void main() { await googleSignIn.initialize(); await googleSignIn.authenticate(scopeHint: scopes); - final VerificationResult verification = verify( - mockPlatform.authenticate(captureAny), - ); + final VerificationResult verification = verify(mockPlatform.authenticate(captureAny)); final params = verification.captured[0] as AuthenticateParameters; expect(params.scopeHint, scopes); }); @@ -476,9 +424,7 @@ void main() { test('reports exceptions', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - const exception = GoogleSignInException( - code: GoogleSignInExceptionCode.interrupted, - ); + const exception = GoogleSignInException(code: GoogleSignInExceptionCode.interrupted); when(mockPlatform.authenticate(any)).thenThrow(exception); await googleSignIn.initialize(); @@ -505,22 +451,17 @@ void main() { authenticationTokens: AuthenticationTokenData(idToken: 'idToken'), ), ); - when( - mockPlatform.clientAuthorizationTokensForScopes(any), - ).thenAnswer((_) async => null); + when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer((_) async => null); await googleSignIn.initialize(); - final GoogleSignInAccount authentication = await googleSignIn - .authenticate(); + final GoogleSignInAccount authentication = await googleSignIn.authenticate(); const scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizationForScopes(scopes); final VerificationResult verification = verify( mockPlatform.clientAuthorizationTokensForScopes(captureAny), ); - final params = - verification.captured[0] - as ClientAuthorizationTokensForScopesParameters; + final params = verification.captured[0] as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, defaultUser.id); expect(params.request.email, defaultUser.email); @@ -530,9 +471,7 @@ void main() { test('passes expected paramaters when called without a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when( - mockPlatform.clientAuthorizationTokensForScopes(any), - ).thenAnswer((_) async => null); + when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer((_) async => null); const scopes = ['scope1', 'scope2']; await googleSignIn.authorizationClient.authorizationForScopes(scopes); @@ -540,9 +479,7 @@ void main() { final VerificationResult verification = verify( mockPlatform.clientAuthorizationTokensForScopes(captureAny), ); - final params = - verification.captured[0] - as ClientAuthorizationTokensForScopesParameters; + final params = verification.captured[0] as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, null); expect(params.request.email, null); @@ -553,14 +490,12 @@ void main() { final GoogleSignIn googleSignIn = GoogleSignIn.instance; const accessToken = 'accessToken'; - when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: accessToken), - ); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => const ClientAuthorizationTokenData(accessToken: accessToken)); const scopes = ['scope1', 'scope2']; - final GoogleSignInClientAuthorization? auth = await googleSignIn - .authorizationClient + final GoogleSignInClientAuthorization? auth = await googleSignIn.authorizationClient .authorizationForScopes(scopes); expect(auth?.accessToken, accessToken); }); @@ -568,15 +503,10 @@ void main() { test('reports null', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when( - mockPlatform.clientAuthorizationTokensForScopes(any), - ).thenAnswer((_) async => null); + when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer((_) async => null); const scopes = ['scope1', 'scope2']; - expect( - await googleSignIn.authorizationClient.authorizationForScopes(scopes), - null, - ); + expect(await googleSignIn.authorizationClient.authorizationForScopes(scopes), null); }); }); @@ -590,23 +520,19 @@ void main() { authenticationTokens: AuthenticationTokenData(idToken: 'idToken'), ), ); - when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: 'accessToken'), - ); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => const ClientAuthorizationTokenData(accessToken: 'accessToken')); await googleSignIn.initialize(); - final GoogleSignInAccount authentication = await googleSignIn - .authenticate(); + final GoogleSignInAccount authentication = await googleSignIn.authenticate(); const scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizeScopes(scopes); final VerificationResult verification = verify( mockPlatform.clientAuthorizationTokensForScopes(captureAny), ); - final params = - verification.captured[0] - as ClientAuthorizationTokensForScopesParameters; + final params = verification.captured[0] as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, defaultUser.id); expect(params.request.email, defaultUser.email); @@ -616,10 +542,9 @@ void main() { test('passes expected paramaters when called without a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: 'accessToken'), - ); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => const ClientAuthorizationTokenData(accessToken: 'accessToken')); const scopes = ['scope1', 'scope2']; await googleSignIn.authorizationClient.authorizeScopes(scopes); @@ -627,9 +552,7 @@ void main() { final VerificationResult verification = verify( mockPlatform.clientAuthorizationTokensForScopes(captureAny), ); - final params = - verification.captured[0] - as ClientAuthorizationTokensForScopesParameters; + final params = verification.captured[0] as ClientAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, null); expect(params.request.email, null); @@ -640,14 +563,12 @@ void main() { final GoogleSignIn googleSignIn = GoogleSignIn.instance; const accessToken = 'accessToken'; - when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ClientAuthorizationTokenData(accessToken: accessToken), - ); + when( + mockPlatform.clientAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => const ClientAuthorizationTokenData(accessToken: accessToken)); const scopes = ['scope1', 'scope2']; - final GoogleSignInClientAuthorization auth = await googleSignIn - .authorizationClient + final GoogleSignInClientAuthorization auth = await googleSignIn.authorizationClient .authorizeScopes(scopes); expect(auth.accessToken, accessToken); }); @@ -655,9 +576,7 @@ void main() { test('throws for unexpected null', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when( - mockPlatform.clientAuthorizationTokensForScopes(any), - ).thenAnswer((_) async => null); + when(mockPlatform.clientAuthorizationTokensForScopes(any)).thenAnswer((_) async => null); const scopes = ['scope1', 'scope2']; await expectLater( @@ -683,22 +602,17 @@ void main() { authenticationTokens: AuthenticationTokenData(idToken: 'idToken'), ), ); - when( - mockPlatform.serverAuthorizationTokensForScopes(any), - ).thenAnswer((_) async => null); + when(mockPlatform.serverAuthorizationTokensForScopes(any)).thenAnswer((_) async => null); await googleSignIn.initialize(); - final GoogleSignInAccount authentication = await googleSignIn - .authenticate(); + final GoogleSignInAccount authentication = await googleSignIn.authenticate(); const scopes = ['scope1', 'scope2']; await authentication.authorizationClient.authorizeServer(scopes); final VerificationResult verification = verify( mockPlatform.serverAuthorizationTokensForScopes(captureAny), ); - final params = - verification.captured[0] - as ServerAuthorizationTokensForScopesParameters; + final params = verification.captured[0] as ServerAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, defaultUser.id); expect(params.request.email, defaultUser.email); @@ -708,9 +622,7 @@ void main() { test('passes expected paramaters when called without a user', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when( - mockPlatform.serverAuthorizationTokensForScopes(any), - ).thenAnswer((_) async => null); + when(mockPlatform.serverAuthorizationTokensForScopes(any)).thenAnswer((_) async => null); const scopes = ['scope1', 'scope2']; await googleSignIn.authorizationClient.authorizeServer(scopes); @@ -718,9 +630,7 @@ void main() { final VerificationResult verification = verify( mockPlatform.serverAuthorizationTokensForScopes(captureAny), ); - final params = - verification.captured[0] - as ServerAuthorizationTokensForScopesParameters; + final params = verification.captured[0] as ServerAuthorizationTokensForScopesParameters; expect(params.request.scopes, scopes); expect(params.request.userId, null); expect(params.request.email, null); @@ -731,14 +641,12 @@ void main() { final GoogleSignIn googleSignIn = GoogleSignIn.instance; const authCode = 'authCode'; - when(mockPlatform.serverAuthorizationTokensForScopes(any)).thenAnswer( - (_) async => - const ServerAuthorizationTokenData(serverAuthCode: authCode), - ); + when( + mockPlatform.serverAuthorizationTokensForScopes(any), + ).thenAnswer((_) async => const ServerAuthorizationTokenData(serverAuthCode: authCode)); const scopes = ['scope1', 'scope2']; - final GoogleSignInServerAuthorization? auth = await googleSignIn - .authorizationClient + final GoogleSignInServerAuthorization? auth = await googleSignIn.authorizationClient .authorizeServer(scopes); expect(auth?.serverAuthCode, authCode); }); @@ -746,15 +654,10 @@ void main() { test('reports null', () async { final GoogleSignIn googleSignIn = GoogleSignIn.instance; - when( - mockPlatform.serverAuthorizationTokensForScopes(any), - ).thenAnswer((_) async => null); + when(mockPlatform.serverAuthorizationTokensForScopes(any)).thenAnswer((_) async => null); const scopes = ['scope1', 'scope2']; - expect( - await googleSignIn.authorizationClient.authorizeServer(scopes), - null, - ); + expect(await googleSignIn.authorizationClient.authorizeServer(scopes), null); }); }); @@ -763,9 +666,7 @@ void main() { final GoogleSignIn googleSignIn = GoogleSignIn.instance; const token = 'someAccessToken'; - await googleSignIn.authorizationClient.clearAuthorizationToken( - accessToken: token, - ); + await googleSignIn.authorizationClient.clearAuthorizationToken(accessToken: token); final VerificationResult verification = verify( mockPlatform.clearAuthorizationToken(captureAny), diff --git a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart index 241078983583..2dabff1b4ad8 100644 --- a/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in/test/google_sign_in_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; -import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' - as _i3; +import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' as _i3; import 'package:google_sign_in_platform_interface/src/types.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; @@ -24,8 +23,7 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class -class _FakeAuthenticationResults_0 extends _i1.SmartFake - implements _i2.AuthenticationResults { +class _FakeAuthenticationResults_0 extends _i1.SmartFake implements _i2.AuthenticationResults { _FakeAuthenticationResults_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -33,109 +31,80 @@ class _FakeAuthenticationResults_0 extends _i1.SmartFake /// A class which mocks [GoogleSignInPlatform]. /// /// See the documentation for Mockito's code generation for more information. -class MockGoogleSignInPlatform extends _i1.Mock - implements _i3.GoogleSignInPlatform { +class MockGoogleSignInPlatform extends _i1.Mock implements _i3.GoogleSignInPlatform { MockGoogleSignInPlatform() { _i1.throwOnMissingStub(this); } @override - _i4.Future init(_i2.InitParameters? params) => - (super.noSuchMethod( - Invocation.method(#init, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future init(_i2.InitParameters? params) => (super.noSuchMethod( + Invocation.method(#init, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future<_i2.AuthenticationResults?>? attemptLightweightAuthentication( _i2.AttemptLightweightAuthenticationParameters? params, ) => - (super.noSuchMethod( - Invocation.method(#attemptLightweightAuthentication, [params]), - ) + (super.noSuchMethod(Invocation.method(#attemptLightweightAuthentication, [params])) as _i4.Future<_i2.AuthenticationResults?>?); @override bool supportsAuthenticate() => - (super.noSuchMethod( - Invocation.method(#supportsAuthenticate, []), - returnValue: false, - ) + (super.noSuchMethod(Invocation.method(#supportsAuthenticate, []), returnValue: false) as bool); @override - _i4.Future<_i2.AuthenticationResults> authenticate( - _i2.AuthenticateParameters? params, - ) => + _i4.Future<_i2.AuthenticationResults> authenticate(_i2.AuthenticateParameters? params) => (super.noSuchMethod( - Invocation.method(#authenticate, [params]), - returnValue: _i4.Future<_i2.AuthenticationResults>.value( - _FakeAuthenticationResults_0( - this, - Invocation.method(#authenticate, [params]), - ), - ), - ) - as _i4.Future<_i2.AuthenticationResults>); + Invocation.method(#authenticate, [params]), + returnValue: _i4.Future<_i2.AuthenticationResults>.value( + _FakeAuthenticationResults_0(this, Invocation.method(#authenticate, [params])), + ), + ) as _i4.Future<_i2.AuthenticationResults>); @override - bool authorizationRequiresUserInteraction() => - (super.noSuchMethod( - Invocation.method(#authorizationRequiresUserInteraction, []), - returnValue: false, - ) - as bool); + bool authorizationRequiresUserInteraction() => (super.noSuchMethod( + Invocation.method(#authorizationRequiresUserInteraction, []), + returnValue: false, + ) as bool); @override - _i4.Future<_i2.ClientAuthorizationTokenData?> - clientAuthorizationTokensForScopes( + _i4.Future<_i2.ClientAuthorizationTokenData?> clientAuthorizationTokensForScopes( _i2.ClientAuthorizationTokensForScopesParameters? params, - ) => - (super.noSuchMethod( - Invocation.method(#clientAuthorizationTokensForScopes, [params]), - returnValue: _i4.Future<_i2.ClientAuthorizationTokenData?>.value(), - ) - as _i4.Future<_i2.ClientAuthorizationTokenData?>); + ) => (super.noSuchMethod( + Invocation.method(#clientAuthorizationTokensForScopes, [params]), + returnValue: _i4.Future<_i2.ClientAuthorizationTokenData?>.value(), + ) as _i4.Future<_i2.ClientAuthorizationTokenData?>); @override - _i4.Future<_i2.ServerAuthorizationTokenData?> - serverAuthorizationTokensForScopes( + _i4.Future<_i2.ServerAuthorizationTokenData?> serverAuthorizationTokensForScopes( _i2.ServerAuthorizationTokensForScopesParameters? params, - ) => - (super.noSuchMethod( - Invocation.method(#serverAuthorizationTokensForScopes, [params]), - returnValue: _i4.Future<_i2.ServerAuthorizationTokenData?>.value(), - ) - as _i4.Future<_i2.ServerAuthorizationTokenData?>); + ) => (super.noSuchMethod( + Invocation.method(#serverAuthorizationTokensForScopes, [params]), + returnValue: _i4.Future<_i2.ServerAuthorizationTokenData?>.value(), + ) as _i4.Future<_i2.ServerAuthorizationTokenData?>); @override - _i4.Future clearAuthorizationToken( - _i2.ClearAuthorizationTokenParams? params, - ) => + _i4.Future clearAuthorizationToken(_i2.ClearAuthorizationTokenParams? params) => (super.noSuchMethod( - Invocation.method(#clearAuthorizationToken, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#clearAuthorizationToken, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future signOut(_i2.SignOutParams? params) => - (super.noSuchMethod( - Invocation.method(#signOut, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future signOut(_i2.SignOutParams? params) => (super.noSuchMethod( + Invocation.method(#signOut, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future disconnect(_i2.DisconnectParams? params) => - (super.noSuchMethod( - Invocation.method(#disconnect, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future disconnect(_i2.DisconnectParams? params) => (super.noSuchMethod( + Invocation.method(#disconnect, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/google_sign_in/google_sign_in/test/widgets_test.dart b/packages/google_sign_in/google_sign_in/test/widgets_test.dart index e0eccbfe1936..d90d59461f96 100644 --- a/packages/google_sign_in/google_sign_in/test/widgets_test.dart +++ b/packages/google_sign_in/google_sign_in/test/widgets_test.dart @@ -61,9 +61,7 @@ final Uint8List _transparentImage = Uint8List.fromList([ /// A mocked [HttpClientResponse] which is empty and has a [statusCode] of 200 /// and returns valid image. class _MockHttpResponse extends Fake implements HttpClientResponse { - final Stream _delegate = Stream.value( - _transparentImage, - ); + final Stream _delegate = Stream.value(_transparentImage); @override int get contentLength => -1; @@ -80,12 +78,7 @@ class _MockHttpResponse extends Fake implements HttpClientResponse { void Function()? onDone, bool? cancelOnError, }) { - return _delegate.listen( - onData, - onError: onError, - onDone: onDone, - cancelOnError: cancelOnError, - ); + return _delegate.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } @override diff --git a/packages/google_sign_in/google_sign_in_android/example/lib/main.dart b/packages/google_sign_in/google_sign_in_android/example/lib/main.dart index ef366b84cb61..6c72e56e9a7e 100644 --- a/packages/google_sign_in/google_sign_in_android/example/lib/main.dart +++ b/packages/google_sign_in/google_sign_in_android/example/lib/main.dart @@ -11,9 +11,7 @@ import 'package:flutter/material.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:http/http.dart' as http; -const List _scopes = [ - 'https://www.googleapis.com/auth/contacts.readonly', -]; +const List _scopes = ['https://www.googleapis.com/auth/contacts.readonly']; void main() { runApp(const MaterialApp(title: 'Google Sign In', home: SignInDemo())); @@ -43,11 +41,10 @@ class SignInDemoState extends State { Future _ensureInitialized() { // The example app uses the parsing of values from google-services.json // to provide the serverClientId, otherwise it would be required here. - return _initialization ??= - GoogleSignInPlatform.instance.init(const InitParameters()) - ..catchError((dynamic _) { - _initialization = null; - }); + return _initialization ??= GoogleSignInPlatform.instance.init(const InitParameters()) + ..catchError((dynamic _) { + _initialization = null; + }); } void _setUser(GoogleSignInUserData? user) { @@ -64,9 +61,7 @@ class SignInDemoState extends State { await _ensureInitialized(); try { final AuthenticationResults? result = await GoogleSignInPlatform.instance - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + .attemptLightweightAuthentication(const AttemptLightweightAuthenticationParameters()); _setUser(result?.user); } on GoogleSignInException catch (e) { setState(() { @@ -79,8 +74,7 @@ class SignInDemoState extends State { Future _handleAuthorizeScopes(GoogleSignInUserData user) async { try { - final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform - .instance + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform.instance .clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( request: AuthorizationRequestDetails( @@ -106,11 +100,8 @@ class SignInDemoState extends State { } } - Future?> _getAuthHeaders( - GoogleSignInUserData user, - ) async { - final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform - .instance + Future?> _getAuthHeaders(GoogleSignInUserData user) async { + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform.instance .clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( request: AuthorizationRequestDetails( @@ -161,8 +152,7 @@ class SignInDemoState extends State { return; } final data = json.decode(response.body) as Map; - final int contactCount = - (data['connections'] as List?)?.length ?? 0; + final int contactCount = (data['connections'] as List?)?.length ?? 0; setState(() { _contactText = '$contactCount contacts found'; }); @@ -171,8 +161,9 @@ class SignInDemoState extends State { Future _handleSignIn() async { try { await _ensureInitialized(); - final AuthenticationResults result = await GoogleSignInPlatform.instance - .authenticate(const AuthenticateParameters()); + final AuthenticationResults result = await GoogleSignInPlatform.instance.authenticate( + const AuthenticateParameters(), + ); _setUser(result.user); } on GoogleSignInException catch (e) { setState(() { @@ -194,22 +185,13 @@ class SignInDemoState extends State { mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ if (user != null) ...[ - ListTile( - title: Text(user.displayName ?? ''), - subtitle: Text(user.email), - ), + ListTile(title: Text(user.displayName ?? ''), subtitle: Text(user.email)), const Text('Signed in successfully.'), - ElevatedButton( - onPressed: _handleSignOut, - child: const Text('SIGN OUT'), - ), + ElevatedButton(onPressed: _handleSignOut, child: const Text('SIGN OUT')), if (_isAuthorized) ...[ // The user has Authorized all required scopes. if (_contactText.isNotEmpty) Text(_contactText), - ElevatedButton( - child: const Text('REFRESH'), - onPressed: () => _handleGetContact(user), - ), + ElevatedButton(child: const Text('REFRESH'), onPressed: () => _handleGetContact(user)), ] else ...[ // The user has NOT Authorized all required scopes. const Text('Authorization needed to read your contacts.'), @@ -220,10 +202,7 @@ class SignInDemoState extends State { ], ] else ...[ const Text('You are not currently signed in.'), - ElevatedButton( - onPressed: _handleSignIn, - child: const Text('SIGN IN'), - ), + ElevatedButton(onPressed: _handleSignIn, child: const Text('SIGN IN')), ], if (_errorMessage.isNotEmpty) Text(_errorMessage), ], @@ -234,10 +213,7 @@ class SignInDemoState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Google Sign In')), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - ), + body: ConstrainedBox(constraints: const BoxConstraints.expand(), child: _buildBody()), ); } } diff --git a/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart b/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart index f233d4f2a7d1..fe5800105b6f 100644 --- a/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart +++ b/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart @@ -38,9 +38,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { @override Future init(InitParameters params) async { _hostedDomain = params.hostedDomain; - _serverClientId = - params.serverClientId ?? - await _hostApi.getGoogleServicesJsonServerClientId(); + _serverClientId = params.serverClientId ?? await _hostApi.getGoogleServicesJsonServerClientId(); _nonce = params.nonce; // The clientId parameter is not supported on Android. // Android apps are identified by their package name and the SHA-1 of their signing key. @@ -77,18 +75,14 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { ), ); } - return credential == null - ? null - : _authenticationResultFromPlatformCredential(credential); + return credential == null ? null : _authenticationResultFromPlatformCredential(credential); } @override bool supportsAuthenticate() => true; @override - Future authenticate( - AuthenticateParameters params, - ) async { + Future authenticate(AuthenticateParameters params) async { // Attempt to authorize with minimal interaction. final PlatformGoogleIdTokenCredential? credential = await _authenticate( useButtonFlow: true, @@ -130,10 +124,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { // https://developer.android.com/identity/authorization#revoke-permissions) // an arbitrary granted scope is used here. await _hostApi.revokeAccess( - PlatformRevokeAccessRequest( - accountEmail: entry.key, - scopes: [entry.value], - ), + PlatformRevokeAccessRequest(accountEmail: entry.key, scopes: [entry.value]), ); } _cachedAccounts.clear(); @@ -151,9 +142,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { params.request, requestOfflineAccess: false, ); - return accessToken == null - ? null - : ClientAuthorizationTokenData(accessToken: accessToken); + return accessToken == null ? null : ClientAuthorizationTokenData(accessToken: accessToken); } @override @@ -228,11 +217,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { case GetCredentialFailureType.unknown: code = GoogleSignInExceptionCode.unknownError; } - throw GoogleSignInException( - code: code, - description: message, - details: authnResult.details, - ); + throw GoogleSignInException(code: code, description: message, details: authnResult.details); case GetCredentialSuccess(): // Store a preliminary entry using the 'openid' scope, which in practice // always seems to be granted at authentication time, so that an account @@ -252,9 +237,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { scopes: request.scopes, accountEmail: email, hostedDomain: _hostedDomain, - serverClientIdForForcedRefreshToken: requestOfflineAccess - ? _serverClientId - : null, + serverClientIdForForcedRefreshToken: requestOfflineAccess ? _serverClientId : null, ), promptIfUnauthorized: request.promptIfUnauthorized, ); @@ -278,11 +261,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { case AuthorizeFailureType.noActivity: code = GoogleSignInExceptionCode.uiUnavailable; } - throw GoogleSignInException( - code: code, - description: message, - details: result.details, - ); + throw GoogleSignInException(code: code, description: message, details: result.details); case PlatformAuthorizationResult(): final String? accessToken = result.accessToken; if (accessToken == null) { @@ -301,10 +280,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { _cachedAccounts[email] = scope; } } - return ( - accessToken: accessToken, - serverAuthCode: result.serverAuthCode, - ); + return (accessToken: accessToken, serverAuthCode: result.serverAuthCode); } } @@ -330,9 +306,7 @@ class GoogleSignInAndroid extends GoogleSignInPlatform { displayName: credential.displayName, photoUrl: credential.profilePictureUri, ), - authenticationTokens: AuthenticationTokenData( - idToken: credential.idToken, - ), + authenticationTokens: AuthenticationTokenData(idToken: credential.idToken), ); } } @@ -353,8 +327,7 @@ String? _idFromIdToken(String idToken) { final String? payload = match?.namedGroup('payload'); if (payload != null) { try { - final contents = - _jwtCodec.decode(base64.normalize(payload)) as Map?; + final contents = _jwtCodec.decode(base64.normalize(payload)) as Map?; if (contents != null) { return contents['sub'] as String?; } diff --git a/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart b/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart index 343a3c3ab1fb..f00f330d2dbc 100644 --- a/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart +++ b/packages/google_sign_in/google_sign_in_android/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -113,12 +111,7 @@ class PlatformAuthorizationRequest { String? serverClientIdForForcedRefreshToken; List _toList() { - return [ - scopes, - hostedDomain, - accountEmail, - serverClientIdForForcedRefreshToken, - ]; + return [scopes, hostedDomain, accountEmail, serverClientIdForForcedRefreshToken]; } Object encode() { @@ -138,8 +131,7 @@ class PlatformAuthorizationRequest { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformAuthorizationRequest || - other.runtimeType != runtimeType) { + if (other is! PlatformAuthorizationRequest || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -184,13 +176,7 @@ class GetCredentialRequestParams { String? nonce; List _toList() { - return [ - useButtonFlow, - googleIdOptionParams, - serverClientId, - hostedDomain, - nonce, - ]; + return [useButtonFlow, googleIdOptionParams, serverClientId, hostedDomain, nonce]; } Object encode() { @@ -201,8 +187,7 @@ class GetCredentialRequestParams { result as List; return GetCredentialRequestParams( useButtonFlow: result[0]! as bool, - googleIdOptionParams: - result[1]! as GetCredentialRequestGoogleIdOptionParams, + googleIdOptionParams: result[1]! as GetCredentialRequestGoogleIdOptionParams, serverClientId: result[2] as String?, hostedDomain: result[3] as String?, nonce: result[4] as String?, @@ -212,8 +197,7 @@ class GetCredentialRequestParams { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! GetCredentialRequestParams || - other.runtimeType != runtimeType) { + if (other is! GetCredentialRequestParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -256,8 +240,7 @@ class GetCredentialRequestGoogleIdOptionParams { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! GetCredentialRequestGoogleIdOptionParams || - other.runtimeType != runtimeType) { + if (other is! GetCredentialRequestGoogleIdOptionParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -276,10 +259,7 @@ class GetCredentialRequestGoogleIdOptionParams { /// Corresponds to the native RevokeAccessRequest. /// https://developers.google.com/android/reference/com/google/android/gms/auth/api/identity/RevokeAccessRequest class PlatformRevokeAccessRequest { - PlatformRevokeAccessRequest({ - required this.accountEmail, - required this.scopes, - }); + PlatformRevokeAccessRequest({required this.accountEmail, required this.scopes}); /// The email for the Google account to revoke authorizations for. String accountEmail; @@ -309,8 +289,7 @@ class PlatformRevokeAccessRequest { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformRevokeAccessRequest || - other.runtimeType != runtimeType) { + if (other is! PlatformRevokeAccessRequest || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -348,14 +327,7 @@ class PlatformGoogleIdTokenCredential { String? profilePictureUri; List _toList() { - return [ - displayName, - familyName, - givenName, - id, - idToken, - profilePictureUri, - ]; + return [displayName, familyName, givenName, id, idToken, profilePictureUri]; } Object encode() { @@ -377,8 +349,7 @@ class PlatformGoogleIdTokenCredential { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformGoogleIdTokenCredential || - other.runtimeType != runtimeType) { + if (other is! PlatformGoogleIdTokenCredential || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -463,9 +434,7 @@ class GetCredentialSuccess extends GetCredentialResult { static GetCredentialSuccess decode(Object result) { result as List; - return GetCredentialSuccess( - credential: result[0]! as PlatformGoogleIdTokenCredential, - ); + return GetCredentialSuccess(credential: result[0]! as PlatformGoogleIdTokenCredential); } @override @@ -539,11 +508,7 @@ class AuthorizeFailure extends AuthorizeResult { /// /// Corresponds to a native AuthorizationResult. class PlatformAuthorizationResult extends AuthorizeResult { - PlatformAuthorizationResult({ - this.accessToken, - this.serverAuthCode, - required this.grantedScopes, - }); + PlatformAuthorizationResult({this.accessToken, this.serverAuthCode, required this.grantedScopes}); String? accessToken; @@ -571,8 +536,7 @@ class PlatformAuthorizationResult extends AuthorizeResult { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformAuthorizationResult || - other.runtimeType != runtimeType) { + if (other is! PlatformAuthorizationResult || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -645,9 +609,7 @@ class _PigeonCodec extends StandardMessageCodec { case 132: return GetCredentialRequestParams.decode(readValue(buffer)!); case 133: - return GetCredentialRequestGoogleIdOptionParams.decode( - readValue(buffer)!, - ); + return GetCredentialRequestGoogleIdOptionParams.decode(readValue(buffer)!); case 134: return PlatformRevokeAccessRequest.decode(readValue(buffer)!); case 135: @@ -670,13 +632,11 @@ class GoogleSignInApi { /// Constructor for [GoogleSignInApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - GoogleSignInApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + GoogleSignInApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -688,15 +648,13 @@ class GoogleSignInApi { Future getGoogleServicesJsonServerClientId() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.getGoogleServicesJsonServerClientId$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -712,22 +670,16 @@ class GoogleSignInApi { /// Requests an authentication credential (sign in) via CredentialManager's /// getCredential. - Future getCredential( - GetCredentialRequestParams params, - ) async { + Future getCredential(GetCredentialRequestParams params) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.getCredential$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [params], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([params]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -750,15 +702,13 @@ class GoogleSignInApi { Future clearCredentialState() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.clearCredentialState$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -776,17 +726,13 @@ class GoogleSignInApi { Future clearAuthorizationToken(String token) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.clearAuthorizationToken$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [token], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([token]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -807,17 +753,16 @@ class GoogleSignInApi { }) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.authorize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [params, promptIfUnauthorized], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + params, + promptIfUnauthorized, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -839,17 +784,13 @@ class GoogleSignInApi { Future revokeAccess(PlatformRevokeAccessRequest params) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_android.GoogleSignInApi.revokeAccess$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [params], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([params]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart b/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart index 9a490e4fbb9f..1efafc776e76 100644 --- a/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart +++ b/packages/google_sign_in/google_sign_in_android/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/googlesignin/Messages.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/googlesignin/Messages.kt', kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.googlesignin'), copyrightHeader: 'pigeons/copyright.txt', ), @@ -71,10 +70,7 @@ class GetCredentialRequestGoogleIdOptionParams { /// Corresponds to the native RevokeAccessRequest. /// https://developers.google.com/android/reference/com/google/android/gms/auth/api/identity/RevokeAccessRequest class PlatformRevokeAccessRequest { - PlatformRevokeAccessRequest({ - required this.accountEmail, - required this.scopes, - }); + PlatformRevokeAccessRequest({required this.accountEmail, required this.scopes}); /// The email for the Google account to revoke authorizations for. String accountEmail; diff --git a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart index e13e26c41396..6d0acc09c1e1 100644 --- a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart +++ b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.dart @@ -43,9 +43,7 @@ void main() { credential: PlatformGoogleIdTokenCredential(id: '', idToken: ''), ), ); - provideDummy( - PlatformAuthorizationResult(grantedScopes: []), - ); + provideDummy(PlatformAuthorizationResult(grantedScopes: [])); }); test('registered instance', () { @@ -67,26 +65,20 @@ void main() { test('passes explicit server client ID', () async { const serverClientId = 'aServerClient'; - await googleSignIn.init( - const InitParameters(serverClientId: serverClientId), - ); + await googleSignIn.init(const InitParameters(serverClientId: serverClientId)); await googleSignIn.attemptLightweightAuthentication( const AttemptLightweightAuthenticationParameters(), ); verifyNever(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); final hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); }); test('passes JSON server client ID if not overridden', () async { const serverClientId = 'aServerClient'; - when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => serverClientId); + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => serverClientId); // Passing no server client ID should cause it to be queried via // getGoogleServicesJsonServerClientId(). @@ -96,9 +88,7 @@ void main() { ); verify(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); final hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); }); @@ -106,16 +96,12 @@ void main() { test('passes nonce if provided', () async { const nonce = 'nonce'; - await googleSignIn.init( - const InitParameters(nonce: nonce, serverClientId: 'id'), - ); + await googleSignIn.init(const InitParameters(nonce: nonce, serverClientId: 'id')); await googleSignIn.attemptLightweightAuthentication( const AttemptLightweightAuthenticationParameters(), ); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); final hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.nonce, nonce); }); @@ -133,51 +119,43 @@ void main() { ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final AuthenticationResults? result = await googleSignIn - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + final AuthenticationResults? result = await googleSignIn.attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result?.user, _testUser); expect(result?.authenticationTokens, _testAuthnToken); }); test('returns null for missing auth', () async { - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.noCredential), - ); + when( + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.noCredential)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final AuthenticationResults? result = await googleSignIn - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + final AuthenticationResults? result = await googleSignIn.attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result, null); }); test('calls with and without filterToAuthorized', () async { - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.noCredential), - ); + when( + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.noCredential)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); await googleSignIn.attemptLightweightAuthentication( const AttemptLightweightAuthenticationParameters(), ); - final List verifications = verifyInOrder( - >[ - mockApi.getCredential(captureAny), - mockApi.getCredential(captureAny), - ], - ); - final firstParams = - verifications[0].captured[0] as GetCredentialRequestParams; - final secondParams = - verifications[1].captured[0] as GetCredentialRequestParams; + final List verifications = verifyInOrder(>[ + mockApi.getCredential(captureAny), + mockApi.getCredential(captureAny), + ]); + final firstParams = verifications[0].captured[0] as GetCredentialRequestParams; + final secondParams = verifications[1].captured[0] as GetCredentialRequestParams; expect(firstParams.useButtonFlow, isFalse); expect(firstParams.googleIdOptionParams.filterToAuthorized, isTrue); expect(firstParams.googleIdOptionParams.autoSelectEnabled, isTrue); @@ -186,58 +164,43 @@ void main() { expect(secondParams.googleIdOptionParams.autoSelectEnabled, isFalse); }); - test( - 'only calls with filterToAuthorized if hosted domain is set', - () async { - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.noCredential), - ); + test('only calls with filterToAuthorized if hosted domain is set', () async { + when( + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.noCredential)); - await googleSignIn.init( - const InitParameters( - serverClientId: 'id', - hostedDomain: 'example.com', - ), - ); - await googleSignIn.attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + await googleSignIn.init( + const InitParameters(serverClientId: 'id', hostedDomain: 'example.com'), + ); + await googleSignIn.attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); - expect(verification.callCount, 1); - final params = verification.captured[0] as GetCredentialRequestParams; - expect(params.useButtonFlow, isFalse); - expect(params.googleIdOptionParams.filterToAuthorized, isTrue); - expect(params.googleIdOptionParams.autoSelectEnabled, isTrue); - }, - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); + expect(verification.callCount, 1); + final params = verification.captured[0] as GetCredentialRequestParams; + expect(params.useButtonFlow, isFalse); + expect(params.googleIdOptionParams.filterToAuthorized, isTrue); + expect(params.googleIdOptionParams.autoSelectEnabled, isTrue); + }); }); group('authenticate', () { test('passes explicit server client ID', () async { const serverClientId = 'aServerClient'; - await googleSignIn.init( - const InitParameters(serverClientId: serverClientId), - ); + await googleSignIn.init(const InitParameters(serverClientId: serverClientId)); await googleSignIn.authenticate(const AuthenticateParameters()); verifyNever(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); final hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); }); test('passes JSON server client ID if not overridden', () async { const serverClientId = 'aServerClient'; - when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => serverClientId); + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => serverClientId); // Passing no server client ID should cause it to be queried via // getGoogleServicesJsonServerClientId(). @@ -245,9 +208,7 @@ void main() { await googleSignIn.authenticate(const AuthenticateParameters()); verify(mockApi.getGoogleServicesJsonServerClientId()); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); final hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.serverClientId, serverClientId); }); @@ -258,9 +219,7 @@ void main() { await googleSignIn.init(const InitParameters(hostedDomain: hostedDomain)); await googleSignIn.authenticate(const AuthenticateParameters()); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); final hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.hostedDomain, hostedDomain); }); @@ -271,9 +230,7 @@ void main() { await googleSignIn.init(const InitParameters(nonce: nonce)); await googleSignIn.authenticate(const AuthenticateParameters()); - final VerificationResult verification = verify( - mockApi.getCredential(captureAny), - ); + final VerificationResult verification = verify(mockApi.getCredential(captureAny)); final hostParams = verification.captured[0] as GetCredentialRequestParams; expect(hostParams.nonce, nonce); }); @@ -300,10 +257,9 @@ void main() { }); test('throws unknown for missing auth', () async { - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.noCredential), - ); + when( + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.noCredential)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( @@ -318,79 +274,62 @@ void main() { ); }); - test( - 'throws client configuration error for missing server client ID', - () async { - when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer( - (_) async => GetCredentialFailure( - type: GetCredentialFailureType.missingServerClientId, - ), - ); + test('throws client configuration error for missing server client ID', () async { + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialFailure(type: GetCredentialFailureType.missingServerClientId), + ); - await googleSignIn.init(const InitParameters()); - expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA( - isInstanceOf() - .having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.clientConfigurationError, - ) - .having( - (GoogleSignInException e) => e.description, - 'description', - contains('serverClientId must be provided'), - ), - ), - ); - }, - ); + await googleSignIn.init(const InitParameters()); + expect( + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.clientConfigurationError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('serverClientId must be provided'), + ), + ), + ); + }); - test( - 'throws provider configuration error for wrong credential type', - () async { - when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer( - (_) async => GetCredentialFailure( - type: GetCredentialFailureType.unexpectedCredentialType, - ), - ); + test('throws provider configuration error for wrong credential type', () async { + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => null); + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialFailure(type: GetCredentialFailureType.unexpectedCredentialType), + ); - await googleSignIn.init(const InitParameters()); - expect( - googleSignIn.authenticate(const AuthenticateParameters()), - throwsA( - isInstanceOf() - .having( - (GoogleSignInException e) => e.code, - 'code', - GoogleSignInExceptionCode.providerConfigurationError, - ) - .having( - (GoogleSignInException e) => e.description, - 'description', - contains('Unexpected credential type'), - ), - ), - ); - }, - ); + await googleSignIn.init(const InitParameters()); + expect( + googleSignIn.authenticate(const AuthenticateParameters()), + throwsA( + isInstanceOf() + .having( + (GoogleSignInException e) => e.code, + 'code', + GoogleSignInExceptionCode.providerConfigurationError, + ) + .having( + (GoogleSignInException e) => e.description, + 'description', + contains('Unexpected credential type'), + ), + ), + ); + }); test('throws provider configuration error if device does not ' 'support Credential Manager', () async { + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => null); when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.unsupported), - ); + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.unsupported)); await googleSignIn.init(const InitParameters()); expect( @@ -413,13 +352,10 @@ void main() { test('throws provider configuration error for SDK-reported ' 'provider configuration error', () async { - when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => null); + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => null); when(mockApi.getCredential(any)).thenAnswer( - (_) async => GetCredentialFailure( - type: GetCredentialFailureType.providerConfigurationIssue, - ), + (_) async => + GetCredentialFailure(type: GetCredentialFailureType.providerConfigurationIssue), ); await googleSignIn.init(const InitParameters()); @@ -436,13 +372,10 @@ void main() { }); test('throws interrupted from SDK', () async { + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => null); when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.interrupted), - ); + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.interrupted)); await googleSignIn.init(const InitParameters()); expect( @@ -458,13 +391,10 @@ void main() { }); test('throws canceled from SDK', () async { + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => null); when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.canceled), - ); + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.canceled)); await googleSignIn.init(const InitParameters()); expect( @@ -480,13 +410,10 @@ void main() { }); test('throws unknown from SDK', () async { + when(mockApi.getGoogleServicesJsonServerClientId()).thenAnswer((_) async => null); when( - mockApi.getGoogleServicesJsonServerClientId(), - ).thenAnswer((_) async => null); - when(mockApi.getCredential(any)).thenAnswer( - (_) async => - GetCredentialFailure(type: GetCredentialFailureType.unknown), - ); + mockApi.getCredential(any), + ).thenAnswer((_) async => GetCredentialFailure(type: GetCredentialFailureType.unknown)); await googleSignIn.init(const InitParameters()); expect( @@ -521,9 +448,7 @@ void main() { when( mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), - ).thenAnswer( - (_) async => PlatformAuthorizationResult(grantedScopes: []), - ); + ).thenAnswer((_) async => PlatformAuthorizationResult(grantedScopes: [])); await googleSignIn.init( const InitParameters(serverClientId: 'id', hostedDomain: hostedDomain), @@ -540,13 +465,9 @@ void main() { ); final VerificationResult verification = verify( - mockApi.authorize( - captureAny, - promptIfUnauthorized: promptIfUnauthorized, - ), + mockApi.authorize(captureAny, promptIfUnauthorized: promptIfUnauthorized), ); - final hostParams = - verification.captured[0] as PlatformAuthorizationRequest; + final hostParams = verification.captured[0] as PlatformAuthorizationRequest; expect(hostParams.scopes, scopes); expect(hostParams.accountEmail, userEmail); expect(hostParams.hostedDomain, hostedDomain); @@ -559,9 +480,7 @@ void main() { when( mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), - ).thenAnswer( - (_) async => PlatformAuthorizationResult(grantedScopes: []), - ); + ).thenAnswer((_) async => PlatformAuthorizationResult(grantedScopes: [])); await googleSignIn.init(const InitParameters(serverClientId: 'id')); await googleSignIn.clientAuthorizationTokensForScopes( @@ -575,43 +494,35 @@ void main() { ), ); - verify( - mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), - ); + verify(mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)); }); test('passes success data to caller', () async { const accessToken = 'token'; when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => PlatformAuthorizationResult( - grantedScopes: [], - accessToken: accessToken, - ), + (_) async => + PlatformAuthorizationResult(grantedScopes: [], accessToken: accessToken), ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); final ClientAuthorizationTokenData? result = await googleSignIn .clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ClientAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ); expect(result?.accessToken, accessToken); }); test('returns null when unauthorized', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.unauthorized), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.unauthorized)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ClientAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), null, ); @@ -619,16 +530,13 @@ void main() { test('thows canceled if pending intent fails', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.pendingIntentException), + (_) async => AuthorizeFailure(type: AuthorizeFailureType.pendingIntentException), ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ClientAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf().having( @@ -641,17 +549,14 @@ void main() { }); test('throws unknown if authorization fails', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ClientAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf().having( @@ -664,16 +569,14 @@ void main() { }); test('throws unknown for API exception', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.apiException), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.apiException)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ClientAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf() @@ -692,16 +595,14 @@ void main() { }); test('throws UI unavailable if there is no activity available', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ClientAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf().having( @@ -734,15 +635,10 @@ void main() { when( mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), - ).thenAnswer( - (_) async => PlatformAuthorizationResult(grantedScopes: []), - ); + ).thenAnswer((_) async => PlatformAuthorizationResult(grantedScopes: [])); await googleSignIn.init( - const InitParameters( - serverClientId: serverClientId, - hostedDomain: hostedDomain, - ), + const InitParameters(serverClientId: serverClientId, hostedDomain: hostedDomain), ); await googleSignIn.serverAuthorizationTokensForScopes( const ServerAuthorizationTokensForScopesParameters( @@ -756,13 +652,9 @@ void main() { ); final VerificationResult verification = verify( - mockApi.authorize( - captureAny, - promptIfUnauthorized: promptIfUnauthorized, - ), + mockApi.authorize(captureAny, promptIfUnauthorized: promptIfUnauthorized), ); - final hostParams = - verification.captured[0] as PlatformAuthorizationRequest; + final hostParams = verification.captured[0] as PlatformAuthorizationRequest; expect(hostParams.scopes, scopes); expect(hostParams.accountEmail, userEmail); expect(hostParams.hostedDomain, hostedDomain); @@ -777,9 +669,7 @@ void main() { when( mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), - ).thenAnswer( - (_) async => PlatformAuthorizationResult(grantedScopes: []), - ); + ).thenAnswer((_) async => PlatformAuthorizationResult(grantedScopes: [])); await googleSignIn.init(const InitParameters(serverClientId: 'id')); await googleSignIn.serverAuthorizationTokensForScopes( @@ -793,54 +683,47 @@ void main() { ), ); - verify( - mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized), - ); + verify(mockApi.authorize(any, promptIfUnauthorized: promptIfUnauthorized)); }, ); - test( - 'serverAuthorizationTokensForScopes passes success data to caller', - () async { - const scopes = ['a', 'b']; - const authCode = 'code'; + test('serverAuthorizationTokensForScopes passes success data to caller', () async { + const scopes = ['a', 'b']; + const authCode = 'code'; - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => PlatformAuthorizationResult( - grantedScopes: [], - accessToken: 'token', - serverAuthCode: authCode, - ), - ); + when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( + (_) async => PlatformAuthorizationResult( + grantedScopes: [], + accessToken: 'token', + serverAuthCode: authCode, + ), + ); - await googleSignIn.init(const InitParameters(serverClientId: 'id')); - final ServerAuthorizationTokenData? result = await googleSignIn - .serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false, - ), + await googleSignIn.init(const InitParameters(serverClientId: 'id')); + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, ), - ); + ), + ); - expect(result?.serverAuthCode, authCode); - }, - ); + expect(result?.serverAuthCode, authCode); + }); test('returns null when unauthorized', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.unauthorized), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.unauthorized)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( await googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ServerAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), null, ); @@ -848,16 +731,13 @@ void main() { test('thows canceled if pending intent fails', () async { when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.pendingIntentException), + (_) async => AuthorizeFailure(type: AuthorizeFailureType.pendingIntentException), ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ServerAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf().having( @@ -870,17 +750,14 @@ void main() { }); test('throws unknown if authorization fails', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => - AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.authorizeFailure)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ServerAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf().having( @@ -893,16 +770,14 @@ void main() { }); test('throws unknown for API exception', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.apiException), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.apiException)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ServerAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf() @@ -921,16 +796,14 @@ void main() { }); test('throws UI unavailable if there is no activity available', () async { - when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity), - ); + when( + mockApi.authorize(any, promptIfUnauthorized: false), + ).thenAnswer((_) async => AuthorizeFailure(type: AuthorizeFailureType.noActivity)); await googleSignIn.init(const InitParameters(serverClientId: 'id')); expect( googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ServerAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), throwsA( isInstanceOf().having( @@ -955,10 +828,8 @@ void main() { const userEmail = 'user@example.com'; const aScope = 'grantedScope'; when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => PlatformAuthorizationResult( - grantedScopes: [aScope], - accessToken: 'token', - ), + (_) async => + PlatformAuthorizationResult(grantedScopes: [aScope], accessToken: 'token'), ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); await googleSignIn.clientAuthorizationTokensForScopes( @@ -974,53 +845,42 @@ void main() { await googleSignIn.disconnect(const DisconnectParams()); - final VerificationResult verification = verify( - mockApi.revokeAccess(captureAny), - ); - final hostParams = - verification.captured[0] as PlatformRevokeAccessRequest; + final VerificationResult verification = verify(mockApi.revokeAccess(captureAny)); + final hostParams = verification.captured[0] as PlatformRevokeAccessRequest; expect(hostParams.accountEmail, userEmail); expect(hostParams.scopes.first, aScope); }); - test( - 'calls through with non-authorized accounts, using "openid"', - () async { - // Populate the cache of users. - when(mockApi.getCredential(any)).thenAnswer( - (_) async => GetCredentialSuccess( - credential: PlatformGoogleIdTokenCredential( - displayName: _testUser.displayName, - profilePictureUri: _testUser.photoUrl, - id: _testUser.email, - idToken: _testAuthnToken.idToken!, - ), + test('calls through with non-authorized accounts, using "openid"', () async { + // Populate the cache of users. + when(mockApi.getCredential(any)).thenAnswer( + (_) async => GetCredentialSuccess( + credential: PlatformGoogleIdTokenCredential( + displayName: _testUser.displayName, + profilePictureUri: _testUser.photoUrl, + id: _testUser.email, + idToken: _testAuthnToken.idToken!, ), - ); - await googleSignIn.init(const InitParameters(serverClientId: 'id')); - await googleSignIn.authenticate(const AuthenticateParameters()); + ), + ); + await googleSignIn.init(const InitParameters(serverClientId: 'id')); + await googleSignIn.authenticate(const AuthenticateParameters()); - await googleSignIn.disconnect(const DisconnectParams()); + await googleSignIn.disconnect(const DisconnectParams()); - final VerificationResult verification = verify( - mockApi.revokeAccess(captureAny), - ); - final hostParams = - verification.captured[0] as PlatformRevokeAccessRequest; - expect(hostParams.accountEmail, _testUser.email); - expect(hostParams.scopes.first, 'openid'); - }, - ); + final VerificationResult verification = verify(mockApi.revokeAccess(captureAny)); + final hostParams = verification.captured[0] as PlatformRevokeAccessRequest; + expect(hostParams.accountEmail, _testUser.email); + expect(hostParams.scopes.first, 'openid'); + }); test('does not re-revoke for repeated disconnect', () async { // Populate the cache of users. const userEmail = 'user@example.com'; const aScope = 'grantedScope'; when(mockApi.authorize(any, promptIfUnauthorized: false)).thenAnswer( - (_) async => PlatformAuthorizationResult( - grantedScopes: [aScope], - accessToken: 'token', - ), + (_) async => + PlatformAuthorizationResult(grantedScopes: [aScope], accessToken: 'token'), ); await googleSignIn.init(const InitParameters(serverClientId: 'id')); await googleSignIn.clientAuthorizationTokensForScopes( diff --git a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart index 45eeb22c02aa..96ef5f05fc48 100644 --- a/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_android/test/google_sign_in_android_test.mocks.dart @@ -28,109 +28,73 @@ import 'package:mockito/src/dummies.dart' as _i3; /// See the documentation for Mockito's code generation for more information. class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future getGoogleServicesJsonServerClientId() => - (super.noSuchMethod( - Invocation.method(#getGoogleServicesJsonServerClientId, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future getGoogleServicesJsonServerClientId() => (super.noSuchMethod( + Invocation.method(#getGoogleServicesJsonServerClientId, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future<_i2.GetCredentialResult> getCredential( _i2.GetCredentialRequestParams? params, - ) => - (super.noSuchMethod( - Invocation.method(#getCredential, [params]), - returnValue: _i4.Future<_i2.GetCredentialResult>.value( - _i3.dummyValue<_i2.GetCredentialResult>( - this, - Invocation.method(#getCredential, [params]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.GetCredentialResult>.value( - _i3.dummyValue<_i2.GetCredentialResult>( - this, - Invocation.method(#getCredential, [params]), - ), - ), - ) - as _i4.Future<_i2.GetCredentialResult>); + ) => (super.noSuchMethod( + Invocation.method(#getCredential, [params]), + returnValue: _i4.Future<_i2.GetCredentialResult>.value( + _i3.dummyValue<_i2.GetCredentialResult>(this, Invocation.method(#getCredential, [params])), + ), + returnValueForMissingStub: _i4.Future<_i2.GetCredentialResult>.value( + _i3.dummyValue<_i2.GetCredentialResult>(this, Invocation.method(#getCredential, [params])), + ), + ) as _i4.Future<_i2.GetCredentialResult>); @override - _i4.Future clearCredentialState() => - (super.noSuchMethod( - Invocation.method(#clearCredentialState, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future clearCredentialState() => (super.noSuchMethod( + Invocation.method(#clearCredentialState, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future clearAuthorizationToken(String? token) => - (super.noSuchMethod( - Invocation.method(#clearAuthorizationToken, [token]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future clearAuthorizationToken(String? token) => (super.noSuchMethod( + Invocation.method(#clearAuthorizationToken, [token]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override _i4.Future<_i2.AuthorizeResult> authorize( _i2.PlatformAuthorizationRequest? params, { required bool? promptIfUnauthorized, - }) => - (super.noSuchMethod( - Invocation.method( - #authorize, - [params], - {#promptIfUnauthorized: promptIfUnauthorized}, - ), - returnValue: _i4.Future<_i2.AuthorizeResult>.value( - _i3.dummyValue<_i2.AuthorizeResult>( - this, - Invocation.method( - #authorize, - [params], - {#promptIfUnauthorized: promptIfUnauthorized}, - ), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.AuthorizeResult>.value( - _i3.dummyValue<_i2.AuthorizeResult>( - this, - Invocation.method( - #authorize, - [params], - {#promptIfUnauthorized: promptIfUnauthorized}, - ), - ), - ), - ) - as _i4.Future<_i2.AuthorizeResult>); + }) => (super.noSuchMethod( + Invocation.method(#authorize, [params], {#promptIfUnauthorized: promptIfUnauthorized}), + returnValue: _i4.Future<_i2.AuthorizeResult>.value( + _i3.dummyValue<_i2.AuthorizeResult>( + this, + Invocation.method(#authorize, [params], {#promptIfUnauthorized: promptIfUnauthorized}), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.AuthorizeResult>.value( + _i3.dummyValue<_i2.AuthorizeResult>( + this, + Invocation.method(#authorize, [params], {#promptIfUnauthorized: promptIfUnauthorized}), + ), + ), + ) as _i4.Future<_i2.AuthorizeResult>); @override - _i4.Future revokeAccess(_i2.PlatformRevokeAccessRequest? params) => - (super.noSuchMethod( - Invocation.method(#revokeAccess, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future revokeAccess(_i2.PlatformRevokeAccessRequest? params) => (super.noSuchMethod( + Invocation.method(#revokeAccess, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart b/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart index 5a58f59d1521..f9573b08aecd 100644 --- a/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart +++ b/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart @@ -11,10 +11,7 @@ import 'package:flutter/material.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:http/http.dart' as http; -const List _scopes = [ - 'email', - 'https://www.googleapis.com/auth/contacts.readonly', -]; +const List _scopes = ['email', 'https://www.googleapis.com/auth/contacts.readonly']; void main() { runApp(const MaterialApp(title: 'Google Sign In', home: SignInDemo())); @@ -42,11 +39,10 @@ class SignInDemoState extends State { } Future _ensureInitialized() { - return _initialization ??= - GoogleSignInPlatform.instance.init(const InitParameters()) - ..catchError((dynamic _) { - _initialization = null; - }); + return _initialization ??= GoogleSignInPlatform.instance.init(const InitParameters()) + ..catchError((dynamic _) { + _initialization = null; + }); } void _setUser(GoogleSignInUserData? user) { @@ -63,9 +59,7 @@ class SignInDemoState extends State { await _ensureInitialized(); try { final AuthenticationResults? result = await GoogleSignInPlatform.instance - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + .attemptLightweightAuthentication(const AttemptLightweightAuthenticationParameters()); _setUser(result?.user); } on GoogleSignInException catch (e) { setState(() { @@ -78,8 +72,7 @@ class SignInDemoState extends State { Future _handleAuthorizeScopes(GoogleSignInUserData user) async { try { - final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform - .instance + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform.instance .clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( request: AuthorizationRequestDetails( @@ -105,11 +98,8 @@ class SignInDemoState extends State { } } - Future?> _getAuthHeaders( - GoogleSignInUserData user, - ) async { - final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform - .instance + Future?> _getAuthHeaders(GoogleSignInUserData user) async { + final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform.instance .clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters( request: AuthorizationRequestDetails( @@ -160,8 +150,7 @@ class SignInDemoState extends State { return; } final data = json.decode(response.body) as Map; - final int contactCount = - (data['connections'] as List?)?.length ?? 0; + final int contactCount = (data['connections'] as List?)?.length ?? 0; setState(() { _contactText = '$contactCount contacts found'; }); @@ -170,8 +159,9 @@ class SignInDemoState extends State { Future _handleSignIn() async { try { await _ensureInitialized(); - final AuthenticationResults result = await GoogleSignInPlatform.instance - .authenticate(const AuthenticateParameters()); + final AuthenticationResults result = await GoogleSignInPlatform.instance.authenticate( + const AuthenticateParameters(), + ); _setUser(result.user); } on GoogleSignInException catch (e) { setState(() { @@ -193,22 +183,13 @@ class SignInDemoState extends State { mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ if (user != null) ...[ - ListTile( - title: Text(user.displayName ?? ''), - subtitle: Text(user.email), - ), + ListTile(title: Text(user.displayName ?? ''), subtitle: Text(user.email)), const Text('Signed in successfully.'), - ElevatedButton( - onPressed: _handleSignOut, - child: const Text('SIGN OUT'), - ), + ElevatedButton(onPressed: _handleSignOut, child: const Text('SIGN OUT')), if (_isAuthorized) ...[ // The user has Authorized all required scopes. if (_contactText.isNotEmpty) Text(_contactText), - ElevatedButton( - child: const Text('REFRESH'), - onPressed: () => _handleGetContact(user), - ), + ElevatedButton(child: const Text('REFRESH'), onPressed: () => _handleGetContact(user)), ] else ...[ // The user has NOT Authorized all required scopes. const Text('Authorization needed to read your contacts.'), @@ -219,10 +200,7 @@ class SignInDemoState extends State { ], ] else ...[ const Text('You are not currently signed in.'), - ElevatedButton( - onPressed: _handleSignIn, - child: const Text('SIGN IN'), - ), + ElevatedButton(onPressed: _handleSignIn, child: const Text('SIGN IN')), ], if (_errorMessage.isNotEmpty) Text(_errorMessage), ], @@ -233,10 +211,7 @@ class SignInDemoState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Google Sign In')), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - ), + body: ConstrainedBox(constraints: const BoxConstraints.expand(), child: _buildBody()), ); } } diff --git a/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart b/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart index 2f11c953e5b6..c1fe921a1c5b 100644 --- a/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart +++ b/packages/google_sign_in/google_sign_in_ios/lib/google_sign_in_ios.dart @@ -12,8 +12,7 @@ import 'src/messages.g.dart'; /// iOS implementation of [GoogleSignInPlatform]. class GoogleSignInIOS extends GoogleSignInPlatform { /// Creates a new plugin implementation instance. - GoogleSignInIOS({@visibleForTesting GoogleSignInApi? api}) - : _api = api ?? GoogleSignInApi(); + GoogleSignInIOS({@visibleForTesting GoogleSignInApi? api}) : _api = api ?? GoogleSignInApi(); final GoogleSignInApi _api; @@ -85,9 +84,7 @@ class GoogleSignInIOS extends GoogleSignInPlatform { bool supportsAuthenticate() => true; @override - Future authenticate( - AuthenticateParameters params, - ) async { + Future authenticate(AuthenticateParameters params) async { final SignInResult result = await _signIn(params.scopeHint, _nonce); // This should never happen; the corresponding native error code is @@ -135,35 +132,28 @@ class GoogleSignInIOS extends GoogleSignInPlatform { Future clientAuthorizationTokensForScopes( ClientAuthorizationTokensForScopesParameters params, ) async { - final String? accessToken = (await _getAuthorizationTokens( - params.request, - )).accessToken; - return accessToken == null - ? null - : ClientAuthorizationTokenData(accessToken: accessToken); + final String? accessToken = (await _getAuthorizationTokens(params.request)).accessToken; + return accessToken == null ? null : ClientAuthorizationTokenData(accessToken: accessToken); } @override Future serverAuthorizationTokensForScopes( ServerAuthorizationTokensForScopesParameters params, ) async { - final String? serverAuthCode = (await _getAuthorizationTokens( - params.request, - )).serverAuthCode; + final String? serverAuthCode = (await _getAuthorizationTokens(params.request)).serverAuthCode; return serverAuthCode == null ? null : ServerAuthorizationTokenData(serverAuthCode: serverAuthCode); } @override - Future clearAuthorizationToken( - ClearAuthorizationTokenParams params, - ) async { + Future clearAuthorizationToken(ClearAuthorizationTokenParams params) async { // No-op; the iOS SDK handles token invalidation internally. } - Future<({String? accessToken, String? serverAuthCode})> - _getAuthorizationTokens(AuthorizationRequestDetails request) async { + Future<({String? accessToken, String? serverAuthCode})> _getAuthorizationTokens( + AuthorizationRequestDetails request, + ) async { String? userId = request.userId; // The Google Sign In SDK requires authentication before authorization, so @@ -221,8 +211,7 @@ class GoogleSignInIOS extends GoogleSignInPlatform { if (success != null) { if (request.scopes.any( (String scope) => - !openIdConnectScopes.contains(scope) && - !success.grantedScopes.contains(scope), + !openIdConnectScopes.contains(scope) && !success.grantedScopes.contains(scope), )) { return (accessToken: null, serverAuthCode: null); } @@ -232,8 +221,9 @@ class GoogleSignInIOS extends GoogleSignInPlatform { return _processAuthorizationResult(result); } - Future<({String? accessToken, String? serverAuthCode})> - _processAuthorizationResult(SignInResult result) async { + Future<({String? accessToken, String? serverAuthCode})> _processAuthorizationResult( + SignInResult result, + ) async { final SignInFailure? failure = result.error; if (failure != null) { throw GoogleSignInException( @@ -268,9 +258,7 @@ class GoogleSignInIOS extends GoogleSignInPlatform { _cachedServerAuthCodeUserId = success?.user.userId; } - AuthenticationResults _authenticationResultsFromSignInSuccess( - SignInSuccess result, - ) { + AuthenticationResults _authenticationResultsFromSignInSuccess(SignInSuccess result) { final UserData userData = result.user; final user = GoogleSignInUserData( email: userData.email, @@ -284,8 +272,9 @@ class GoogleSignInIOS extends GoogleSignInPlatform { ); } - ({String? accessToken, String? serverAuthCode}) - _authorizationTokenDataFromSignInSuccess(SignInSuccess? result) { + ({String? accessToken, String? serverAuthCode}) _authorizationTokenDataFromSignInSuccess( + SignInSuccess? result, + ) { // Check for a relevant cached auth code to add if needed. final String? cachedAuthCode = result != null && result.user.userId == _cachedServerAuthCodeUserId @@ -298,18 +287,13 @@ class GoogleSignInIOS extends GoogleSignInPlatform { ); } - GoogleSignInExceptionCode _exceptionCodeForErrorPlatformErrorCode( - GoogleSignInErrorCode code, - ) { + GoogleSignInExceptionCode _exceptionCodeForErrorPlatformErrorCode(GoogleSignInErrorCode code) { return switch (code) { GoogleSignInErrorCode.unknown => GoogleSignInExceptionCode.unknownError, - GoogleSignInErrorCode.keychainError => - GoogleSignInExceptionCode.providerConfigurationError, + GoogleSignInErrorCode.keychainError => GoogleSignInExceptionCode.providerConfigurationError, GoogleSignInErrorCode.canceled => GoogleSignInExceptionCode.canceled, - GoogleSignInErrorCode.eemError => - GoogleSignInExceptionCode.providerConfigurationError, - GoogleSignInErrorCode.userMismatch => - GoogleSignInExceptionCode.userMismatch, + GoogleSignInErrorCode.eemError => GoogleSignInExceptionCode.providerConfigurationError, + GoogleSignInErrorCode.userMismatch => GoogleSignInExceptionCode.userMismatch, // These should never be mapped to a GoogleSignInException; the caller // should handle them. GoogleSignInErrorCode.noAuthInKeychain => throw StateError( diff --git a/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart b/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart index f5ca43100818..9f6091377e7e 100644 --- a/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart +++ b/packages/google_sign_in/google_sign_in_ios/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -68,11 +66,7 @@ enum GoogleSignInErrorCode { } class PlatformConfigurationParams { - PlatformConfigurationParams({ - this.clientId, - this.serverClientId, - this.hostedDomain, - }); + PlatformConfigurationParams({this.clientId, this.serverClientId, this.hostedDomain}); String? clientId; @@ -100,8 +94,7 @@ class PlatformConfigurationParams { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformConfigurationParams || - other.runtimeType != runtimeType) { + if (other is! PlatformConfigurationParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -197,10 +190,7 @@ class SignInResult { static SignInResult decode(Object result) { result as List; - return SignInResult( - success: result[0] as SignInSuccess?, - error: result[1] as SignInFailure?, - ); + return SignInResult(success: result[0] as SignInSuccess?, error: result[1] as SignInFailure?); } @override @@ -380,13 +370,11 @@ class GoogleSignInApi { /// Constructor for [GoogleSignInApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - GoogleSignInApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + GoogleSignInApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -397,17 +385,13 @@ class GoogleSignInApi { Future configure(PlatformConfigurationParams params) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.configure$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [params], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([params]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -426,15 +410,13 @@ class GoogleSignInApi { Future restorePreviousSignIn() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.restorePreviousSignIn$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -457,17 +439,16 @@ class GoogleSignInApi { Future signIn(List scopeHint, String? nonce) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signIn$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [scopeHint, nonce], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + scopeHint, + nonce, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -490,17 +471,13 @@ class GoogleSignInApi { Future getRefreshedAuthorizationTokens(String userId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.getRefreshedAuthorizationTokens$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [userId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([userId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -523,17 +500,13 @@ class GoogleSignInApi { Future addScopes(List scopes, String userId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.addScopes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [scopes, userId], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([scopes, userId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -556,15 +529,13 @@ class GoogleSignInApi { Future signOut() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.signOut$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -582,15 +553,13 @@ class GoogleSignInApi { Future disconnect() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.google_sign_in_ios.GoogleSignInApi.disconnect$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart b/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart index 4fdf92f61c50..7f636f6d7b55 100644 --- a/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart +++ b/packages/google_sign_in/google_sign_in_ios/pigeons/messages.dart @@ -9,8 +9,7 @@ import 'package:pigeon/pigeon.dart'; dartOut: 'lib/src/messages.g.dart', objcHeaderOut: 'darwin/google_sign_in_ios/Sources/google_sign_in_ios/include/google_sign_in_ios/messages.g.h', - objcSourceOut: - 'darwin/google_sign_in_ios/Sources/google_sign_in_ios/messages.g.m', + objcSourceOut: 'darwin/google_sign_in_ios/Sources/google_sign_in_ios/messages.g.m', objcOptions: ObjcOptions( prefix: 'FSI', headerIncludePath: './include/google_sign_in_ios/messages.g.h', @@ -19,11 +18,7 @@ import 'package:pigeon/pigeon.dart'; ), ) class PlatformConfigurationParams { - PlatformConfigurationParams({ - this.clientId, - this.serverClientId, - this.hostedDomain, - }); + PlatformConfigurationParams({this.clientId, this.serverClientId, this.hostedDomain}); final String? clientId; final String? serverClientId; diff --git a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart index c39b626591c3..459d117d045e 100644 --- a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart +++ b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.dart @@ -59,11 +59,8 @@ void main() { ), ); - final VerificationResult verification = verify( - mockApi.configure(captureAny), - ); - final hostParams = - verification.captured[0] as PlatformConfigurationParams; + final VerificationResult verification = verify(mockApi.configure(captureAny)); + final hostParams = verification.captured[0] as PlatformConfigurationParams; expect(hostParams.clientId, clientId); expect(hostParams.serverClientId, serverClientId); expect(hostParams.hostedDomain, hostedDomain); @@ -89,10 +86,9 @@ void main() { ), ); - final AuthenticationResults? result = await googleSignIn - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + final AuthenticationResults? result = await googleSignIn.attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result?.user, _testUser); expect(result?.authenticationTokens.idToken, idToken); @@ -100,24 +96,20 @@ void main() { test('returns null for missing auth', () async { when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), ); - final AuthenticationResults? result = await googleSignIn - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + final AuthenticationResults? result = await googleSignIn.attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(result, null); }); test('throws for other errors', () async { when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.keychainError), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.keychainError)), ); expect( @@ -188,9 +180,8 @@ void main() { test('throws unknown for missing auth', () async { when(mockApi.signIn(any, null)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), ); expect( @@ -213,9 +204,7 @@ void main() { test('throws provider configuration error for keychain error', () async { when(mockApi.signIn(any, null)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.keychainError), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.keychainError)), ); expect( @@ -232,9 +221,7 @@ void main() { test('throws provider configuration error for EEM error', () async { when(mockApi.signIn(any, null)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.eemError), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.eemError)), ); expect( @@ -251,9 +238,7 @@ void main() { test('throws canceled from SDK', () async { when(mockApi.signIn(any, null)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.canceled), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.canceled)), ); expect( @@ -270,9 +255,7 @@ void main() { test('throws user mismatch from SDK', () async { when(mockApi.signIn(any, null)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.userMismatch), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.userMismatch)), ); expect( @@ -289,9 +272,7 @@ void main() { test('throws unknown from SDK', () async { when(mockApi.signIn(any, null)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.unknown), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.unknown)), ); expect( @@ -317,49 +298,9 @@ void main() { promptIfUnauthorized: false, ); - test( - 'passes expected values to addScopes if interaction is allowed', - () async { - const scopes = ['a', 'b']; - when(mockApi.addScopes(any, _testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: scopes, - ), - ), - ); - - await googleSignIn.clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ), - ), - ); - - final VerificationResult verification = verify( - mockApi.addScopes(captureAny, _testUser.id), - ); - final passedScopes = verification.captured[0] as List; - expect(passedScopes, scopes); - }, - ); - - test('passes expected values to getRefreshedAuthorizationTokens if ' - 'interaction is not allowed', () async { + test('passes expected values to addScopes if interaction is allowed', () async { const scopes = ['a', 'b']; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + when(mockApi.addScopes(any, _testUser.id)).thenAnswer( (_) async => SignInResult( success: SignInSuccess( user: UserData( @@ -381,19 +322,21 @@ void main() { scopes: scopes, userId: _testUser.id, email: _testUser.email, - promptIfUnauthorized: false, + promptIfUnauthorized: true, ), ), ); - verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + final VerificationResult verification = verify(mockApi.addScopes(captureAny, _testUser.id)); + final passedScopes = verification.captured[0] as List; + expect(passedScopes, scopes); }); - test( - 'attempts to restore previous sign in if no user is provided', - () async { - const scopes = ['a', 'b']; - final signInResult = SignInResult( + test('passes expected values to getRefreshedAuthorizationTokens if ' + 'interaction is not allowed', () async { + const scopes = ['a', 'b']; + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( success: SignInSuccess( user: UserData( displayName: _testUser.displayName, @@ -403,72 +346,95 @@ void main() { idToken: '', ), accessToken: '', - grantedScopes: [], + grantedScopes: scopes, ), - ); - when( - mockApi.restorePreviousSignIn(), - ).thenAnswer((_) async => signInResult); - when( - mockApi.getRefreshedAuthorizationTokens(_testUser.id), - ).thenAnswer((_) async => signInResult); + ), + ); - await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false, - ), + await googleSignIn.clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, ), - ); - - // With no user ID provided to clientAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that succeeds, get the authorization tokens for that user. - verify(mockApi.restorePreviousSignIn()); - verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); - }, - ); + ), + ); + + verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + }); + + test('attempts to restore previous sign in if no user is provided', () async { + const scopes = ['a', 'b']; + final signInResult = SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: [], + ), + ); + when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => signInResult); + when( + mockApi.getRefreshedAuthorizationTokens(_testUser.id), + ).thenAnswer((_) async => signInResult); - test( - 'returns null if unauthenticated and interaction is not allowed', - () async { - when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + await googleSignIn.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, ), - ); - - final ClientAuthorizationTokenData? result = await googleSignIn - .clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: ['a', 'b'], - userId: null, - email: null, - promptIfUnauthorized: false, - ), + ), + ); + + // With no user ID provided to clientAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that succeeds, get the authorization tokens for that user. + verify(mockApi.restorePreviousSignIn()); + verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + }); + + test('returns null if unauthenticated and interaction is not allowed', () async { + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), + ); + + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: ['a', 'b'], + userId: null, + email: null, + promptIfUnauthorized: false, ), - ); - - // With no user ID provided to clientAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that fails, return null since without prompting, there is no way - // to authenticate. - verify(mockApi.restorePreviousSignIn()); - expect(result, null); - }, - ); + ), + ); + + // With no user ID provided to clientAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that fails, return null since without prompting, there is no way + // to authenticate. + verify(mockApi.restorePreviousSignIn()); + expect(result, null); + }); test('attempts to authenticate if no user is provided or already signed in ' 'and interaction is allowed', () async { const scopes = ['a', 'b']; when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), ); when(mockApi.signIn(scopes, null)).thenAnswer( (_) async => SignInResult( @@ -504,42 +470,39 @@ void main() { verify(mockApi.signIn(scopes, null)); }); - test( - 'passes success data to caller when refreshing existing auth', - () async { - const scopes = ['a', 'b']; - const accessToken = 'token'; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: accessToken, - grantedScopes: scopes, + test('passes success data to caller when refreshing existing auth', () async { + const scopes = ['a', 'b']; + const accessToken = 'token'; + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', ), + accessToken: accessToken, + grantedScopes: scopes, ), - ); - - final ClientAuthorizationTokenData? result = await googleSignIn - .clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ), + ), + ); + + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, ), - ); + ), + ); - expect(result?.accessToken, accessToken); - }, - ); + expect(result?.accessToken, accessToken); + }); test('passes success data to caller when calling addScopes', () async { const scopes = ['a', 'b']; @@ -580,11 +543,8 @@ void main() { const scopes = ['a', 'b']; const accessToken = 'token'; when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure( - type: GoogleSignInErrorCode.scopesAlreadyGranted, - ), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.scopesAlreadyGranted)), ); when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( (_) async => SignInResult( @@ -620,56 +580,50 @@ void main() { expect(result?.accessToken, accessToken); }); - test( - 'returns null if re-using existing auth and scopes are missing', - () async { - const requestedScopes = ['a', 'b']; - const grantedScopes = ['a']; - const accessToken = 'token'; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: accessToken, - grantedScopes: grantedScopes, + test('returns null if re-using existing auth and scopes are missing', () async { + const requestedScopes = ['a', 'b']; + const grantedScopes = ['a']; + const accessToken = 'token'; + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', ), + accessToken: accessToken, + grantedScopes: grantedScopes, ), - ); - - final ClientAuthorizationTokenData? result = await googleSignIn - .clientAuthorizationTokensForScopes( - ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: requestedScopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ), + ), + ); + + final ClientAuthorizationTokenData? result = await googleSignIn + .clientAuthorizationTokensForScopes( + ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: requestedScopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, ), - ); + ), + ); - expect(result, null); - }, - ); + expect(result, null); + }); test('returns null when unauthorized', () async { when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), ); expect( await googleSignIn.clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ClientAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), null, ); @@ -677,9 +631,7 @@ void main() { test('thows canceled from SDK', () async { when(mockApi.addScopes(any, any)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.canceled), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.canceled)), ); expect( @@ -705,9 +657,7 @@ void main() { test('throws unknown from SDK', () async { when(mockApi.addScopes(any, any)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.unknown), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.unknown)), ); expect( @@ -733,9 +683,7 @@ void main() { test('throws user mismatch from SDK', () async { when(mockApi.addScopes(any, any)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.userMismatch), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.userMismatch)), ); expect( @@ -770,49 +718,9 @@ void main() { promptIfUnauthorized: false, ); - test( - 'passes expected values to addScopes if interaction is allowed', - () async { - const scopes = ['a', 'b']; - when(mockApi.addScopes(any, _testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ), - accessToken: '', - grantedScopes: scopes, - ), - ), - ); - - await googleSignIn.serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ), - ), - ); - - final VerificationResult verification = verify( - mockApi.addScopes(captureAny, _testUser.id), - ); - final passedScopes = verification.captured[0] as List; - expect(passedScopes, scopes); - }, - ); - - test('passes expected values to getRefreshedAuthorizationTokens if ' - 'interaction is not allowed', () async { + test('passes expected values to addScopes if interaction is allowed', () async { const scopes = ['a', 'b']; - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + when(mockApi.addScopes(any, _testUser.id)).thenAnswer( (_) async => SignInResult( success: SignInSuccess( user: UserData( @@ -834,19 +742,21 @@ void main() { scopes: scopes, userId: _testUser.id, email: _testUser.email, - promptIfUnauthorized: false, + promptIfUnauthorized: true, ), ), ); - verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + final VerificationResult verification = verify(mockApi.addScopes(captureAny, _testUser.id)); + final passedScopes = verification.captured[0] as List; + expect(passedScopes, scopes); }); - test( - 'attempts to restore previous sign in if no user is provided', - () async { - const scopes = ['a', 'b']; - final signInResult = SignInResult( + test('passes expected values to getRefreshedAuthorizationTokens if ' + 'interaction is not allowed', () async { + const scopes = ['a', 'b']; + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( success: SignInSuccess( user: UserData( displayName: _testUser.displayName, @@ -856,72 +766,95 @@ void main() { idToken: '', ), accessToken: '', - grantedScopes: [], + grantedScopes: scopes, ), - ); - when( - mockApi.restorePreviousSignIn(), - ).thenAnswer((_) async => signInResult); - when( - mockApi.getRefreshedAuthorizationTokens(_testUser.id), - ).thenAnswer((_) async => signInResult); + ), + ); - await googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false, - ), + await googleSignIn.serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, ), - ); - - // With no user ID provided to serverAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that succeeds, get the authorization tokens for that user. - verify(mockApi.restorePreviousSignIn()); - verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); - }, - ); + ), + ); + + verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + }); + + test('attempts to restore previous sign in if no user is provided', () async { + const scopes = ['a', 'b']; + final signInResult = SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ), + accessToken: '', + grantedScopes: [], + ), + ); + when(mockApi.restorePreviousSignIn()).thenAnswer((_) async => signInResult); + when( + mockApi.getRefreshedAuthorizationTokens(_testUser.id), + ).thenAnswer((_) async => signInResult); - test( - 'returns null if unauthenticated and interaction is not allowed', - () async { - when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), + await googleSignIn.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, ), - ); - - final ServerAuthorizationTokenData? result = await googleSignIn - .serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: ['a', 'b'], - userId: null, - email: null, - promptIfUnauthorized: false, - ), + ), + ); + + // With no user ID provided to serverAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that succeeds, get the authorization tokens for that user. + verify(mockApi.restorePreviousSignIn()); + verify(mockApi.getRefreshedAuthorizationTokens(_testUser.id)); + }); + + test('returns null if unauthenticated and interaction is not allowed', () async { + when(mockApi.restorePreviousSignIn()).thenAnswer( + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), + ); + + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: ['a', 'b'], + userId: null, + email: null, + promptIfUnauthorized: false, ), - ); - - // With no user ID provided to serverAuthorizationTokensForScopes, the - // implementation should attempt to restore an existing sign-in, and then - // when that fails, return null since without prompting, there is no way - // to authenticate. - verify(mockApi.restorePreviousSignIn()); - expect(result, null); - }, - ); + ), + ); + + // With no user ID provided to serverAuthorizationTokensForScopes, the + // implementation should attempt to restore an existing sign-in, and then + // when that fails, return null since without prompting, there is no way + // to authenticate. + verify(mockApi.restorePreviousSignIn()); + expect(result, null); + }); test('attempts to authenticate if no user is provided or already signed in ' 'and interaction is allowed', () async { const scopes = ['a', 'b']; when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), ); when(mockApi.signIn(scopes, null)).thenAnswer( (_) async => SignInResult( @@ -957,58 +890,53 @@ void main() { verify(mockApi.signIn(scopes, null)); }); - test( - 'returns cached token from authn when refreshing existing authz', - () async { - final userData = UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: '', - ); - const scopes = ['a', 'b']; - const accessToken = 'accessToken'; - const serverAuthCode = 'authCode'; - when(mockApi.signIn(scopes, null)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: userData, - accessToken: accessToken, - serverAuthCode: serverAuthCode, - grantedScopes: [], - ), + test('returns cached token from authn when refreshing existing authz', () async { + final userData = UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: '', + ); + const scopes = ['a', 'b']; + const accessToken = 'accessToken'; + const serverAuthCode = 'authCode'; + when(mockApi.signIn(scopes, null)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: userData, + accessToken: accessToken, + serverAuthCode: serverAuthCode, + grantedScopes: [], ), - ); - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: userData, - accessToken: accessToken, - // serverAuthCode will always be null for getRefreshedAuthorizationTokens. - grantedScopes: scopes, - ), + ), + ); + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: userData, + accessToken: accessToken, + // serverAuthCode will always be null for getRefreshedAuthorizationTokens. + grantedScopes: scopes, ), - ); - - await googleSignIn.authenticate( - const AuthenticateParameters(scopeHint: scopes), - ); - final ServerAuthorizationTokenData? result = await googleSignIn - .serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ), + ), + ); + + await googleSignIn.authenticate(const AuthenticateParameters(scopeHint: scopes)); + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, ), - ); + ), + ); - expect(result?.serverAuthCode, serverAuthCode); - }, - ); + expect(result?.serverAuthCode, serverAuthCode); + }); test('does not return cached token from authn if user changes', () async { const scopes = ['a', 'b']; @@ -1049,9 +977,7 @@ void main() { ), ); - await googleSignIn.authenticate( - const AuthenticateParameters(scopeHint: scopes), - ); + await googleSignIn.authenticate(const AuthenticateParameters(scopeHint: scopes)); final ServerAuthorizationTokenData? result = await googleSignIn .serverAuthorizationTokensForScopes( ServerAuthorizationTokensForScopesParameters( @@ -1099,9 +1025,7 @@ void main() { ), ); - await googleSignIn.authenticate( - const AuthenticateParameters(scopeHint: scopes), - ); + await googleSignIn.authenticate(const AuthenticateParameters(scopeHint: scopes)); await googleSignIn.signOut(const SignOutParams()); final ServerAuthorizationTokenData? result = await googleSignIn .serverAuthorizationTokensForScopes( @@ -1150,9 +1074,7 @@ void main() { ), ); - await googleSignIn.authenticate( - const AuthenticateParameters(scopeHint: scopes), - ); + await googleSignIn.authenticate(const AuthenticateParameters(scopeHint: scopes)); await googleSignIn.disconnect(const DisconnectParams()); final ServerAuthorizationTokenData? result = await googleSignIn .serverAuthorizationTokensForScopes( @@ -1169,93 +1091,87 @@ void main() { expect(result, null); }); - test( - 'passes returned data to caller when calling addScopes without cache', - () async { - const scopes = ['a', 'b']; - const serverAuthCode = 'authCode'; - when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ), - accessToken: 'token', - serverAuthCode: serverAuthCode, - grantedScopes: scopes, + test('passes returned data to caller when calling addScopes without cache', () async { + const scopes = ['a', 'b']; + const serverAuthCode = 'authCode'; + when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', ), + accessToken: 'token', + serverAuthCode: serverAuthCode, + grantedScopes: scopes, ), - ); - - final ServerAuthorizationTokenData? result = await googleSignIn - .serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ), + ), + ); + + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, ), - ); + ), + ); - expect(result?.serverAuthCode, serverAuthCode); - }, - ); + expect(result?.serverAuthCode, serverAuthCode); + }); - test( - 'passes returned data to caller when calling addScopes, not cached data', - () async { - const scopes = ['a', 'b']; - final userData = UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ); - const serverAuthCode = 'authCode'; - when(mockApi.signIn([], null)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: userData, - accessToken: 'token', - serverAuthCode: 'no-scope-auth-code', - grantedScopes: [], - ), + test('passes returned data to caller when calling addScopes, not cached data', () async { + const scopes = ['a', 'b']; + final userData = UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ); + const serverAuthCode = 'authCode'; + when(mockApi.signIn([], null)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: userData, + accessToken: 'token', + serverAuthCode: 'no-scope-auth-code', + grantedScopes: [], ), - ); - when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: userData, - accessToken: 'token', - serverAuthCode: serverAuthCode, - grantedScopes: scopes, - ), + ), + ); + when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: userData, + accessToken: 'token', + serverAuthCode: serverAuthCode, + grantedScopes: scopes, ), - ); - - await googleSignIn.authenticate(const AuthenticateParameters()); - final ServerAuthorizationTokenData? result = await googleSignIn - .serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: true, - ), + ), + ); + + await googleSignIn.authenticate(const AuthenticateParameters()); + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: true, ), - ); + ), + ); - expect(result?.serverAuthCode, serverAuthCode); - }, - ); + expect(result?.serverAuthCode, serverAuthCode); + }); test('successfully returns cached token if addScopes indicates the ' 'requested scopes are already granted', () async { @@ -1279,11 +1195,8 @@ void main() { ), ); when(mockApi.addScopes(scopes, _testUser.id)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure( - type: GoogleSignInErrorCode.scopesAlreadyGranted, - ), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.scopesAlreadyGranted)), ); when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( (_) async => SignInResult( @@ -1296,9 +1209,7 @@ void main() { ), ); - await googleSignIn.authenticate( - const AuthenticateParameters(scopeHint: scopes), - ); + await googleSignIn.authenticate(const AuthenticateParameters(scopeHint: scopes)); final ServerAuthorizationTokenData? result = await googleSignIn .serverAuthorizationTokensForScopes( ServerAuthorizationTokensForScopesParameters( @@ -1317,69 +1228,63 @@ void main() { expect(result?.serverAuthCode, serverAuthCode); }); - test( - 'returns null if re-using existing authz and scopes are missing', - () async { - const requestedScopes = ['a', 'b']; - const grantedScopes = ['a']; - const accessToken = 'token'; - final userData = UserData( - displayName: _testUser.displayName, - email: _testUser.email, - userId: _testUser.id, - photoUrl: _testUser.photoUrl, - idToken: 'idToken', - ); - when(mockApi.signIn([], null)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: userData, - accessToken: 'token', - serverAuthCode: 'no-scope-auth-code', - grantedScopes: [], - ), + test('returns null if re-using existing authz and scopes are missing', () async { + const requestedScopes = ['a', 'b']; + const grantedScopes = ['a']; + const accessToken = 'token'; + final userData = UserData( + displayName: _testUser.displayName, + email: _testUser.email, + userId: _testUser.id, + photoUrl: _testUser.photoUrl, + idToken: 'idToken', + ); + when(mockApi.signIn([], null)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: userData, + accessToken: 'token', + serverAuthCode: 'no-scope-auth-code', + grantedScopes: [], ), - ); - when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( - (_) async => SignInResult( - success: SignInSuccess( - user: userData, - accessToken: accessToken, - serverAuthCode: 'wrong-scope-auth-code', - grantedScopes: grantedScopes, - ), + ), + ); + when(mockApi.getRefreshedAuthorizationTokens(_testUser.id)).thenAnswer( + (_) async => SignInResult( + success: SignInSuccess( + user: userData, + accessToken: accessToken, + serverAuthCode: 'wrong-scope-auth-code', + grantedScopes: grantedScopes, ), - ); - - await googleSignIn.authenticate(const AuthenticateParameters()); - final ServerAuthorizationTokenData? result = await googleSignIn - .serverAuthorizationTokensForScopes( - ServerAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: requestedScopes, - userId: _testUser.id, - email: _testUser.email, - promptIfUnauthorized: false, - ), + ), + ); + + await googleSignIn.authenticate(const AuthenticateParameters()); + final ServerAuthorizationTokenData? result = await googleSignIn + .serverAuthorizationTokensForScopes( + ServerAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: requestedScopes, + userId: _testUser.id, + email: _testUser.email, + promptIfUnauthorized: false, ), - ); + ), + ); - expect(result, null); - }, - ); + expect(result, null); + }); test('returns null when unauthorized', () async { when(mockApi.restorePreviousSignIn()).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain), - ), + (_) async => + SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.noAuthInKeychain)), ); expect( await googleSignIn.serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: defaultAuthRequest, - ), + const ServerAuthorizationTokensForScopesParameters(request: defaultAuthRequest), ), null, ); @@ -1387,9 +1292,7 @@ void main() { test('thows canceled from SDK', () async { when(mockApi.addScopes(any, any)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.canceled), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.canceled)), ); expect( @@ -1415,9 +1318,7 @@ void main() { test('throws unknown from SDK', () async { when(mockApi.addScopes(any, any)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.unknown), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.unknown)), ); expect( @@ -1443,9 +1344,7 @@ void main() { test('throws user mismatch from SDK', () async { when(mockApi.addScopes(any, any)).thenAnswer( - (_) async => SignInResult( - error: SignInFailure(type: GoogleSignInErrorCode.userMismatch), - ), + (_) async => SignInResult(error: SignInFailure(type: GoogleSignInErrorCode.userMismatch)), ); expect( diff --git a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart index fd93477a6d51..0c7198ee8e30 100644 --- a/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_ios/test/google_sign_in_ios_test.mocks.dart @@ -24,8 +24,7 @@ import 'package:mockito/src/dummies.dart' as _i3; // ignore_for_file: subtype_of_sealed_class class _FakeSignInResult_0 extends _i1.SmartFake implements _i2.SignInResult { - _FakeSignInResult_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeSignInResult_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [GoogleSignInApi]. @@ -37,97 +36,64 @@ class MockGoogleSignInApi extends _i1.Mock implements _i2.GoogleSignInApi { } @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + ) as String); @override - _i4.Future configure(_i2.PlatformConfigurationParams? params) => - (super.noSuchMethod( - Invocation.method(#configure, [params]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future configure(_i2.PlatformConfigurationParams? params) => (super.noSuchMethod( + Invocation.method(#configure, [params]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.SignInResult> restorePreviousSignIn() => - (super.noSuchMethod( - Invocation.method(#restorePreviousSignIn, []), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, - Invocation.method(#restorePreviousSignIn, []), - ), - ), - ) - as _i4.Future<_i2.SignInResult>); + _i4.Future<_i2.SignInResult> restorePreviousSignIn() => (super.noSuchMethod( + Invocation.method(#restorePreviousSignIn, []), + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0(this, Invocation.method(#restorePreviousSignIn, [])), + ), + ) as _i4.Future<_i2.SignInResult>); @override _i4.Future<_i2.SignInResult> signIn(List? scopeHint, String? nonce) => (super.noSuchMethod( - Invocation.method(#signIn, [scopeHint, nonce]), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, - Invocation.method(#signIn, [scopeHint, nonce]), - ), - ), - ) - as _i4.Future<_i2.SignInResult>); + Invocation.method(#signIn, [scopeHint, nonce]), + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0(this, Invocation.method(#signIn, [scopeHint, nonce])), + ), + ) as _i4.Future<_i2.SignInResult>); @override - _i4.Future<_i2.SignInResult> getRefreshedAuthorizationTokens( - String? userId, - ) => + _i4.Future<_i2.SignInResult> getRefreshedAuthorizationTokens(String? userId) => (super.noSuchMethod( - Invocation.method(#getRefreshedAuthorizationTokens, [userId]), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, - Invocation.method(#getRefreshedAuthorizationTokens, [userId]), - ), - ), - ) - as _i4.Future<_i2.SignInResult>); + Invocation.method(#getRefreshedAuthorizationTokens, [userId]), + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0(this, Invocation.method(#getRefreshedAuthorizationTokens, [userId])), + ), + ) as _i4.Future<_i2.SignInResult>); @override - _i4.Future<_i2.SignInResult> addScopes( - List? scopes, - String? userId, - ) => + _i4.Future<_i2.SignInResult> addScopes(List? scopes, String? userId) => (super.noSuchMethod( - Invocation.method(#addScopes, [scopes, userId]), - returnValue: _i4.Future<_i2.SignInResult>.value( - _FakeSignInResult_0( - this, - Invocation.method(#addScopes, [scopes, userId]), - ), - ), - ) - as _i4.Future<_i2.SignInResult>); + Invocation.method(#addScopes, [scopes, userId]), + returnValue: _i4.Future<_i2.SignInResult>.value( + _FakeSignInResult_0(this, Invocation.method(#addScopes, [scopes, userId])), + ), + ) as _i4.Future<_i2.SignInResult>); @override - _i4.Future signOut() => - (super.noSuchMethod( - Invocation.method(#signOut, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future signOut() => (super.noSuchMethod( + Invocation.method(#signOut, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future disconnect() => - (super.noSuchMethod( - Invocation.method(#disconnect, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future disconnect() => (super.noSuchMethod( + Invocation.method(#disconnect, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart b/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart index cf2c04d93901..7de66a82c218 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart +++ b/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart @@ -100,9 +100,7 @@ abstract class GoogleSignInPlatform extends PlatformInterface { /// Clears any token cache for the given access token. Future clearAuthorizationToken(ClearAuthorizationTokenParams params) { - throw UnimplementedError( - 'clearAuthorizationToken() has not been implemented.', - ); + throw UnimplementedError('clearAuthorizationToken() has not been implemented.'); } /// Signs out previously signed in accounts. diff --git a/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart b/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart index 2f6e273ef13e..d09a4b19df4f 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart +++ b/packages/google_sign_in/google_sign_in_platform_interface/lib/src/types.dart @@ -9,11 +9,7 @@ import 'package:flutter/foundation.dart' show immutable; @immutable class GoogleSignInException implements Exception { /// Crceates a new exception with the given information. - const GoogleSignInException({ - required this.code, - this.description, - this.details, - }); + const GoogleSignInException({required this.code, this.description, this.details}); /// The type of failure. final GoogleSignInExceptionCode code; @@ -25,8 +21,7 @@ class GoogleSignInException implements Exception { final Object? details; @override - String toString() => - 'GoogleSignInException(code $code, $description, $details)'; + String toString() => 'GoogleSignInException(code $code, $description, $details)'; } /// Types of [GoogleSignInException]s, as indicated by @@ -80,12 +75,7 @@ enum GoogleSignInExceptionCode { @immutable class InitParameters { /// The parameters to use when initializing the sign in process. - const InitParameters({ - this.clientId, - this.serverClientId, - this.nonce, - this.hostedDomain, - }); + const InitParameters({this.clientId, this.serverClientId, this.nonce, this.hostedDomain}); /// The OAuth client ID of the app. /// @@ -316,8 +306,7 @@ class ClientAuthorizationTokenData { if (other.runtimeType != runtimeType) { return false; } - return other is ClientAuthorizationTokenData && - other.accessToken == accessToken; + return other is ClientAuthorizationTokenData && other.accessToken == accessToken; } } @@ -339,8 +328,7 @@ class ServerAuthorizationTokenData { if (other.runtimeType != runtimeType) { return false; } - return other is ServerAuthorizationTokenData && - other.serverAuthCode == serverAuthCode; + return other is ServerAuthorizationTokenData && other.serverAuthCode == serverAuthCode; } } @@ -351,10 +339,7 @@ class ServerAuthorizationTokenData { @immutable class AuthenticationResults { /// Creates a new result object. - const AuthenticationResults({ - required this.user, - required this.authenticationTokens, - }); + const AuthenticationResults({required this.user, required this.authenticationTokens}); /// The user that was authenticated. final GoogleSignInUserData user; @@ -381,8 +366,7 @@ class ClearAuthorizationTokenParams { if (other.runtimeType != runtimeType) { return false; } - return other is ClearAuthorizationTokenParams && - other.accessToken == accessToken; + return other is ClearAuthorizationTokenParams && other.accessToken == accessToken; } } @@ -417,10 +401,7 @@ sealed class AuthenticationEvent { @immutable class AuthenticationEventSignIn extends AuthenticationEvent { /// Creates an event for a successful sign in. - const AuthenticationEventSignIn({ - required this.user, - required this.authenticationTokens, - }); + const AuthenticationEventSignIn({required this.user, required this.authenticationTokens}); /// The user that was authenticated. final GoogleSignInUserData user; diff --git a/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart b/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart index e0a89f34842b..dd02daac7797 100644 --- a/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart +++ b/packages/google_sign_in/google_sign_in_platform_interface/test/google_sign_in_platform_interface_test.dart @@ -38,19 +38,16 @@ void main() { expect(ExtendsGoogleSignInPlatform().authenticationEvents, null); }); - test( - 'Default implementation of clearAuthorizationToken throws unimplemented error', - () { - final platform = ExtendsGoogleSignInPlatform(); - - expect( - () => platform.clearAuthorizationToken( - const ClearAuthorizationTokenParams(accessToken: 'someToken'), - ), - throwsUnimplementedError, - ); - }, - ); + test('Default implementation of clearAuthorizationToken throws unimplemented error', () { + final platform = ExtendsGoogleSignInPlatform(); + + expect( + () => platform.clearAuthorizationToken( + const ClearAuthorizationTokenParams(accessToken: 'someToken'), + ), + throwsUnimplementedError, + ); + }); }); group('GoogleSignInUserData', () { @@ -81,24 +78,16 @@ void main() { group('ClientAuthorizationTokenData', () { test('can be compared by == operator', () { - const firstInstance = ClientAuthorizationTokenData( - accessToken: 'accessToken', - ); - const secondInstance = ClientAuthorizationTokenData( - accessToken: 'accessToken', - ); + const firstInstance = ClientAuthorizationTokenData(accessToken: 'accessToken'); + const secondInstance = ClientAuthorizationTokenData(accessToken: 'accessToken'); expect(firstInstance == secondInstance, isTrue); }); }); group('ServerAuthorizationTokenData', () { test('can be compared by == operator', () { - const firstInstance = ServerAuthorizationTokenData( - serverAuthCode: 'serverAuthCode', - ); - const secondInstance = ServerAuthorizationTokenData( - serverAuthCode: 'serverAuthCode', - ); + const firstInstance = ServerAuthorizationTokenData(serverAuthCode: 'serverAuthCode'); + const secondInstance = ServerAuthorizationTokenData(serverAuthCode: 'serverAuthCode'); expect(firstInstance == secondInstance, isTrue); }); }); @@ -108,8 +97,7 @@ class MockImplementation extends Mock with MockPlatformInterfaceMixin implements GoogleSignInPlatform {} -class ImplementsGoogleSignInPlatform extends Mock - implements GoogleSignInPlatform {} +class ImplementsGoogleSignInPlatform extends Mock implements GoogleSignInPlatform {} class ExtendsGoogleSignInPlatform extends GoogleSignInPlatform { @override diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart index b99975256164..1bc7aee0206d 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/flexible_size_html_element_view_test.dart @@ -22,9 +22,7 @@ void main() { widgetFactoryNumber++; }); - testWidgets('empty case, calls onElementCreated', ( - WidgetTester tester, - ) async { + testWidgets('empty case, calls onElementCreated', (WidgetTester tester) async { final viewCreatedCompleter = Completer(); await pumpResizableWidget( @@ -38,15 +36,10 @@ void main() { await expectLater(viewCreatedCompleter.future, completes); }); - testWidgets('empty case, renders with initial size', ( - WidgetTester tester, - ) async { + testWidgets('empty case, renders with initial size', (WidgetTester tester) async { const initialSize = Size(160, 100); - final Element element = await pumpResizableWidget( - tester, - initialSize: initialSize, - ); + final Element element = await pumpResizableWidget(tester, initialSize: initialSize); await tester.pumpAndSettle(); // Expect that the element matches the initialSize. @@ -54,9 +47,7 @@ void main() { expect(element.size!.height, initialSize.height); }); - testWidgets('initialSize null, adopts size of injected element', ( - WidgetTester tester, - ) async { + testWidgets('initialSize null, adopts size of injected element', (WidgetTester tester) async { const childSize = Size(300, 40); final resizable = web.document.createElement('div') as web.HTMLDivElement; @@ -73,9 +64,7 @@ void main() { expect(element.size!.height, childSize.height); }); - testWidgets('with initialSize, adopts size of injected element', ( - WidgetTester tester, - ) async { + testWidgets('with initialSize, adopts size of injected element', (WidgetTester tester) async { const initialSize = Size(160, 100); const newSize = Size(300, 40); @@ -94,18 +83,13 @@ void main() { expect(element.size!.height, newSize.height); }); - testWidgets('with injected element that resizes, follows resizes', ( - WidgetTester tester, - ) async { + testWidgets('with injected element that resizes, follows resizes', (WidgetTester tester) async { const initialSize = Size(160, 100); final Size expandedSize = initialSize * 2; final Size contractedSize = initialSize / 2; final resizable = web.document.createElement('div') as web.HTMLDivElement - ..setAttribute( - 'style', - 'width: 100%; height: 100%; background: #fabada;', - ); + ..setAttribute('style', 'width: 100%; height: 100%; background: #fabada;'); final Element element = await pumpResizableWidget( tester, @@ -163,24 +147,16 @@ Future pumpResizableWidget( } class ResizableFromJs extends StatelessWidget { - ResizableFromJs({ - required this.instanceId, - this.onElementCreated, - this.initialSize, - super.key, - }) { - ui_web.platformViewRegistry.registerViewFactory( - 'resizable_from_js_$instanceId', - (int viewId) { - final element = web.document.createElement('div') as web.HTMLDivElement; - element.setAttribute( - 'style', - 'width: 100%; height: 100%; overflow: hidden; background: red;', - ); - element.id = 'test_element_$viewId'; - return element; - }, - ); + ResizableFromJs({required this.instanceId, this.onElementCreated, this.initialSize, super.key}) { + ui_web.platformViewRegistry.registerViewFactory('resizable_from_js_$instanceId', (int viewId) { + final element = web.document.createElement('div') as web.HTMLDivElement; + element.setAttribute( + 'style', + 'width: 100%; height: 100%; overflow: hidden; background: red;', + ); + element.id = 'test_element_$viewId'; + return element; + }); } final int instanceId; diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart index e102d6521175..fb735f6c3b5b 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.dart @@ -55,28 +55,19 @@ void main() { setUp(() { mockGis = MockGisSdkClient(); - plugin = GoogleSignInPlugin( - debugOverrideLoader: true, - debugOverrideGisSdkClient: mockGis, - ); + plugin = GoogleSignInPlugin(debugOverrideLoader: true, debugOverrideGisSdkClient: mockGis); }); testWidgets('initializes if all is OK', (_) async { - await plugin.init( - const InitParameters(clientId: 'some-non-null-client-id'), - ); + await plugin.init(const InitParameters(clientId: 'some-non-null-client-id')); }); testWidgets('throws if init is called twice', (_) async { - await plugin.init( - const InitParameters(clientId: 'some-non-null-client-id'), - ); + await plugin.init(const InitParameters(clientId: 'some-non-null-client-id')); // Calling init() a second time should throw state error expect( - () => plugin.init( - const InitParameters(clientId: 'some-non-null-client-id'), - ), + () => plugin.init(const InitParameters(clientId: 'some-non-null-client-id')), throwsStateError, ); }); @@ -88,9 +79,7 @@ void main() { // Calling init() a second time synchronously should throw state error expect( - () => plugin.init( - const InitParameters(clientId: 'some-non-null-client-id'), - ), + () => plugin.init(const InitParameters(clientId: 'some-non-null-client-id')), throwsStateError, ); @@ -122,9 +111,7 @@ void main() { expect(plugin.supportsAuthenticate(), false); }); - testWidgets('reports requirement for user interaction to authorize', ( - _, - ) async { + testWidgets('reports requirement for user interaction to authorize', (_) async { final plugin = GoogleSignInPlugin(debugOverrideLoader: true); expect(plugin.authorizationRequiresUserInteraction(), true); @@ -138,10 +125,7 @@ void main() { setUp(() { mockGis = MockGisSdkClient(); - plugin = GoogleSignInPlugin( - debugOverrideLoader: true, - debugOverrideGisSdkClient: mockGis, - ); + plugin = GoogleSignInPlugin(debugOverrideLoader: true, debugOverrideGisSdkClient: mockGis); }); group('attemptLightweightAuthentication', () { @@ -150,14 +134,11 @@ void main() { }); testWidgets('Calls requestOneTap on GIS client', (_) async { - mockito - .when(mockGis.requestOneTap()) - .thenAnswer((_) => Future.value()); + mockito.when(mockGis.requestOneTap()).thenAnswer((_) => Future.value()); - final Future? future = plugin - .attemptLightweightAuthentication( - const AttemptLightweightAuthenticationParameters(), - ); + final Future? future = plugin.attemptLightweightAuthentication( + const AttemptLightweightAuthenticationParameters(), + ); expect(future, null); @@ -188,25 +169,22 @@ void main() { ) .thenAnswer((_) => Future.value(someAccessToken)); - final ClientAuthorizationTokenData? token = await plugin - .clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: null, - email: null, - promptIfUnauthorized: false, - ), - ), - ); + final ClientAuthorizationTokenData? token = await plugin.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: null, + email: null, + promptIfUnauthorized: false, + ), + ), + ); final List arguments = mockito .verify( mockGis.requestScopes( mockito.captureAny, - promptIfUnauthorized: mockito.captureAnyNamed( - 'promptIfUnauthorized', - ), + promptIfUnauthorized: mockito.captureAnyNamed('promptIfUnauthorized'), userHint: mockito.captureAnyNamed('userHint'), ), ) @@ -231,25 +209,22 @@ void main() { ) .thenAnswer((_) => Future.value(someAccessToken)); - final ClientAuthorizationTokenData? token = await plugin - .clientAuthorizationTokensForScopes( - const ClientAuthorizationTokensForScopesParameters( - request: AuthorizationRequestDetails( - scopes: scopes, - userId: someUserId, - email: 'someone@example.com', - promptIfUnauthorized: true, - ), - ), - ); + final ClientAuthorizationTokenData? token = await plugin.clientAuthorizationTokensForScopes( + const ClientAuthorizationTokensForScopesParameters( + request: AuthorizationRequestDetails( + scopes: scopes, + userId: someUserId, + email: 'someone@example.com', + promptIfUnauthorized: true, + ), + ), + ); final List arguments = mockito .verify( mockGis.requestScopes( mockito.captureAny, - promptIfUnauthorized: mockito.captureAnyNamed( - 'promptIfUnauthorized', - ), + promptIfUnauthorized: mockito.captureAnyNamed('promptIfUnauthorized'), userHint: mockito.captureAnyNamed('userHint'), ), ) @@ -298,12 +273,9 @@ void main() { email: null, promptIfUnauthorized: true, ); - final ServerAuthorizationTokenData? token = await plugin - .serverAuthorizationTokensForScopes( - const ServerAuthorizationTokensForScopesParameters( - request: request, - ), - ); + final ServerAuthorizationTokenData? token = await plugin.serverAuthorizationTokensForScopes( + const ServerAuthorizationTokensForScopesParameters(request: request), + ); final List arguments = mockito .verify(mockGis.requestServerAuthCode(mockito.captureAny)) @@ -315,10 +287,7 @@ void main() { expect(passedRequest.scopes, request.scopes); expect(passedRequest.userId, request.userId); expect(passedRequest.email, request.email); - expect( - passedRequest.promptIfUnauthorized, - request.promptIfUnauthorized, - ); + expect(passedRequest.promptIfUnauthorized, request.promptIfUnauthorized); }); testWidgets('asserts no scopes have any spaces', (_) async { @@ -370,8 +339,7 @@ void main() { }); testWidgets('accepts async user data events from GIS.', (_) async { - final Future event = - plugin.authenticationEvents.first; + final Future event = plugin.authenticationEvents.first; const AuthenticationEvent expected = AuthenticationEventSignIn( user: GoogleSignInUserData(email: 'someone@example.com', id: 'user_id'), @@ -379,14 +347,9 @@ void main() { ); controller.add(expected); - expect( - await event, - expected, - reason: 'Sign-in events should be propagated', - ); + expect(await event, expected, reason: 'Sign-in events should be propagated'); - final Future nextEvent = - plugin.authenticationEvents.first; + final Future nextEvent = plugin.authenticationEvents.first; controller.add(AuthenticationEventSignOut()); expect( diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart index ccd87c6e17fb..c76def566316 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/google_sign_in_web_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' - as _i5; +import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' as _i5; import 'package:google_sign_in_web/src/button_configuration.dart' as _i4; import 'package:google_sign_in_web/src/gis_client.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; @@ -30,51 +29,38 @@ import 'package:mockito/mockito.dart' as _i1; /// See the documentation for Mockito's code generation for more information. class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { @override - void requestOneTap() => super.noSuchMethod( - Invocation.method(#requestOneTap, []), - returnValueForMissingStub: null, - ); + void requestOneTap() => + super.noSuchMethod(Invocation.method(#requestOneTap, []), returnValueForMissingStub: null); @override - _i3.Future renderButton( - Object? parent, - _i4.GSIButtonConfiguration? options, - ) => + _i3.Future renderButton(Object? parent, _i4.GSIButtonConfiguration? options) => (super.noSuchMethod( - Invocation.method(#renderButton, [parent, options]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#renderButton, [parent, options]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future requestServerAuthCode( - _i5.AuthorizationRequestDetails? request, - ) => + _i3.Future requestServerAuthCode(_i5.AuthorizationRequestDetails? request) => (super.noSuchMethod( - Invocation.method(#requestServerAuthCode, [request]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#requestServerAuthCode, [request]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future signOut() => - (super.noSuchMethod( - Invocation.method(#signOut, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future signOut() => (super.noSuchMethod( + Invocation.method(#signOut, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future disconnect() => - (super.noSuchMethod( - Invocation.method(#disconnect, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future disconnect() => (super.noSuchMethod( + Invocation.method(#disconnect, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override void clearAuthorizationToken(String? token) => super.noSuchMethod( @@ -87,18 +73,13 @@ class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { List? scopes, { required bool? promptIfUnauthorized, String? userHint, - }) => - (super.noSuchMethod( - Invocation.method( - #requestScopes, - [scopes], - { - #promptIfUnauthorized: promptIfUnauthorized, - #userHint: userHint, - }, - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + }) => (super.noSuchMethod( + Invocation.method( + #requestScopes, + [scopes], + {#promptIfUnauthorized: promptIfUnauthorized, #userHint: userHint}, + ), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); } diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart index 5e7626d786f9..6859520cb7f4 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/src/jwt_examples.dart @@ -7,23 +7,23 @@ import 'package:google_identity_services_web/id.dart'; import 'jsify_as.dart'; /// A CredentialResponse with null `credential`. -final CredentialResponse nullCredential = jsifyAs( - {'credential': null}, -); +final CredentialResponse nullCredential = jsifyAs({ + 'credential': null, +}); /// A CredentialResponse wrapping a known good JWT Token as its `credential`. -final CredentialResponse goodCredential = jsifyAs( - {'credential': goodJwtToken}, -); +final CredentialResponse goodCredential = jsifyAs({ + 'credential': goodJwtToken, +}); /// A CredentialResponse wrapping a known good JWT Token as its `credential`. -final CredentialResponse minimalCredential = jsifyAs( - {'credential': minimalJwtToken}, -); +final CredentialResponse minimalCredential = jsifyAs({ + 'credential': minimalJwtToken, +}); -final CredentialResponse expiredCredential = jsifyAs( - {'credential': expiredJwtToken}, -); +final CredentialResponse expiredCredential = jsifyAs({ + 'credential': expiredJwtToken, +}); /// A JWT token with predefined values. /// @@ -58,8 +58,7 @@ const String minimalJwtToken = /// /// 'email': 'adultman@example.com', /// 'sub': '123456' -const String minimalPayload = - 'eyJlbWFpbCI6ImFkdWx0bWFuQGV4YW1wbGUuY29tIiwic3ViIjoiMTIzNDU2In0'; +const String minimalPayload = 'eyJlbWFpbCI6ImFkdWx0bWFuQGV4YW1wbGUuY29tIiwic3ViIjoiMTIzNDU2In0'; /// A JWT token with minimal set of predefined values and an expiration timestamp. /// diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart index 5cd060b02a07..4b6b51b7a7ab 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/utils_test.dart @@ -19,8 +19,7 @@ void main() { group('gisResponsesToAuthenticationEvent', () { testWidgets('happy case', (_) async { final signIn = - gisResponsesToAuthenticationEvent(goodCredential)! - as AuthenticationEventSignIn; + gisResponsesToAuthenticationEvent(goodCredential)! as AuthenticationEventSignIn; final GoogleSignInUserData data = signIn.user; expect(data.displayName, 'Vincent Adultman'); @@ -32,8 +31,7 @@ void main() { testWidgets('happy case (minimal)', (_) async { final signIn = - gisResponsesToAuthenticationEvent(minimalCredential)! - as AuthenticationEventSignIn; + gisResponsesToAuthenticationEvent(minimalCredential)! as AuthenticationEventSignIn; final GoogleSignInUserData data = signIn.user; expect(data.displayName, isNull); @@ -52,38 +50,29 @@ void main() { }); testWidgets('invalid payload -> null', (_) async { - final CredentialResponse response = jsifyAs( - { - 'credential': 'some-bogus.thing-that-is-not.valid-jwt', - }, - ); + final CredentialResponse response = jsifyAs({ + 'credential': 'some-bogus.thing-that-is-not.valid-jwt', + }); expect(gisResponsesToAuthenticationEvent(response), isNull); }); }); group('getCredentialResponseExpirationTimestamp', () { testWidgets('Good payload -> data', (_) async { - final DateTime? expiration = getCredentialResponseExpirationTimestamp( - expiredCredential, - ); + final DateTime? expiration = getCredentialResponseExpirationTimestamp(expiredCredential); expect(expiration, isNotNull); expect(expiration!.millisecondsSinceEpoch, 1430330400 * 1000); }); testWidgets('No expiration -> null', (_) async { - expect( - getCredentialResponseExpirationTimestamp(minimalCredential), - isNull, - ); + expect(getCredentialResponseExpirationTimestamp(minimalCredential), isNull); }); testWidgets('Bad data -> null', (_) async { - final CredentialResponse bogus = jsifyAs( - { - 'credential': 'some-bogus.thing-that-is-not.valid-jwt', - }, - ); + final CredentialResponse bogus = jsifyAs({ + 'credential': 'some-bogus.thing-that-is-not.valid-jwt', + }); expect(getCredentialResponseExpirationTimestamp(bogus), isNull); }); @@ -97,13 +86,7 @@ void main() { expect(data, containsPair('name', 'Vincent Adultman')); expect(data, containsPair('email', 'adultman@example.com')); expect(data, containsPair('sub', '123456')); - expect( - data, - containsPair( - 'picture', - 'https://thispersondoesnotexist.com/image?x=.jpg', - ), - ); + expect(data, containsPair('picture', 'https://thispersondoesnotexist.com/image?x=.jpg')); }); testWidgets('happy case (minimal) -> data', (_) async { @@ -141,13 +124,7 @@ void main() { expect(data, containsPair('name', 'Vincent Adultman')); expect(data, containsPair('email', 'adultman@example.com')); expect(data, containsPair('sub', '123456')); - expect( - data, - containsPair( - 'picture', - 'https://thispersondoesnotexist.com/image?x=.jpg', - ), - ); + expect(data, containsPair('picture', 'https://thispersondoesnotexist.com/image?x=.jpg')); }); testWidgets('Proper JSON payload -> data', (_) async { diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart index 5e0260e23d5e..8027c23f8035 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.dart @@ -5,8 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; -import 'package:google_sign_in_web/google_sign_in_web.dart' - show GoogleSignInPlugin; +import 'package:google_sign_in_web/google_sign_in_web.dart' show GoogleSignInPlugin; import 'package:google_sign_in_web/src/flexible_size_html_element_view.dart'; import 'package:google_sign_in_web/src/gis_client.dart'; import 'package:google_sign_in_web/web_only.dart' as web; @@ -47,27 +46,19 @@ void main() { debugOverrideLoader: true, debugOverrideGisSdkClient: mockGis, ); - await GoogleSignInPlatform.instance.init( - const InitParameters(clientId: 'does-not-matter'), - ); + await GoogleSignInPlatform.instance.init(const InitParameters(clientId: 'does-not-matter')); }); testWidgets('renderButton returns successfully', (WidgetTester _) async { - when( - mockGis.renderButton(any, any), - ).thenAnswer((_) => Future.value()); + when(mockGis.renderButton(any, any)).thenAnswer((_) => Future.value()); final Widget button = web.renderButton(); expect(button, isNotNull); }); - testWidgets('renderButton shows loading then renders button', ( - WidgetTester tester, - ) async { - await tester.pumpWidget( - MaterialApp(home: Scaffold(body: web.renderButton())), - ); + testWidgets('renderButton shows loading then renders button', (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp(home: Scaffold(body: web.renderButton()))); expect(find.text('Getting ready'), findsOneWidget); diff --git a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart index 97a7fa915134..47e94a1ef2d3 100644 --- a/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart +++ b/packages/google_sign_in/google_sign_in_web/example/integration_test/web_only_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' - as _i5; +import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart' as _i5; import 'package:google_sign_in_web/src/button_configuration.dart' as _i4; import 'package:google_sign_in_web/src/gis_client.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; @@ -30,51 +29,38 @@ import 'package:mockito/mockito.dart' as _i1; /// See the documentation for Mockito's code generation for more information. class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { @override - void requestOneTap() => super.noSuchMethod( - Invocation.method(#requestOneTap, []), - returnValueForMissingStub: null, - ); + void requestOneTap() => + super.noSuchMethod(Invocation.method(#requestOneTap, []), returnValueForMissingStub: null); @override - _i3.Future renderButton( - Object? parent, - _i4.GSIButtonConfiguration? options, - ) => + _i3.Future renderButton(Object? parent, _i4.GSIButtonConfiguration? options) => (super.noSuchMethod( - Invocation.method(#renderButton, [parent, options]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#renderButton, [parent, options]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future requestServerAuthCode( - _i5.AuthorizationRequestDetails? request, - ) => + _i3.Future requestServerAuthCode(_i5.AuthorizationRequestDetails? request) => (super.noSuchMethod( - Invocation.method(#requestServerAuthCode, [request]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#requestServerAuthCode, [request]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future signOut() => - (super.noSuchMethod( - Invocation.method(#signOut, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future signOut() => (super.noSuchMethod( + Invocation.method(#signOut, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future disconnect() => - (super.noSuchMethod( - Invocation.method(#disconnect, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future disconnect() => (super.noSuchMethod( + Invocation.method(#disconnect, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override void clearAuthorizationToken(String? token) => super.noSuchMethod( @@ -87,18 +73,13 @@ class MockGisSdkClient extends _i1.Mock implements _i2.GisSdkClient { List? scopes, { required bool? promptIfUnauthorized, String? userHint, - }) => - (super.noSuchMethod( - Invocation.method( - #requestScopes, - [scopes], - { - #promptIfUnauthorized: promptIfUnauthorized, - #userHint: userHint, - }, - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + }) => (super.noSuchMethod( + Invocation.method( + #requestScopes, + [scopes], + {#promptIfUnauthorized: promptIfUnauthorized, #userHint: userHint}, + ), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); } diff --git a/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart b/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart index 3bb6b4cdf6e3..f2501c1983d7 100644 --- a/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart +++ b/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart @@ -14,14 +14,9 @@ import 'src/button_configuration_column.dart'; final GoogleSignInPlatform _platform = GoogleSignInPlatform.instance; Future main() async { - await _platform.init( - const InitParameters(clientId: 'your-client_id.apps.googleusercontent.com'), - ); + await _platform.init(const InitParameters(clientId: 'your-client_id.apps.googleusercontent.com')); runApp( - const MaterialApp( - title: 'Sign in with Google button Tester', - home: ButtonConfiguratorDemo(), - ), + const MaterialApp(title: 'Sign in with Google button Tester', home: ButtonConfiguratorDemo()), ); } @@ -71,14 +66,10 @@ class _ButtonConfiguratorState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - if (_userData == null) - renderButton(configuration: _buttonConfiguration), + if (_userData == null) renderButton(configuration: _buttonConfiguration), if (_userData != null) ...[ Text('Hello, ${_userData!.displayName}!'), - ElevatedButton( - onPressed: _handleSignOut, - child: const Text('SIGN OUT'), - ), + ElevatedButton(onPressed: _handleSignOut, child: const Text('SIGN OUT')), ], ], ), @@ -95,10 +86,7 @@ class _ButtonConfiguratorState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sign in with Google button Tester')), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - ), + body: ConstrainedBox(constraints: const BoxConstraints.expand(), child: _buildBody()), ); } } diff --git a/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart b/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart index 3d949f101ec3..6588460a1045 100644 --- a/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart +++ b/packages/google_sign_in/google_sign_in_web/example/lib/src/button_configuration_column.dart @@ -9,11 +9,10 @@ import 'package:google_sign_in_web/web_only.dart'; typedef OnWebConfigChangeFn = void Function(GSIButtonConfiguration newConfig); /// The type of the widget builder function for each Card in the ListView builder -typedef CardBuilder = - Widget Function( - GSIButtonConfiguration? currentConfig, - OnWebConfigChangeFn? onChange, - ); +typedef CardBuilder = Widget Function( + GSIButtonConfiguration? currentConfig, + OnWebConfigChangeFn? onChange, +); // (Incomplete) List of the locales that can be used to configure the button. const List _availableLocales = [ @@ -27,19 +26,17 @@ const List _availableLocales = [ // The builder functions for the Cards that let users customize the button. final List _cards = [ - (GSIButtonConfiguration? currentConfig, OnWebConfigChangeFn? onChange) => - _renderLocaleCard( - value: currentConfig?.locale ?? 'en_US', - locales: _availableLocales, - onChanged: _onChanged(currentConfig, onChange), - ), - (GSIButtonConfiguration? currentConfig, OnWebConfigChangeFn? onChange) => - _renderMinimumWidthCard( - value: currentConfig?.minimumWidth, - max: 500, - actualMax: 400, - onChanged: _onChanged(currentConfig, onChange), - ), + (GSIButtonConfiguration? currentConfig, OnWebConfigChangeFn? onChange) => _renderLocaleCard( + value: currentConfig?.locale ?? 'en_US', + locales: _availableLocales, + onChanged: _onChanged(currentConfig, onChange), + ), + (GSIButtonConfiguration? currentConfig, OnWebConfigChangeFn? onChange) => _renderMinimumWidthCard( + value: currentConfig?.minimumWidth, + max: 500, + actualMax: 400, + onChanged: _onChanged(currentConfig, onChange), + ), (GSIButtonConfiguration? currentConfig, OnWebConfigChangeFn? onChange) => _renderRadioListTileCard( title: 'ButtonType', @@ -99,8 +96,7 @@ Widget renderWebButtonConfiguration( child: ListView.builder( controller: scrollController, itemCount: _cards.length, - itemBuilder: (BuildContext _, int index) => - _cards[index](currentConfig, onChange), + itemBuilder: (BuildContext _, int index) => _cards[index](currentConfig, onChange), ), ), ); @@ -119,12 +115,7 @@ Widget _renderLocaleCard({ padding: const EdgeInsets.symmetric(horizontal: 16), child: DropdownButton( items: locales - .map( - (String locale) => DropdownMenuItem( - value: locale, - child: Text(locale), - ), - ) + .map((String locale) => DropdownMenuItem(value: locale, child: Text(locale))) .toList(), value: value, onChanged: onChanged, @@ -193,19 +184,13 @@ Widget _renderRadioListTileCard({ } /// Renders a Card where we render some `children` that change config. -Widget _renderConfigCard({ - required String title, - required List children, -}) { +Widget _renderConfigCard({required String title, required List children}) { return Card( child: Column( mainAxisSize: MainAxisSize.min, children: [ ListTile( - title: Text( - title, - style: const TextStyle(fontWeight: FontWeight.bold), - ), + title: Text(title, style: const TextStyle(fontWeight: FontWeight.bold)), dense: true, ), ...children, @@ -215,15 +200,10 @@ Widget _renderConfigCard({ } /// Sets a `value` into an `old` configuration object. -GSIButtonConfiguration _copyConfigWith( - GSIButtonConfiguration? old, - T? value, -) { +GSIButtonConfiguration _copyConfigWith(GSIButtonConfiguration? old, T? value) { return GSIButtonConfiguration( locale: value is String ? value : old?.locale, - minimumWidth: value is double - ? (value == 0 ? null : value) - : old?.minimumWidth, + minimumWidth: value is double ? (value == 0 ? null : value) : old?.minimumWidth, type: value is GSIButtonType ? value : old?.type, theme: value is GSIButtonTheme ? value : old?.theme, size: value is GSIButtonSize ? value : old?.size, @@ -234,10 +214,7 @@ GSIButtonConfiguration _copyConfigWith( } /// Returns a function that modifies the `current` configuration with a `value`, then calls `fn` with it. -void Function(T?)? _onChanged( - GSIButtonConfiguration? current, - OnWebConfigChangeFn? fn, -) { +void Function(T?)? _onChanged(GSIButtonConfiguration? current, OnWebConfigChangeFn? fn) { if (fn == null) { return null; } diff --git a/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart b/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart index e31c10a8d283..d033c456c938 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/google_sign_in_web.dart @@ -47,12 +47,10 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { GoogleSignInPlugin({ @visibleForTesting bool debugOverrideLoader = false, @visibleForTesting GisSdkClient? debugOverrideGisSdkClient, - @visibleForTesting - StreamController? debugAuthenticationController, + @visibleForTesting StreamController? debugAuthenticationController, }) : _debugOverrideGisSdkClient = debugOverrideGisSdkClient, _authenticationController = - debugAuthenticationController ?? - StreamController.broadcast() { + debugAuthenticationController ?? StreamController.broadcast() { autoDetectedClientId = web.document .querySelector(clientIdMetaSelector) ?.getAttribute(clientIdAttributeName); @@ -121,10 +119,7 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { ' or pass clientId when initializing GoogleSignIn', ); - assert( - params.serverClientId == null, - 'serverClientId is not supported on Web.', - ); + assert(params.serverClientId == null, 'serverClientId is not supported on Web.'); await _jsSdkLoadedFuture; @@ -160,9 +155,7 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { bool authorizationRequiresUserInteraction() => true; @override - Future authenticate( - AuthenticateParameters params, - ) async { + Future authenticate(AuthenticateParameters params) async { throw UnimplementedError( 'authenticate is not supported on the web. ' 'Instead, use renderButton to create a sign-in widget.', @@ -195,9 +188,7 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { promptIfUnauthorized: params.request.promptIfUnauthorized, userHint: params.request.userId, ); - return token == null - ? null - : ClientAuthorizationTokenData(accessToken: token); + return token == null ? null : ClientAuthorizationTokenData(accessToken: token); } @override @@ -213,12 +204,8 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { return null; } - final String? code = await _gisSdkClient.requestServerAuthCode( - params.request, - ); - return code == null - ? null - : ServerAuthorizationTokenData(serverAuthCode: code); + final String? code = await _gisSdkClient.requestServerAuthCode(params.request); + return code == null ? null : ServerAuthorizationTokenData(serverAuthCode: code); } void _validateScopes(List scopes) { @@ -234,24 +221,19 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { } @override - Future clearAuthorizationToken( - ClearAuthorizationTokenParams params, - ) async { + Future clearAuthorizationToken(ClearAuthorizationTokenParams params) async { await _initialized; return _gisSdkClient.clearAuthorizationToken(params.accessToken); } @override - Stream get authenticationEvents => - _authenticationController.stream; + Stream get authenticationEvents => _authenticationController.stream; // -------- // Register a factory for the Button HtmlElementView. void _registerButtonFactory() { - ui_web.platformViewRegistry.registerViewFactory('gsi_login_button', ( - int viewId, - ) { + ui_web.platformViewRegistry.registerViewFactory('gsi_login_button', (int viewId) { final web.Element element = web.document.createElement('div'); element.setAttribute( 'style', @@ -264,8 +246,7 @@ class GoogleSignInPlugin extends GoogleSignInPlatform { /// Render the GSI button web experience. Widget renderButton({GSIButtonConfiguration? configuration}) { - final GSIButtonConfiguration config = - configuration ?? GSIButtonConfiguration(); + final GSIButtonConfiguration config = configuration ?? GSIButtonConfiguration(); return FutureBuilder( key: Key(config.hashCode.toString()), future: _initialized, diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart b/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart index 61df0777a52b..09e9ef0bcd4b 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/button_configuration.dart @@ -5,9 +5,7 @@ import 'package:google_identity_services_web/id.dart' as id; /// Converts user-facing `GisButtonConfiguration` into the JS-Interop `id.GsiButtonConfiguration`. -id.GsiButtonConfiguration? convertButtonConfiguration( - GSIButtonConfiguration? config, -) { +id.GsiButtonConfiguration? convertButtonConfiguration(GSIButtonConfiguration? config) { if (config == null) { return null; } @@ -93,11 +91,10 @@ enum GSIButtonType { icon, } -const Map _idType = - { - GSIButtonType.icon: id.ButtonType.icon, - GSIButtonType.standard: id.ButtonType.standard, - }; +const Map _idType = { + GSIButtonType.icon: id.ButtonType.icon, + GSIButtonType.standard: id.ButtonType.standard, +}; /// The theme of the button to be rendered. /// @@ -114,12 +111,11 @@ enum GSIButtonTheme { filledBlack, } -const Map _idTheme = - { - GSIButtonTheme.outline: id.ButtonTheme.outline, - GSIButtonTheme.filledBlue: id.ButtonTheme.filled_blue, - GSIButtonTheme.filledBlack: id.ButtonTheme.filled_black, - }; +const Map _idTheme = { + GSIButtonTheme.outline: id.ButtonTheme.outline, + GSIButtonTheme.filledBlue: id.ButtonTheme.filled_blue, + GSIButtonTheme.filledBlack: id.ButtonTheme.filled_black, +}; /// The size of the button to be rendered. /// @@ -136,12 +132,11 @@ enum GSIButtonSize { small, } -const Map _idSize = - { - GSIButtonSize.large: id.ButtonSize.large, - GSIButtonSize.medium: id.ButtonSize.medium, - GSIButtonSize.small: id.ButtonSize.small, - }; +const Map _idSize = { + GSIButtonSize.large: id.ButtonSize.large, + GSIButtonSize.medium: id.ButtonSize.medium, + GSIButtonSize.small: id.ButtonSize.small, +}; /// The button text. /// @@ -161,13 +156,12 @@ enum GSIButtonText { signin, } -const Map _idText = - { - GSIButtonText.signinWith: id.ButtonText.signin_with, - GSIButtonText.signupWith: id.ButtonText.signup_with, - GSIButtonText.continueWith: id.ButtonText.continue_with, - GSIButtonText.signin: id.ButtonText.signin, - }; +const Map _idText = { + GSIButtonText.signinWith: id.ButtonText.signin_with, + GSIButtonText.signupWith: id.ButtonText.signup_with, + GSIButtonText.continueWith: id.ButtonText.continue_with, + GSIButtonText.signin: id.ButtonText.signin, +}; /// The button shape. /// @@ -182,11 +176,10 @@ enum GSIButtonShape { // Does this need circle and square? } -const Map _idShape = - { - GSIButtonShape.rectangular: id.ButtonShape.rectangular, - GSIButtonShape.pill: id.ButtonShape.pill, - }; +const Map _idShape = { + GSIButtonShape.rectangular: id.ButtonShape.rectangular, + GSIButtonShape.pill: id.ButtonShape.pill, +}; /// The alignment of the Google logo. The default value is left. This attribute only applies to the standard button type. /// diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart b/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart index 05a57f6dffca..4eb8f60846a3 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/flexible_size_html_element_view.dart @@ -72,10 +72,7 @@ class _FlexHtmlElementView extends State { } /// The function called whenever an observed resize occurs. - void _onResizeEntries( - JSArray resizes, - web.ResizeObserver observer, - ) { + void _onResizeEntries(JSArray resizes, web.ResizeObserver observer) { final web.DOMRectReadOnly rect = resizes.toDart.last.contentRect; if (rect.width > 0 && rect.height > 0) { // TODO(dit): Remove the following ignore once the repo leaves web:0.5.1 behind. https://github.com/flutter/flutter/issues/152657 @@ -88,10 +85,7 @@ class _FlexHtmlElementView extends State { /// /// When mutations are received, this function attaches a Resize Observer to /// the first child of the mutation, which will drive - void _onMutationRecords( - JSArray mutations, - web.MutationObserver observer, - ) { + void _onMutationRecords(JSArray mutations, web.MutationObserver observer) { for (final web.MutationRecord mutation in mutations.toDart) { if (mutation.addedNodes.length > 0) { final web.Element? element = _locateSizeProvider(mutation.addedNodes); @@ -121,8 +115,7 @@ class _FlexHtmlElementView extends State { viewType: widget.viewType, onPlatformViewCreated: (int viewId) { final ElementCreatedCallback? callback = widget.onElementCreated; - final root = - ui_web.platformViewRegistry.getViewById(viewId) as web.Element; + final root = ui_web.platformViewRegistry.getViewById(viewId) as web.Element; _registerListeners(root); if (callback != null) { callback(root); diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart b/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart index f5620926dac8..7d9daf254365 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart @@ -10,8 +10,7 @@ import 'package:google_identity_services_web/oauth2.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:web/web.dart' as web; -import 'button_configuration.dart' - show GSIButtonConfiguration, convertButtonConfiguration; +import 'button_configuration.dart' show GSIButtonConfiguration, convertButtonConfiguration; import 'utils.dart' as utils; /// A client to hide (most) of the interaction with the GIS SDK from the plugin. @@ -47,11 +46,7 @@ class GisSdkClient { void _logIfEnabled(String message, [List? more]) { if (_loggingEnabled) { - final String log = [ - '[google_sign_in_web]', - message, - ...?more, - ].join(' '); + final String log = ['[google_sign_in_web]', message, ...?more].join(' '); web.console.info(log.toJS); } } @@ -103,8 +98,7 @@ class GisSdkClient { auto_select: true, // Attempt to sign-in silently. nonce: nonce, hd: hostedDomain, - use_fedcm_for_prompt: - useFedCM, // Use the native browser prompt, when available. + use_fedcm_for_prompt: useFedCM, // Use the native browser prompt, when available. ); id.initialize(idConfig); } @@ -185,9 +179,7 @@ class GisSdkClient { break; case MomentDismissedReason.cancel_called: _credentialResponses.addError( - const GoogleSignInException( - code: GoogleSignInExceptionCode.canceled, - ), + const GoogleSignInException(code: GoogleSignInExceptionCode.canceled), ); case MomentDismissedReason.flow_restarted: // Ignore, as this is not a final state. @@ -217,18 +209,13 @@ class GisSdkClient { } /// Calls `id.renderButton` on [parent] with the given [options]. - Future renderButton( - Object parent, - GSIButtonConfiguration options, - ) async { + Future renderButton(Object parent, GSIButtonConfiguration options) async { return id.renderButton(parent, convertButtonConfiguration(options)); } /// Requests a server auth code per: /// https://developers.google.com/identity/oauth2/web/guides/use-code-model#initialize_a_code_client - Future requestServerAuthCode( - AuthorizationRequestDetails request, - ) async { + Future requestServerAuthCode(AuthorizationRequestDetails request) async { final completer = Completer<(String? code, Exception? e)>(); final CodeClient codeClient = _initializeCodeClient( userHint: request.userId, @@ -299,8 +286,7 @@ class GisSdkClient { final (TokenResponse? cachedResponse, DateTime? cacheExpiration) = _lastClientAuthorizationByUser[userHint] ?? (null, null); if (cachedResponse != null) { - final bool isTokenValid = - cacheExpiration?.isAfter(DateTime.now()) ?? false; + final bool isTokenValid = cacheExpiration?.isAfter(DateTime.now()) ?? false; if (isTokenValid && oauth2.hasGrantedAllScopes(cachedResponse, scopes)) { return cachedResponse.access_token; } @@ -323,9 +309,7 @@ class GisSdkClient { if (token == null) { _lastClientAuthorizationByUser.remove(userHint); } else { - final DateTime expiration = DateTime.now().add( - Duration(seconds: response.expires_in!), - ); + final DateTime expiration = DateTime.now().add(Duration(seconds: response.expires_in!)); _lastClientAuthorizationByUser[userHint] = (response, expiration); } completer.complete((response.access_token, null)); @@ -355,9 +339,7 @@ class GisSdkClient { return token; } - GoogleSignInException _exceptionForGisError( - GoogleIdentityServicesError? error, - ) { + GoogleSignInException _exceptionForGisError(GoogleIdentityServicesError? error) { final GoogleSignInExceptionCode code; switch (error?.type) { case GoogleIdentityServicesErrorType.missing_required_parameter: @@ -392,8 +374,7 @@ class GisSdkClient { // request that was not associated with a known user (i.e., no user ID hint // was provided with the request). final Map - _lastClientAuthorizationByUser = - {}; + _lastClientAuthorizationByUser = {}; /// The StreamController onto which the GIS Client propagates user authentication events. /// diff --git a/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart b/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart index d246f5e12e02..4fbc87fe6d43 100644 --- a/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart +++ b/packages/google_sign_in/google_sign_in_web/lib/src/utils.dart @@ -65,9 +65,7 @@ Map? getResponsePayload(CredentialResponse? response) { /// /// May return `null`, if the `credentialResponse` is null, or its `credential` /// cannot be decoded. -AuthenticationEvent? gisResponsesToAuthenticationEvent( - CredentialResponse? credentialResponse, -) { +AuthenticationEvent? gisResponsesToAuthenticationEvent(CredentialResponse? credentialResponse) { final Map? payload = getResponsePayload(credentialResponse); if (payload == null) { return null; @@ -85,9 +83,7 @@ AuthenticationEvent? gisResponsesToAuthenticationEvent( displayName: payload['name'] as String?, photoUrl: payload['picture'] as String?, ), - authenticationTokens: AuthenticationTokenData( - idToken: credentialResponse!.credential, - ), + authenticationTokens: AuthenticationTokenData(idToken: credentialResponse!.credential), ); } @@ -95,9 +91,7 @@ AuthenticationEvent? gisResponsesToAuthenticationEvent( /// /// May return `null` if the `credentialResponse` is null, its `credential` /// cannot be decoded, or the `exp` field is not set on the JWT payload. -DateTime? getCredentialResponseExpirationTimestamp( - CredentialResponse? credentialResponse, -) { +DateTime? getCredentialResponseExpirationTimestamp(CredentialResponse? credentialResponse) { final Map? payload = getResponsePayload(credentialResponse); // Get the 'exp' field from the payload, if present. final int? exp = (payload != null) ? payload['exp'] as int? : null; diff --git a/packages/image_picker/image_picker/example/lib/main.dart b/packages/image_picker/image_picker/example/lib/main.dart index c49b3c121018..221dad2fb6e7 100755 --- a/packages/image_picker/image_picker/example/lib/main.dart +++ b/packages/image_picker/image_picker/example/lib/main.dart @@ -220,15 +220,9 @@ class _MyHomePageState extends State { return retrieveError; } if (_controller == null) { - return const Text( - 'You have not yet picked a video', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked a video', textAlign: TextAlign.center); } - return Padding( - padding: const EdgeInsets.all(10.0), - child: AspectRatioVideo(_controller), - ); + return Padding(padding: const EdgeInsets.all(10.0), child: AspectRatioVideo(_controller)); } Widget _previewImages() { @@ -254,15 +248,9 @@ class _MyHomePageState extends State { ? Image.file( File(_mediaFileList![index].path), errorBuilder: - ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { + (BuildContext context, Object error, StackTrace? stackTrace) { return const Center( - child: Text( - 'This image type is not supported', - ), + child: Text('This image type is not supported'), ); }, ) @@ -273,22 +261,14 @@ class _MyHomePageState extends State { ), ); } else if (_pickImageError != null) { - return Text( - 'Pick image error: $_pickImageError', - textAlign: TextAlign.center, - ); + return Text('Pick image error: $_pickImageError', textAlign: TextAlign.center); } else { - return const Text( - 'You have not yet picked an image.', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked an image.', textAlign: TextAlign.center); } } Widget _buildInlineVideoPlayer(int index) { - final controller = VideoPlayerController.file( - File(_mediaFileList![index].path), - ); + final controller = VideoPlayerController.file(File(_mediaFileList![index].path)); const volume = kIsWeb ? 0.0 : 1.0; controller.setVolume(volume); controller.initialize(); @@ -384,11 +364,7 @@ class _MyHomePageState extends State { child: FloatingActionButton( onPressed: () { isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'image1', tooltip: 'Pick multiple images', @@ -400,11 +376,7 @@ class _MyHomePageState extends State { child: FloatingActionButton( onPressed: () { isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - isMedia: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, isMedia: true); }, heroTag: 'media', tooltip: 'Pick item from gallery', @@ -460,11 +432,7 @@ class _MyHomePageState extends State { backgroundColor: Colors.red, onPressed: () { isVideo = true; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'multiVideo', tooltip: 'Pick multiple videos', @@ -514,36 +482,24 @@ class _MyHomePageState extends State { children: [ TextField( controller: maxWidthController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxWidth if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxWidth if desired'), ), TextField( controller: maxHeightController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxHeight if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxHeight if desired'), ), TextField( controller: qualityController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter quality if desired', - ), + decoration: const InputDecoration(hintText: 'Enter quality if desired'), ), if (isMulti) TextField( controller: limitController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter limit if desired', - ), + decoration: const InputDecoration(hintText: 'Enter limit if desired'), ), ], ), @@ -580,13 +536,12 @@ class _MyHomePageState extends State { } } -typedef OnPickImageCallback = - void Function( - double? maxWidth, - double? maxHeight, - int? quality, - int? limit, - ); +typedef OnPickImageCallback = void Function( + double? maxWidth, + double? maxHeight, + int? quality, + int? limit, +); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {super.key}); diff --git a/packages/image_picker/image_picker/example/lib/readme_excerpts.dart b/packages/image_picker/image_picker/example/lib/readme_excerpts.dart index 8f52ca531559..836f2884a06c 100644 --- a/packages/image_picker/image_picker/example/lib/readme_excerpts.dart +++ b/packages/image_picker/image_picker/example/lib/readme_excerpts.dart @@ -6,6 +6,7 @@ import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; // #docregion CameraDelegate import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; + // #enddocregion CameraDelegate /// Example of a camera delegate @@ -13,20 +14,19 @@ import 'package:image_picker_platform_interface/image_picker_platform_interface. class MyCameraDelegate extends ImagePickerCameraDelegate { @override Future takePhoto({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return _takeAPhoto(options.preferredCameraDevice); } @override Future takeVideo({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return _takeAVideo(options.preferredCameraDevice); } } + // #enddocregion CameraDelegate /// Example function for README demonstration of various pick* calls. @@ -38,9 +38,7 @@ Future> readmePickExample() async { // Capture a photo. final XFile? photo = await picker.pickImage(source: ImageSource.camera); // Pick a video. - final XFile? galleryVideo = await picker.pickVideo( - source: ImageSource.gallery, - ); + final XFile? galleryVideo = await picker.pickVideo(source: ImageSource.gallery); // Capture a video. final XFile? cameraVideo = await picker.pickVideo(source: ImageSource.camera); // Pick multiple images. @@ -78,6 +76,7 @@ Future getLostData() async { _handleError(response.exception); } } + // #enddocregion LostData /// Example of camera delegate setup. @@ -88,6 +87,7 @@ void setUpCameraDelegate() { instance.cameraDelegate = MyCameraDelegate(); } } + // #enddocregion CameraDelegate // Stubs for the getLostData function. diff --git a/packages/image_picker/image_picker/example/test/readme_excerpts_test.dart b/packages/image_picker/image_picker/example/test/readme_excerpts_test.dart index 2231d4738e52..3761db586fff 100644 --- a/packages/image_picker/image_picker/example/test/readme_excerpts_test.dart +++ b/packages/image_picker/image_picker/example/test/readme_excerpts_test.dart @@ -20,10 +20,7 @@ void main() { expect(results.length, greaterThan(4)); // And the calls should all be different. This works since each fake call // returns a different result. - expect( - results.map((XFile? file) => file?.path).toSet().length, - results.length, - ); + expect(results.map((XFile? file) => file?.path).toSet().length, results.length); }); test('sanity check getLostData', () async { diff --git a/packages/image_picker/image_picker/lib/image_picker.dart b/packages/image_picker/image_picker/lib/image_picker.dart index 95fcd19120b9..d354f3e235df 100755 --- a/packages/image_picker/image_picker/lib/image_picker.dart +++ b/packages/image_picker/image_picker/lib/image_picker.dart @@ -85,10 +85,7 @@ class ImagePicker { requestFullMetadata: requestFullMetadata, ); - return platform.getImageFromSource( - source: source, - options: imagePickerOptions, - ); + return platform.getImageFromSource(source: source, options: imagePickerOptions); } /// Returns a [List] object wrapping the images that were picked. @@ -141,10 +138,7 @@ class ImagePicker { ); return platform.getMultiImageWithOptions( - options: MultiImagePickerOptions.createAndValidate( - imageOptions: imageOptions, - limit: limit, - ), + options: MultiImagePickerOptions.createAndValidate(imageOptions: imageOptions, limit: limit), ); } diff --git a/packages/image_picker/image_picker/test/image_picker_test.dart b/packages/image_picker/image_picker/test/image_picker_test.dart index 6230481169f3..c38334eba92c 100644 --- a/packages/image_picker/image_picker/test/image_picker_test.dart +++ b/packages/image_picker/image_picker/test/image_picker_test.dart @@ -16,10 +16,7 @@ import 'image_picker_test.mocks.dart' as base_mock; class _MockImagePickerPlatform extends base_mock.MockImagePickerPlatform with MockPlatformInterfaceMixin {} -@GenerateMocks( - [], - customMocks: >[MockSpec()], -) +@GenerateMocks([], customMocks: >[MockSpec()]) void main() { group('ImagePicker', () { late _MockImagePickerPlatform mockPlatform; @@ -48,17 +45,11 @@ void main() { verifyInOrder([ mockPlatform.getImageFromSource( source: ImageSource.camera, - options: argThat( - isInstanceOf(), - named: 'options', - ), + options: argThat(isInstanceOf(), named: 'options'), ), mockPlatform.getImageFromSource( source: ImageSource.gallery, - options: argThat( - isInstanceOf(), - named: 'options', - ), + options: argThat(isInstanceOf(), named: 'options'), ), ]); }); @@ -68,21 +59,9 @@ void main() { await picker.pickImage(source: ImageSource.camera); await picker.pickImage(source: ImageSource.camera, maxWidth: 10.0); await picker.pickImage(source: ImageSource.camera, maxHeight: 10.0); - await picker.pickImage( - source: ImageSource.camera, - maxWidth: 10.0, - maxHeight: 20.0, - ); - await picker.pickImage( - source: ImageSource.camera, - maxWidth: 10.0, - imageQuality: 70, - ); - await picker.pickImage( - source: ImageSource.camera, - maxHeight: 10.0, - imageQuality: 70, - ); + await picker.pickImage(source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0); + await picker.pickImage(source: ImageSource.camera, maxWidth: 10.0, imageQuality: 70); + await picker.pickImage(source: ImageSource.camera, maxHeight: 10.0, imageQuality: 70); await picker.pickImage( source: ImageSource.camera, maxWidth: 10.0, @@ -95,16 +74,8 @@ void main() { source: ImageSource.camera, options: argThat( isInstanceOf() - .having( - (ImagePickerOptions options) => options.maxWidth, - 'maxWidth', - isNull, - ) - .having( - (ImagePickerOptions options) => options.maxHeight, - 'maxHeight', - isNull, - ) + .having((ImagePickerOptions options) => options.maxWidth, 'maxWidth', isNull) + .having((ImagePickerOptions options) => options.maxHeight, 'maxHeight', isNull) .having( (ImagePickerOptions options) => options.imageQuality, 'imageQuality', @@ -122,11 +93,7 @@ void main() { 'maxWidth', equals(10.0), ) - .having( - (ImagePickerOptions options) => options.maxHeight, - 'maxHeight', - isNull, - ) + .having((ImagePickerOptions options) => options.maxHeight, 'maxHeight', isNull) .having( (ImagePickerOptions options) => options.imageQuality, 'imageQuality', @@ -139,11 +106,7 @@ void main() { source: ImageSource.camera, options: argThat( isInstanceOf() - .having( - (ImagePickerOptions options) => options.maxWidth, - 'maxWidth', - isNull, - ) + .having((ImagePickerOptions options) => options.maxWidth, 'maxWidth', isNull) .having( (ImagePickerOptions options) => options.maxHeight, 'maxHeight', @@ -188,11 +151,7 @@ void main() { 'maxWidth', equals(10.0), ) - .having( - (ImagePickerOptions options) => options.maxHeight, - 'maxHeight', - isNull, - ) + .having((ImagePickerOptions options) => options.maxHeight, 'maxHeight', isNull) .having( (ImagePickerOptions options) => options.imageQuality, 'imageQuality', @@ -205,11 +164,7 @@ void main() { source: ImageSource.camera, options: argThat( isInstanceOf() - .having( - (ImagePickerOptions options) => options.maxWidth, - 'maxWidth', - isNull, - ) + .having((ImagePickerOptions options) => options.maxWidth, 'maxWidth', isNull) .having( (ImagePickerOptions options) => options.maxHeight, 'maxHeight', @@ -330,10 +285,7 @@ void main() { test('passes the full metadata argument correctly', () async { final picker = ImagePicker(); - await picker.pickImage( - source: ImageSource.gallery, - requestFullMetadata: false, - ); + await picker.pickImage(source: ImageSource.gallery, requestFullMetadata: false); verify( mockPlatform.getImageFromSource( @@ -438,40 +390,28 @@ void main() { expect(response.file!.path, '/example/path'); }); - test( - 'retrieveLostData should successfully retrieve multiple files', - () async { - final picker = ImagePicker(); - final lostFiles = [ - XFile('/example/path0'), - XFile('/example/path1'), - ]; - when(mockPlatform.getLostData()).thenAnswer( - (Invocation _) async => LostDataResponse( - file: lostFiles.last, - files: lostFiles, - type: RetrieveType.image, - ), - ); + test('retrieveLostData should successfully retrieve multiple files', () async { + final picker = ImagePicker(); + final lostFiles = [XFile('/example/path0'), XFile('/example/path1')]; + when(mockPlatform.getLostData()).thenAnswer( + (Invocation _) async => + LostDataResponse(file: lostFiles.last, files: lostFiles, type: RetrieveType.image), + ); - final LostDataResponse response = await picker.retrieveLostData(); + final LostDataResponse response = await picker.retrieveLostData(); - expect(response.type, RetrieveType.image); - expect(response.file, isNotNull); - expect(response.file!.path, '/example/path1'); - expect(response.files!.first.path, '/example/path0'); - expect(response.files!.length, 2); - }, - ); + expect(response.type, RetrieveType.image); + expect(response.file, isNotNull); + expect(response.file!.path, '/example/path1'); + expect(response.files!.first.path, '/example/path0'); + expect(response.files!.length, 2); + }); test('retrieveLostData get error response', () async { final picker = ImagePicker(); when(mockPlatform.getLostData()).thenAnswer( (Invocation _) async => LostDataResponse( - exception: PlatformException( - code: 'test_error_code', - message: 'test_error_message', - ), + exception: PlatformException(code: 'test_error_code', message: 'test_error_message'), type: RetrieveType.video, ), ); @@ -499,10 +439,7 @@ void main() { verifyInOrder([ mockPlatform.getMultiVideoWithOptions( - options: argThat( - isInstanceOf(), - named: 'options', - ), + options: argThat(isInstanceOf(), named: 'options'), ), mockPlatform.getMultiVideoWithOptions( options: argThat( @@ -545,30 +482,17 @@ void main() { await picker.pickMultiImage(maxWidth: 10.0, maxHeight: 20.0); await picker.pickMultiImage(maxWidth: 10.0, imageQuality: 70); await picker.pickMultiImage(maxHeight: 10.0, imageQuality: 70); - await picker.pickMultiImage( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); - await picker.pickMultiImage( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - limit: 5, - ); + await picker.pickMultiImage(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); + await picker.pickMultiImage(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70, limit: 5); verifyInOrder([ mockPlatform.getMultiImageWithOptions( - options: argThat( - isInstanceOf(), - named: 'options', - ), + options: argThat(isInstanceOf(), named: 'options'), ), mockPlatform.getMultiImageWithOptions( options: argThat( isInstanceOf().having( - (MultiImagePickerOptions options) => - options.imageOptions.maxWidth, + (MultiImagePickerOptions options) => options.imageOptions.maxWidth, 'maxWidth', equals(10.0), ), @@ -578,8 +502,7 @@ void main() { mockPlatform.getMultiImageWithOptions( options: argThat( isInstanceOf().having( - (MultiImagePickerOptions options) => - options.imageOptions.maxHeight, + (MultiImagePickerOptions options) => options.imageOptions.maxHeight, 'maxHeight', equals(10.0), ), @@ -590,14 +513,12 @@ void main() { options: argThat( isInstanceOf() .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxWidth, + (MultiImagePickerOptions options) => options.imageOptions.maxWidth, 'maxWidth', equals(10.0), ) .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxHeight, + (MultiImagePickerOptions options) => options.imageOptions.maxHeight, 'maxHeight', equals(20.0), ), @@ -608,14 +529,12 @@ void main() { options: argThat( isInstanceOf() .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxWidth, + (MultiImagePickerOptions options) => options.imageOptions.maxWidth, 'maxWidth', equals(10.0), ) .having( - (MultiImagePickerOptions options) => - options.imageOptions.imageQuality, + (MultiImagePickerOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -626,14 +545,12 @@ void main() { options: argThat( isInstanceOf() .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxHeight, + (MultiImagePickerOptions options) => options.imageOptions.maxHeight, 'maxHeight', equals(10.0), ) .having( - (MultiImagePickerOptions options) => - options.imageOptions.imageQuality, + (MultiImagePickerOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -644,20 +561,17 @@ void main() { options: argThat( isInstanceOf() .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxWidth, + (MultiImagePickerOptions options) => options.imageOptions.maxWidth, 'maxWidth', equals(10.0), ) .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxHeight, + (MultiImagePickerOptions options) => options.imageOptions.maxHeight, 'maxHeight', equals(20.0), ) .having( - (MultiImagePickerOptions options) => - options.imageOptions.imageQuality, + (MultiImagePickerOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -668,28 +582,21 @@ void main() { options: argThat( isInstanceOf() .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxWidth, + (MultiImagePickerOptions options) => options.imageOptions.maxWidth, 'maxWidth', equals(10.0), ) .having( - (MultiImagePickerOptions options) => - options.imageOptions.maxHeight, + (MultiImagePickerOptions options) => options.imageOptions.maxHeight, 'maxHeight', equals(20.0), ) .having( - (MultiImagePickerOptions options) => - options.imageOptions.imageQuality, + (MultiImagePickerOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ) - .having( - (MultiImagePickerOptions options) => options.limit, - 'limit', - equals(5), - ), + .having((MultiImagePickerOptions options) => options.limit, 'limit', equals(5)), named: 'options', ), ), @@ -698,15 +605,9 @@ void main() { test('does not accept a negative width or height argument', () { final picker = ImagePicker(); - expect( - () => picker.pickMultiImage(maxWidth: -1.0), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(maxWidth: -1.0), throwsArgumentError); - expect( - () => picker.pickMultiImage(maxHeight: -1.0), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(maxHeight: -1.0), throwsArgumentError); }); test('does not accept a limit argument lower than 2', () { @@ -733,8 +634,7 @@ void main() { mockPlatform.getMultiImageWithOptions( options: argThat( isInstanceOf().having( - (MultiImagePickerOptions options) => - options.imageOptions.requestFullMetadata, + (MultiImagePickerOptions options) => options.imageOptions.requestFullMetadata, 'requestFullMetadata', isTrue, ), @@ -752,8 +652,7 @@ void main() { mockPlatform.getMultiImageWithOptions( options: argThat( isInstanceOf().having( - (MultiImagePickerOptions options) => - options.imageOptions.requestFullMetadata, + (MultiImagePickerOptions options) => options.imageOptions.requestFullMetadata, 'requestFullMetadata', isFalse, ), @@ -781,21 +680,11 @@ void main() { await picker.pickMedia(maxWidth: 10.0, maxHeight: 20.0); await picker.pickMedia(maxWidth: 10.0, imageQuality: 70); await picker.pickMedia(maxHeight: 10.0, imageQuality: 70); - await picker.pickMedia( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); - await picker.pickMedia( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); + await picker.pickMedia(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); + await picker.pickMedia(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); verifyInOrder([ - mockPlatform.getMedia( - options: argThat(isInstanceOf(), named: 'options'), - ), + mockPlatform.getMedia(options: argThat(isInstanceOf(), named: 'options')), mockPlatform.getMedia( options: argThat( isInstanceOf().having( @@ -841,8 +730,7 @@ void main() { equals(10.0), ) .having( - (MediaOptions options) => - options.imageOptions.imageQuality, + (MediaOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -858,8 +746,7 @@ void main() { equals(10.0), ) .having( - (MediaOptions options) => - options.imageOptions.imageQuality, + (MediaOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -880,8 +767,7 @@ void main() { equals(10.0), ) .having( - (MediaOptions options) => - options.imageOptions.imageQuality, + (MediaOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -913,8 +799,7 @@ void main() { mockPlatform.getMedia( options: argThat( isInstanceOf().having( - (MediaOptions options) => - options.imageOptions.requestFullMetadata, + (MediaOptions options) => options.imageOptions.requestFullMetadata, 'requestFullMetadata', isTrue, ), @@ -932,8 +817,7 @@ void main() { mockPlatform.getMedia( options: argThat( isInstanceOf().having( - (MediaOptions options) => - options.imageOptions.requestFullMetadata, + (MediaOptions options) => options.imageOptions.requestFullMetadata, 'requestFullMetadata', isFalse, ), @@ -953,11 +837,7 @@ void main() { await picker.pickMultipleMedia(maxWidth: 10.0, maxHeight: 20.0); await picker.pickMultipleMedia(maxWidth: 10.0, imageQuality: 70); await picker.pickMultipleMedia(maxHeight: 10.0, imageQuality: 70); - await picker.pickMultipleMedia( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); + await picker.pickMultipleMedia(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); await picker.pickMultipleMedia( maxWidth: 10.0, maxHeight: 20.0, @@ -966,9 +846,7 @@ void main() { ); verifyInOrder([ - mockPlatform.getMedia( - options: argThat(isInstanceOf(), named: 'options'), - ), + mockPlatform.getMedia(options: argThat(isInstanceOf(), named: 'options')), mockPlatform.getMedia( options: argThat( isInstanceOf().having( @@ -1014,8 +892,7 @@ void main() { equals(10.0), ) .having( - (MediaOptions options) => - options.imageOptions.imageQuality, + (MediaOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -1031,8 +908,7 @@ void main() { equals(10.0), ) .having( - (MediaOptions options) => - options.imageOptions.imageQuality, + (MediaOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -1053,8 +929,7 @@ void main() { equals(10.0), ) .having( - (MediaOptions options) => - options.imageOptions.imageQuality, + (MediaOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ), @@ -1075,16 +950,11 @@ void main() { equals(10.0), ) .having( - (MediaOptions options) => - options.imageOptions.imageQuality, + (MediaOptions options) => options.imageOptions.imageQuality, 'imageQuality', equals(70), ) - .having( - (MediaOptions options) => options.limit, - 'limit', - equals(5), - ), + .having((MediaOptions options) => options.limit, 'limit', equals(5)), named: 'options', ), ), @@ -1093,23 +963,14 @@ void main() { test('does not accept a negative width or height argument', () { final picker = ImagePicker(); - expect( - () => picker.pickMultipleMedia(maxWidth: -1.0), - throwsArgumentError, - ); + expect(() => picker.pickMultipleMedia(maxWidth: -1.0), throwsArgumentError); - expect( - () => picker.pickMultipleMedia(maxHeight: -1.0), - throwsArgumentError, - ); + expect(() => picker.pickMultipleMedia(maxHeight: -1.0), throwsArgumentError); }); test('does not accept a limit argument lower than 2', () { final picker = ImagePicker(); - expect( - () => picker.pickMultipleMedia(limit: -1), - throwsArgumentError, - ); + expect(() => picker.pickMultipleMedia(limit: -1), throwsArgumentError); expect(() => picker.pickMultipleMedia(limit: 0), throwsArgumentError); @@ -1131,8 +992,7 @@ void main() { mockPlatform.getMedia( options: argThat( isInstanceOf().having( - (MediaOptions options) => - options.imageOptions.requestFullMetadata, + (MediaOptions options) => options.imageOptions.requestFullMetadata, 'requestFullMetadata', isTrue, ), @@ -1150,8 +1010,7 @@ void main() { mockPlatform.getMedia( options: argThat( isInstanceOf().having( - (MediaOptions options) => - options.imageOptions.requestFullMetadata, + (MediaOptions options) => options.imageOptions.requestFullMetadata, 'requestFullMetadata', isFalse, ), diff --git a/packages/image_picker/image_picker/test/image_picker_test.mocks.dart b/packages/image_picker/image_picker/test/image_picker_test.mocks.dart index 6aaca18fcac5..2766142dc2bf 100644 --- a/packages/image_picker/image_picker/test/image_picker_test.mocks.dart +++ b/packages/image_picker/image_picker/test/image_picker_test.mocks.dart @@ -26,12 +26,10 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class class _FakeLostData_0 extends _i1.SmartFake implements _i2.LostData { - _FakeLostData_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeLostData_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeLostDataResponse_1 extends _i1.SmartFake - implements _i2.LostDataResponse { +class _FakeLostDataResponse_1 extends _i1.SmartFake implements _i2.LostDataResponse { _FakeLostDataResponse_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -39,8 +37,7 @@ class _FakeLostDataResponse_1 extends _i1.SmartFake /// A class which mocks [ImagePickerPlatform]. /// /// See the documentation for Mockito's code generation for more information. -class MockImagePickerPlatform extends _i1.Mock - implements _i3.ImagePickerPlatform { +class MockImagePickerPlatform extends _i1.Mock implements _i3.ImagePickerPlatform { MockImagePickerPlatform() { _i1.throwOnMissingStub(this); } @@ -52,60 +49,52 @@ class MockImagePickerPlatform extends _i1.Mock double? maxHeight, int? imageQuality, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, - }) => - (super.noSuchMethod( - Invocation.method(#pickImage, [], { - #source: source, - #maxWidth: maxWidth, - #maxHeight: maxHeight, - #imageQuality: imageQuality, - #preferredCameraDevice: preferredCameraDevice, - }), - returnValue: _i4.Future<_i2.PickedFile?>.value(), - ) - as _i4.Future<_i2.PickedFile?>); + }) => (super.noSuchMethod( + Invocation.method(#pickImage, [], { + #source: source, + #maxWidth: maxWidth, + #maxHeight: maxHeight, + #imageQuality: imageQuality, + #preferredCameraDevice: preferredCameraDevice, + }), + returnValue: _i4.Future<_i2.PickedFile?>.value(), + ) as _i4.Future<_i2.PickedFile?>); @override _i4.Future?> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, - }) => - (super.noSuchMethod( - Invocation.method(#pickMultiImage, [], { - #maxWidth: maxWidth, - #maxHeight: maxHeight, - #imageQuality: imageQuality, - }), - returnValue: _i4.Future?>.value(), - ) - as _i4.Future?>); + }) => (super.noSuchMethod( + Invocation.method(#pickMultiImage, [], { + #maxWidth: maxWidth, + #maxHeight: maxHeight, + #imageQuality: imageQuality, + }), + returnValue: _i4.Future?>.value(), + ) as _i4.Future?>); @override _i4.Future<_i2.PickedFile?> pickVideo({ required _i2.ImageSource? source, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, Duration? maxDuration, - }) => - (super.noSuchMethod( - Invocation.method(#pickVideo, [], { - #source: source, - #preferredCameraDevice: preferredCameraDevice, - #maxDuration: maxDuration, - }), - returnValue: _i4.Future<_i2.PickedFile?>.value(), - ) - as _i4.Future<_i2.PickedFile?>); + }) => (super.noSuchMethod( + Invocation.method(#pickVideo, [], { + #source: source, + #preferredCameraDevice: preferredCameraDevice, + #maxDuration: maxDuration, + }), + returnValue: _i4.Future<_i2.PickedFile?>.value(), + ) as _i4.Future<_i2.PickedFile?>); @override - _i4.Future<_i2.LostData> retrieveLostData() => - (super.noSuchMethod( - Invocation.method(#retrieveLostData, []), - returnValue: _i4.Future<_i2.LostData>.value( - _FakeLostData_0(this, Invocation.method(#retrieveLostData, [])), - ), - ) - as _i4.Future<_i2.LostData>); + _i4.Future<_i2.LostData> retrieveLostData() => (super.noSuchMethod( + Invocation.method(#retrieveLostData, []), + returnValue: _i4.Future<_i2.LostData>.value( + _FakeLostData_0(this, Invocation.method(#retrieveLostData, [])), + ), + ) as _i4.Future<_i2.LostData>); @override _i4.Future<_i5.XFile?> getImage({ @@ -114,115 +103,86 @@ class MockImagePickerPlatform extends _i1.Mock double? maxHeight, int? imageQuality, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, - }) => - (super.noSuchMethod( - Invocation.method(#getImage, [], { - #source: source, - #maxWidth: maxWidth, - #maxHeight: maxHeight, - #imageQuality: imageQuality, - #preferredCameraDevice: preferredCameraDevice, - }), - returnValue: _i4.Future<_i5.XFile?>.value(), - ) - as _i4.Future<_i5.XFile?>); + }) => (super.noSuchMethod( + Invocation.method(#getImage, [], { + #source: source, + #maxWidth: maxWidth, + #maxHeight: maxHeight, + #imageQuality: imageQuality, + #preferredCameraDevice: preferredCameraDevice, + }), + returnValue: _i4.Future<_i5.XFile?>.value(), + ) as _i4.Future<_i5.XFile?>); @override _i4.Future?> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, - }) => - (super.noSuchMethod( - Invocation.method(#getMultiImage, [], { - #maxWidth: maxWidth, - #maxHeight: maxHeight, - #imageQuality: imageQuality, - }), - returnValue: _i4.Future?>.value(), - ) - as _i4.Future?>); + }) => (super.noSuchMethod( + Invocation.method(#getMultiImage, [], { + #maxWidth: maxWidth, + #maxHeight: maxHeight, + #imageQuality: imageQuality, + }), + returnValue: _i4.Future?>.value(), + ) as _i4.Future?>); @override - _i4.Future> getMedia({required _i2.MediaOptions? options}) => - (super.noSuchMethod( - Invocation.method(#getMedia, [], {#options: options}), - returnValue: _i4.Future>.value(<_i5.XFile>[]), - ) - as _i4.Future>); + _i4.Future> getMedia({required _i2.MediaOptions? options}) => (super.noSuchMethod( + Invocation.method(#getMedia, [], {#options: options}), + returnValue: _i4.Future>.value(<_i5.XFile>[]), + ) as _i4.Future>); @override _i4.Future<_i5.XFile?> getVideo({ required _i2.ImageSource? source, _i2.CameraDevice? preferredCameraDevice = _i2.CameraDevice.rear, Duration? maxDuration, - }) => - (super.noSuchMethod( - Invocation.method(#getVideo, [], { - #source: source, - #preferredCameraDevice: preferredCameraDevice, - #maxDuration: maxDuration, - }), - returnValue: _i4.Future<_i5.XFile?>.value(), - ) - as _i4.Future<_i5.XFile?>); + }) => (super.noSuchMethod( + Invocation.method(#getVideo, [], { + #source: source, + #preferredCameraDevice: preferredCameraDevice, + #maxDuration: maxDuration, + }), + returnValue: _i4.Future<_i5.XFile?>.value(), + ) as _i4.Future<_i5.XFile?>); @override - _i4.Future<_i2.LostDataResponse> getLostData() => - (super.noSuchMethod( - Invocation.method(#getLostData, []), - returnValue: _i4.Future<_i2.LostDataResponse>.value( - _FakeLostDataResponse_1( - this, - Invocation.method(#getLostData, []), - ), - ), - ) - as _i4.Future<_i2.LostDataResponse>); + _i4.Future<_i2.LostDataResponse> getLostData() => (super.noSuchMethod( + Invocation.method(#getLostData, []), + returnValue: _i4.Future<_i2.LostDataResponse>.value( + _FakeLostDataResponse_1(this, Invocation.method(#getLostData, [])), + ), + ) as _i4.Future<_i2.LostDataResponse>); @override _i4.Future<_i5.XFile?> getImageFromSource({ required _i2.ImageSource? source, _i2.ImagePickerOptions? options = const _i2.ImagePickerOptions(), - }) => - (super.noSuchMethod( - Invocation.method(#getImageFromSource, [], { - #source: source, - #options: options, - }), - returnValue: _i4.Future<_i5.XFile?>.value(), - ) - as _i4.Future<_i5.XFile?>); + }) => (super.noSuchMethod( + Invocation.method(#getImageFromSource, [], {#source: source, #options: options}), + returnValue: _i4.Future<_i5.XFile?>.value(), + ) as _i4.Future<_i5.XFile?>); @override _i4.Future> getMultiImageWithOptions({ _i2.MultiImagePickerOptions? options = const _i2.MultiImagePickerOptions(), - }) => - (super.noSuchMethod( - Invocation.method(#getMultiImageWithOptions, [], { - #options: options, - }), - returnValue: _i4.Future>.value(<_i5.XFile>[]), - ) - as _i4.Future>); + }) => (super.noSuchMethod( + Invocation.method(#getMultiImageWithOptions, [], {#options: options}), + returnValue: _i4.Future>.value(<_i5.XFile>[]), + ) as _i4.Future>); @override _i4.Future> getMultiVideoWithOptions({ _i2.MultiVideoPickerOptions? options = const _i2.MultiVideoPickerOptions(), - }) => - (super.noSuchMethod( - Invocation.method(#getMultiVideoWithOptions, [], { - #options: options, - }), - returnValue: _i4.Future>.value(<_i5.XFile>[]), - ) - as _i4.Future>); + }) => (super.noSuchMethod( + Invocation.method(#getMultiVideoWithOptions, [], {#options: options}), + returnValue: _i4.Future>.value(<_i5.XFile>[]), + ) as _i4.Future>); @override bool supportsImageSource(_i2.ImageSource? source) => - (super.noSuchMethod( - Invocation.method(#supportsImageSource, [source]), - returnValue: false, - ) + (super.noSuchMethod(Invocation.method(#supportsImageSource, [source]), returnValue: false) as bool); } diff --git a/packages/image_picker/image_picker_android/example/lib/main.dart b/packages/image_picker/image_picker_android/example/lib/main.dart index 2fb883526de9..eaa970ba8582 100755 --- a/packages/image_picker/image_picker_android/example/lib/main.dart +++ b/packages/image_picker/image_picker_android/example/lib/main.dart @@ -26,8 +26,7 @@ void appMain() { void main() { // Set to use Android Photo Picker. // #docregion photo-picker-example - final ImagePickerPlatform imagePickerImplementation = - ImagePickerPlatform.instance; + final ImagePickerPlatform imagePickerImplementation = ImagePickerPlatform.instance; if (imagePickerImplementation is ImagePickerAndroid) { imagePickerImplementation.useAndroidPhotoPicker = true; } @@ -137,10 +136,7 @@ class _MyHomePageState extends State { ), ) : await _picker.getMultiImageWithOptions( - options: MultiImagePickerOptions( - imageOptions: imageOptions, - limit: limit, - ), + options: MultiImagePickerOptions(imageOptions: imageOptions, limit: limit), ); if (pickedFileList.isNotEmpty && context.mounted) { _showPickedSnackBar(context, pickedFileList); @@ -246,15 +242,9 @@ class _MyHomePageState extends State { return retrieveError; } if (_controller == null) { - return const Text( - 'You have not yet picked a video', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked a video', textAlign: TextAlign.center); } - return Padding( - padding: const EdgeInsets.all(10.0), - child: AspectRatioVideo(_controller), - ); + return Padding(padding: const EdgeInsets.all(10.0), child: AspectRatioVideo(_controller)); } Widget _previewImages() { @@ -273,25 +263,16 @@ class _MyHomePageState extends State { return Column( mainAxisSize: MainAxisSize.min, children: [ - Text( - image.name, - key: const Key('image_picker_example_picked_image_name'), - ), + Text(image.name, key: const Key('image_picker_example_picked_image_name')), Semantics( label: 'image_picker_example_picked_image', child: mime == null || mime.startsWith('image/') ? Image.file( File(_mediaFileList![index].path), errorBuilder: - ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { + (BuildContext context, Object error, StackTrace? stackTrace) { return const Center( - child: Text( - 'This image type is not supported', - ), + child: Text('This image type is not supported'), ); }, ) @@ -304,22 +285,14 @@ class _MyHomePageState extends State { ), ); } else if (_pickImageError != null) { - return Text( - 'Pick image error: $_pickImageError', - textAlign: TextAlign.center, - ); + return Text('Pick image error: $_pickImageError', textAlign: TextAlign.center); } else { - return const Text( - 'You have not yet picked an image.', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked an image.', textAlign: TextAlign.center); } } Widget _buildInlineVideoPlayer(int index) { - final controller = VideoPlayerController.file( - File(_mediaFileList![index].path), - ); + final controller = VideoPlayerController.file(File(_mediaFileList![index].path)); controller.setVolume(1.0); controller.initialize(); controller.setLooping(true); @@ -417,11 +390,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'image1', tooltip: 'Pick multiple images', @@ -434,11 +403,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - isMedia: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, isMedia: true); }, heroTag: 'media', tooltip: 'Pick item from gallery', @@ -497,11 +462,7 @@ class _MyHomePageState extends State { backgroundColor: Colors.red, onPressed: () { _isVideo = true; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'multiVideo', tooltip: 'Pick multiple videos', @@ -551,36 +512,24 @@ class _MyHomePageState extends State { children: [ TextField( controller: maxWidthController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxWidth if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxWidth if desired'), ), TextField( controller: maxHeightController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxHeight if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxHeight if desired'), ), TextField( controller: qualityController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter quality if desired', - ), + decoration: const InputDecoration(hintText: 'Enter quality if desired'), ), if (isMulti) TextField( controller: limitController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter limit if desired', - ), + decoration: const InputDecoration(hintText: 'Enter limit if desired'), ), ], ), @@ -626,13 +575,12 @@ class _MyHomePageState extends State { } } -typedef OnPickImageCallback = - void Function( - double? maxWidth, - double? maxHeight, - int? quality, - int? limit, - ); +typedef OnPickImageCallback = void Function( + double? maxWidth, + double? maxHeight, + int? quality, + int? limit, +); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {super.key}); diff --git a/packages/image_picker/image_picker_android/lib/image_picker_android.dart b/packages/image_picker/image_picker_android/lib/image_picker_android.dart index fd7080f536b5..acb79a4d2db4 100644 --- a/packages/image_picker/image_picker_android/lib/image_picker_android.dart +++ b/packages/image_picker/image_picker_android/lib/image_picker_android.dart @@ -12,8 +12,7 @@ import 'src/messages.g.dart'; /// An Android implementation of [ImagePickerPlatform]. class ImagePickerAndroid extends ImagePickerPlatform { /// Creates a new plugin implementation instance. - ImagePickerAndroid({@visibleForTesting ImagePickerApi? api}) - : _hostApi = api ?? ImagePickerApi(); + ImagePickerAndroid({@visibleForTesting ImagePickerApi? api}) : _hostApi = api ?? ImagePickerApi(); final ImagePickerApi _hostApi; @@ -70,11 +69,7 @@ class ImagePickerAndroid extends ImagePickerPlatform { int? limit, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { @@ -91,16 +86,8 @@ class ImagePickerAndroid extends ImagePickerPlatform { return _hostApi.pickImages( SourceSpecification(type: SourceType.gallery), - ImageSelectionOptions( - maxWidth: maxWidth, - maxHeight: maxHeight, - quality: imageQuality ?? 100, - ), - GeneralOptions( - allowMultiple: true, - usePhotoPicker: useAndroidPhotoPicker, - limit: limit, - ), + ImageSelectionOptions(maxWidth: maxWidth, maxHeight: maxHeight, quality: imageQuality ?? 100), + GeneralOptions(allowMultiple: true, usePhotoPicker: useAndroidPhotoPicker, limit: limit), ); } @@ -113,11 +100,7 @@ class ImagePickerAndroid extends ImagePickerPlatform { bool requestFullMetadata = true, }) async { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { @@ -130,15 +113,8 @@ class ImagePickerAndroid extends ImagePickerPlatform { final List paths = await _hostApi.pickImages( _buildSourceSpec(source, preferredCameraDevice), - ImageSelectionOptions( - maxWidth: maxWidth, - maxHeight: maxHeight, - quality: imageQuality ?? 100, - ), - GeneralOptions( - allowMultiple: false, - usePhotoPicker: useAndroidPhotoPicker, - ), + ImageSelectionOptions(maxWidth: maxWidth, maxHeight: maxHeight, quality: imageQuality ?? 100), + GeneralOptions(allowMultiple: false, usePhotoPicker: useAndroidPhotoPicker), ); return paths.isEmpty ? null : paths.first; } @@ -165,10 +141,7 @@ class ImagePickerAndroid extends ImagePickerPlatform { final List paths = await _hostApi.pickVideos( _buildSourceSpec(source, preferredCameraDevice), VideoSelectionOptions(maxDurationSeconds: maxDuration?.inSeconds), - GeneralOptions( - allowMultiple: false, - usePhotoPicker: useAndroidPhotoPicker, - ), + GeneralOptions(allowMultiple: false, usePhotoPicker: useAndroidPhotoPicker), ); return paths.isEmpty ? null : paths.first; } @@ -286,13 +259,9 @@ class ImagePickerAndroid extends ImagePickerPlatform { return paths.map((String path) => XFile(path)).toList(); } - MediaSelectionOptions _mediaOptionsToMediaSelectionOptions( - MediaOptions mediaOptions, - ) { + MediaSelectionOptions _mediaOptionsToMediaSelectionOptions(MediaOptions mediaOptions) { final ImageSelectionOptions imageSelectionOptions = - _imageOptionsToImageSelectionOptionsWithValidator( - mediaOptions.imageOptions, - ); + _imageOptionsToImageSelectionOptionsWithValidator(mediaOptions.imageOptions); return MediaSelectionOptions(imageSelectionOptions: imageSelectionOptions); } @@ -305,11 +274,7 @@ class ImagePickerAndroid extends ImagePickerPlatform { final int? imageQuality = imageOptions?.imageQuality; if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { @@ -382,9 +347,7 @@ class ImagePickerAndroid extends ImagePickerPlatform { // Entries are guaranteed not to be null, even though that's not currently // expressible in Pigeon. - final List pickedFileList = result.paths - .map((String? path) => XFile(path!)) - .toList(); + final List pickedFileList = result.paths.map((String? path) => XFile(path!)).toList(); return LostDataResponse( file: pickedFileList.isEmpty ? null : pickedFileList.last, @@ -394,10 +357,7 @@ class ImagePickerAndroid extends ImagePickerPlatform { ); } - SourceSpecification _buildSourceSpec( - ImageSource source, - CameraDevice device, - ) { + SourceSpecification _buildSourceSpec(ImageSource source, CameraDevice device) { return SourceSpecification( type: _sourceSpecTypeForSource(source), camera: _sourceSpecCameraForDevice(device), diff --git a/packages/image_picker/image_picker_android/lib/src/messages.g.dart b/packages/image_picker/image_picker_android/lib/src/messages.g.dart index 3952984b7ebb..8408a50e6947 100644 --- a/packages/image_picker/image_picker_android/lib/src/messages.g.dart +++ b/packages/image_picker/image_picker_android/lib/src/messages.g.dart @@ -49,9 +49,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -107,11 +105,7 @@ enum SourceType { camera, gallery } enum CacheRetrievalType { image, video } class GeneralOptions { - GeneralOptions({ - required this.allowMultiple, - required this.usePhotoPicker, - this.limit, - }); + GeneralOptions({required this.allowMultiple, required this.usePhotoPicker, this.limit}); bool allowMultiple; @@ -221,9 +215,7 @@ class MediaSelectionOptions { static MediaSelectionOptions decode(Object result) { result as List; - return MediaSelectionOptions( - imageSelectionOptions: result[0]! as ImageSelectionOptions, - ); + return MediaSelectionOptions(imageSelectionOptions: result[0]! as ImageSelectionOptions); } @override @@ -298,10 +290,7 @@ class SourceSpecification { static SourceSpecification decode(Object result) { result as List; - return SourceSpecification( - type: result[0]! as SourceType, - camera: result[1] as SourceCamera?, - ); + return SourceSpecification(type: result[0]! as SourceType, camera: result[1] as SourceCamera?); } @override @@ -341,10 +330,7 @@ class CacheRetrievalError { static CacheRetrievalError decode(Object result) { result as List; - return CacheRetrievalError( - code: result[0]! as String, - message: result[1] as String?, - ); + return CacheRetrievalError(code: result[0]! as String, message: result[1] as String?); } @override @@ -366,11 +352,7 @@ class CacheRetrievalError { /// The result of retrieving cached results from a previous run. class CacheRetrievalResult { - CacheRetrievalResult({ - required this.type, - this.error, - this.paths = const [], - }); + CacheRetrievalResult({required this.type, this.error, this.paths = const []}); /// The type of the retrieved data. CacheRetrievalType type; @@ -495,13 +477,11 @@ class ImagePickerApi { /// Constructor for [ImagePickerApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - ImagePickerApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + ImagePickerApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -521,9 +501,11 @@ class ImagePickerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [source, options, generalOptions], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + source, + options, + generalOptions, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -547,9 +529,11 @@ class ImagePickerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [source, options, generalOptions], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + source, + options, + generalOptions, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -572,9 +556,10 @@ class ImagePickerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [mediaSelectionOptions, generalOptions], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + mediaSelectionOptions, + generalOptions, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( diff --git a/packages/image_picker/image_picker_android/pigeons/messages.dart b/packages/image_picker/image_picker_android/pigeons/messages.dart index 502cd575e069..3f91422cef4a 100644 --- a/packages/image_picker/image_picker_android/pigeons/messages.dart +++ b/packages/image_picker/image_picker_android/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/imagepicker/Messages.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/imagepicker/Messages.kt', kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.imagepicker'), copyrightHeader: 'pigeons/copyright.txt', ), @@ -77,11 +76,7 @@ enum CacheRetrievalType { image, video } /// The result of retrieving cached results from a previous run. class CacheRetrievalResult { - CacheRetrievalResult({ - required this.type, - this.error, - this.paths = const [], - }); + CacheRetrievalResult({required this.type, this.error, this.paths = const []}); /// The type of the retrieved data. final CacheRetrievalType type; diff --git a/packages/image_picker/image_picker_android/test/image_picker_android_test.dart b/packages/image_picker/image_picker_android/test/image_picker_android_test.dart index 891764af5d36..7d05b51a3092 100644 --- a/packages/image_picker/image_picker_android/test/image_picker_android_test.dart +++ b/packages/image_picker/image_picker_android/test/image_picker_android_test.dart @@ -27,9 +27,7 @@ void main() { test('calls the method correctly', () async { const fakePath = '/foo.jpg'; api.returnValue = [fakePath]; - final PickedFile? result = await picker.pickImage( - source: ImageSource.camera, - ); + final PickedFile? result = await picker.pickImage(source: ImageSource.camera); expect(result?.path, fakePath); expect(api.lastCall, _LastPickType.image); @@ -117,10 +115,7 @@ void main() { }); test('camera position can be set to front', () async { - await picker.pickImage( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.pickImage(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -163,11 +158,7 @@ void main() { }); test('passes image option arguments correctly', () async { - await picker.pickMultiImage( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); + await picker.pickMultiImage(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); @@ -181,15 +172,9 @@ void main() { }); test('does not accept an invalid imageQuality argument', () { - expect( - () => picker.pickMultiImage(imageQuality: -1), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(imageQuality: -1), throwsArgumentError); - expect( - () => picker.pickMultiImage(imageQuality: 101), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(imageQuality: 101), throwsArgumentError); }); test('handles an empty path response gracefully', () async { @@ -216,9 +201,7 @@ void main() { test('calls the method correctly', () async { const fakePath = '/foo.jpg'; api.returnValue = [fakePath]; - final PickedFile? result = await picker.pickVideo( - source: ImageSource.camera, - ); + final PickedFile? result = await picker.pickVideo(source: ImageSource.camera); expect(result?.path, fakePath); expect(api.lastCall, _LastPickType.video); @@ -245,10 +228,7 @@ void main() { }); test('passes the duration argument correctly', () async { - await picker.pickVideo( - source: ImageSource.camera, - maxDuration: const Duration(minutes: 1), - ); + await picker.pickVideo(source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); expect(api.passedVideoOptions?.maxDurationSeconds, 60); }); @@ -267,10 +247,7 @@ void main() { }); test('camera position can set to front', () async { - await picker.pickVideo( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.pickVideo(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -306,10 +283,7 @@ void main() { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: [], - error: CacheRetrievalError( - code: 'test_error_code', - message: 'test_error_message', - ), + error: CacheRetrievalError(code: 'test_error_code', message: 'test_error_message'), ); final LostData response = await picker.retrieveLostData(); @@ -329,10 +303,7 @@ void main() { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: ['/example/path'], - error: CacheRetrievalError( - code: 'test_error_code', - message: 'test_error_message', - ), + error: CacheRetrievalError(code: 'test_error_code', message: 'test_error_message'), ); expect(picker.retrieveLostData(), throwsAssertionError); @@ -431,10 +402,7 @@ void main() { }); test('camera position can set to front', () async { - await picker.getImage( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.getImage(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -477,11 +445,7 @@ void main() { }); test('passes image option arguments correctly', () async { - await picker.getMultiImage( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); + await picker.getMultiImage(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); expect(api.passedImageOptions?.maxWidth, 10.0); expect(api.passedImageOptions?.maxHeight, 20.0); @@ -497,10 +461,7 @@ void main() { test('does not accept an invalid imageQuality argument', () { expect(() => picker.getMultiImage(imageQuality: -1), throwsArgumentError); - expect( - () => picker.getMultiImage(imageQuality: 101), - throwsArgumentError, - ); + expect(() => picker.getMultiImage(imageQuality: 101), throwsArgumentError); }); test('handles an empty image path response gracefully', () async { @@ -555,10 +516,7 @@ void main() { }); test('passes the duration argument correctly', () async { - await picker.getVideo( - source: ImageSource.camera, - maxDuration: const Duration(minutes: 1), - ); + await picker.getVideo(source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); expect(api.passedVideoOptions?.maxDurationSeconds, 60); }); @@ -577,10 +535,7 @@ void main() { }); test('camera position can set to front', () async { - await picker.getVideo( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.getVideo(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -614,10 +569,7 @@ void main() { test('passes the arguments correctly', () async { api.returnValue = []; await picker.getMultiVideoWithOptions( - options: const MultiVideoPickerOptions( - maxDuration: Duration(seconds: 10), - limit: 5, - ), + options: const MultiVideoPickerOptions(maxDuration: Duration(seconds: 10), limit: 5), ); expect(api.passedSource?.type, SourceType.gallery); @@ -657,10 +609,7 @@ void main() { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: [], - error: CacheRetrievalError( - code: 'test_error_code', - message: 'test_error_message', - ), + error: CacheRetrievalError(code: 'test_error_code', message: 'test_error_message'), ); final LostDataResponse response = await picker.getLostData(); @@ -680,10 +629,7 @@ void main() { api.returnValue = CacheRetrievalResult( type: CacheRetrievalType.video, paths: ['/example/path'], - error: CacheRetrievalError( - code: 'test_error_code', - message: 'test_error_message', - ), + error: CacheRetrievalError(code: 'test_error_code', message: 'test_error_message'), ); expect(picker.getLostData(), throwsAssertionError); @@ -718,11 +664,7 @@ void main() { await picker.getMedia( options: const MediaOptions( allowMultiple: true, - imageOptions: ImageOptions( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ), + imageOptions: ImageOptions(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70), limit: 5, ), ); @@ -781,40 +723,28 @@ void main() { final Matcher throwsLimitArgumentError = throwsA( isA() .having((ArgumentError error) => error.name, 'name', 'limit') - .having( - (ArgumentError error) => error.message, - 'message', - 'cannot be lower than 2', - ), + .having((ArgumentError error) => error.message, 'message', 'cannot be lower than 2'), ); expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: true, limit: -1), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: true, limit: -1)), throwsLimitArgumentError, ); expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: true, limit: 0), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: true, limit: 0)), throwsLimitArgumentError, ); expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: true, limit: 1), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: true, limit: 1)), throwsLimitArgumentError, ); }); test('does not accept a not null limit when allowMultiple is false', () { expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: false, limit: 5), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: false, limit: 5)), throwsArgumentError, ); }); @@ -822,10 +752,7 @@ void main() { test('handles an empty path response gracefully', () async { api.returnValue = []; - expect( - await picker.getMedia(options: const MediaOptions(allowMultiple: true)), - [], - ); + expect(await picker.getMedia(options: const MediaOptions(allowMultiple: true)), []); }); test('defaults to not using Android Photo Picker', () async { @@ -876,11 +803,7 @@ void main() { test('passes image option arguments correctly', () async { await picker.getImageFromSource( source: ImageSource.camera, - options: const ImagePickerOptions( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ), + options: const ImagePickerOptions(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70), ); expect(api.passedImageOptions?.maxWidth, 10.0); @@ -943,14 +866,8 @@ void main() { test('handles a null image path response gracefully', () async { api.returnValue = null; - expect( - await picker.getImageFromSource(source: ImageSource.gallery), - isNull, - ); - expect( - await picker.getImageFromSource(source: ImageSource.camera), - isNull, - ); + expect(await picker.getImageFromSource(source: ImageSource.gallery), isNull); + expect(await picker.getImageFromSource(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { @@ -962,9 +879,7 @@ void main() { test('camera position can be set to front', () async { await picker.getImageFromSource( source: ImageSource.camera, - options: const ImagePickerOptions( - preferredCameraDevice: CameraDevice.front, - ), + options: const ImagePickerOptions(preferredCameraDevice: CameraDevice.front), ); expect(api.passedSource?.camera, SourceCamera.front); diff --git a/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart b/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart index dc24f0aa74b1..ed0931f09029 100644 --- a/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart +++ b/packages/image_picker/image_picker_for_web/example/integration_test/image_picker_for_web_test.dart @@ -22,15 +22,8 @@ final web.FilePropertyBag options = web.FilePropertyBag( lastModified: DateTime.utc(2017, 12, 13).millisecondsSinceEpoch, )..type = 'text/plain'; -final web.File textFile = web.File( - [bytes.toJS].toJS, - 'hello.txt', - options, -); -final web.File secondTextFile = web.File( - [otherBytes.toJS].toJS, - 'secondFile.txt', -); +final web.File textFile = web.File([bytes.toJS].toJS, 'hello.txt', options); +final web.File secondTextFile = web.File([otherBytes.toJS].toJS, 'secondFile.txt'); void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -51,14 +44,9 @@ void main() { final plugin = ImagePickerPlugin(overrides: overrides); // Init the pick file dialog... - final Future image = plugin.getImageFromSource( - source: ImageSource.camera, - ); + final Future image = plugin.getImageFromSource(source: ImageSource.camera); - expect( - web.document.querySelector('flt-image-picker-inputs')?.children.length, - isNonZero, - ); + expect(web.document.querySelector('flt-image-picker-inputs')?.children.length, isNonZero); // Mock the browser behavior of selecting a file... mockInput.dispatchEvent(web.Event('change')); @@ -77,23 +65,15 @@ void main() { file.lastModified(), completion(DateTime.fromMillisecondsSinceEpoch(textFile.lastModified)), ); - expect( - web.document.querySelector('flt-image-picker-inputs')?.children.length, - isZero, - ); + expect(web.document.querySelector('flt-image-picker-inputs')?.children.length, isZero); }); - testWidgets('getMultiImageWithOptions can select multiple files', ( - WidgetTester _, - ) async { + testWidgets('getMultiImageWithOptions can select multiple files', (WidgetTester _) async { final mockInput = web.HTMLInputElement()..type = 'file'; final overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = ((_) => [ - textFile, - secondTextFile, - ]); + ..getMultipleFilesFromInput = ((_) => [textFile, secondTextFile]); final plugin = ImagePickerPlugin(overrides: overrides); @@ -121,10 +101,7 @@ void main() { final overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = ((_) => [ - textFile, - secondTextFile, - ]); + ..getMultipleFilesFromInput = ((_) => [textFile, secondTextFile]); final plugin = ImagePickerPlugin(overrides: overrides); @@ -149,17 +126,12 @@ void main() { expect(secondFile.length(), completion(secondTextFile.size)); }); - testWidgets('getMultiVideoWithOptions can select multiple files', ( - WidgetTester _, - ) async { + testWidgets('getMultiVideoWithOptions can select multiple files', (WidgetTester _) async { final mockInput = web.HTMLInputElement()..type = 'file'; final overrides = ImagePickerPluginTestOverrides() ..createInputElement = ((_, __) => mockInput) - ..getMultipleFilesFromInput = ((_) => [ - textFile, - secondTextFile, - ]); + ..getMultipleFilesFromInput = ((_) => [textFile, secondTextFile]); final plugin = ImagePickerPlugin(overrides: overrides); @@ -217,9 +189,7 @@ void main() { expect(await files, isEmpty); }); - testWidgets('getMultiImageWithOptions - returns empty list', ( - WidgetTester _, - ) async { + testWidgets('getMultiImageWithOptions - returns empty list', (WidgetTester _) async { final Future?> files = plugin.getMultiImageWithOptions(); mockCancel(); @@ -228,9 +198,7 @@ void main() { }); testWidgets('getImageFromSource - returns null', (WidgetTester _) async { - final Future file = plugin.getImageFromSource( - source: ImageSource.gallery, - ); + final Future file = plugin.getImageFromSource(source: ImageSource.gallery); mockCancel(); expect(file, completes); @@ -245,9 +213,7 @@ void main() { expect(await file, isNull); }); - testWidgets('getMultiVideoWithOptions - returns empty list', ( - WidgetTester _, - ) async { + testWidgets('getMultiVideoWithOptions - returns empty list', (WidgetTester _) async { final Future?> files = plugin.getMultiVideoWithOptions(); mockCancel(); @@ -257,22 +223,10 @@ void main() { }); testWidgets('computeCaptureAttribute', (WidgetTester tester) async { - expect( - plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.front), - isNull, - ); - expect( - plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.rear), - isNull, - ); - expect( - plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.front), - 'user', - ); - expect( - plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.rear), - 'environment', - ); + expect(plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.front), isNull); + expect(plugin.computeCaptureAttribute(ImageSource.gallery, CameraDevice.rear), isNull); + expect(plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.front), 'user'); + expect(plugin.computeCaptureAttribute(ImageSource.camera, CameraDevice.rear), 'environment'); }); group('createInputElement', () { @@ -292,28 +246,16 @@ void main() { expect(input.hasAttribute('multiple'), false); }); - testWidgets('accept: any, capture: null, multi: true', ( - WidgetTester tester, - ) async { - final web.Element input = plugin.createInputElement( - 'any', - null, - multiple: true, - ); + testWidgets('accept: any, capture: null, multi: true', (WidgetTester tester) async { + final web.Element input = plugin.createInputElement('any', null, multiple: true); expect(input.getAttribute('accept'), 'any'); expect(input.hasAttribute('capture'), false); expect(input.hasAttribute('multiple'), true); }); - testWidgets('accept: any, capture: something, multi: true', ( - WidgetTester tester, - ) async { - final web.Element input = plugin.createInputElement( - 'any', - 'something', - multiple: true, - ); + testWidgets('accept: any, capture: something, multi: true', (WidgetTester tester) async { + final web.Element input = plugin.createInputElement('any', 'something', multiple: true); expect(input.getAttribute('accept'), 'any'); expect(input.getAttribute('capture'), 'something'); @@ -345,9 +287,7 @@ void main() { group('getImage', () { testWidgets('can select a file', (WidgetTester _) async { // ignore: deprecated_member_use - final Future image = plugin.getImage( - source: ImageSource.camera, - ); + final Future image = plugin.getImage(source: ImageSource.camera); // Mock the browser behavior when selecting a file... mockChange(); @@ -364,17 +304,13 @@ void main() { expect(file.mimeType, textFile.type); expect( file.lastModified(), - completion( - DateTime.fromMillisecondsSinceEpoch(textFile.lastModified), - ), + completion(DateTime.fromMillisecondsSinceEpoch(textFile.lastModified)), ); }); testWidgets('returns null when canceled', (WidgetTester _) async { // ignore: deprecated_member_use - final Future file = plugin.getImage( - source: ImageSource.gallery, - ); + final Future file = plugin.getImage(source: ImageSource.gallery); mockCancel(); expect(file, completes); @@ -385,10 +321,7 @@ void main() { group('getMultiImage', () { testWidgets('can select multiple files', (WidgetTester _) async { // Override the returned files... - overrides.getMultipleFilesFromInput = (_) => [ - textFile, - secondTextFile, - ]; + overrides.getMultipleFilesFromInput = (_) => [textFile, secondTextFile]; // ignore: deprecated_member_use final Future> files = plugin.getMultiImage(); @@ -409,9 +342,7 @@ void main() { expect(secondFile.length(), completion(secondTextFile.size)); }); - testWidgets('returns an empty list when canceled', ( - WidgetTester _, - ) async { + testWidgets('returns an empty list when canceled', (WidgetTester _) async { // ignore: deprecated_member_use final Future?> files = plugin.getMultiImage(); mockCancel(); diff --git a/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart b/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart index 95d36b44c5c2..0f099384321c 100644 --- a/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart +++ b/packages/image_picker/image_picker_for_web/example/integration_test/image_resizer_test.dart @@ -34,9 +34,7 @@ void main() { }); testWidgets('image is loaded correctly ', (WidgetTester tester) async { - final web.HTMLImageElement imageElement = await imageResizer.loadImage( - pngFile.path, - ); + final web.HTMLImageElement imageElement = await imageResizer.loadImage(pngFile.path); expect(imageElement.width, 10); expect(imageElement.height, 10); }); @@ -44,9 +42,7 @@ void main() { testWidgets( "canvas is loaded with image's width and height when max width and max height are null", (WidgetTester widgetTester) async { - final web.HTMLImageElement imageElement = await imageResizer.loadImage( - pngFile.path, - ); + final web.HTMLImageElement imageElement = await imageResizer.loadImage(pngFile.path); final web.HTMLCanvasElement canvas = imageResizer.resizeImageElement( imageElement, null, @@ -57,102 +53,52 @@ void main() { }, ); - testWidgets( - 'canvas size is scaled when max width and max height are not null', - (WidgetTester widgetTester) async { - final web.HTMLImageElement imageElement = await imageResizer.loadImage( - pngFile.path, - ); - final web.HTMLCanvasElement canvas = imageResizer.resizeImageElement( - imageElement, - 8, - 8, - ); - expect(canvas.width, 8); - expect(canvas.height, 8); - }, - ); + testWidgets('canvas size is scaled when max width and max height are not null', ( + WidgetTester widgetTester, + ) async { + final web.HTMLImageElement imageElement = await imageResizer.loadImage(pngFile.path); + final web.HTMLCanvasElement canvas = imageResizer.resizeImageElement(imageElement, 8, 8); + expect(canvas.width, 8); + expect(canvas.height, 8); + }); testWidgets('resized image is returned after converting canvas to file', ( WidgetTester widgetTester, ) async { - final web.HTMLImageElement imageElement = await imageResizer.loadImage( - pngFile.path, - ); - final web.HTMLCanvasElement canvas = imageResizer.resizeImageElement( - imageElement, - null, - null, - ); - final XFile resizedImage = await imageResizer.writeCanvasToFile( - pngFile, - canvas, - null, - ); + final web.HTMLImageElement imageElement = await imageResizer.loadImage(pngFile.path); + final web.HTMLCanvasElement canvas = imageResizer.resizeImageElement(imageElement, null, null); + final XFile resizedImage = await imageResizer.writeCanvasToFile(pngFile, canvas, null); expect(resizedImage.name, 'scaled_${pngFile.name}'); }); - testWidgets('image is scaled when maxWidth is set', ( - WidgetTester tester, - ) async { - final XFile scaledImage = await imageResizer.resizeImageIfNeeded( - pngFile, - 5, - null, - null, - ); + testWidgets('image is scaled when maxWidth is set', (WidgetTester tester) async { + final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, 5, null, null); expect(scaledImage.name, 'scaled_${pngFile.name}'); final Size scaledImageSize = await _getImageSize(scaledImage); expect(scaledImageSize, const Size(5, 5)); }); - testWidgets('image is scaled when maxHeight is set', ( - WidgetTester tester, - ) async { - final XFile scaledImage = await imageResizer.resizeImageIfNeeded( - pngFile, - null, - 6, - null, - ); + testWidgets('image is scaled when maxHeight is set', (WidgetTester tester) async { + final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, null, 6, null); expect(scaledImage.name, 'scaled_${pngFile.name}'); final Size scaledImageSize = await _getImageSize(scaledImage); expect(scaledImageSize, const Size(6, 6)); }); - testWidgets('image is scaled when imageQuality is set', ( - WidgetTester tester, - ) async { - final XFile scaledImage = await imageResizer.resizeImageIfNeeded( - pngFile, - null, - null, - 89, - ); + testWidgets('image is scaled when imageQuality is set', (WidgetTester tester) async { + final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, null, null, 89); expect(scaledImage.name, 'scaled_${pngFile.name}'); }); testWidgets('image is scaled when maxWidth,maxHeight,imageQuality are set', ( WidgetTester tester, ) async { - final XFile scaledImage = await imageResizer.resizeImageIfNeeded( - pngFile, - 3, - 4, - 89, - ); + final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, 3, 4, 89); expect(scaledImage.name, 'scaled_${pngFile.name}'); }); - testWidgets('image is not scaled when maxWidth,maxHeight, is set', ( - WidgetTester tester, - ) async { - final XFile scaledImage = await imageResizer.resizeImageIfNeeded( - pngFile, - null, - null, - null, - ); + testWidgets('image is not scaled when maxWidth,maxHeight, is set', (WidgetTester tester) async { + final XFile scaledImage = await imageResizer.resizeImageIfNeeded(pngFile, null, null, null); expect(scaledImage.name, pngFile.name); }); } diff --git a/packages/image_picker/image_picker_for_web/example/integration_test/readme_excerpts_test.dart b/packages/image_picker/image_picker_for_web/example/integration_test/readme_excerpts_test.dart index e76dc04ec23d..ecbe5ac9f2d2 100644 --- a/packages/image_picker/image_picker_for_web/example/integration_test/readme_excerpts_test.dart +++ b/packages/image_picker/image_picker_for_web/example/integration_test/readme_excerpts_test.dart @@ -15,9 +15,7 @@ import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - testWidgets('getImageFromPath loads image from XFile path', ( - WidgetTester tester, - ) async { + testWidgets('getImageFromPath loads image from XFile path', (WidgetTester tester) async { final XFile file = createXFileWeb(); // Use the excerpt code to get an Image from the XFile path. @@ -29,9 +27,7 @@ void main() { expect(find.byType(Image), findsOneWidget); }); - testWidgets('getImageFromBytes loads image from XFile bytes', ( - WidgetTester tester, - ) async { + testWidgets('getImageFromBytes loads image from XFile bytes', (WidgetTester tester) async { final XFile file = createXFileWeb(); // Use the excerpt code to get an Image from the XFile byte data. diff --git a/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart b/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart index 117c68774e20..d992ab84033d 100644 --- a/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart +++ b/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart @@ -50,14 +50,8 @@ class ImagePickerPlugin extends ImagePickerPlatform { required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { - final String? capture = computeCaptureAttribute( - source, - options.preferredCameraDevice, - ); - final List files = await getFiles( - accept: _kAcceptImageMimeType, - capture: capture, - ); + final String? capture = computeCaptureAttribute(source, options.preferredCameraDevice); + final List files = await getFiles(accept: _kAcceptImageMimeType, capture: capture); return files.isEmpty ? null : _imageResizer.resizeImageIfNeeded( @@ -73,10 +67,7 @@ class ImagePickerPlugin extends ImagePickerPlatform { Future> getMultiImageWithOptions({ MultiImagePickerOptions options = const MultiImagePickerOptions(), }) async { - final List images = await getFiles( - accept: _kAcceptImageMimeType, - multiple: true, - ); + final List images = await getFiles(accept: _kAcceptImageMimeType, multiple: true); final Iterable> resized = images.map( (XFile image) => _imageResizer.resizeImageIfNeeded( image, @@ -107,14 +98,8 @@ class ImagePickerPlugin extends ImagePickerPlatform { CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { - final String? capture = computeCaptureAttribute( - source, - preferredCameraDevice, - ); - final List files = await getFiles( - accept: _kAcceptVideoMimeType, - capture: capture, - ); + final String? capture = computeCaptureAttribute(source, preferredCameraDevice); + final List files = await getFiles(accept: _kAcceptVideoMimeType, capture: capture); return files.isEmpty ? null : files.first; } @@ -122,10 +107,7 @@ class ImagePickerPlugin extends ImagePickerPlatform { Future> getMultiVideoWithOptions({ MultiVideoPickerOptions options = const MultiVideoPickerOptions(), }) async { - final List files = await getFiles( - accept: _kAcceptVideoMimeType, - multiple: true, - ); + final List files = await getFiles(accept: _kAcceptVideoMimeType, multiple: true); return files; } @@ -161,16 +143,8 @@ class ImagePickerPlugin extends ImagePickerPlatform { /// /// See https://caniuse.com/#feat=html-media-capture @visibleForTesting - Future> getFiles({ - String? accept, - String? capture, - bool multiple = false, - }) { - final web.HTMLInputElement input = createInputElement( - accept, - capture, - multiple: multiple, - ); + Future> getFiles({String? accept, String? capture, bool multiple = false}) { + final web.HTMLInputElement input = createInputElement(accept, capture, multiple: multiple); _injectAndActivate(input); return _getSelectedXFiles(input).whenComplete(() { @@ -273,9 +247,7 @@ class ImagePickerPlugin extends ImagePickerPlatform { web.URL.createObjectURL(file), name: file.name, length: file.size, - lastModified: DateTime.fromMillisecondsSinceEpoch( - file.lastModified, - ), + lastModified: DateTime.fromMillisecondsSinceEpoch(file.lastModified), mimeType: file.type, ); }).toList(), @@ -302,9 +274,8 @@ class ImagePickerPlugin extends ImagePickerPlatform { web.Element _ensureInitialized(String id) { web.Element? target = web.document.querySelector('#$id'); if (target == null) { - final web.Element targetElement = web.document.createElement( - 'flt-image-picker-inputs', - )..id = id; + final web.Element targetElement = web.document.createElement('flt-image-picker-inputs') + ..id = id; // TODO(ditman): Append inside the `view` of the running app. web.document.body!.append(targetElement); target = targetElement; @@ -351,13 +322,16 @@ class ImagePickerPlugin extends ImagePickerPlatform { // Some tools to override behavior for unit-testing /// A function that creates a file input with the passed in `accept` and `capture` attributes. @visibleForTesting -typedef OverrideCreateInputFunction = - web.HTMLInputElement Function(String? accept, String? capture); +typedef OverrideCreateInputFunction = web.HTMLInputElement Function( + String? accept, + String? capture, +); /// A function that extracts list of files from the file `input` passed in. @visibleForTesting -typedef OverrideExtractMultipleFilesFromInputFunction = - List Function(web.HTMLInputElement? input); +typedef OverrideExtractMultipleFilesFromInputFunction = List Function( + web.HTMLInputElement? input, +); /// Overrides for some of the functionality above. @visibleForTesting diff --git a/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart b/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart index c09dcc884bc9..c7683f004200 100644 --- a/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart +++ b/packages/image_picker/image_picker_for_web/lib/src/image_resizer.dart @@ -23,23 +23,14 @@ class ImageResizer { double? maxHeight, int? imageQuality, ) async { - if (!imageResizeNeeded(maxWidth, maxHeight, imageQuality) || - file.mimeType == 'image/gif') { + if (!imageResizeNeeded(maxWidth, maxHeight, imageQuality) || file.mimeType == 'image/gif') { // Implement maxWidth and maxHeight for image/gif return file; } try { final web.HTMLImageElement imageElement = await loadImage(file.path); - final web.HTMLCanvasElement canvas = resizeImageElement( - imageElement, - maxWidth, - maxHeight, - ); - final XFile resizedImage = await writeCanvasToFile( - file, - canvas, - imageQuality, - ); + final web.HTMLCanvasElement canvas = resizeImageElement(imageElement, maxWidth, maxHeight); + final XFile resizedImage = await writeCanvasToFile(file, canvas, imageQuality); web.URL.revokeObjectURL(file.path); return resizedImage; } catch (e) { @@ -82,13 +73,7 @@ class ImageResizer { if (maxHeight == null && maxWidth == null) { context.drawImage(source, 0, 0); } else { - context.drawImage( - source, - 0, - 0, - canvas.width.toDouble(), - canvas.height.toDouble(), - ); + context.drawImage(source, 0, 0, canvas.width.toDouble(), canvas.height.toDouble()); } return canvas; } @@ -101,8 +86,7 @@ class ImageResizer { web.HTMLCanvasElement canvas, int? imageQuality, ) async { - final double calculatedImageQuality = - (min(imageQuality ?? 100, 100)) / 100.0; + final double calculatedImageQuality = (min(imageQuality ?? 100, 100)) / 100.0; final completer = Completer(); final web.BlobCallback blobCallback = (web.Blob blob) { completer.complete( @@ -115,11 +99,7 @@ class ImageResizer { ), ); }.toJS; - canvas.toBlob( - blobCallback, - originalFile.mimeType ?? '', - calculatedImageQuality.toJS, - ); + canvas.toBlob(blobCallback, originalFile.mimeType ?? '', calculatedImageQuality.toJS); return completer.future; } } diff --git a/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart b/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart index 84ec823398c3..c062ba41fd0f 100644 --- a/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart +++ b/packages/image_picker/image_picker_for_web/lib/src/image_resizer_utils.dart @@ -24,15 +24,9 @@ bool isImageQualityValid(int imageQuality) { /// imageHeight is the height of the image /// maxWidth is the maximum width of the scaled image /// maxHeight is the maximum height of the scaled image -Size calculateSizeOfDownScaledImage( - Size imageSize, - double? maxWidth, - double? maxHeight, -) { +Size calculateSizeOfDownScaledImage(Size imageSize, double? maxWidth, double? maxHeight) { final double widthFactor = maxWidth != null ? imageSize.width / maxWidth : 1; - final double heightFactor = maxHeight != null - ? imageSize.height / maxHeight - : 1; + final double heightFactor = maxHeight != null ? imageSize.height / maxHeight : 1; final double resizeFactor = max(widthFactor, heightFactor); return resizeFactor > 1 ? imageSize ~/ resizeFactor : imageSize; } diff --git a/packages/image_picker/image_picker_for_web/lib/src/pkg_web_tweaks.dart b/packages/image_picker/image_picker_for_web/lib/src/pkg_web_tweaks.dart index 0817d1c7f042..32610c634a18 100644 --- a/packages/image_picker/image_picker_for_web/lib/src/pkg_web_tweaks.dart +++ b/packages/image_picker/image_picker_for_web/lib/src/pkg_web_tweaks.dart @@ -9,7 +9,5 @@ extension WebFileListToDartList on web.FileList { /// Converts a [web.FileList] into a [List] of [web.File]. /// /// This method makes a copy. - List get toList => [ - for (int i = 0; i < length; i++) item(i)!, - ]; + List get toList => [for (int i = 0; i < length; i++) item(i)!]; } diff --git a/packages/image_picker/image_picker_for_web/test/image_resizer_utils_test.dart b/packages/image_picker/image_picker_for_web/test/image_resizer_utils_test.dart index 59dfefdf3249..6bd7f413358f 100644 --- a/packages/image_picker/image_picker_for_web/test/image_resizer_utils_test.dart +++ b/packages/image_picker/image_picker_for_web/test/image_resizer_utils_test.dart @@ -19,15 +19,12 @@ void main() { }, ); - test( - 'scaled image height and width are same if max width and max height are null', - () { - expect( - calculateSizeOfDownScaledImage(const Size(500, 300), null, null), - const Size(500, 300), - ); - }, - ); + test('scaled image height and width are same if max width and max height are null', () { + expect( + calculateSizeOfDownScaledImage(const Size(500, 300), null, null), + const Size(500, 300), + ); + }); test('image size is scaled when maxWidth is set', () { const imageSize = Size(500, 300); @@ -92,13 +89,10 @@ void main() { expect(isImageQualityValid(100), true); }); - test( - 'image quality is not valid when imageQuality is less than 0 or greater than 100', - () { - expect(isImageQualityValid(-1), false); - expect(isImageQualityValid(101), false); - }, - ); + test('image quality is not valid when imageQuality is less than 0 or greater than 100', () { + expect(isImageQualityValid(-1), false); + expect(isImageQualityValid(101), false); + }); }); }); } diff --git a/packages/image_picker/image_picker_ios/example/lib/main.dart b/packages/image_picker/image_picker_ios/example/lib/main.dart index 28fc2875266f..33ad721b27ec 100755 --- a/packages/image_picker/image_picker_ios/example/lib/main.dart +++ b/packages/image_picker/image_picker_ios/example/lib/main.dart @@ -118,10 +118,7 @@ class _MyHomePageState extends State { ), ) : await _picker.getMultiImageWithOptions( - options: MultiImagePickerOptions( - imageOptions: imageOptions, - limit: limit, - ), + options: MultiImagePickerOptions(imageOptions: imageOptions, limit: limit), ); if (pickedFileList.isNotEmpty && context.mounted) { _showPickedSnackBar(context, pickedFileList); @@ -227,15 +224,9 @@ class _MyHomePageState extends State { return retrieveError; } if (_controller == null) { - return const Text( - 'You have not yet picked a video', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked a video', textAlign: TextAlign.center); } - return Padding( - padding: const EdgeInsets.all(10.0), - child: AspectRatioVideo(_controller), - ); + return Padding(padding: const EdgeInsets.all(10.0), child: AspectRatioVideo(_controller)); } Widget _previewImages() { @@ -256,16 +247,9 @@ class _MyHomePageState extends State { child: mime == null || mime.startsWith('image/') ? Image.file( File(image.path), - errorBuilder: - ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { - return const Center( - child: Text('This image type is not supported'), - ); - }, + errorBuilder: (BuildContext context, Object error, StackTrace? stackTrace) { + return const Center(child: Text('This image type is not supported')); + }, ) : _buildInlineVideoPlayer(index), ); @@ -274,22 +258,14 @@ class _MyHomePageState extends State { ), ); } else if (_pickImageError != null) { - return Text( - 'Pick image error: $_pickImageError', - textAlign: TextAlign.center, - ); + return Text('Pick image error: $_pickImageError', textAlign: TextAlign.center); } else { - return const Text( - 'You have not yet picked an image.', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked an image.', textAlign: TextAlign.center); } } Widget _buildInlineVideoPlayer(int index) { - final controller = VideoPlayerController.file( - File(_mediaFileList![index].path), - ); + final controller = VideoPlayerController.file(File(_mediaFileList![index].path)); controller.setVolume(1.0); controller.initialize(); controller.setLooping(true); @@ -332,11 +308,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'image1', tooltip: 'Pick multiple images', @@ -349,11 +321,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - isMedia: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, isMedia: true); }, heroTag: 'media', tooltip: 'Pick item from gallery', @@ -412,11 +380,7 @@ class _MyHomePageState extends State { backgroundColor: Colors.red, onPressed: () { _isVideo = true; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'multiVideo', tooltip: 'Pick multiple videos', @@ -466,36 +430,24 @@ class _MyHomePageState extends State { children: [ TextField( controller: maxWidthController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxWidth if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxWidth if desired'), ), TextField( controller: maxHeightController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxHeight if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxHeight if desired'), ), TextField( controller: qualityController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter quality if desired', - ), + decoration: const InputDecoration(hintText: 'Enter quality if desired'), ), if (isMulti) TextField( controller: limitController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter limit if desired', - ), + decoration: const InputDecoration(hintText: 'Enter limit if desired'), ), ], ), @@ -541,13 +493,12 @@ class _MyHomePageState extends State { } } -typedef OnPickImageCallback = - void Function( - double? maxWidth, - double? maxHeight, - int? quality, - int? limit, - ); +typedef OnPickImageCallback = void Function( + double? maxWidth, + double? maxHeight, + int? quality, + int? limit, +); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {super.key}); diff --git a/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart b/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart index fa373a31bb0c..4eeb6f183842 100644 --- a/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart +++ b/packages/image_picker/image_picker_ios/lib/image_picker_ios.dart @@ -45,8 +45,7 @@ SourceCamera _convertCamera(CameraDevice camera) { /// An implementation of [ImagePickerPlatform] for iOS. class ImagePickerIOS extends ImagePickerPlatform { /// Creates a new plugin implementation instance. - ImagePickerIOS({@visibleForTesting ImagePickerApi? api}) - : _hostApi = api ?? ImagePickerApi(); + ImagePickerIOS({@visibleForTesting ImagePickerApi? api}) : _hostApi = api ?? ImagePickerApi(); final ImagePickerApi _hostApi; @@ -80,10 +79,7 @@ class ImagePickerIOS extends ImagePickerPlatform { required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { - final String? path = await _pickImageAsPath( - source: source, - options: options, - ); + final String? path = await _pickImageAsPath(source: source, options: options); return path != null ? XFile(path) : null; } @@ -124,11 +120,7 @@ class ImagePickerIOS extends ImagePickerPlatform { }) async { final int? imageQuality = options.imageOptions.imageQuality; if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } final double? maxWidth = options.imageOptions.maxWidth; @@ -160,11 +152,7 @@ class ImagePickerIOS extends ImagePickerPlatform { }) { final int? imageQuality = options.imageQuality; if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } final double? maxHeight = options.maxHeight; @@ -190,8 +178,9 @@ class ImagePickerIOS extends ImagePickerPlatform { @override Future> getMedia({required MediaOptions options}) async { - final MediaSelectionOptions mediaSelectionOptions = - _mediaOptionsToMediaSelectionOptions(options); + final MediaSelectionOptions mediaSelectionOptions = _mediaOptionsToMediaSelectionOptions( + options, + ); return (await _hostApi.pickMedia( mediaSelectionOptions, @@ -204,11 +193,7 @@ class ImagePickerIOS extends ImagePickerPlatform { final int? imageQuality = imageOptions.imageQuality; if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { @@ -222,12 +207,8 @@ class ImagePickerIOS extends ImagePickerPlatform { return MaxSize(width: maxWidth, height: maxHeight); } - MediaSelectionOptions _mediaOptionsToMediaSelectionOptions( - MediaOptions mediaOptions, - ) { - final MaxSize maxSize = _imageOptionsToMaxSizeWithValidation( - mediaOptions.imageOptions, - ); + MediaSelectionOptions _mediaOptionsToMediaSelectionOptions(MediaOptions mediaOptions) { + final MaxSize maxSize = _imageOptionsToMaxSizeWithValidation(mediaOptions.imageOptions); final bool allowMultiple = mediaOptions.allowMultiple; final int? limit = mediaOptions.limit; diff --git a/packages/image_picker/image_picker_ios/lib/src/messages.g.dart b/packages/image_picker/image_picker_ios/lib/src/messages.g.dart index 81aedec71b51..6d16ea63ee5f 100644 --- a/packages/image_picker/image_picker_ios/lib/src/messages.g.dart +++ b/packages/image_picker/image_picker_ios/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -97,13 +95,7 @@ class MediaSelectionOptions { int? limit; List _toList() { - return [ - maxSize, - imageQuality, - requestFullMetadata, - allowMultiple, - limit, - ]; + return [maxSize, imageQuality, requestFullMetadata, allowMultiple, limit]; } Object encode() { @@ -155,10 +147,7 @@ class SourceSpecification { static SourceSpecification decode(Object result) { result as List; - return SourceSpecification( - type: result[0]! as SourceType, - camera: result[1]! as SourceCamera, - ); + return SourceSpecification(type: result[0]! as SourceType, camera: result[1]! as SourceCamera); } @override @@ -230,13 +219,11 @@ class ImagePickerApi { /// Constructor for [ImagePickerApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - ImagePickerApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + ImagePickerApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -251,17 +238,18 @@ class ImagePickerApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickImage$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [source, maxSize, imageQuality, requestFullMetadata], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + source, + maxSize, + imageQuality, + requestFullMetadata, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -283,17 +271,18 @@ class ImagePickerApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMultiImage$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [maxSize, imageQuality, requestFullMetadata, limit], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + maxSize, + imageQuality, + requestFullMetadata, + limit, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -312,23 +301,19 @@ class ImagePickerApi { } } - Future pickVideo( - SourceSpecification source, - int? maxDurationSeconds, - ) async { + Future pickVideo(SourceSpecification source, int? maxDurationSeconds) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickVideo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [source, maxDurationSeconds], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + source, + maxDurationSeconds, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -342,23 +327,19 @@ class ImagePickerApi { } } - Future> pickMultiVideo( - int? maxDurationSeconds, - int? limit, - ) async { + Future> pickMultiVideo(int? maxDurationSeconds, int? limit) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMultiVideo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [maxDurationSeconds, limit], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + maxDurationSeconds, + limit, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -378,22 +359,18 @@ class ImagePickerApi { } /// Selects images and videos and returns their paths. - Future> pickMedia( - MediaSelectionOptions mediaSelectionOptions, - ) async { + Future> pickMedia(MediaSelectionOptions mediaSelectionOptions) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.image_picker_ios.ImagePickerApi.pickMedia$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [mediaSelectionOptions], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + mediaSelectionOptions, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/image_picker/image_picker_ios/test/image_picker_ios_test.dart b/packages/image_picker/image_picker_ios/test/image_picker_ios_test.dart index d423acd05de8..024118ec129e 100644 --- a/packages/image_picker/image_picker_ios/test/image_picker_ios_test.dart +++ b/packages/image_picker/image_picker_ios/test/image_picker_ios_test.dart @@ -27,9 +27,7 @@ void main() { group('#pickImage', () { test('calls the method correctly with default arguments', () async { api.returnValue = ['/foo.png']; - final PickedFile? result = await picker.pickImage( - source: ImageSource.camera, - ); + final PickedFile? result = await picker.pickImage(source: ImageSource.camera); expect(result?.path, '/foo.png'); expect(api.passedSelectionType, _SelectionType.image); @@ -53,11 +51,7 @@ void main() { }); test('passes width and height arguments correctly', () async { - await picker.pickImage( - source: ImageSource.camera, - maxWidth: 10.0, - maxHeight: 20.0, - ); + await picker.pickImage(source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0); expect(api.passedMaxSize?.width, 10); expect(api.passedMaxSize?.height, 20); @@ -110,10 +104,7 @@ void main() { }); test('camera position can set to front', () async { - await picker.pickImage( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.pickImage(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -149,15 +140,9 @@ void main() { }); test('does not accept an invalid imageQuality argument', () { - expect( - () => picker.pickMultiImage(imageQuality: -1), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(imageQuality: -1), throwsArgumentError); - expect( - () => picker.pickMultiImage(imageQuality: 101), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(imageQuality: 101), throwsArgumentError); }); test('returns null for an empty list', () async { @@ -170,9 +155,7 @@ void main() { group('#pickVideo', () { test('calls the method correctly with default arguments', () async { api.returnValue = ['/foo.mp4']; - final PickedFile? result = await picker.pickVideo( - source: ImageSource.camera, - ); + final PickedFile? result = await picker.pickVideo(source: ImageSource.camera); expect(result?.path, '/foo.mp4'); expect(api.passedSelectionType, _SelectionType.video); @@ -192,10 +175,7 @@ void main() { }); test('passes the duration argument correctly', () async { - await picker.pickVideo( - source: ImageSource.camera, - maxDuration: const Duration(minutes: 1), - ); + await picker.pickVideo(source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); expect(api.passedMaxDurationSeconds, 60); }); @@ -208,10 +188,7 @@ void main() { }); test('camera position can set to front', () async { - await picker.pickVideo( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.pickVideo(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -243,11 +220,7 @@ void main() { }); test('passes the width and height arguments correctly', () async { - await picker.getImage( - source: ImageSource.camera, - maxWidth: 10.0, - maxHeight: 20.0, - ); + await picker.getImage(source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0); expect(api.passedMaxSize?.width, 10); expect(api.passedMaxSize?.height, 20); @@ -307,10 +280,7 @@ void main() { }); test('camera position can set to front', () async { - await picker.getImage( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.getImage(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -354,10 +324,7 @@ void main() { test('does not accept an invalid imageQuality argument', () { expect(() => picker.getMultiImage(imageQuality: -1), throwsArgumentError); - expect( - () => picker.getMultiImage(imageQuality: 101), - throwsArgumentError, - ); + expect(() => picker.getMultiImage(imageQuality: 101), throwsArgumentError); }); test('returns null for an empty list', () async { @@ -390,10 +357,7 @@ void main() { await picker.getMedia( options: MediaOptions( allowMultiple: true, - imageOptions: ImageOptions.createAndValidate( - maxWidth: 10.0, - maxHeight: 20.0, - ), + imageOptions: ImageOptions.createAndValidate(maxWidth: 10.0, maxHeight: 20.0), ), ); @@ -477,40 +441,28 @@ void main() { final Matcher throwsLimitArgumentError = throwsA( isA() .having((ArgumentError error) => error.name, 'name', 'limit') - .having( - (ArgumentError error) => error.message, - 'message', - 'cannot be lower than 2', - ), + .having((ArgumentError error) => error.message, 'message', 'cannot be lower than 2'), ); expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: true, limit: -1), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: true, limit: -1)), throwsLimitArgumentError, ); expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: true, limit: 0), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: true, limit: 0)), throwsLimitArgumentError, ); expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: true, limit: 1), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: true, limit: 1)), throwsLimitArgumentError, ); }); test('does not accept a not null limit when allowMultiple is false', () { expect( - () => picker.getMedia( - options: const MediaOptions(allowMultiple: false, limit: 5), - ), + () => picker.getMedia(options: const MediaOptions(allowMultiple: false, limit: 5)), throwsArgumentError, ); }); @@ -518,10 +470,7 @@ void main() { test('handles a empty path response gracefully', () async { api.returnValue = []; - expect( - await picker.getMedia(options: const MediaOptions(allowMultiple: true)), - [], - ); + expect(await picker.getMedia(options: const MediaOptions(allowMultiple: true)), []); }); }); @@ -548,10 +497,7 @@ void main() { }); test('passes the duration argument correctly', () async { - await picker.getVideo( - source: ImageSource.camera, - maxDuration: const Duration(minutes: 1), - ); + await picker.getVideo(source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); expect(api.passedMaxDurationSeconds, 60); }); @@ -570,10 +516,7 @@ void main() { }); test('camera position can set to front', () async { - await picker.getVideo( - source: ImageSource.camera, - preferredCameraDevice: CameraDevice.front, - ); + await picker.getVideo(source: ImageSource.camera, preferredCameraDevice: CameraDevice.front); expect(api.passedSource?.camera, SourceCamera.front); }); @@ -595,10 +538,7 @@ void main() { test('passes the arguments correctly', () async { api.returnValue = []; await picker.getMultiVideoWithOptions( - options: const MultiVideoPickerOptions( - maxDuration: Duration(seconds: 10), - limit: 5, - ), + options: const MultiVideoPickerOptions(maxDuration: Duration(seconds: 10), limit: 5), ); expect(api.passedMaxDurationSeconds, 10); @@ -609,9 +549,7 @@ void main() { group('#getImageFromSource', () { test('calls the method correctly with default arguments', () async { api.returnValue = ['/foo.png']; - final XFile? result = await picker.getImageFromSource( - source: ImageSource.camera, - ); + final XFile? result = await picker.getImageFromSource(source: ImageSource.camera); expect(result?.path, '/foo.png'); expect(api.passedSelectionType, _SelectionType.image); @@ -707,14 +645,8 @@ void main() { test('handles a null image path response gracefully', () async { api.returnValue = []; - expect( - await picker.getImageFromSource(source: ImageSource.gallery), - isNull, - ); - expect( - await picker.getImageFromSource(source: ImageSource.camera), - isNull, - ); + expect(await picker.getImageFromSource(source: ImageSource.gallery), isNull); + expect(await picker.getImageFromSource(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { @@ -726,9 +658,7 @@ void main() { test('camera position can set to front', () async { await picker.getImageFromSource( source: ImageSource.camera, - options: const ImagePickerOptions( - preferredCameraDevice: CameraDevice.front, - ), + options: const ImagePickerOptions(preferredCameraDevice: CameraDevice.front), ); expect(api.passedSource?.camera, SourceCamera.front); @@ -773,18 +703,14 @@ void main() { test('passes the image quality argument correctly', () async { await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(imageQuality: 70), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(imageQuality: 70)), ); expect(api.passedImageQuality, 70); }); test('passes the limit argument correctly', () async { - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions(limit: 5), - ); + await picker.getMultiImageWithOptions(options: const MultiImagePickerOptions(limit: 5)); expect(api.passedLimit, 5); }); @@ -792,18 +718,14 @@ void main() { test('does not accept a negative width or height argument', () { expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxWidth: -1.0), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(maxWidth: -1.0)), ), throwsArgumentError, ); expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxHeight: -1.0), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(maxHeight: -1.0)), ), throwsArgumentError, ); @@ -812,18 +734,14 @@ void main() { test('does not accept an invalid imageQuality argument', () { expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(imageQuality: -1), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(imageQuality: -1)), ), throwsArgumentError, ); expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(imageQuality: 101), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(imageQuality: 101)), ), throwsArgumentError, ); @@ -833,31 +751,21 @@ void main() { final Matcher throwsLimitArgumentError = throwsA( isA() .having((ArgumentError error) => error.name, 'name', 'limit') - .having( - (ArgumentError error) => error.message, - 'message', - 'cannot be lower than 2', - ), + .having((ArgumentError error) => error.message, 'message', 'cannot be lower than 2'), ); expect( - () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions(limit: -1), - ), + () => picker.getMultiImageWithOptions(options: const MultiImagePickerOptions(limit: -1)), throwsLimitArgumentError, ); expect( - () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions(limit: 0), - ), + () => picker.getMultiImageWithOptions(options: const MultiImagePickerOptions(limit: 0)), throwsLimitArgumentError, ); expect( - () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions(limit: 1), - ), + () => picker.getMultiImageWithOptions(options: const MultiImagePickerOptions(limit: 1)), throwsLimitArgumentError, ); }); @@ -928,19 +836,14 @@ class _FakeImagePickerApi implements ImagePickerApi { } @override - Future> pickMedia( - MediaSelectionOptions mediaSelectionOptions, - ) async { + Future> pickMedia(MediaSelectionOptions mediaSelectionOptions) async { passedSelectionType = _SelectionType.media; passedMediaSelectionOptions = mediaSelectionOptions; return returnValue; } @override - Future pickVideo( - SourceSpecification source, - int? maxDurationSeconds, - ) async { + Future pickVideo(SourceSpecification source, int? maxDurationSeconds) async { passedSelectionType = _SelectionType.video; passedSource = source; passedMaxDurationSeconds = maxDurationSeconds; @@ -948,10 +851,7 @@ class _FakeImagePickerApi implements ImagePickerApi { } @override - Future> pickMultiVideo( - int? maxDurationSeconds, - int? limit, - ) async { + Future> pickMultiVideo(int? maxDurationSeconds, int? limit) async { passedSelectionType = _SelectionType.multiVideo; passedMaxDurationSeconds = maxDurationSeconds; passedLimit = limit; diff --git a/packages/image_picker/image_picker_linux/example/lib/main.dart b/packages/image_picker/image_picker_linux/example/lib/main.dart index 4bc0ab606c30..5f73ceab67f5 100644 --- a/packages/image_picker/image_picker_linux/example/lib/main.dart +++ b/packages/image_picker/image_picker_linux/example/lib/main.dart @@ -110,15 +110,10 @@ class _MyHomePageState extends State { ); final List pickedFileList = isMedia ? await _picker.getMedia( - options: MediaOptions( - allowMultiple: allowMultiple, - imageOptions: imageOptions, - ), + options: MediaOptions(allowMultiple: allowMultiple, imageOptions: imageOptions), ) : await _picker.getMultiImageWithOptions( - options: MultiImagePickerOptions( - imageOptions: imageOptions, - ), + options: MultiImagePickerOptions(imageOptions: imageOptions), ); if (pickedFileList.isNotEmpty && context.mounted) { _showPickedSnackBar(context, pickedFileList); @@ -222,15 +217,9 @@ class _MyHomePageState extends State { return retrieveError; } if (_controller == null) { - return const Text( - 'You have not yet picked a video', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked a video', textAlign: TextAlign.center); } - return Padding( - padding: const EdgeInsets.all(10.0), - child: AspectRatioVideo(_controller), - ); + return Padding(padding: const EdgeInsets.all(10.0), child: AspectRatioVideo(_controller)); } Widget _previewImages() { @@ -249,25 +238,16 @@ class _MyHomePageState extends State { return Column( mainAxisSize: MainAxisSize.min, children: [ - Text( - image.name, - key: const Key('image_picker_example_picked_image_name'), - ), + Text(image.name, key: const Key('image_picker_example_picked_image_name')), Semantics( label: 'image_picker_example_picked_image', child: mime == null || mime.startsWith('image/') ? Image.file( File(_mediaFileList![index].path), errorBuilder: - ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { + (BuildContext context, Object error, StackTrace? stackTrace) { return const Center( - child: Text( - 'This image type is not supported', - ), + child: Text('This image type is not supported'), ); }, ) @@ -280,22 +260,14 @@ class _MyHomePageState extends State { ), ); } else if (_pickImageError != null) { - return Text( - 'Pick image error: $_pickImageError', - textAlign: TextAlign.center, - ); + return Text('Pick image error: $_pickImageError', textAlign: TextAlign.center); } else { - return const Text( - 'You have not yet picked an image.', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked an image.', textAlign: TextAlign.center); } } Widget _buildInlineVideoPlayer(int index) { - final controller = VideoPlayerController.file( - File(_mediaFileList![index].path), - ); + final controller = VideoPlayerController.file(File(_mediaFileList![index].path)); controller.setVolume(1.0); controller.initialize(); controller.setLooping(true); @@ -338,11 +310,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'image1', tooltip: 'Pick multiple images', @@ -355,11 +323,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - isMedia: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, isMedia: true); }, heroTag: 'media', tooltip: 'Pick item from gallery', @@ -419,11 +383,7 @@ class _MyHomePageState extends State { backgroundColor: Colors.red, onPressed: () { _isVideo = true; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'multiVideo', tooltip: 'Pick multiple videos', @@ -460,10 +420,7 @@ class _MyHomePageState extends State { return null; } - Future _displayPickImageDialog( - BuildContext context, - OnPickImageCallback onPick, - ) async { + Future _displayPickImageDialog(BuildContext context, OnPickImageCallback onPick) async { return showDialog( context: context, builder: (BuildContext context) { @@ -473,28 +430,18 @@ class _MyHomePageState extends State { children: [ TextField( controller: maxWidthController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxWidth if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxWidth if desired'), ), TextField( controller: maxHeightController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxHeight if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxHeight if desired'), ), TextField( controller: qualityController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter quality if desired', - ), + decoration: const InputDecoration(hintText: 'Enter quality if desired'), ), ], ), @@ -537,8 +484,7 @@ class _MyHomePageState extends State { } } -typedef OnPickImageCallback = - void Function(double? maxWidth, double? maxHeight, int? quality); +typedef OnPickImageCallback = void Function(double? maxWidth, double? maxHeight, int? quality); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {super.key}); diff --git a/packages/image_picker/image_picker_linux/lib/image_picker_linux.dart b/packages/image_picker/image_picker_linux/lib/image_picker_linux.dart index bd6c87fbaa7e..a9d90e8ce449 100644 --- a/packages/image_picker/image_picker_linux/lib/image_picker_linux.dart +++ b/packages/image_picker/image_picker_linux/lib/image_picker_linux.dart @@ -103,10 +103,7 @@ class ImagePickerLinux extends CameraDelegatingImagePickerPlatform { case ImageSource.camera: return super.getImageFromSource(source: source); case ImageSource.gallery: - const typeGroup = XTypeGroup( - label: 'Images', - mimeTypes: ['image/*'], - ); + const typeGroup = XTypeGroup(label: 'Images', mimeTypes: ['image/*']); final XFile? file = await fileSelector.openFile( acceptedTypeGroups: [typeGroup], ); @@ -137,10 +134,7 @@ class ImagePickerLinux extends CameraDelegatingImagePickerPlatform { maxDuration: maxDuration, ); case ImageSource.gallery: - const typeGroup = XTypeGroup( - label: 'Videos', - mimeTypes: ['video/*'], - ); + const typeGroup = XTypeGroup(label: 'Videos', mimeTypes: ['video/*']); final XFile? file = await fileSelector.openFile( acceptedTypeGroups: [typeGroup], ); @@ -160,10 +154,7 @@ class ImagePickerLinux extends CameraDelegatingImagePickerPlatform { double? maxHeight, int? imageQuality, }) async { - const typeGroup = XTypeGroup( - label: 'Images', - mimeTypes: ['image/*'], - ); + const typeGroup = XTypeGroup(label: 'Images', mimeTypes: ['image/*']); final List files = await fileSelector.openFiles( acceptedTypeGroups: [typeGroup], ); @@ -174,10 +165,7 @@ class ImagePickerLinux extends CameraDelegatingImagePickerPlatform { Future> getMultiVideoWithOptions({ MultiVideoPickerOptions options = const MultiVideoPickerOptions(), }) async { - const typeGroup = XTypeGroup( - label: 'Videos', - mimeTypes: ['video/*'], - ); + const typeGroup = XTypeGroup(label: 'Videos', mimeTypes: ['video/*']); final List files = await fileSelector.openFiles( acceptedTypeGroups: [typeGroup], ); @@ -197,13 +185,9 @@ class ImagePickerLinux extends CameraDelegatingImagePickerPlatform { List files; if (options.allowMultiple) { - files = await fileSelector.openFiles( - acceptedTypeGroups: [typeGroup], - ); + files = await fileSelector.openFiles(acceptedTypeGroups: [typeGroup]); } else { - final XFile? file = await fileSelector.openFile( - acceptedTypeGroups: [typeGroup], - ); + final XFile? file = await fileSelector.openFile(acceptedTypeGroups: [typeGroup]); files = [if (file != null) file]; } return files; diff --git a/packages/image_picker/image_picker_linux/test/image_picker_linux_test.dart b/packages/image_picker/image_picker_linux/test/image_picker_linux_test.dart index 0d8207545f6c..f24ca08227ad 100644 --- a/packages/image_picker/image_picker_linux/test/image_picker_linux_test.dart +++ b/packages/image_picker/image_picker_linux/test/image_picker_linux_test.dart @@ -29,15 +29,11 @@ void main() { mockFileSelectorPlatform = MockFileSelectorPlatform(); when( - mockFileSelectorPlatform.openFile( - acceptedTypeGroups: anyNamed('acceptedTypeGroups'), - ), + mockFileSelectorPlatform.openFile(acceptedTypeGroups: anyNamed('acceptedTypeGroups')), ).thenAnswer((_) async => null); when( - mockFileSelectorPlatform.openFiles( - acceptedTypeGroups: anyNamed('acceptedTypeGroups'), - ), + mockFileSelectorPlatform.openFiles(acceptedTypeGroups: anyNamed('acceptedTypeGroups')), ).thenAnswer((_) async => List.empty()); ImagePickerLinux.fileSelector = mockFileSelectorPlatform; @@ -71,38 +67,26 @@ void main() { expect(capturedTypeGroups(result)[0].mimeTypes, ['image/*']); }); - test( - 'getImageFromSource passes the accepted type groups correctly', - () async { - await plugin.getImageFromSource(source: ImageSource.gallery); + test('getImageFromSource passes the accepted type groups correctly', () async { + await plugin.getImageFromSource(source: ImageSource.gallery); - final VerificationResult result = verify( - mockFileSelectorPlatform.openFile( - acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), - ), - ); - expect(capturedTypeGroups(result)[0].mimeTypes, ['image/*']); - }, - ); + final VerificationResult result = verify( + mockFileSelectorPlatform.openFile( + acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), + ), + ); + expect(capturedTypeGroups(result)[0].mimeTypes, ['image/*']); + }); test('getImageFromSource calls delegate when source is camera', () async { const fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); - expect( - (await plugin.getImageFromSource(source: ImageSource.camera))!.path, - fakePath, - ); + expect((await plugin.getImageFromSource(source: ImageSource.camera))!.path, fakePath); }); - test( - 'getImageFromSource throws StateError when source is camera with no delegate', - () async { - await expectLater( - plugin.getImageFromSource(source: ImageSource.camera), - throwsStateError, - ); - }, - ); + test('getImageFromSource throws StateError when source is camera with no delegate', () async { + await expectLater(plugin.getImageFromSource(source: ImageSource.camera), throwsStateError); + }); test('getMultiImage passes the accepted type groups correctly', () async { await plugin.getMultiImage(); @@ -142,35 +126,23 @@ void main() { test('getVideo calls delegate when source is camera', () async { const fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); - expect( - (await plugin.getVideo(source: ImageSource.camera))!.path, - fakePath, - ); + expect((await plugin.getVideo(source: ImageSource.camera))!.path, fakePath); + }); + + test('getVideo throws StateError when source is camera with no delegate', () async { + await expectLater(plugin.getVideo(source: ImageSource.camera), throwsStateError); }); - test( - 'getVideo throws StateError when source is camera with no delegate', - () async { - await expectLater( - plugin.getVideo(source: ImageSource.camera), - throwsStateError, - ); - }, - ); - - test( - 'getMultiVideoWithOptions passes the accepted type groups correctly', - () async { - await plugin.getMultiVideoWithOptions(); - - final VerificationResult result = verify( - mockFileSelectorPlatform.openFiles( - acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), - ), - ); - expect(capturedTypeGroups(result)[0].mimeTypes, ['video/*']); - }, - ); + test('getMultiVideoWithOptions passes the accepted type groups correctly', () async { + await plugin.getMultiVideoWithOptions(); + + final VerificationResult result = verify( + mockFileSelectorPlatform.openFiles( + acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), + ), + ); + expect(capturedTypeGroups(result)[0].mimeTypes, ['video/*']); + }); }); group('media', () { @@ -182,26 +154,15 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect(capturedTypeGroups(result)[0].mimeTypes, [ - 'image/*', - 'video/*', - ]); + expect(capturedTypeGroups(result)[0].mimeTypes, ['image/*', 'video/*']); }); test('multiple media handles an empty path response gracefully', () async { - expect( - await plugin.getMedia(options: const MediaOptions(allowMultiple: true)), - [], - ); + expect(await plugin.getMedia(options: const MediaOptions(allowMultiple: true)), []); }); test('single media handles an empty path response gracefully', () async { - expect( - await plugin.getMedia( - options: const MediaOptions(allowMultiple: false), - ), - [], - ); + expect(await plugin.getMedia(options: const MediaOptions(allowMultiple: false)), []); }); }); } @@ -213,16 +174,14 @@ class FakeCameraDelegate extends ImagePickerCameraDelegate { @override Future takePhoto({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } @override Future takeVideo({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } diff --git a/packages/image_picker/image_picker_linux/test/image_picker_linux_test.mocks.dart b/packages/image_picker/image_picker_linux/test/image_picker_linux_test.mocks.dart index 3f78fa4574a7..9aa7e665f7e3 100644 --- a/packages/image_picker/image_picker_linux/test/image_picker_linux_test.mocks.dart +++ b/packages/image_picker/image_picker_linux/test/image_picker_linux_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:file_selector_platform_interface/file_selector_platform_interface.dart' - as _i2; +import 'package:file_selector_platform_interface/file_selector_platform_interface.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -25,8 +24,7 @@ import 'package:mockito/mockito.dart' as _i1; /// A class which mocks [FileSelectorPlatform]. /// /// See the documentation for Mockito's code generation for more information. -class MockFileSelectorPlatform extends _i1.Mock - implements _i2.FileSelectorPlatform { +class MockFileSelectorPlatform extends _i1.Mock implements _i2.FileSelectorPlatform { MockFileSelectorPlatform() { _i1.throwOnMissingStub(this); } @@ -36,32 +34,28 @@ class MockFileSelectorPlatform extends _i1.Mock List<_i2.XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#openFile, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future<_i2.XFile?>.value(), - ) - as _i3.Future<_i2.XFile?>); + }) => (super.noSuchMethod( + Invocation.method(#openFile, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future<_i2.XFile?>.value(), + ) as _i3.Future<_i2.XFile?>); @override _i3.Future> openFiles({ List<_i2.XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#openFiles, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future>.value(<_i2.XFile>[]), - ) - as _i3.Future>); + }) => (super.noSuchMethod( + Invocation.method(#openFiles, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future>.value(<_i2.XFile>[]), + ) as _i3.Future>); @override _i3.Future getSavePath({ @@ -69,57 +63,47 @@ class MockFileSelectorPlatform extends _i1.Mock String? initialDirectory, String? suggestedName, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#getSavePath, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #suggestedName: suggestedName, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future.value(), - ) - as _i3.Future); + }) => (super.noSuchMethod( + Invocation.method(#getSavePath, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #suggestedName: suggestedName, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future.value(), + ) as _i3.Future); @override _i3.Future<_i2.FileSaveLocation?> getSaveLocation({ List<_i2.XTypeGroup>? acceptedTypeGroups, _i2.SaveDialogOptions? options = const _i2.SaveDialogOptions(), - }) => - (super.noSuchMethod( - Invocation.method(#getSaveLocation, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #options: options, - }), - returnValue: _i3.Future<_i2.FileSaveLocation?>.value(), - ) - as _i3.Future<_i2.FileSaveLocation?>); + }) => (super.noSuchMethod( + Invocation.method(#getSaveLocation, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #options: options, + }), + returnValue: _i3.Future<_i2.FileSaveLocation?>.value(), + ) as _i3.Future<_i2.FileSaveLocation?>); @override - _i3.Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) => + _i3.Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) => (super.noSuchMethod( - Invocation.method(#getDirectoryPath, [], { - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#getDirectoryPath, [], { + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future.value(), + ) as _i3.Future); @override _i3.Future> getDirectoryPaths({ String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#getDirectoryPaths, [], { - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future>.value([]), - ) - as _i3.Future>); + }) => (super.noSuchMethod( + Invocation.method(#getDirectoryPaths, [], { + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future>.value([]), + ) as _i3.Future>); } diff --git a/packages/image_picker/image_picker_macos/example/lib/main.dart b/packages/image_picker/image_picker_macos/example/lib/main.dart index 4bc0ab606c30..5f73ceab67f5 100644 --- a/packages/image_picker/image_picker_macos/example/lib/main.dart +++ b/packages/image_picker/image_picker_macos/example/lib/main.dart @@ -110,15 +110,10 @@ class _MyHomePageState extends State { ); final List pickedFileList = isMedia ? await _picker.getMedia( - options: MediaOptions( - allowMultiple: allowMultiple, - imageOptions: imageOptions, - ), + options: MediaOptions(allowMultiple: allowMultiple, imageOptions: imageOptions), ) : await _picker.getMultiImageWithOptions( - options: MultiImagePickerOptions( - imageOptions: imageOptions, - ), + options: MultiImagePickerOptions(imageOptions: imageOptions), ); if (pickedFileList.isNotEmpty && context.mounted) { _showPickedSnackBar(context, pickedFileList); @@ -222,15 +217,9 @@ class _MyHomePageState extends State { return retrieveError; } if (_controller == null) { - return const Text( - 'You have not yet picked a video', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked a video', textAlign: TextAlign.center); } - return Padding( - padding: const EdgeInsets.all(10.0), - child: AspectRatioVideo(_controller), - ); + return Padding(padding: const EdgeInsets.all(10.0), child: AspectRatioVideo(_controller)); } Widget _previewImages() { @@ -249,25 +238,16 @@ class _MyHomePageState extends State { return Column( mainAxisSize: MainAxisSize.min, children: [ - Text( - image.name, - key: const Key('image_picker_example_picked_image_name'), - ), + Text(image.name, key: const Key('image_picker_example_picked_image_name')), Semantics( label: 'image_picker_example_picked_image', child: mime == null || mime.startsWith('image/') ? Image.file( File(_mediaFileList![index].path), errorBuilder: - ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { + (BuildContext context, Object error, StackTrace? stackTrace) { return const Center( - child: Text( - 'This image type is not supported', - ), + child: Text('This image type is not supported'), ); }, ) @@ -280,22 +260,14 @@ class _MyHomePageState extends State { ), ); } else if (_pickImageError != null) { - return Text( - 'Pick image error: $_pickImageError', - textAlign: TextAlign.center, - ); + return Text('Pick image error: $_pickImageError', textAlign: TextAlign.center); } else { - return const Text( - 'You have not yet picked an image.', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked an image.', textAlign: TextAlign.center); } } Widget _buildInlineVideoPlayer(int index) { - final controller = VideoPlayerController.file( - File(_mediaFileList![index].path), - ); + final controller = VideoPlayerController.file(File(_mediaFileList![index].path)); controller.setVolume(1.0); controller.initialize(); controller.setLooping(true); @@ -338,11 +310,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'image1', tooltip: 'Pick multiple images', @@ -355,11 +323,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - isMedia: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, isMedia: true); }, heroTag: 'media', tooltip: 'Pick item from gallery', @@ -419,11 +383,7 @@ class _MyHomePageState extends State { backgroundColor: Colors.red, onPressed: () { _isVideo = true; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'multiVideo', tooltip: 'Pick multiple videos', @@ -460,10 +420,7 @@ class _MyHomePageState extends State { return null; } - Future _displayPickImageDialog( - BuildContext context, - OnPickImageCallback onPick, - ) async { + Future _displayPickImageDialog(BuildContext context, OnPickImageCallback onPick) async { return showDialog( context: context, builder: (BuildContext context) { @@ -473,28 +430,18 @@ class _MyHomePageState extends State { children: [ TextField( controller: maxWidthController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxWidth if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxWidth if desired'), ), TextField( controller: maxHeightController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxHeight if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxHeight if desired'), ), TextField( controller: qualityController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter quality if desired', - ), + decoration: const InputDecoration(hintText: 'Enter quality if desired'), ), ], ), @@ -537,8 +484,7 @@ class _MyHomePageState extends State { } } -typedef OnPickImageCallback = - void Function(double? maxWidth, double? maxHeight, int? quality); +typedef OnPickImageCallback = void Function(double? maxWidth, double? maxHeight, int? quality); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {super.key}); diff --git a/packages/image_picker/image_picker_macos/lib/image_picker_macos.dart b/packages/image_picker/image_picker_macos/lib/image_picker_macos.dart index 886b5cc9b875..f9b1901b10bf 100644 --- a/packages/image_picker/image_picker_macos/lib/image_picker_macos.dart +++ b/packages/image_picker/image_picker_macos/lib/image_picker_macos.dart @@ -104,9 +104,7 @@ class ImagePickerMacOS extends CameraDelegatingImagePickerPlatform { // TODO(stuartmorgan): Add a native implementation that can use // PHPickerViewController on macOS 13+, with this as a fallback for // older OS versions: https://github.com/flutter/flutter/issues/125829. - const typeGroup = XTypeGroup( - uniformTypeIdentifiers: ['public.image'], - ); + const typeGroup = XTypeGroup(uniformTypeIdentifiers: ['public.image']); final XFile? file = await fileSelector.openFile( acceptedTypeGroups: [typeGroup], ); @@ -137,9 +135,7 @@ class ImagePickerMacOS extends CameraDelegatingImagePickerPlatform { maxDuration: maxDuration, ); case ImageSource.gallery: - const typeGroup = XTypeGroup( - uniformTypeIdentifiers: ['public.movie'], - ); + const typeGroup = XTypeGroup(uniformTypeIdentifiers: ['public.movie']); final XFile? file = await fileSelector.openFile( acceptedTypeGroups: [typeGroup], ); @@ -162,9 +158,7 @@ class ImagePickerMacOS extends CameraDelegatingImagePickerPlatform { // TODO(stuartmorgan): Add a native implementation that can use // PHPickerViewController on macOS 13+, with this as a fallback for // older OS versions: https://github.com/flutter/flutter/issues/125829. - const typeGroup = XTypeGroup( - uniformTypeIdentifiers: ['public.image'], - ); + const typeGroup = XTypeGroup(uniformTypeIdentifiers: ['public.image']); final List files = await fileSelector.openFiles( acceptedTypeGroups: [typeGroup], ); @@ -178,9 +172,7 @@ class ImagePickerMacOS extends CameraDelegatingImagePickerPlatform { // TODO(stuartmorgan): Add a native implementation that can use // PHPickerViewController on macOS 13+, with this as a fallback for // older OS versions: https://github.com/flutter/flutter/issues/125829. - const typeGroup = XTypeGroup( - uniformTypeIdentifiers: ['public.movie'], - ); + const typeGroup = XTypeGroup(uniformTypeIdentifiers: ['public.movie']); final List files = await fileSelector.openFiles( acceptedTypeGroups: [typeGroup], ); @@ -200,13 +192,9 @@ class ImagePickerMacOS extends CameraDelegatingImagePickerPlatform { List files; if (options.allowMultiple) { - files = await fileSelector.openFiles( - acceptedTypeGroups: [typeGroup], - ); + files = await fileSelector.openFiles(acceptedTypeGroups: [typeGroup]); } else { - final XFile? file = await fileSelector.openFile( - acceptedTypeGroups: [typeGroup], - ); + final XFile? file = await fileSelector.openFile(acceptedTypeGroups: [typeGroup]); files = [if (file != null) file]; } return files; diff --git a/packages/image_picker/image_picker_macos/test/image_picker_macos_test.dart b/packages/image_picker/image_picker_macos/test/image_picker_macos_test.dart index 0cdae2a1107d..c505ce16caf1 100644 --- a/packages/image_picker/image_picker_macos/test/image_picker_macos_test.dart +++ b/packages/image_picker/image_picker_macos/test/image_picker_macos_test.dart @@ -29,15 +29,11 @@ void main() { mockFileSelectorPlatform = MockFileSelectorPlatform(); when( - mockFileSelectorPlatform.openFile( - acceptedTypeGroups: anyNamed('acceptedTypeGroups'), - ), + mockFileSelectorPlatform.openFile(acceptedTypeGroups: anyNamed('acceptedTypeGroups')), ).thenAnswer((_) async => null); when( - mockFileSelectorPlatform.openFiles( - acceptedTypeGroups: anyNamed('acceptedTypeGroups'), - ), + mockFileSelectorPlatform.openFiles(acceptedTypeGroups: anyNamed('acceptedTypeGroups')), ).thenAnswer((_) async => List.empty()); ImagePickerMacOS.fileSelector = mockFileSelectorPlatform; @@ -57,9 +53,7 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, [ - 'public.image', - ]); + expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, ['public.image']); }); test('getImage passes the accepted type groups correctly', () async { @@ -70,45 +64,29 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, [ - 'public.image', - ]); + expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, ['public.image']); }); - test( - 'getImageFromSource passes the accepted type groups correctly', - () async { - await plugin.getImageFromSource(source: ImageSource.gallery); - - final VerificationResult result = verify( - mockFileSelectorPlatform.openFile( - acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), - ), - ); - expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, [ - 'public.image', - ]); - }, - ); + test('getImageFromSource passes the accepted type groups correctly', () async { + await plugin.getImageFromSource(source: ImageSource.gallery); + + final VerificationResult result = verify( + mockFileSelectorPlatform.openFile( + acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), + ), + ); + expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, ['public.image']); + }); test('getImageFromSource calls delegate when source is camera', () async { const fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); - expect( - (await plugin.getImageFromSource(source: ImageSource.camera))!.path, - fakePath, - ); + expect((await plugin.getImageFromSource(source: ImageSource.camera))!.path, fakePath); }); - test( - 'getImageFromSource throws StateError when source is camera with no delegate', - () async { - await expectLater( - plugin.getImageFromSource(source: ImageSource.camera), - throwsStateError, - ); - }, - ); + test('getImageFromSource throws StateError when source is camera with no delegate', () async { + await expectLater(plugin.getImageFromSource(source: ImageSource.camera), throwsStateError); + }); test('getMultiImage passes the accepted type groups correctly', () async { await plugin.getMultiImage(); @@ -118,9 +96,7 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, [ - 'public.image', - ]); + expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, ['public.image']); }); }); @@ -133,9 +109,7 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, [ - 'public.movie', - ]); + expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, ['public.movie']); }); test('getVideo passes the accepted type groups correctly', () async { @@ -146,45 +120,29 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, [ - 'public.movie', - ]); + expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, ['public.movie']); }); test('getVideo calls delegate when source is camera', () async { const fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); - expect( - (await plugin.getVideo(source: ImageSource.camera))!.path, - fakePath, - ); + expect((await plugin.getVideo(source: ImageSource.camera))!.path, fakePath); + }); + + test('getVideo throws StateError when source is camera with no delegate', () async { + await expectLater(plugin.getVideo(source: ImageSource.camera), throwsStateError); }); - test( - 'getVideo throws StateError when source is camera with no delegate', - () async { - await expectLater( - plugin.getVideo(source: ImageSource.camera), - throwsStateError, - ); - }, - ); - - test( - 'getMultiVideoWithOptions passes the accepted type groups correctly', - () async { - await plugin.getMultiVideoWithOptions(); - - final VerificationResult result = verify( - mockFileSelectorPlatform.openFiles( - acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), - ), - ); - expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, [ - 'public.movie', - ]); - }, - ); + test('getMultiVideoWithOptions passes the accepted type groups correctly', () async { + await plugin.getMultiVideoWithOptions(); + + final VerificationResult result = verify( + mockFileSelectorPlatform.openFiles( + acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), + ), + ); + expect(capturedTypeGroups(result)[0].uniformTypeIdentifiers, ['public.movie']); + }); }); group('media', () { @@ -196,26 +154,15 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect(capturedTypeGroups(result)[0].extensions, [ - 'public.image', - 'public.movie', - ]); + expect(capturedTypeGroups(result)[0].extensions, ['public.image', 'public.movie']); }); test('multiple media handles an empty path response gracefully', () async { - expect( - await plugin.getMedia(options: const MediaOptions(allowMultiple: true)), - [], - ); + expect(await plugin.getMedia(options: const MediaOptions(allowMultiple: true)), []); }); test('single media handles an empty path response gracefully', () async { - expect( - await plugin.getMedia( - options: const MediaOptions(allowMultiple: false), - ), - [], - ); + expect(await plugin.getMedia(options: const MediaOptions(allowMultiple: false)), []); }); }); } @@ -227,16 +174,14 @@ class FakeCameraDelegate extends ImagePickerCameraDelegate { @override Future takePhoto({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } @override Future takeVideo({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } diff --git a/packages/image_picker/image_picker_macos/test/image_picker_macos_test.mocks.dart b/packages/image_picker/image_picker_macos/test/image_picker_macos_test.mocks.dart index 9b03fe8feb3e..734945d41c49 100644 --- a/packages/image_picker/image_picker_macos/test/image_picker_macos_test.mocks.dart +++ b/packages/image_picker/image_picker_macos/test/image_picker_macos_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:file_selector_platform_interface/file_selector_platform_interface.dart' - as _i2; +import 'package:file_selector_platform_interface/file_selector_platform_interface.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -25,8 +24,7 @@ import 'package:mockito/mockito.dart' as _i1; /// A class which mocks [FileSelectorPlatform]. /// /// See the documentation for Mockito's code generation for more information. -class MockFileSelectorPlatform extends _i1.Mock - implements _i2.FileSelectorPlatform { +class MockFileSelectorPlatform extends _i1.Mock implements _i2.FileSelectorPlatform { MockFileSelectorPlatform() { _i1.throwOnMissingStub(this); } @@ -36,32 +34,28 @@ class MockFileSelectorPlatform extends _i1.Mock List<_i2.XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#openFile, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future<_i2.XFile?>.value(), - ) - as _i3.Future<_i2.XFile?>); + }) => (super.noSuchMethod( + Invocation.method(#openFile, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future<_i2.XFile?>.value(), + ) as _i3.Future<_i2.XFile?>); @override _i3.Future> openFiles({ List<_i2.XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#openFiles, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future>.value(<_i2.XFile>[]), - ) - as _i3.Future>); + }) => (super.noSuchMethod( + Invocation.method(#openFiles, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future>.value(<_i2.XFile>[]), + ) as _i3.Future>); @override _i3.Future getSavePath({ @@ -69,57 +63,47 @@ class MockFileSelectorPlatform extends _i1.Mock String? initialDirectory, String? suggestedName, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#getSavePath, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #suggestedName: suggestedName, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future.value(), - ) - as _i3.Future); + }) => (super.noSuchMethod( + Invocation.method(#getSavePath, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #suggestedName: suggestedName, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future.value(), + ) as _i3.Future); @override _i3.Future<_i2.FileSaveLocation?> getSaveLocation({ List<_i2.XTypeGroup>? acceptedTypeGroups, _i2.SaveDialogOptions? options = const _i2.SaveDialogOptions(), - }) => - (super.noSuchMethod( - Invocation.method(#getSaveLocation, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #options: options, - }), - returnValue: _i3.Future<_i2.FileSaveLocation?>.value(), - ) - as _i3.Future<_i2.FileSaveLocation?>); + }) => (super.noSuchMethod( + Invocation.method(#getSaveLocation, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #options: options, + }), + returnValue: _i3.Future<_i2.FileSaveLocation?>.value(), + ) as _i3.Future<_i2.FileSaveLocation?>); @override - _i3.Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) => + _i3.Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) => (super.noSuchMethod( - Invocation.method(#getDirectoryPath, [], { - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#getDirectoryPath, [], { + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future.value(), + ) as _i3.Future); @override _i3.Future> getDirectoryPaths({ String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#getDirectoryPaths, [], { - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future>.value([]), - ) - as _i3.Future>); + }) => (super.noSuchMethod( + Invocation.method(#getDirectoryPaths, [], { + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future>.value([]), + ) as _i3.Future>); } diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart b/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart index 7ed9dc66df5e..eac1ee19b86a 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/method_channel/method_channel_image_picker.dart @@ -61,11 +61,7 @@ class MethodChannelImagePicker extends ImagePickerPlatform { int? limit, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { @@ -76,14 +72,13 @@ class MethodChannelImagePicker extends ImagePickerPlatform { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } - return _channel - .invokeMethod?>('pickMultiImage', { - 'maxWidth': maxWidth, - 'maxHeight': maxHeight, - 'imageQuality': imageQuality, - 'requestFullMetadata': requestFullMetadata, - 'limit': limit, - }); + return _channel.invokeMethod?>('pickMultiImage', { + 'maxWidth': maxWidth, + 'maxHeight': maxHeight, + 'imageQuality': imageQuality, + 'requestFullMetadata': requestFullMetadata, + 'limit': limit, + }); } Future _getImagePath({ @@ -95,11 +90,7 @@ class MethodChannelImagePicker extends ImagePickerPlatform { bool requestFullMetadata = true, }) { if (imageQuality != null && (imageQuality < 0 || imageQuality > 100)) { - throw ArgumentError.value( - imageQuality, - 'imageQuality', - 'must be between 0 and 100', - ); + throw ArgumentError.value(imageQuality, 'imageQuality', 'must be between 0 and 100'); } if (maxWidth != null && maxWidth < 0) { @@ -148,8 +139,9 @@ class MethodChannelImagePicker extends ImagePickerPlatform { @override Future retrieveLostData() async { - final Map? result = await _channel - .invokeMapMethod('retrieve'); + final Map? result = await _channel.invokeMapMethod( + 'retrieve', + ); if (result == null) { return LostData.empty(); @@ -269,8 +261,7 @@ class MethodChannelImagePicker extends ImagePickerPlatform { final List? paths = await _channel .invokeMethod?>('pickMedia', args) .then( - (List? paths) => - paths?.map((dynamic path) => XFile(path as String)).toList(), + (List? paths) => paths?.map((dynamic path) => XFile(path as String)).toList(), ); return paths ?? []; @@ -294,8 +285,9 @@ class MethodChannelImagePicker extends ImagePickerPlatform { Future getLostData() async { List? pickedFileList; - final Map? result = await _channel - .invokeMapMethod('retrieve'); + final Map? result = await _channel.invokeMapMethod( + 'retrieve', + ); if (result == null) { return LostDataResponse.empty(); @@ -326,8 +318,7 @@ class MethodChannelImagePicker extends ImagePickerPlatform { final path = result['path'] as String?; - final List? pathList = (result['pathList'] as List?) - ?.cast(); + final List? pathList = (result['pathList'] as List?)?.cast(); if (pathList != null) { pickedFileList = []; for (final String path in pathList) { diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/platform_interface/image_picker_platform.dart b/packages/image_picker/image_picker_platform_interface/lib/src/platform_interface/image_picker_platform.dart index 703c7a960ec8..57b7d652d661 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/platform_interface/image_picker_platform.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/platform_interface/image_picker_platform.dart @@ -205,11 +205,7 @@ abstract class ImagePickerPlatform extends PlatformInterface { /// /// If no images were picked, the return value is null. @Deprecated('Use getMultiImageWithOptions instead.') - Future?> getMultiImage({ - double? maxWidth, - double? maxHeight, - int? imageQuality, - }) { + Future?> getMultiImage({double? maxWidth, double? maxHeight, int? imageQuality}) { throw UnimplementedError('getMultiImage() has not been implemented.'); } @@ -331,9 +327,7 @@ abstract class ImagePickerPlatform extends PlatformInterface { Future> getMultiVideoWithOptions({ MultiVideoPickerOptions options = const MultiVideoPickerOptions(), }) { - throw UnimplementedError( - 'getMultiVideoWithOptions() has not been implemented.', - ); + throw UnimplementedError('getMultiVideoWithOptions() has not been implemented.'); } /// Returns true if the implementation supports [source]. diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart b/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart index 568a903b60bc..a67838c6f278 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/types/camera_delegate.dart @@ -38,8 +38,7 @@ abstract class ImagePickerCameraDelegate { /// /// Returns null if the photo could not be taken, or the user cancelled. Future takePhoto({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }); /// Records a video with the given [options] and returns an [XFile] to the @@ -47,7 +46,6 @@ abstract class ImagePickerCameraDelegate { /// /// Returns null if the video could not be recorded, or the user cancelled. Future takeVideo({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }); } diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/types/multi_image_picker_options.dart b/packages/image_picker/image_picker_platform_interface/lib/src/types/multi_image_picker_options.dart index ea9b22e11c98..71ebbcc87a1a 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/types/multi_image_picker_options.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/types/multi_image_picker_options.dart @@ -7,10 +7,7 @@ import 'image_options.dart'; /// Specifies options for picking multiple images from the device's gallery. class MultiImagePickerOptions { /// Creates an instance with the given [imageOptions] and [limit]. - const MultiImagePickerOptions({ - this.imageOptions = const ImageOptions(), - this.limit, - }); + const MultiImagePickerOptions({this.imageOptions = const ImageOptions(), this.limit}); /// Creates an instance with the given [imageOptions] and [limit]. /// diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart index 4c77f9550b1e..62da2a51e8a4 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/html.dart @@ -17,9 +17,7 @@ class PickedFile extends PickedFileBase { /// /// Optionally, this can be initialized with `bytes` /// so no http requests are performed to retrieve files later. - const PickedFile(this.path, {Uint8List? bytes}) - : _initBytes = bytes, - super(path); + const PickedFile(this.path, {Uint8List? bytes}) : _initBytes = bytes, super(path); @override final String path; diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart index 2ece3021f80f..18af26dff6a2 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart @@ -32,8 +32,6 @@ class PickedFile extends PickedFileBase { @override Stream openRead([int? start, int? end]) { - return _file - .openRead(start ?? 0, end) - .map((List chunk) => Uint8List.fromList(chunk)); + return _file.openRead(start ?? 0, end).map((List chunk) => Uint8List.fromList(chunk)); } } diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/picked_file.dart b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/picked_file.dart index 5cf41d443aaa..5818ae1be8ec 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/picked_file.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/picked_file.dart @@ -5,6 +5,4 @@ // TODO(dit): Remove this, https://github.com/flutter/flutter/issues/144286 export 'lost_data.dart'; -export 'unsupported.dart' - if (dart.library.js_interop) 'html.dart' - if (dart.library.io) 'io.dart'; +export 'unsupported.dart' if (dart.library.js_interop) 'html.dart' if (dart.library.io) 'io.dart'; diff --git a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/unsupported.dart b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/unsupported.dart index 449b03aca224..683cb0aeaa6c 100644 --- a/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/unsupported.dart +++ b/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/unsupported.dart @@ -12,8 +12,6 @@ class PickedFile extends PickedFileBase { /// /// Optionally, you may pass a `path`. See caveats in [PickedFileBase.path]. PickedFile(super.path) { - throw UnimplementedError( - 'PickedFile is not available in your current platform.', - ); + throw UnimplementedError('PickedFile is not available in your current platform.'); } } diff --git a/packages/image_picker/image_picker_platform_interface/test/image_picker_platform_test.dart b/packages/image_picker/image_picker_platform_interface/test/image_picker_platform_test.dart index 0d30e9b544cf..c7196442f29c 100644 --- a/packages/image_picker/image_picker_platform_interface/test/image_picker_platform_test.dart +++ b/packages/image_picker/image_picker_platform_interface/test/image_picker_platform_test.dart @@ -16,72 +16,48 @@ void main() { }); group('CameraDelegatingImagePickerPlatform', () { - test( - 'supportsImageSource returns false for camera when there is no delegate', - () async { - final implementation = FakeCameraDelegatingImagePickerPlatform(); - - expect(implementation.supportsImageSource(ImageSource.camera), false); - }, - ); - - test( - 'supportsImageSource returns true for camera when there is a delegate', - () async { - final implementation = FakeCameraDelegatingImagePickerPlatform(); - implementation.cameraDelegate = FakeCameraDelegate(); - - expect(implementation.supportsImageSource(ImageSource.camera), true); - }, - ); - - test( - 'getImageFromSource for camera throws if delegate is not set', - () async { - final implementation = FakeCameraDelegatingImagePickerPlatform(); - - await expectLater( - implementation.getImageFromSource(source: ImageSource.camera), - throwsStateError, - ); - }, - ); + test('supportsImageSource returns false for camera when there is no delegate', () async { + final implementation = FakeCameraDelegatingImagePickerPlatform(); - test('getVideo for camera throws if delegate is not set', () async { + expect(implementation.supportsImageSource(ImageSource.camera), false); + }); + + test('supportsImageSource returns true for camera when there is a delegate', () async { + final implementation = FakeCameraDelegatingImagePickerPlatform(); + implementation.cameraDelegate = FakeCameraDelegate(); + + expect(implementation.supportsImageSource(ImageSource.camera), true); + }); + + test('getImageFromSource for camera throws if delegate is not set', () async { final implementation = FakeCameraDelegatingImagePickerPlatform(); await expectLater( - implementation.getVideo(source: ImageSource.camera), + implementation.getImageFromSource(source: ImageSource.camera), throwsStateError, ); }); + test('getVideo for camera throws if delegate is not set', () async { + final implementation = FakeCameraDelegatingImagePickerPlatform(); + + await expectLater(implementation.getVideo(source: ImageSource.camera), throwsStateError); + }); + test('getImageFromSource for camera calls delegate if set', () async { const fakePath = '/tmp/foo'; final implementation = FakeCameraDelegatingImagePickerPlatform(); - implementation.cameraDelegate = FakeCameraDelegate( - result: XFile(fakePath), - ); + implementation.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); - expect( - (await implementation.getImageFromSource( - source: ImageSource.camera, - ))!.path, - fakePath, - ); + expect((await implementation.getImageFromSource(source: ImageSource.camera))!.path, fakePath); }); test('getVideo for camera calls delegate if set', () async { const fakePath = '/tmp/foo'; final implementation = FakeCameraDelegatingImagePickerPlatform(); - implementation.cameraDelegate = FakeCameraDelegate( - result: XFile(fakePath), - ); + implementation.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); - expect( - (await implementation.getVideo(source: ImageSource.camera))!.path, - fakePath, - ); + expect((await implementation.getVideo(source: ImageSource.camera))!.path, fakePath); }); }); @@ -89,17 +65,13 @@ void main() { 'unimplemented error', () { final implementation = FakeCameraDelegatingImagePickerPlatform(); - expect( - () => implementation.getMultiVideoWithOptions(), - throwsUnimplementedError, - ); + expect(() => implementation.getMultiVideoWithOptions(), throwsUnimplementedError); }); } class FakeImagePickerPlatform extends ImagePickerPlatform {} -class FakeCameraDelegatingImagePickerPlatform - extends CameraDelegatingImagePickerPlatform {} +class FakeCameraDelegatingImagePickerPlatform extends CameraDelegatingImagePickerPlatform {} class FakeCameraDelegate extends ImagePickerCameraDelegate { FakeCameraDelegate({this.result}); @@ -108,16 +80,14 @@ class FakeCameraDelegate extends ImagePickerCameraDelegate { @override Future takePhoto({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } @override Future takeVideo({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } diff --git a/packages/image_picker/image_picker_platform_interface/test/media_options_test.dart b/packages/image_picker/image_picker_platform_interface/test/media_options_test.dart index 11ecbec7b50d..3b5b5616db2a 100644 --- a/packages/image_picker/image_picker_platform_interface/test/media_options_test.dart +++ b/packages/image_picker/image_picker_platform_interface/test/media_options_test.dart @@ -8,34 +8,21 @@ import 'package:image_picker_platform_interface/src/types/types.dart'; void main() { group('MediaOptions', () { test('createAndValidate does not throw when allowMultiple is true', () { - expect( - () => MediaOptions.createAndValidate(allowMultiple: true), - returnsNormally, - ); + expect(() => MediaOptions.createAndValidate(allowMultiple: true), returnsNormally); }); test('createAndValidate does not throw when allowMultiple is false', () { - expect( - () => MediaOptions.createAndValidate(allowMultiple: false), - returnsNormally, - ); + expect(() => MediaOptions.createAndValidate(allowMultiple: false), returnsNormally); }); test('createAndValidate does not throw error for correct limit', () { - expect( - () => MediaOptions.createAndValidate(allowMultiple: true, limit: 2), - returnsNormally, - ); + expect(() => MediaOptions.createAndValidate(allowMultiple: true, limit: 2), returnsNormally); }); test('createAndValidate throws error for too small limit', () { final Matcher throwsLimitArgumentError = throwsA( isA() .having((ArgumentError error) => error.name, 'name', 'limit') - .having( - (ArgumentError error) => error.message, - 'message', - 'cannot be lower than 2', - ), + .having((ArgumentError error) => error.message, 'message', 'cannot be lower than 2'), ); expect( @@ -52,14 +39,11 @@ void main() { ); }); - test( - 'createAndValidate throw error when allowMultiple is false and has limit', - () { - expect( - () => MediaOptions.createAndValidate(allowMultiple: false, limit: 2), - throwsArgumentError, - ); - }, - ); + test('createAndValidate throw error when allowMultiple is false and has limit', () { + expect( + () => MediaOptions.createAndValidate(allowMultiple: false, limit: 2), + throwsArgumentError, + ); + }); }); } diff --git a/packages/image_picker/image_picker_platform_interface/test/method_channel_image_picker_test.dart b/packages/image_picker/image_picker_platform_interface/test/method_channel_image_picker_test.dart index 3401dd0a6b75..d26450ebc722 100644 --- a/packages/image_picker/image_picker_platform_interface/test/method_channel_image_picker_test.dart +++ b/packages/image_picker/image_picker_platform_interface/test/method_channel_image_picker_test.dart @@ -18,13 +18,13 @@ void main() { setUp(() { returnValue = ''; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - return returnValue; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + log.add(methodCall); + return returnValue; + }, + ); log.clear(); }); @@ -64,21 +64,9 @@ void main() { await picker.pickImage(source: ImageSource.camera); await picker.pickImage(source: ImageSource.camera, maxWidth: 10.0); await picker.pickImage(source: ImageSource.camera, maxHeight: 10.0); - await picker.pickImage( - source: ImageSource.camera, - maxWidth: 10.0, - maxHeight: 20.0, - ); - await picker.pickImage( - source: ImageSource.camera, - maxWidth: 10.0, - imageQuality: 70, - ); - await picker.pickImage( - source: ImageSource.camera, - maxHeight: 10.0, - imageQuality: 70, - ); + await picker.pickImage(source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0); + await picker.pickImage(source: ImageSource.camera, maxWidth: 10.0, imageQuality: 70); + await picker.pickImage(source: ImageSource.camera, maxHeight: 10.0, imageQuality: 70); await picker.pickImage( source: ImageSource.camera, maxWidth: 10.0, @@ -174,8 +162,7 @@ void main() { ); expect( - () => - picker.pickImage(imageQuality: 101, source: ImageSource.gallery), + () => picker.pickImage(imageQuality: 101, source: ImageSource.gallery), throwsArgumentError, ); @@ -203,11 +190,10 @@ void main() { }); test('handles a null image path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect(await picker.pickImage(source: ImageSource.gallery), isNull); expect(await picker.pickImage(source: ImageSource.camera), isNull); @@ -280,11 +266,7 @@ void main() { await picker.pickMultiImage(maxWidth: 10.0, maxHeight: 20.0); await picker.pickMultiImage(maxWidth: 10.0, imageQuality: 70); await picker.pickMultiImage(maxHeight: 10.0, imageQuality: 70); - await picker.pickMultiImage( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); + await picker.pickMultiImage(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); expect(log, [ isMethodCall( @@ -362,36 +344,23 @@ void main() { test('does not accept a negative width or height argument', () { returnValue = ['0', '1']; - expect( - () => picker.pickMultiImage(maxWidth: -1.0), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(maxWidth: -1.0), throwsArgumentError); - expect( - () => picker.pickMultiImage(maxHeight: -1.0), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(maxHeight: -1.0), throwsArgumentError); }); test('does not accept an invalid imageQuality argument', () { returnValue = ['0', '1']; - expect( - () => picker.pickMultiImage(imageQuality: -1), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(imageQuality: -1), throwsArgumentError); - expect( - () => picker.pickMultiImage(imageQuality: 101), - throwsArgumentError, - ); + expect(() => picker.pickMultiImage(imageQuality: 101), throwsArgumentError); }); test('handles a null image path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect(await picker.pickMultiImage(), isNull); expect(await picker.pickMultiImage(), isNull); @@ -406,19 +375,11 @@ void main() { expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'cameraDevice': 0, - 'maxDuration': null, - }, + arguments: {'source': 0, 'cameraDevice': 0, 'maxDuration': null}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 1, - 'cameraDevice': 0, - 'maxDuration': null, - }, + arguments: {'source': 1, 'cameraDevice': 0, 'maxDuration': null}, ), ]); }); @@ -429,56 +390,33 @@ void main() { source: ImageSource.camera, maxDuration: const Duration(seconds: 10), ); - await picker.pickVideo( - source: ImageSource.camera, - maxDuration: const Duration(minutes: 1), - ); - await picker.pickVideo( - source: ImageSource.camera, - maxDuration: const Duration(hours: 1), - ); + await picker.pickVideo(source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); + await picker.pickVideo(source: ImageSource.camera, maxDuration: const Duration(hours: 1)); expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': null, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': null, 'cameraDevice': 0}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': 10, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': 10, 'cameraDevice': 0}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': 60, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': 60, 'cameraDevice': 0}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': 3600, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': 3600, 'cameraDevice': 0}, ), ]); }); test('handles a null video path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect(await picker.pickVideo(source: ImageSource.gallery), isNull); expect(await picker.pickVideo(source: ImageSource.camera), isNull); @@ -490,11 +428,7 @@ void main() { expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'cameraDevice': 0, - 'maxDuration': null, - }, + arguments: {'source': 0, 'cameraDevice': 0, 'maxDuration': null}, ), ]); }); @@ -508,11 +442,7 @@ void main() { expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': null, - 'cameraDevice': 1, - }, + arguments: {'source': 0, 'maxDuration': null, 'cameraDevice': 1}, ), ]); }); @@ -520,12 +450,12 @@ void main() { group('#retrieveLostData', () { test('retrieveLostData get success response', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return {'type': 'image', 'path': '/example/path'}; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return {'type': 'image', 'path': '/example/path'}; + }, + ); final LostData response = await picker.retrieveLostData(); expect(response.type, RetrieveType.image); expect(response.file, isNotNull); @@ -533,16 +463,16 @@ void main() { }); test('retrieveLostData get error response', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return { - 'type': 'video', - 'errorCode': 'test_error_code', - 'errorMessage': 'test_error_message', - }; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return { + 'type': 'video', + 'errorCode': 'test_error_code', + 'errorMessage': 'test_error_message', + }; + }, + ); final LostData response = await picker.retrieveLostData(); expect(response.type, RetrieveType.video); expect(response.exception, isNotNull); @@ -551,27 +481,27 @@ void main() { }); test('retrieveLostData get null response', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return null; + }, + ); expect((await picker.retrieveLostData()).isEmpty, true); }); test('retrieveLostData get both path and error should throw', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return { - 'type': 'video', - 'errorCode': 'test_error_code', - 'errorMessage': 'test_error_message', - 'path': '/example/path', - }; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return { + 'type': 'video', + 'errorCode': 'test_error_code', + 'errorMessage': 'test_error_message', + 'path': '/example/path', + }; + }, + ); expect(picker.retrieveLostData(), throwsAssertionError); }); }); @@ -611,21 +541,9 @@ void main() { await picker.getImage(source: ImageSource.camera); await picker.getImage(source: ImageSource.camera, maxWidth: 10.0); await picker.getImage(source: ImageSource.camera, maxHeight: 10.0); - await picker.getImage( - source: ImageSource.camera, - maxWidth: 10.0, - maxHeight: 20.0, - ); - await picker.getImage( - source: ImageSource.camera, - maxWidth: 10.0, - imageQuality: 70, - ); - await picker.getImage( - source: ImageSource.camera, - maxHeight: 10.0, - imageQuality: 70, - ); + await picker.getImage(source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0); + await picker.getImage(source: ImageSource.camera, maxWidth: 10.0, imageQuality: 70); + await picker.getImage(source: ImageSource.camera, maxHeight: 10.0, imageQuality: 70); await picker.getImage( source: ImageSource.camera, maxWidth: 10.0, @@ -749,11 +667,10 @@ void main() { }); test('handles a null image path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect(await picker.getImage(source: ImageSource.gallery), isNull); expect(await picker.getImage(source: ImageSource.camera), isNull); @@ -826,11 +743,7 @@ void main() { await picker.getMultiImage(maxWidth: 10.0, maxHeight: 20.0); await picker.getMultiImage(maxWidth: 10.0, imageQuality: 70); await picker.getMultiImage(maxHeight: 10.0, imageQuality: 70); - await picker.getMultiImage( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ); + await picker.getMultiImage(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70); expect(log, [ isMethodCall( @@ -910,31 +823,21 @@ void main() { returnValue = ['0', '1']; expect(() => picker.getMultiImage(maxWidth: -1.0), throwsArgumentError); - expect( - () => picker.getMultiImage(maxHeight: -1.0), - throwsArgumentError, - ); + expect(() => picker.getMultiImage(maxHeight: -1.0), throwsArgumentError); }); test('does not accept an invalid imageQuality argument', () { returnValue = ['0', '1']; - expect( - () => picker.getMultiImage(imageQuality: -1), - throwsArgumentError, - ); + expect(() => picker.getMultiImage(imageQuality: -1), throwsArgumentError); - expect( - () => picker.getMultiImage(imageQuality: 101), - throwsArgumentError, - ); + expect(() => picker.getMultiImage(imageQuality: 101), throwsArgumentError); }); test('handles a null image path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect(await picker.getMultiImage(), isNull); expect(await picker.getMultiImage(), isNull); @@ -944,9 +847,7 @@ void main() { group('#getMedia', () { test('calls the method correctly', () async { returnValue = ['0']; - await picker.getMedia( - options: MediaOptions.createAndValidate(allowMultiple: true), - ); + await picker.getMedia(options: MediaOptions.createAndValidate(allowMultiple: true)); expect(log, [ isMethodCall( @@ -965,9 +866,7 @@ void main() { test('passes the selection options correctly', () async { // Default options returnValue = ['0']; - await picker.getMedia( - options: MediaOptions.createAndValidate(allowMultiple: true), - ); + await picker.getMedia(options: MediaOptions.createAndValidate(allowMultiple: true)); // Various image options returnValue = ['0']; await picker.getMedia( @@ -1101,39 +1000,26 @@ void main() { final Matcher throwsLimitArgumentError = throwsA( isA() .having((ArgumentError error) => error.name, 'name', 'limit') - .having( - (ArgumentError error) => error.message, - 'message', - 'cannot be lower than 2', - ), + .having((ArgumentError error) => error.message, 'message', 'cannot be lower than 2'), ); expect( () => picker.getMedia( - options: MediaOptions.createAndValidate( - allowMultiple: true, - limit: -1, - ), + options: MediaOptions.createAndValidate(allowMultiple: true, limit: -1), ), throwsLimitArgumentError, ); expect( () => picker.getMedia( - options: MediaOptions.createAndValidate( - allowMultiple: true, - limit: 0, - ), + options: MediaOptions.createAndValidate(allowMultiple: true, limit: 0), ), throwsLimitArgumentError, ); expect( () => picker.getMedia( - options: MediaOptions.createAndValidate( - allowMultiple: true, - limit: 1, - ), + options: MediaOptions.createAndValidate(allowMultiple: true, limit: 1), ), throwsLimitArgumentError, ); @@ -1142,25 +1028,19 @@ void main() { test('does not accept a not null limit when allowMultiple is false', () { expect( () => picker.getMedia( - options: MediaOptions.createAndValidate( - allowMultiple: false, - limit: 5, - ), + options: MediaOptions.createAndValidate(allowMultiple: false, limit: 5), ), throwsArgumentError, ); }); test('handles a null path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect( - await picker.getMedia( - options: MediaOptions.createAndValidate(allowMultiple: true), - ), + await picker.getMedia(options: MediaOptions.createAndValidate(allowMultiple: true)), [], ); }); @@ -1174,79 +1054,45 @@ void main() { expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'cameraDevice': 0, - 'maxDuration': null, - }, + arguments: {'source': 0, 'cameraDevice': 0, 'maxDuration': null}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 1, - 'cameraDevice': 0, - 'maxDuration': null, - }, + arguments: {'source': 1, 'cameraDevice': 0, 'maxDuration': null}, ), ]); }); test('passes the duration argument correctly', () async { await picker.getVideo(source: ImageSource.camera); - await picker.getVideo( - source: ImageSource.camera, - maxDuration: const Duration(seconds: 10), - ); - await picker.getVideo( - source: ImageSource.camera, - maxDuration: const Duration(minutes: 1), - ); - await picker.getVideo( - source: ImageSource.camera, - maxDuration: const Duration(hours: 1), - ); + await picker.getVideo(source: ImageSource.camera, maxDuration: const Duration(seconds: 10)); + await picker.getVideo(source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); + await picker.getVideo(source: ImageSource.camera, maxDuration: const Duration(hours: 1)); expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': null, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': null, 'cameraDevice': 0}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': 10, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': 10, 'cameraDevice': 0}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': 60, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': 60, 'cameraDevice': 0}, ), isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': 3600, - 'cameraDevice': 0, - }, + arguments: {'source': 0, 'maxDuration': 3600, 'cameraDevice': 0}, ), ]); }); test('handles a null video path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect(await picker.getVideo(source: ImageSource.gallery), isNull); expect(await picker.getVideo(source: ImageSource.camera), isNull); @@ -1258,11 +1104,7 @@ void main() { expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'cameraDevice': 0, - 'maxDuration': null, - }, + arguments: {'source': 0, 'cameraDevice': 0, 'maxDuration': null}, ), ]); }); @@ -1276,11 +1118,7 @@ void main() { expect(log, [ isMethodCall( 'pickVideo', - arguments: { - 'source': 0, - 'maxDuration': null, - 'cameraDevice': 1, - }, + arguments: {'source': 0, 'maxDuration': null, 'cameraDevice': 1}, ), ]); }); @@ -1288,12 +1126,12 @@ void main() { group('#getLostData', () { test('getLostData get success response', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return {'type': 'image', 'path': '/example/path'}; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return {'type': 'image', 'path': '/example/path'}; + }, + ); final LostDataResponse response = await picker.getLostData(); expect(response.type, RetrieveType.image); expect(response.file, isNotNull); @@ -1301,16 +1139,16 @@ void main() { }); test('getLostData should successfully retrieve multiple files', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return { - 'type': 'image', - 'path': '/example/path1', - 'pathList': ['/example/path0', '/example/path1'], - }; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return { + 'type': 'image', + 'path': '/example/path1', + 'pathList': ['/example/path0', '/example/path1'], + }; + }, + ); final LostDataResponse response = await picker.getLostData(); expect(response.type, RetrieveType.image); expect(response.file, isNotNull); @@ -1320,16 +1158,16 @@ void main() { }); test('getLostData get error response', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return { - 'type': 'video', - 'errorCode': 'test_error_code', - 'errorMessage': 'test_error_message', - }; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return { + 'type': 'video', + 'errorCode': 'test_error_code', + 'errorMessage': 'test_error_message', + }; + }, + ); final LostDataResponse response = await picker.getLostData(); expect(response.type, RetrieveType.video); expect(response.exception, isNotNull); @@ -1338,27 +1176,27 @@ void main() { }); test('getLostData get null response', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return null; + }, + ); expect((await picker.getLostData()).isEmpty, true); }); test('getLostData get both path and error should throw', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(picker.channel, ( - MethodCall methodCall, - ) async { - return { - 'type': 'video', - 'errorCode': 'test_error_code', - 'errorMessage': 'test_error_message', - 'path': '/example/path', - }; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) async { + return { + 'type': 'video', + 'errorCode': 'test_error_code', + 'errorMessage': 'test_error_message', + 'path': '/example/path', + }; + }, + ); expect(picker.getLostData(), throwsAssertionError); }); }); @@ -1418,11 +1256,7 @@ void main() { ); await picker.getImageFromSource( source: ImageSource.camera, - options: const ImagePickerOptions( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ), + options: const ImagePickerOptions(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70), ); expect(log, [ @@ -1559,20 +1393,13 @@ void main() { }); test('handles a null image path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); - - expect( - await picker.getImageFromSource(source: ImageSource.gallery), - isNull, - ); - expect( - await picker.getImageFromSource(source: ImageSource.camera), - isNull, + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, ); + + expect(await picker.getImageFromSource(source: ImageSource.gallery), isNull); + expect(await picker.getImageFromSource(source: ImageSource.camera), isNull); }); test('camera position defaults to back', () async { @@ -1596,9 +1423,7 @@ void main() { test('camera position can set to front', () async { await picker.getImageFromSource( source: ImageSource.camera, - options: const ImagePickerOptions( - preferredCameraDevice: CameraDevice.front, - ), + options: const ImagePickerOptions(preferredCameraDevice: CameraDevice.front), ); expect(log, [ @@ -1657,157 +1482,138 @@ void main() { ]); }); - test( - 'passes the width, height and imageQuality arguments correctly', - () async { - returnValue = ['0', '1']; - await picker.getMultiImageWithOptions(); - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxWidth: 10.0), - ), - ); - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxHeight: 10.0), - ), - ); - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxWidth: 10.0, maxHeight: 20.0), - ), - ); - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxWidth: 10.0, imageQuality: 70), - ), - ); - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxHeight: 10.0, imageQuality: 70), - ), - ); - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ), - ), - ); - await picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions( - maxWidth: 10.0, - maxHeight: 20.0, - imageQuality: 70, - ), - limit: 5, - ), - ); - - expect(log, [ - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': null, - 'maxHeight': null, - 'imageQuality': null, - 'requestFullMetadata': true, - 'limit': null, - }, - ), - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': 10.0, - 'maxHeight': null, - 'imageQuality': null, - 'requestFullMetadata': true, - 'limit': null, - }, - ), - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': null, - 'maxHeight': 10.0, - 'imageQuality': null, - 'requestFullMetadata': true, - 'limit': null, - }, - ), - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': 10.0, - 'maxHeight': 20.0, - 'imageQuality': null, - 'requestFullMetadata': true, - 'limit': null, - }, - ), - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': 10.0, - 'maxHeight': null, - 'imageQuality': 70, - 'requestFullMetadata': true, - 'limit': null, - }, - ), - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': null, - 'maxHeight': 10.0, - 'imageQuality': 70, - 'requestFullMetadata': true, - 'limit': null, - }, - ), - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': 10.0, - 'maxHeight': 20.0, - 'imageQuality': 70, - 'requestFullMetadata': true, - 'limit': null, - }, - ), - isMethodCall( - 'pickMultiImage', - arguments: { - 'maxWidth': 10.0, - 'maxHeight': 20.0, - 'imageQuality': 70, - 'requestFullMetadata': true, - 'limit': 5, - }, - ), - ]); - }, - ); + test('passes the width, height and imageQuality arguments correctly', () async { + returnValue = ['0', '1']; + await picker.getMultiImageWithOptions(); + await picker.getMultiImageWithOptions( + options: const MultiImagePickerOptions(imageOptions: ImageOptions(maxWidth: 10.0)), + ); + await picker.getMultiImageWithOptions( + options: const MultiImagePickerOptions(imageOptions: ImageOptions(maxHeight: 10.0)), + ); + await picker.getMultiImageWithOptions( + options: const MultiImagePickerOptions( + imageOptions: ImageOptions(maxWidth: 10.0, maxHeight: 20.0), + ), + ); + await picker.getMultiImageWithOptions( + options: const MultiImagePickerOptions( + imageOptions: ImageOptions(maxWidth: 10.0, imageQuality: 70), + ), + ); + await picker.getMultiImageWithOptions( + options: const MultiImagePickerOptions( + imageOptions: ImageOptions(maxHeight: 10.0, imageQuality: 70), + ), + ); + await picker.getMultiImageWithOptions( + options: const MultiImagePickerOptions( + imageOptions: ImageOptions(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70), + ), + ); + await picker.getMultiImageWithOptions( + options: const MultiImagePickerOptions( + imageOptions: ImageOptions(maxWidth: 10.0, maxHeight: 20.0, imageQuality: 70), + limit: 5, + ), + ); + + expect(log, [ + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': null, + 'maxHeight': null, + 'imageQuality': null, + 'requestFullMetadata': true, + 'limit': null, + }, + ), + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': 10.0, + 'maxHeight': null, + 'imageQuality': null, + 'requestFullMetadata': true, + 'limit': null, + }, + ), + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': null, + 'maxHeight': 10.0, + 'imageQuality': null, + 'requestFullMetadata': true, + 'limit': null, + }, + ), + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': 10.0, + 'maxHeight': 20.0, + 'imageQuality': null, + 'requestFullMetadata': true, + 'limit': null, + }, + ), + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': 10.0, + 'maxHeight': null, + 'imageQuality': 70, + 'requestFullMetadata': true, + 'limit': null, + }, + ), + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': null, + 'maxHeight': 10.0, + 'imageQuality': 70, + 'requestFullMetadata': true, + 'limit': null, + }, + ), + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': 10.0, + 'maxHeight': 20.0, + 'imageQuality': 70, + 'requestFullMetadata': true, + 'limit': null, + }, + ), + isMethodCall( + 'pickMultiImage', + arguments: { + 'maxWidth': 10.0, + 'maxHeight': 20.0, + 'imageQuality': 70, + 'requestFullMetadata': true, + 'limit': 5, + }, + ), + ]); + }); test('does not accept a negative width or height argument', () { returnValue = ['0', '1']; expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxWidth: -1.0), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(maxWidth: -1.0)), ), throwsArgumentError, ); expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(maxHeight: -1.0), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(maxHeight: -1.0)), ), throwsArgumentError, ); @@ -1817,18 +1623,14 @@ void main() { returnValue = ['0', '1']; expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(imageQuality: -1), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(imageQuality: -1)), ), throwsArgumentError, ); expect( () => picker.getMultiImageWithOptions( - options: const MultiImagePickerOptions( - imageOptions: ImageOptions(imageQuality: 101), - ), + options: const MultiImagePickerOptions(imageOptions: ImageOptions(imageQuality: 101)), ), throwsArgumentError, ); @@ -1839,11 +1641,7 @@ void main() { final Matcher throwsLimitArgumentError = throwsA( isA() .having((ArgumentError error) => error.name, 'name', 'limit') - .having( - (ArgumentError error) => error.message, - 'message', - 'cannot be lower than 2', - ), + .having((ArgumentError error) => error.message, 'message', 'cannot be lower than 2'), ); expect( @@ -1869,11 +1667,10 @@ void main() { }); test('handles a null image path response gracefully', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler( - picker.channel, - (MethodCall methodCall) => null, - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + picker.channel, + (MethodCall methodCall) => null, + ); expect(await picker.getMultiImage(), isNull); expect(await picker.getMultiImage(), isNull); diff --git a/packages/image_picker/image_picker_platform_interface/test/multi_image_picker_options_test.dart b/packages/image_picker/image_picker_platform_interface/test/multi_image_picker_options_test.dart index 5ef48cc06203..72cc03782e0c 100644 --- a/packages/image_picker/image_picker_platform_interface/test/multi_image_picker_options_test.dart +++ b/packages/image_picker/image_picker_platform_interface/test/multi_image_picker_options_test.dart @@ -8,35 +8,19 @@ import 'package:image_picker_platform_interface/src/types/types.dart'; void main() { group('MultiImagePickerOptions', () { test('createAndValidate does not throw error for correct limit', () { - expect( - () => MultiImagePickerOptions.createAndValidate(limit: 2), - returnsNormally, - ); + expect(() => MultiImagePickerOptions.createAndValidate(limit: 2), returnsNormally); }); test('createAndValidate throws error for too small limit', () { final Matcher throwsLimitArgumentError = throwsA( isA() .having((ArgumentError error) => error.name, 'name', 'limit') - .having( - (ArgumentError error) => error.message, - 'message', - 'cannot be lower than 2', - ), + .having((ArgumentError error) => error.message, 'message', 'cannot be lower than 2'), ); - expect( - () => MultiImagePickerOptions.createAndValidate(limit: 1), - throwsLimitArgumentError, - ); - expect( - () => MultiImagePickerOptions.createAndValidate(limit: 0), - throwsLimitArgumentError, - ); - expect( - () => MultiImagePickerOptions.createAndValidate(limit: -1), - throwsLimitArgumentError, - ); + expect(() => MultiImagePickerOptions.createAndValidate(limit: 1), throwsLimitArgumentError); + expect(() => MultiImagePickerOptions.createAndValidate(limit: 0), throwsLimitArgumentError); + expect(() => MultiImagePickerOptions.createAndValidate(limit: -1), throwsLimitArgumentError); }); }); } diff --git a/packages/image_picker/image_picker_platform_interface/test/picked_file_html_test.dart b/packages/image_picker/image_picker_platform_interface/test/picked_file_html_test.dart index a7d87fa0d074..4044028da814 100644 --- a/packages/image_picker/image_picker_platform_interface/test/picked_file_html_test.dart +++ b/packages/image_picker/image_picker_platform_interface/test/picked_file_html_test.dart @@ -15,10 +15,7 @@ import 'package:web/web.dart' as web; const String expectedStringContents = 'Hello, world!'; final Uint8List bytes = utf8.encode(expectedStringContents); -final web.File textFile = web.File( - [bytes.toJS].toJS, - 'hello.txt', -); +final web.File textFile = web.File([bytes.toJS].toJS, 'hello.txt'); final String textFileUrl = web.URL.createObjectURL(textFile); void main() { @@ -37,10 +34,7 @@ void main() { }); test('Stream can be sliced', () async { - expect( - await pickedFile.openRead(2, 5).first, - equals(bytes.sublist(2, 5)), - ); + expect(await pickedFile.openRead(2, 5).first, equals(bytes.sublist(2, 5))); }); }); } diff --git a/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart b/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart index 1393d4912ef4..56fae3eb8891 100644 --- a/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart +++ b/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart @@ -12,9 +12,7 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; -final String pathPrefix = Directory.current.path.endsWith('test') - ? './assets/' - : './test/assets/'; +final String pathPrefix = Directory.current.path.endsWith('test') ? './assets/' : './test/assets/'; final String path = '${pathPrefix}hello.txt'; const String expectedStringContents = 'Hello, world!'; final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents)); @@ -37,10 +35,7 @@ void main() { }); test('Stream can be sliced', () async { - expect( - await pickedFile.openRead(2, 5).first, - equals(bytes.sublist(2, 5)), - ); + expect(await pickedFile.openRead(2, 5).first, equals(bytes.sublist(2, 5))); }); }); } diff --git a/packages/image_picker/image_picker_windows/example/lib/main.dart b/packages/image_picker/image_picker_windows/example/lib/main.dart index 4bc0ab606c30..5f73ceab67f5 100644 --- a/packages/image_picker/image_picker_windows/example/lib/main.dart +++ b/packages/image_picker/image_picker_windows/example/lib/main.dart @@ -110,15 +110,10 @@ class _MyHomePageState extends State { ); final List pickedFileList = isMedia ? await _picker.getMedia( - options: MediaOptions( - allowMultiple: allowMultiple, - imageOptions: imageOptions, - ), + options: MediaOptions(allowMultiple: allowMultiple, imageOptions: imageOptions), ) : await _picker.getMultiImageWithOptions( - options: MultiImagePickerOptions( - imageOptions: imageOptions, - ), + options: MultiImagePickerOptions(imageOptions: imageOptions), ); if (pickedFileList.isNotEmpty && context.mounted) { _showPickedSnackBar(context, pickedFileList); @@ -222,15 +217,9 @@ class _MyHomePageState extends State { return retrieveError; } if (_controller == null) { - return const Text( - 'You have not yet picked a video', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked a video', textAlign: TextAlign.center); } - return Padding( - padding: const EdgeInsets.all(10.0), - child: AspectRatioVideo(_controller), - ); + return Padding(padding: const EdgeInsets.all(10.0), child: AspectRatioVideo(_controller)); } Widget _previewImages() { @@ -249,25 +238,16 @@ class _MyHomePageState extends State { return Column( mainAxisSize: MainAxisSize.min, children: [ - Text( - image.name, - key: const Key('image_picker_example_picked_image_name'), - ), + Text(image.name, key: const Key('image_picker_example_picked_image_name')), Semantics( label: 'image_picker_example_picked_image', child: mime == null || mime.startsWith('image/') ? Image.file( File(_mediaFileList![index].path), errorBuilder: - ( - BuildContext context, - Object error, - StackTrace? stackTrace, - ) { + (BuildContext context, Object error, StackTrace? stackTrace) { return const Center( - child: Text( - 'This image type is not supported', - ), + child: Text('This image type is not supported'), ); }, ) @@ -280,22 +260,14 @@ class _MyHomePageState extends State { ), ); } else if (_pickImageError != null) { - return Text( - 'Pick image error: $_pickImageError', - textAlign: TextAlign.center, - ); + return Text('Pick image error: $_pickImageError', textAlign: TextAlign.center); } else { - return const Text( - 'You have not yet picked an image.', - textAlign: TextAlign.center, - ); + return const Text('You have not yet picked an image.', textAlign: TextAlign.center); } } Widget _buildInlineVideoPlayer(int index) { - final controller = VideoPlayerController.file( - File(_mediaFileList![index].path), - ); + final controller = VideoPlayerController.file(File(_mediaFileList![index].path)); controller.setVolume(1.0); controller.initialize(); controller.setLooping(true); @@ -338,11 +310,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'image1', tooltip: 'Pick multiple images', @@ -355,11 +323,7 @@ class _MyHomePageState extends State { child: FloatingActionButton.extended( onPressed: () { _isVideo = false; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - isMedia: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, isMedia: true); }, heroTag: 'media', tooltip: 'Pick item from gallery', @@ -419,11 +383,7 @@ class _MyHomePageState extends State { backgroundColor: Colors.red, onPressed: () { _isVideo = true; - _onImageButtonPressed( - ImageSource.gallery, - context: context, - allowMultiple: true, - ); + _onImageButtonPressed(ImageSource.gallery, context: context, allowMultiple: true); }, heroTag: 'multiVideo', tooltip: 'Pick multiple videos', @@ -460,10 +420,7 @@ class _MyHomePageState extends State { return null; } - Future _displayPickImageDialog( - BuildContext context, - OnPickImageCallback onPick, - ) async { + Future _displayPickImageDialog(BuildContext context, OnPickImageCallback onPick) async { return showDialog( context: context, builder: (BuildContext context) { @@ -473,28 +430,18 @@ class _MyHomePageState extends State { children: [ TextField( controller: maxWidthController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxWidth if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxWidth if desired'), ), TextField( controller: maxHeightController, - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - decoration: const InputDecoration( - hintText: 'Enter maxHeight if desired', - ), + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(hintText: 'Enter maxHeight if desired'), ), TextField( controller: qualityController, keyboardType: TextInputType.number, - decoration: const InputDecoration( - hintText: 'Enter quality if desired', - ), + decoration: const InputDecoration(hintText: 'Enter quality if desired'), ), ], ), @@ -537,8 +484,7 @@ class _MyHomePageState extends State { } } -typedef OnPickImageCallback = - void Function(double? maxWidth, double? maxHeight, int? quality); +typedef OnPickImageCallback = void Function(double? maxWidth, double? maxHeight, int? quality); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {super.key}); diff --git a/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart b/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart index 3456562909f7..8fe752b69baf 100644 --- a/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart +++ b/packages/image_picker/image_picker_windows/lib/image_picker_windows.dart @@ -214,13 +214,9 @@ class ImagePickerWindows extends CameraDelegatingImagePickerPlatform { List files; if (options.allowMultiple) { - files = await fileSelector.openFiles( - acceptedTypeGroups: [typeGroup], - ); + files = await fileSelector.openFiles(acceptedTypeGroups: [typeGroup]); } else { - final XFile? file = await fileSelector.openFile( - acceptedTypeGroups: [typeGroup], - ); + final XFile? file = await fileSelector.openFile(acceptedTypeGroups: [typeGroup]); files = [if (file != null) file]; } return files; diff --git a/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart b/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart index ed224a8b6de2..5d66e888a4d1 100644 --- a/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart +++ b/packages/image_picker/image_picker_windows/test/image_picker_windows_test.dart @@ -30,15 +30,11 @@ void main() { mockFileSelectorPlatform = MockFileSelectorPlatform(); when( - mockFileSelectorPlatform.openFile( - acceptedTypeGroups: anyNamed('acceptedTypeGroups'), - ), + mockFileSelectorPlatform.openFile(acceptedTypeGroups: anyNamed('acceptedTypeGroups')), ).thenAnswer((_) async => null); when( - mockFileSelectorPlatform.openFiles( - acceptedTypeGroups: anyNamed('acceptedTypeGroups'), - ), + mockFileSelectorPlatform.openFiles(acceptedTypeGroups: anyNamed('acceptedTypeGroups')), ).thenAnswer((_) async => List.empty()); ImagePickerWindows.fileSelector = mockFileSelectorPlatform; @@ -58,10 +54,7 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect( - capturedTypeGroups(result)[0].extensions, - ImagePickerWindows.imageFormats, - ); + expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); test('getImage passes the accepted type groups correctly', () async { @@ -72,10 +65,7 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect( - capturedTypeGroups(result)[0].extensions, - ImagePickerWindows.imageFormats, - ); + expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); test('getMultiImage passes the accepted type groups correctly', () async { @@ -86,21 +76,12 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect( - capturedTypeGroups(result)[0].extensions, - ImagePickerWindows.imageFormats, - ); + expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); - test( - 'getImageFromSource throws StateError when source is camera with no delegate', - () async { - await expectLater( - plugin.getImageFromSource(source: ImageSource.camera), - throwsStateError, - ); - }, - ); + test('getImageFromSource throws StateError when source is camera with no delegate', () async { + await expectLater(plugin.getImageFromSource(source: ImageSource.camera), throwsStateError); + }); test('getMultiImage passes the accepted type groups correctly', () async { await plugin.getMultiImage(); @@ -110,10 +91,7 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect( - capturedTypeGroups(result)[0].extensions, - ImagePickerWindows.imageFormats, - ); + expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.imageFormats); }); }); @@ -126,10 +104,7 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect( - capturedTypeGroups(result)[0].extensions, - ImagePickerWindows.videoFormats, - ); + expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.videoFormats); }); test('getVideo passes the accepted type groups correctly', () async { @@ -140,47 +115,29 @@ void main() { acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), ), ); - expect( - capturedTypeGroups(result)[0].extensions, - ImagePickerWindows.videoFormats, - ); + expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.videoFormats); }); test('getVideo calls delegate when source is camera', () async { const fakePath = '/tmp/foo'; plugin.cameraDelegate = FakeCameraDelegate(result: XFile(fakePath)); - expect( - (await plugin.getVideo(source: ImageSource.camera))!.path, - fakePath, - ); + expect((await plugin.getVideo(source: ImageSource.camera))!.path, fakePath); + }); + + test('getVideo throws StateError when source is camera with no delegate', () async { + await expectLater(plugin.getVideo(source: ImageSource.camera), throwsStateError); }); - test( - 'getVideo throws StateError when source is camera with no delegate', - () async { - await expectLater( - plugin.getVideo(source: ImageSource.camera), - throwsStateError, - ); - }, - ); - - test( - 'getMultiVideoWithOptions passes the accepted type groups correctly', - () async { - await plugin.getMultiVideoWithOptions(); - - final VerificationResult result = verify( - mockFileSelectorPlatform.openFiles( - acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), - ), - ); - expect( - capturedTypeGroups(result)[0].extensions, - ImagePickerWindows.videoFormats, - ); - }, - ); + test('getMultiVideoWithOptions passes the accepted type groups correctly', () async { + await plugin.getMultiVideoWithOptions(); + + final VerificationResult result = verify( + mockFileSelectorPlatform.openFiles( + acceptedTypeGroups: captureAnyNamed('acceptedTypeGroups'), + ), + ); + expect(capturedTypeGroups(result)[0].extensions, ImagePickerWindows.videoFormats); + }); }); group('media', () { @@ -198,23 +155,13 @@ void main() { ]); }); - test( - 'multiple media handles an empty path response gracefully', - () async { - expect( - await plugin.getMedia( - options: const MediaOptions(allowMultiple: true), - ), - [], - ); - }, - ); + test('multiple media handles an empty path response gracefully', () async { + expect(await plugin.getMedia(options: const MediaOptions(allowMultiple: true)), []); + }); test('single media handles an empty path response gracefully', () async { expect( - await plugin.getMedia( - options: const MediaOptions(allowMultiple: false), - ), + await plugin.getMedia(options: const MediaOptions(allowMultiple: false)), [], ); }); @@ -229,16 +176,14 @@ class FakeCameraDelegate extends ImagePickerCameraDelegate { @override Future takePhoto({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } @override Future takeVideo({ - ImagePickerCameraDelegateOptions options = - const ImagePickerCameraDelegateOptions(), + ImagePickerCameraDelegateOptions options = const ImagePickerCameraDelegateOptions(), }) async { return result; } diff --git a/packages/image_picker/image_picker_windows/test/image_picker_windows_test.mocks.dart b/packages/image_picker/image_picker_windows/test/image_picker_windows_test.mocks.dart index ebfafe27adbc..5fed6ecec864 100644 --- a/packages/image_picker/image_picker_windows/test/image_picker_windows_test.mocks.dart +++ b/packages/image_picker/image_picker_windows/test/image_picker_windows_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:file_selector_platform_interface/file_selector_platform_interface.dart' - as _i2; +import 'package:file_selector_platform_interface/file_selector_platform_interface.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -25,8 +24,7 @@ import 'package:mockito/mockito.dart' as _i1; /// A class which mocks [FileSelectorPlatform]. /// /// See the documentation for Mockito's code generation for more information. -class MockFileSelectorPlatform extends _i1.Mock - implements _i2.FileSelectorPlatform { +class MockFileSelectorPlatform extends _i1.Mock implements _i2.FileSelectorPlatform { MockFileSelectorPlatform() { _i1.throwOnMissingStub(this); } @@ -36,32 +34,28 @@ class MockFileSelectorPlatform extends _i1.Mock List<_i2.XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#openFile, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future<_i2.XFile?>.value(), - ) - as _i3.Future<_i2.XFile?>); + }) => (super.noSuchMethod( + Invocation.method(#openFile, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future<_i2.XFile?>.value(), + ) as _i3.Future<_i2.XFile?>); @override _i3.Future> openFiles({ List<_i2.XTypeGroup>? acceptedTypeGroups, String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#openFiles, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future>.value(<_i2.XFile>[]), - ) - as _i3.Future>); + }) => (super.noSuchMethod( + Invocation.method(#openFiles, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future>.value(<_i2.XFile>[]), + ) as _i3.Future>); @override _i3.Future getSavePath({ @@ -69,57 +63,47 @@ class MockFileSelectorPlatform extends _i1.Mock String? initialDirectory, String? suggestedName, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#getSavePath, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #initialDirectory: initialDirectory, - #suggestedName: suggestedName, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future.value(), - ) - as _i3.Future); + }) => (super.noSuchMethod( + Invocation.method(#getSavePath, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #initialDirectory: initialDirectory, + #suggestedName: suggestedName, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future.value(), + ) as _i3.Future); @override _i3.Future<_i2.FileSaveLocation?> getSaveLocation({ List<_i2.XTypeGroup>? acceptedTypeGroups, _i2.SaveDialogOptions? options = const _i2.SaveDialogOptions(), - }) => - (super.noSuchMethod( - Invocation.method(#getSaveLocation, [], { - #acceptedTypeGroups: acceptedTypeGroups, - #options: options, - }), - returnValue: _i3.Future<_i2.FileSaveLocation?>.value(), - ) - as _i3.Future<_i2.FileSaveLocation?>); + }) => (super.noSuchMethod( + Invocation.method(#getSaveLocation, [], { + #acceptedTypeGroups: acceptedTypeGroups, + #options: options, + }), + returnValue: _i3.Future<_i2.FileSaveLocation?>.value(), + ) as _i3.Future<_i2.FileSaveLocation?>); @override - _i3.Future getDirectoryPath({ - String? initialDirectory, - String? confirmButtonText, - }) => + _i3.Future getDirectoryPath({String? initialDirectory, String? confirmButtonText}) => (super.noSuchMethod( - Invocation.method(#getDirectoryPath, [], { - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#getDirectoryPath, [], { + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future.value(), + ) as _i3.Future); @override _i3.Future> getDirectoryPaths({ String? initialDirectory, String? confirmButtonText, - }) => - (super.noSuchMethod( - Invocation.method(#getDirectoryPaths, [], { - #initialDirectory: initialDirectory, - #confirmButtonText: confirmButtonText, - }), - returnValue: _i3.Future>.value([]), - ) - as _i3.Future>); + }) => (super.noSuchMethod( + Invocation.method(#getDirectoryPaths, [], { + #initialDirectory: initialDirectory, + #confirmButtonText: confirmButtonText, + }), + returnValue: _i3.Future>.value([]), + ) as _i3.Future>); } diff --git a/packages/in_app_purchase/in_app_purchase/example/lib/consumable_store.dart b/packages/in_app_purchase/in_app_purchase/example/lib/consumable_store.dart index 6bafda916e14..5cb9a33ad610 100644 --- a/packages/in_app_purchase/in_app_purchase/example/lib/consumable_store.dart +++ b/packages/in_app_purchase/in_app_purchase/example/lib/consumable_store.dart @@ -32,8 +32,7 @@ class ConsumableStore { /// Returns the list of consumables from the store. static Future> load() async { - return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ?? - []; + return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ?? []; } static Future _doSave(String id) async { diff --git a/packages/in_app_purchase/in_app_purchase/example/lib/main.dart b/packages/in_app_purchase/in_app_purchase/example/lib/main.dart index d0f5eb232b23..5bb5f2f054db 100644 --- a/packages/in_app_purchase/in_app_purchase/example/lib/main.dart +++ b/packages/in_app_purchase/in_app_purchase/example/lib/main.dart @@ -55,8 +55,7 @@ class _MyAppState extends State<_MyApp> { @override void initState() { - final Stream> purchaseUpdated = - _inAppPurchase.purchaseStream; + final Stream> purchaseUpdated = _inAppPurchase.purchaseStream; _subscription = purchaseUpdated.listen( (List purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); @@ -88,14 +87,14 @@ class _MyAppState extends State<_MyApp> { } if (Platform.isIOS) { - final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = - _inAppPurchase - .getPlatformAddition(); + final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = _inAppPurchase + .getPlatformAddition(); await iosPlatformAddition.setDelegate(ExamplePaymentQueueDelegate()); } - final ProductDetailsResponse productDetailResponse = await _inAppPurchase - .queryProductDetails(_kProductIds.toSet()); + final ProductDetailsResponse productDetailResponse = await _inAppPurchase.queryProductDetails( + _kProductIds.toSet(), + ); if (productDetailResponse.error != null) { setState(() { _queryProductError = productDetailResponse.error!.message; @@ -138,9 +137,8 @@ class _MyAppState extends State<_MyApp> { @override void dispose() { if (Platform.isIOS) { - final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = - _inAppPurchase - .getPlatformAddition(); + final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition = _inAppPurchase + .getPlatformAddition(); iosPlatformAddition.setDelegate(null); } _subscription.cancel(); @@ -168,10 +166,7 @@ class _MyAppState extends State<_MyApp> { stack.add( const Stack( children: [ - Opacity( - opacity: 0.3, - child: ModalBarrier(dismissible: false, color: Colors.grey), - ), + Opacity(opacity: 0.3, child: ModalBarrier(dismissible: false, color: Colors.grey)), Center(child: CircularProgressIndicator()), ], ), @@ -193,13 +188,9 @@ class _MyAppState extends State<_MyApp> { final Widget storeHeader = ListTile( leading: Icon( _isAvailable ? Icons.check : Icons.block, - color: _isAvailable - ? Colors.green - : ThemeData.light().colorScheme.error, - ), - title: Text( - 'The store is ${_isAvailable ? 'available' : 'unavailable'}.', + color: _isAvailable ? Colors.green : ThemeData.light().colorScheme.error, ), + title: Text('The store is ${_isAvailable ? 'available' : 'unavailable'}.'), ); final children = [storeHeader]; @@ -223,10 +214,7 @@ class _MyAppState extends State<_MyApp> { Card _buildProductList() { if (_loading) { return const Card( - child: ListTile( - leading: CircularProgressIndicator(), - title: Text('Fetching products...'), - ), + child: ListTile(leading: CircularProgressIndicator(), title: Text('Fetching products...')), ); } if (!_isAvailable) { @@ -283,23 +271,22 @@ class _MyAppState extends State<_MyApp> { // verify the latest status of you your subscription by using server side receipt validation // and update the UI accordingly. The subscription purchase status shown // inside the app may not be accurate. - final GooglePlayPurchaseDetails? oldSubscription = - _getOldSubscription(productDetails, purchases); + final GooglePlayPurchaseDetails? oldSubscription = _getOldSubscription( + productDetails, + purchases, + ); purchaseParam = GooglePlayPurchaseParam( productDetails: productDetails, changeSubscriptionParam: (oldSubscription != null) ? ChangeSubscriptionParam( oldPurchaseDetails: oldSubscription, - replacementMode: - ReplacementMode.withTimeProration, + replacementMode: ReplacementMode.withTimeProration, ) : null, ); } else { - purchaseParam = PurchaseParam( - productDetails: productDetails, - ); + purchaseParam = PurchaseParam(productDetails: productDetails); } if (productDetails.id == _kConsumableId) { @@ -308,9 +295,7 @@ class _MyAppState extends State<_MyApp> { autoConsume: _kAutoConsume, ); } else { - _inAppPurchase.buyNonConsumable( - purchaseParam: purchaseParam, - ); + _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam); } }, child: Text(productDetails.price), @@ -319,11 +304,7 @@ class _MyAppState extends State<_MyApp> { }), ); - return Card( - child: Column( - children: [productHeader, const Divider()] + productList, - ), - ); + return Card(child: Column(children: [productHeader, const Divider()] + productList)); } Card _buildConsumableBox() { @@ -434,9 +415,7 @@ class _MyAppState extends State<_MyApp> { // handle invalid purchase here if _verifyPurchase` failed. } - Future _listenToPurchaseUpdated( - List purchaseDetailsList, - ) async { + Future _listenToPurchaseUpdated(List purchaseDetailsList) async { for (final purchaseDetails in purchaseDetailsList) { if (purchaseDetails.status == PurchaseStatus.pending) { showPendingUI(); @@ -455,8 +434,7 @@ class _MyAppState extends State<_MyApp> { } if (Platform.isAndroid) { if (!_kAutoConsume && purchaseDetails.productID == _kConsumableId) { - final InAppPurchaseAndroidPlatformAddition - androidAddition = _inAppPurchase + final InAppPurchaseAndroidPlatformAddition androidAddition = _inAppPurchase .getPlatformAddition(); await androidAddition.consumePurchase(purchaseDetails); } @@ -474,9 +452,8 @@ class _MyAppState extends State<_MyApp> { // https://developer.android.com/google/play/billing/price-changes for more // information on price changes on Android. if (Platform.isIOS) { - final InAppPurchaseStoreKitPlatformAddition iapStoreKitPlatformAddition = - _inAppPurchase - .getPlatformAddition(); + final InAppPurchaseStoreKitPlatformAddition iapStoreKitPlatformAddition = _inAppPurchase + .getPlatformAddition(); await iapStoreKitPlatformAddition.showPriceConsentIfNeeded(); } } @@ -493,14 +470,11 @@ class _MyAppState extends State<_MyApp> { // The old subscription is only required on Android since Apple handles this internally // by using the subscription group feature in iTunesConnect. GooglePlayPurchaseDetails? oldSubscription; - if (productDetails.id == _kSilverSubscriptionId && - purchases[_kGoldSubscriptionId] != null) { - oldSubscription = - purchases[_kGoldSubscriptionId]! as GooglePlayPurchaseDetails; + if (productDetails.id == _kSilverSubscriptionId && purchases[_kGoldSubscriptionId] != null) { + oldSubscription = purchases[_kGoldSubscriptionId]! as GooglePlayPurchaseDetails; } else if (productDetails.id == _kGoldSubscriptionId && purchases[_kSilverSubscriptionId] != null) { - oldSubscription = - purchases[_kSilverSubscriptionId]! as GooglePlayPurchaseDetails; + oldSubscription = purchases[_kSilverSubscriptionId]! as GooglePlayPurchaseDetails; } return oldSubscription; } diff --git a/packages/in_app_purchase/in_app_purchase/lib/in_app_purchase.dart b/packages/in_app_purchase/in_app_purchase/lib/in_app_purchase.dart index 4bc5f9142200..0ee6417bd512 100644 --- a/packages/in_app_purchase/in_app_purchase/lib/in_app_purchase.dart +++ b/packages/in_app_purchase/in_app_purchase/lib/in_app_purchase.dart @@ -68,8 +68,7 @@ class InAppPurchase implements InAppPurchasePlatformAdditionProvider { /// time. If you choose to have multiple subscription at the same time, you /// should be careful at the fact that each subscription will receive all the /// events after they start to listen. - Stream> get purchaseStream => - InAppPurchasePlatform.instance.purchaseStream; + Stream> get purchaseStream => InAppPurchasePlatform.instance.purchaseStream; /// Returns `true` if the payment platform is ready and available. Future isAvailable() => InAppPurchasePlatform.instance.isAvailable(); @@ -114,9 +113,7 @@ class InAppPurchase implements InAppPurchasePlatformAdditionProvider { /// /// Calling this method for consumable items will cause unwanted behaviors! Future buyNonConsumable({required PurchaseParam purchaseParam}) => - InAppPurchasePlatform.instance.buyNonConsumable( - purchaseParam: purchaseParam, - ); + InAppPurchasePlatform.instance.buyNonConsumable(purchaseParam: purchaseParam); /// Buy a consumable product. /// @@ -156,13 +153,11 @@ class InAppPurchase implements InAppPurchasePlatformAdditionProvider { /// /// Calling this method for non consumable items will cause unwanted /// behaviors! - Future buyConsumable({ - required PurchaseParam purchaseParam, - bool autoConsume = true, - }) => InAppPurchasePlatform.instance.buyConsumable( - purchaseParam: purchaseParam, - autoConsume: autoConsume, - ); + Future buyConsumable({required PurchaseParam purchaseParam, bool autoConsume = true}) => + InAppPurchasePlatform.instance.buyConsumable( + purchaseParam: purchaseParam, + autoConsume: autoConsume, + ); /// Mark that purchased content has been delivered to the user. /// @@ -205,9 +200,7 @@ class InAppPurchase implements InAppPurchasePlatformAdditionProvider { /// * [refreshPurchaseVerificationData], for reloading failed /// [PurchaseDetails.verificationData]. Future restorePurchases({String? applicationUserName}) => - InAppPurchasePlatform.instance.restorePurchases( - applicationUserName: applicationUserName, - ); + InAppPurchasePlatform.instance.restorePurchases(applicationUserName: applicationUserName); /// Returns the user's country. /// diff --git a/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart b/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart index 341ff82db151..3768e22a8b76 100644 --- a/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart +++ b/packages/in_app_purchase/in_app_purchase/test/in_app_purchase_test.dart @@ -50,35 +50,26 @@ void main() { test('isAvailable', () async { final bool isAvailable = await inAppPurchase.isAvailable(); expect(isAvailable, true); - expect(fakePlatform.log, [ - isMethodCall('isAvailable', arguments: null), - ]); + expect(fakePlatform.log, [isMethodCall('isAvailable', arguments: null)]); }); test('countryCode', () async { final String country = await inAppPurchase.countryCode(); expect(country, 'USA'); - expect(fakePlatform.log, [ - isMethodCall('countryCode', arguments: null), - ]); + expect(fakePlatform.log, [isMethodCall('countryCode', arguments: null)]); }); test('purchaseStream', () async { final bool isEmptyStream = await inAppPurchase.purchaseStream.isEmpty; expect(isEmptyStream, true); - expect(fakePlatform.log, [ - isMethodCall('purchaseStream', arguments: null), - ]); + expect(fakePlatform.log, [isMethodCall('purchaseStream', arguments: null)]); }); test('queryProductDetails', () async { - final ProductDetailsResponse response = await inAppPurchase - .queryProductDetails({}); + final ProductDetailsResponse response = await inAppPurchase.queryProductDetails({}); expect(response.notFoundIDs.isEmpty, true); expect(response.productDetails.isEmpty, true); - expect(fakePlatform.log, [ - isMethodCall('queryProductDetails', arguments: null), - ]); + expect(fakePlatform.log, [isMethodCall('queryProductDetails', arguments: null)]); }); test('buyNonConsumable', () async { @@ -87,25 +78,18 @@ void main() { ); expect(result, true); - expect(fakePlatform.log, [ - isMethodCall('buyNonConsumable', arguments: null), - ]); + expect(fakePlatform.log, [isMethodCall('buyNonConsumable', arguments: null)]); }); test('buyConsumable', () async { final purchaseParam = PurchaseParam(productDetails: productDetails); - final bool result = await inAppPurchase.buyConsumable( - purchaseParam: purchaseParam, - ); + final bool result = await inAppPurchase.buyConsumable(purchaseParam: purchaseParam); expect(result, true); expect(fakePlatform.log, [ isMethodCall( 'buyConsumable', - arguments: { - 'purchaseParam': purchaseParam, - 'autoConsume': true, - }, + arguments: {'purchaseParam': purchaseParam, 'autoConsume': true}, ), ]); }); @@ -121,10 +105,7 @@ void main() { expect(fakePlatform.log, [ isMethodCall( 'buyConsumable', - arguments: { - 'purchaseParam': purchaseParam, - 'autoConsume': false, - }, + arguments: {'purchaseParam': purchaseParam, 'autoConsume': false}, ), ]); }); @@ -132,17 +113,13 @@ void main() { test('completePurchase', () async { await inAppPurchase.completePurchase(purchaseDetails); - expect(fakePlatform.log, [ - isMethodCall('completePurchase', arguments: null), - ]); + expect(fakePlatform.log, [isMethodCall('completePurchase', arguments: null)]); }); test('restorePurchases', () async { await inAppPurchase.restorePurchases(); - expect(fakePlatform.log, [ - isMethodCall('restorePurchases', arguments: null), - ]); + expect(fakePlatform.log, [isMethodCall('restorePurchases', arguments: null)]); }); }); } @@ -168,10 +145,7 @@ class MockInAppPurchasePlatform extends Fake Future queryProductDetails(Set identifiers) { log.add(const MethodCall('queryProductDetails')); return Future.value( - ProductDetailsResponse( - productDetails: [], - notFoundIDs: [], - ), + ProductDetailsResponse(productDetails: [], notFoundIDs: []), ); } @@ -182,10 +156,7 @@ class MockInAppPurchasePlatform extends Fake } @override - Future buyConsumable({ - required PurchaseParam purchaseParam, - bool autoConsume = true, - }) { + Future buyConsumable({required PurchaseParam purchaseParam, bool autoConsume = true}) { log.add( MethodCall('buyConsumable', { 'purchaseParam': purchaseParam, diff --git a/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart b/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart index b06a166dce11..ba6c6432b0c5 100644 --- a/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/example/integration_test/in_app_purchase_test.dart @@ -16,11 +16,8 @@ void main() { InAppPurchaseAndroidPlatform.registerPlatform(); }); - testWidgets('Can create InAppPurchaseAndroid instance', ( - WidgetTester tester, - ) async { - final InAppPurchasePlatform androidPlatform = - InAppPurchasePlatform.instance; + testWidgets('Can create InAppPurchaseAndroid instance', (WidgetTester tester) async { + final InAppPurchasePlatform androidPlatform = InAppPurchasePlatform.instance; expect(androidPlatform, isNotNull); }); @@ -28,15 +25,10 @@ void main() { late final BillingClient billingClient; setUpAll(() { - billingClient = BillingClient( - (PurchasesResultWrapper _) {}, - (UserChoiceDetailsWrapper _) {}, - ); + billingClient = BillingClient((PurchasesResultWrapper _) {}, (UserChoiceDetailsWrapper _) {}); }); - testWidgets('BillingClient.acknowledgePurchase', ( - WidgetTester tester, - ) async { + testWidgets('BillingClient.acknowledgePurchase', (WidgetTester tester) async { try { await billingClient.acknowledgePurchase('purchaseToken'); } on MissingPluginException { @@ -60,13 +52,9 @@ void main() { } }); - testWidgets('BillingClient.isFeatureSupported', ( - WidgetTester tester, - ) async { + testWidgets('BillingClient.isFeatureSupported', (WidgetTester tester) async { try { - await billingClient.isFeatureSupported( - BillingClientFeature.productDetails, - ); + await billingClient.isFeatureSupported(BillingClientFeature.productDetails); } on MissingPluginException { fail('Method channel is not setup correctly'); } @@ -93,27 +81,20 @@ void main() { } }); - testWidgets('BillingClient.queryProductDetails', ( - WidgetTester tester, - ) async { + testWidgets('BillingClient.queryProductDetails', (WidgetTester tester) async { try { - await billingClient.queryProductDetails( - productList: [], - ); + await billingClient.queryProductDetails(productList: []); } on MissingPluginException { fail('Method channel is not setup correctly'); } on PlatformException catch (e) { // A [PlatformException] is expected, as we send an empty product list. - if (!(e.message?.startsWith('Product list cannot be empty.') ?? - false)) { + if (!(e.message?.startsWith('Product list cannot be empty.') ?? false)) { rethrow; } } }); - testWidgets('BillingClient.queryPurchaseHistory', ( - WidgetTester tester, - ) async { + testWidgets('BillingClient.queryPurchaseHistory', (WidgetTester tester) async { try { // Intentional use of a deprecated method to make sure it still works. // ignore: deprecated_member_use @@ -133,9 +114,7 @@ void main() { testWidgets('BillingClient.startConnection', (WidgetTester tester) async { try { - await billingClient.startConnection( - onBillingServiceDisconnected: () {}, - ); + await billingClient.startConnection(onBillingServiceDisconnected: () {}); } on MissingPluginException { fail('Method channel is not setup correctly'); } diff --git a/packages/in_app_purchase/in_app_purchase_android/example/lib/consumable_store.dart b/packages/in_app_purchase/in_app_purchase_android/example/lib/consumable_store.dart index 6bafda916e14..5cb9a33ad610 100644 --- a/packages/in_app_purchase/in_app_purchase_android/example/lib/consumable_store.dart +++ b/packages/in_app_purchase/in_app_purchase_android/example/lib/consumable_store.dart @@ -32,8 +32,7 @@ class ConsumableStore { /// Returns the list of consumables from the store. static Future> load() async { - return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ?? - []; + return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ?? []; } static Future _doSave(String id) async { diff --git a/packages/in_app_purchase/in_app_purchase_android/example/lib/main.dart b/packages/in_app_purchase/in_app_purchase_android/example/lib/main.dart index 6bb520121d19..15128c7213b1 100644 --- a/packages/in_app_purchase/in_app_purchase_android/example/lib/main.dart +++ b/packages/in_app_purchase/in_app_purchase_android/example/lib/main.dart @@ -41,8 +41,7 @@ class _MyApp extends StatefulWidget { } class _MyAppState extends State<_MyApp> { - final InAppPurchasePlatform _inAppPurchasePlatform = - InAppPurchasePlatform.instance; + final InAppPurchasePlatform _inAppPurchasePlatform = InAppPurchasePlatform.instance; late StreamSubscription> _subscription; late StreamSubscription _userChoiceDetailsStream; List _notFoundIds = []; @@ -61,8 +60,7 @@ class _MyAppState extends State<_MyApp> { @override void initState() { - final Stream> purchaseUpdated = - _inAppPurchasePlatform.purchaseStream; + final Stream> purchaseUpdated = _inAppPurchasePlatform.purchaseStream; _subscription = purchaseUpdated.listen( (List purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); @@ -76,8 +74,7 @@ class _MyAppState extends State<_MyApp> { ); initStoreInfo(); final addition = - InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition; + InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; final Stream userChoiceDetailsUpdated = addition.userChoiceDetailsStream; _userChoiceDetailsStream = userChoiceDetailsUpdated.listen( @@ -109,8 +106,8 @@ class _MyAppState extends State<_MyApp> { return; } - final ProductDetailsResponse productDetailResponse = - await _inAppPurchasePlatform.queryProductDetails(_kProductIds.toSet()); + final ProductDetailsResponse productDetailResponse = await _inAppPurchasePlatform + .queryProductDetails(_kProductIds.toSet()); if (productDetailResponse.error != null) { setState(() { _queryProductError = productDetailResponse.error!.message; @@ -183,10 +180,7 @@ class _MyAppState extends State<_MyApp> { stack.add( const Stack( children: [ - Opacity( - opacity: 0.3, - child: ModalBarrier(dismissible: false, color: Colors.grey), - ), + Opacity(opacity: 0.3, child: ModalBarrier(dismissible: false, color: Colors.grey)), Center(child: CircularProgressIndicator()), ], ), @@ -208,13 +202,9 @@ class _MyAppState extends State<_MyApp> { final Widget storeHeader = ListTile( leading: Icon( _isAvailable ? Icons.check : Icons.block, - color: _isAvailable - ? Colors.green - : ThemeData.light().colorScheme.error, - ), - title: Text( - 'The store is ${_isAvailable ? 'available' : 'unavailable'}.', + color: _isAvailable ? Colors.green : ThemeData.light().colorScheme.error, ), + title: Text('The store is ${_isAvailable ? 'available' : 'unavailable'}.'), ); final children = [storeHeader]; @@ -299,8 +289,7 @@ class _MyAppState extends State<_MyApp> { ), onPressed: () { final addition = - InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition; + InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; unawaited( deliverIsAlternativeBillingOnlyAvailable( addition.isAlternativeBillingOnlyAvailable(), @@ -320,8 +309,7 @@ class _MyAppState extends State<_MyApp> { ), onPressed: () { final addition = - InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition; + InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; unawaited( deliverShowAlternativeBillingOnlyInformationDialogResult( addition.showAlternativeBillingOnlyInformationDialog(), @@ -341,13 +329,8 @@ class _MyAppState extends State<_MyApp> { ), onPressed: () { final addition = - InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition; - unawaited( - addition.setBillingChoice( - BillingChoiceMode.alternativeBillingOnly, - ), - ); + InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; + unawaited(addition.setBillingChoice(BillingChoiceMode.alternativeBillingOnly)); }, child: const Text('setBillingChoice alternativeBillingOnly'), ), @@ -362,8 +345,7 @@ class _MyAppState extends State<_MyApp> { ), onPressed: () { final addition = - InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition; + InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; unawaited( deliverCreateAlternativeBillingOnlyReportingDetails( addition.createAlternativeBillingOnlyReportingDetails(), @@ -376,13 +358,7 @@ class _MyAppState extends State<_MyApp> { ); return Card( child: Column( - children: [ - header, - const Divider(), - ...entries, - const Divider(), - ...buttons, - ], + children: [header, const Divider(), ...entries, const Divider(), ...buttons], ), ); } @@ -393,26 +369,18 @@ class _MyAppState extends State<_MyApp> { for (final String item in _userChoiceDetailsList) { entries.add( ListTile( - title: Text( - item, - style: TextStyle(color: ThemeData.light().colorScheme.primary), - ), + title: Text(item, style: TextStyle(color: ThemeData.light().colorScheme.primary)), subtitle: Text(_countryCode), ), ); } - return Card( - child: Column(children: [header, const Divider(), ...entries]), - ); + return Card(child: Column(children: [header, const Divider(), ...entries])); } Card _buildProductList() { if (_loading) { return const Card( - child: ListTile( - leading: CircularProgressIndicator(), - title: Text('Fetching products...'), - ), + child: ListTile(leading: CircularProgressIndicator(), title: Text('Fetching products...')), ); } if (!_isAvailable) { @@ -463,18 +431,16 @@ class _MyAppState extends State<_MyApp> { // verify the latest status of you your subscription by using server side receipt validation // and update the UI accordingly. The subscription purchase status shown // inside the app may not be accurate. - final GooglePlayPurchaseDetails? oldSubscription = - _getOldSubscription( - productDetails as GooglePlayProductDetails, - purchases, - ); + final GooglePlayPurchaseDetails? oldSubscription = _getOldSubscription( + productDetails as GooglePlayProductDetails, + purchases, + ); final purchaseParam = GooglePlayPurchaseParam( productDetails: productDetails, changeSubscriptionParam: oldSubscription != null ? ChangeSubscriptionParam( oldPurchaseDetails: oldSubscription, - replacementMode: - ReplacementMode.withTimeProration, + replacementMode: ReplacementMode.withTimeProration, ) : null, ); @@ -485,9 +451,7 @@ class _MyAppState extends State<_MyApp> { autoConsume: _kAutoConsume, ); } else { - _inAppPurchasePlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + _inAppPurchasePlatform.buyNonConsumable(purchaseParam: purchaseParam); } }, child: Text(productDetails.price), @@ -496,11 +460,7 @@ class _MyAppState extends State<_MyApp> { }), ); - return Card( - child: Column( - children: [productHeader, const Divider()] + productList, - ), - ); + return Card(child: Column(children: [productHeader, const Divider()] + productList)); } Card _buildConsumableBox() { @@ -567,8 +527,7 @@ class _MyAppState extends State<_MyApp> { ) async { final BillingResultWrapper wrapper = await billingOnly; setState(() { - _isAlternativeBillingOnlyAvailableResponseCode = - wrapper.responseCode.name; + _isAlternativeBillingOnlyAvailableResponseCode = wrapper.responseCode.name; }); } @@ -584,15 +543,12 @@ class _MyAppState extends State<_MyApp> { Future deliverCreateAlternativeBillingOnlyReportingDetails( Future futureWrapper, ) async { - final AlternativeBillingOnlyReportingDetailsWrapper wrapper = - await futureWrapper; + final AlternativeBillingOnlyReportingDetailsWrapper wrapper = await futureWrapper; setState(() { if (wrapper.responseCode == BillingResponse.ok) { - _alternativeBillingOnlyReportingDetailsToken = - wrapper.externalTransactionToken; + _alternativeBillingOnlyReportingDetailsToken = wrapper.externalTransactionToken; } else { - _alternativeBillingOnlyReportingDetailsToken = - wrapper.responseCode.name; + _alternativeBillingOnlyReportingDetailsToken = wrapper.responseCode.name; } }); } @@ -630,9 +586,7 @@ class _MyAppState extends State<_MyApp> { // handle invalid purchase here if _verifyPurchase` failed. } - Future deliverUserChoiceDetails( - GooglePlayUserChoiceDetails details, - ) async { + Future deliverUserChoiceDetails(GooglePlayUserChoiceDetails details) async { final detailDescription = '${details.externalTransactionToken}, ${details.originalExternalTransactionId}, ${details.products.length}'; setState(() { @@ -640,16 +594,13 @@ class _MyAppState extends State<_MyApp> { }); } - Future _listenToPurchaseUpdated( - List purchaseDetailsList, - ) async { + Future _listenToPurchaseUpdated(List purchaseDetailsList) async { for (final purchaseDetails in purchaseDetailsList) { if (purchaseDetails.status == PurchaseStatus.pending) { showPendingUI(); } else { final addition = - InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition; + InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; if (purchaseDetails.status == PurchaseStatus.error) { handleError(purchaseDetails.error!); } else if (purchaseDetails.status == PurchaseStatus.purchased || @@ -686,14 +637,11 @@ class _MyAppState extends State<_MyApp> { // The old subscription is only required on Android since Apple handles this internally // by using the subscription group feature in iTunesConnect. GooglePlayPurchaseDetails? oldSubscription; - if (productDetails.id == _kSilverSubscriptionId && - purchases[_kGoldSubscriptionId] != null) { - oldSubscription = - purchases[_kGoldSubscriptionId]! as GooglePlayPurchaseDetails; + if (productDetails.id == _kSilverSubscriptionId && purchases[_kGoldSubscriptionId] != null) { + oldSubscription = purchases[_kGoldSubscriptionId]! as GooglePlayPurchaseDetails; } else if (productDetails.id == _kGoldSubscriptionId && purchases[_kSilverSubscriptionId] != null) { - oldSubscription = - purchases[_kSilverSubscriptionId]! as GooglePlayPurchaseDetails; + oldSubscription = purchases[_kSilverSubscriptionId]! as GooglePlayPurchaseDetails; } return oldSubscription; } @@ -703,8 +651,7 @@ class _FeatureCard extends StatelessWidget { const _FeatureCard(); InAppPurchaseAndroidPlatformAddition get addition => - InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition; + InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition; @override Widget build(BuildContext context) { @@ -714,8 +661,7 @@ class _FeatureCard extends StatelessWidget { children: [ const ListTile(title: Text('Available features')), const Divider(), - for (final BillingClientFeature feature - in BillingClientFeature.values) + for (final BillingClientFeature feature in BillingClientFeature.values) _buildFeatureWidget(feature), ], ), @@ -733,10 +679,7 @@ class _FeatureCard extends StatelessWidget { } return Padding( padding: const EdgeInsets.fromLTRB(16.0, 4.0, 16.0, 4.0), - child: Text( - _featureToString(feature), - style: TextStyle(color: color), - ), + child: Text(_featureToString(feature), style: TextStyle(color: color)), ); }, ); diff --git a/packages/in_app_purchase/in_app_purchase_android/example/lib/migration_guide_examples.dart b/packages/in_app_purchase/in_app_purchase_android/example/lib/migration_guide_examples.dart index 33e1e930ab87..d09bca619e81 100644 --- a/packages/in_app_purchase/in_app_purchase_android/example/lib/migration_guide_examples.dart +++ b/packages/in_app_purchase/in_app_purchase_android/example/lib/migration_guide_examples.dart @@ -15,12 +15,12 @@ void handleOneTimePurchasePrice(ProductDetails productDetails) { final ProductDetailsWrapper product = productDetails.productDetails; if (product.productType == ProductType.inapp) { // Unwrapping is safe because the product is a one time purchase. - final OneTimePurchaseOfferDetailsWrapper offer = - product.oneTimePurchaseOfferDetails!; + final OneTimePurchaseOfferDetailsWrapper offer = product.oneTimePurchaseOfferDetails!; final String price = offer.formattedPrice; } } } + // #enddocregion one-time-purchase-price // #docregion subscription-free-trial @@ -39,6 +39,7 @@ void handleFreeTrialPeriod(ProductDetails productDetails) { } } } + // #enddocregion subscription-free-trial // #docregion subscription-introductory-price @@ -52,8 +53,7 @@ void handleIntroductoryPricePeriod(ProductDetails productDetails) { product.subscriptionOfferDetails![productDetails.subscriptionIndex!]; final List pricingPhases = offer.pricingPhases; if (pricingPhases.length >= 2 && - pricingPhases.first.priceAmountMicros < - pricingPhases[1].priceAmountMicros) { + pricingPhases.first.priceAmountMicros < pricingPhases[1].priceAmountMicros) { // Introductory pricing period logic. } } diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.dart index bf2cf0f9b481..ea2b2f362639 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.dart @@ -15,8 +15,7 @@ const String kInvalidAlternativeBillingReportingDetailsErrorMessage = /// Params containing the response code and the debug message from the Play Billing API response. @immutable -class AlternativeBillingOnlyReportingDetailsWrapper - implements HasBillingResponse { +class AlternativeBillingOnlyReportingDetailsWrapper implements HasBillingResponse { /// Constructs the object with [responseCode] and [debugMessage]. const AlternativeBillingOnlyReportingDetailsWrapper({ required this.responseCode, @@ -50,6 +49,5 @@ class AlternativeBillingOnlyReportingDetailsWrapper } @override - int get hashCode => - Object.hash(responseCode, debugMessage, externalTransactionToken); + int get hashCode => Object.hash(responseCode, debugMessage, externalTransactionToken); } diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_manager.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_manager.dart index c912863d6141..5e8fcdf3a93f 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_manager.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_manager.dart @@ -22,11 +22,10 @@ abstract class HasBillingResponse { /// Factory for creating BillingClient instances, to allow injection of /// custom billing clients in tests. @visibleForTesting -typedef BillingClientFactory = - BillingClient Function( - PurchasesUpdatedListener onPurchasesUpdated, - UserSelectedAlternativeBillingListener? alternativeBillingListener, - ); +typedef BillingClientFactory = BillingClient Function( + PurchasesUpdatedListener onPurchasesUpdated, + UserSelectedAlternativeBillingListener? alternativeBillingListener, +); /// Utility class that manages a [BillingClient] connection. /// @@ -44,13 +43,10 @@ class BillingClientManager { /// Creates the [BillingClientManager]. /// /// Immediately initializes connection to the underlying [BillingClient]. - BillingClientManager({ - @visibleForTesting BillingClientFactory? billingClientFactory, - }) : _billingChoiceMode = BillingChoiceMode.playBillingOnly, - _pendingPurchasesParams = const PendingPurchasesParamsWrapper( - enablePrepaidPlans: false, - ), - _billingClientFactory = billingClientFactory ?? _createBillingClient { + BillingClientManager({@visibleForTesting BillingClientFactory? billingClientFactory}) + : _billingChoiceMode = BillingChoiceMode.playBillingOnly, + _pendingPurchasesParams = const PendingPurchasesParamsWrapper(enablePrepaidPlans: false), + _billingClientFactory = billingClientFactory ?? _createBillingClient { _connect(); } @@ -88,8 +84,7 @@ class BillingClientManager { final StreamController _purchasesUpdatedController = StreamController.broadcast(); - final StreamController - _userChoiceAlternativeBillingController = + final StreamController _userChoiceAlternativeBillingController = StreamController.broadcast(); BillingChoiceMode _billingChoiceMode; @@ -119,8 +114,7 @@ class BillingClientManager { _debugAssertNotDisposed(); await _readyFuture; final R result = await action(client); - if (result.responseCode == BillingResponse.serviceDisconnected && - !_isDisposed) { + if (result.responseCode == BillingResponse.serviceDisconnected && !_isDisposed) { await _connect(); return runWithClient(action); } else { @@ -137,9 +131,7 @@ class BillingClientManager { /// /// See [runWithClient] for operations that return a subclass /// of [HasBillingResponse]. - Future runWithClientNonRetryable( - Future Function(BillingClient client) action, - ) async { + Future runWithClientNonRetryable(Future Function(BillingClient client) action) async { _debugAssertNotDisposed(); await _readyFuture; return action(client); @@ -168,9 +160,7 @@ class BillingClientManager { /// Callers need to check if [BillingChoiceMode.alternativeBillingOnly] is /// available by calling [BillingClientWrapper.isAlternativeBillingOnlyAvailable] /// first. - Future reconnectWithBillingChoiceMode( - BillingChoiceMode billingChoiceMode, - ) async { + Future reconnectWithBillingChoiceMode(BillingChoiceMode billingChoiceMode) async { _billingChoiceMode = billingChoiceMode; await _reconnect(); } diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.dart index b3df0cf619b9..aff8e9641358 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_client_wrapper.dart @@ -28,12 +28,12 @@ import 'pending_purchases_params_wrapper.dart'; /// /// Wraps a /// [`PurchasesUpdatedListener`](https://developer.android.com/reference/com/android/billingclient/api/PurchasesUpdatedListener.html). -typedef PurchasesUpdatedListener = - void Function(PurchasesResultWrapper purchasesResult); +typedef PurchasesUpdatedListener = void Function(PurchasesResultWrapper purchasesResult); /// Wraps a [UserChoiceBillingListener](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceBillingListener) -typedef UserSelectedAlternativeBillingListener = - void Function(UserChoiceDetailsWrapper userChoiceDetailsWrapper); +typedef UserSelectedAlternativeBillingListener = void Function( + UserChoiceDetailsWrapper userChoiceDetailsWrapper, +); /// This class can be used directly instead of [InAppPurchaseConnection] to call /// Play-specific billing APIs. @@ -102,8 +102,7 @@ class BillingClient { hostCallbackHandler.disconnectCallbacks.length - 1, platformBillingChoiceMode(billingChoiceMode), switch (pendingPurchasesParams) { - final PendingPurchasesParamsWrapper params => - pendingPurchasesParamsFromWrapper(params), + final PendingPurchasesParamsWrapper params => pendingPurchasesParamsFromWrapper(params), null => PlatformPendingPurchasesParams(enablePrepaidPlans: false), }, ), @@ -137,10 +136,7 @@ class BillingClient { return productDetailsResponseWrapperFromPlatform( await _hostApi.queryProductDetailsAsync( productList - .map( - (ProductWrapper product) => - platformQueryProductFromWrapper(product), - ) + .map((ProductWrapper product) => platformQueryProductFromWrapper(product)) .toList(), ), ); @@ -242,9 +238,7 @@ class BillingClient { // broken by the original change to hard-code this on the Java side (instead // of making it a forwarding getter on the Dart side). return purchasesResultWrapperFromPlatform( - await _hostApi.queryPurchasesAsync( - platformProductTypeFromWrapper(productType), - ), + await _hostApi.queryPurchasesAsync(platformProductTypeFromWrapper(productType)), forceOkResponseCode: true, ); } @@ -262,13 +256,9 @@ class BillingClient { /// This wraps /// [`BillingClient#queryPurchaseHistoryAsync(QueryPurchaseHistoryParams, PurchaseHistoryResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient#queryPurchaseHistoryAsync(com.android.billingclient.api.QueryPurchaseHistoryParams,%20com.android.billingclient.api.PurchaseHistoryResponseListener)). @Deprecated('Use queryPurchases') - Future queryPurchaseHistory( - ProductType productType, - ) async { + Future queryPurchaseHistory(ProductType productType) async { return purchaseHistoryResultFromPlatform( - await _hostApi.queryPurchaseHistoryAsync( - platformProductTypeFromWrapper(productType), - ), + await _hostApi.queryPurchaseHistoryAsync(platformProductTypeFromWrapper(productType)), ); } @@ -280,9 +270,7 @@ class BillingClient { /// This wraps /// [`BillingClient#consumeAsync(ConsumeParams, ConsumeResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#consumeAsync(java.lang.String,%20com.android.billingclient.api.ConsumeResponseListener)) Future consumeAsync(String purchaseToken) async { - return resultWrapperFromPlatform( - await _hostApi.consumeAsync(purchaseToken), - ); + return resultWrapperFromPlatform(await _hostApi.consumeAsync(purchaseToken)); } /// Acknowledge an in-app purchase. @@ -304,39 +292,28 @@ class BillingClient { /// This wraps /// [`BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener)`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#acknowledgePurchase(com.android.billingclient.api.AcknowledgePurchaseParams,%20com.android.billingclient.api.AcknowledgePurchaseResponseListener)) Future acknowledgePurchase(String purchaseToken) async { - return resultWrapperFromPlatform( - await _hostApi.acknowledgePurchase(purchaseToken), - ); + return resultWrapperFromPlatform(await _hostApi.acknowledgePurchase(purchaseToken)); } /// Checks if the specified feature or capability is supported by the Play Store. /// Call this to check if a [BillingClientFeature] is supported by the device. Future isFeatureSupported(BillingClientFeature feature) async { - return _hostApi.isFeatureSupported( - billingClientFeatureFromWrapper(feature), - ); + return _hostApi.isFeatureSupported(billingClientFeatureFromWrapper(feature)); } /// Fetches billing config info into a [BillingConfigWrapper] object. Future getBillingConfig() async { - return billingConfigWrapperFromPlatform( - await _hostApi.getBillingConfigAsync(), - ); + return billingConfigWrapperFromPlatform(await _hostApi.getBillingConfigAsync()); } /// Checks if "AlterntitiveBillingOnly" feature is available. Future isAlternativeBillingOnlyAvailable() async { - return resultWrapperFromPlatform( - await _hostApi.isAlternativeBillingOnlyAvailableAsync(), - ); + return resultWrapperFromPlatform(await _hostApi.isAlternativeBillingOnlyAvailableAsync()); } /// Shows the alternative billing only information dialog on top of the calling app. - Future - showAlternativeBillingOnlyInformationDialog() async { - return resultWrapperFromPlatform( - await _hostApi.showAlternativeBillingOnlyInformationDialog(), - ); + Future showAlternativeBillingOnlyInformationDialog() async { + return resultWrapperFromPlatform(await _hostApi.showAlternativeBillingOnlyInformationDialog()); } /// The details used to report transactions made via alternative billing @@ -359,10 +336,7 @@ class BillingClient { class HostBillingClientCallbackHandler implements InAppPurchaseCallbackApi { /// Creates a new handler with the given singleton handlers, and no /// per-connection handlers. - HostBillingClientCallbackHandler( - this.purchasesUpdatedCallback, - this.alternativeBillingListener, - ); + HostBillingClientCallbackHandler(this.purchasesUpdatedCallback, this.alternativeBillingListener); /// The handler for PurchasesUpdatedListener#onPurchasesUpdated. final PurchasesUpdatedListener purchasesUpdatedCallback; @@ -371,8 +345,7 @@ class HostBillingClientCallbackHandler implements InAppPurchaseCallbackApi { UserSelectedAlternativeBillingListener? alternativeBillingListener; /// Handlers for onBillingServiceDisconnected, indexed by handle identifier. - final List disconnectCallbacks = - []; + final List disconnectCallbacks = []; @override void onBillingServiceDisconnected(int callbackHandle) { diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.dart index a9262b887e1b..2cbe6a2a733f 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.dart @@ -10,8 +10,7 @@ import '../../billing_client_wrappers.dart'; /// /// This usually indicates a serious underlining code issue in the plugin. @visibleForTesting -const String kInvalidBillingConfigErrorMessage = - 'Invalid billing config map from method channel.'; +const String kInvalidBillingConfigErrorMessage = 'Invalid billing config map from method channel.'; /// Params containing the response code and the debug message from the Play Billing API response. @immutable diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.dart index 8f971b2cb405..ed2353bd19b3 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_response_wrapper.dart @@ -10,8 +10,7 @@ import '../../billing_client_wrappers.dart'; /// /// This usually indicates a serious underlining code issue in the plugin. @visibleForTesting -const String kInvalidBillingResultErrorMessage = - 'Invalid billing result map from method channel.'; +const String kInvalidBillingResultErrorMessage = 'Invalid billing result map from method channel.'; /// Params containing the response code and the debug message from the Play Billing API response. @immutable diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/pending_purchases_params_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/pending_purchases_params_wrapper.dart index c6bfd87c36ff..c08befba9688 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/pending_purchases_params_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/pending_purchases_params_wrapper.dart @@ -26,8 +26,7 @@ class PendingPurchasesParamsWrapper { return false; } - return other is PendingPurchasesParamsWrapper && - other.enablePrepaidPlans == enablePrepaidPlans; + return other is PendingPurchasesParamsWrapper && other.enablePrepaidPlans == enablePrepaidPlans; } @override diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.dart index 296cfa5abf0c..cf773282494f 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/purchase_wrapper.dart @@ -155,10 +155,7 @@ class PurchaseWrapper { /// This wraps [`com.android.billingclient.api.Purchase.PendingPurchaseUpdate`](https://developer.android.com/reference/com/android/billingclient/api/Purchase.PendingPurchaseUpdate). class PendingPurchaseUpdateWrapper { /// Creates a pending purchase wrapper update wrapper with the given purchase details. - const PendingPurchaseUpdateWrapper({ - required this.purchaseToken, - required this.products, - }); + const PendingPurchaseUpdateWrapper({required this.purchaseToken, required this.products}); /// A token that uniquely identifies this pending transaction. final String purchaseToken; diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.dart index 716f71f1318b..fae618b788d2 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.dart @@ -169,8 +169,7 @@ class InstallmentPlanDetailsWrapper { return other is InstallmentPlanDetailsWrapper && other.commitmentPaymentsCount == commitmentPaymentsCount && - other.subsequentCommitmentPaymentsCount == - subsequentCommitmentPaymentsCount; + other.subsequentCommitmentPaymentsCount == subsequentCommitmentPaymentsCount; } @override diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.dart index 05327ad7f512..4ff613b8ccd9 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/user_choice_details_wrapper.dart @@ -33,11 +33,8 @@ class UserChoiceDetailsWrapper { } @override - int get hashCode => Object.hash( - originalExternalTransactionId, - externalTransactionToken, - products.hashCode, - ); + int get hashCode => + Object.hash(originalExternalTransactionId, externalTransactionToken, products.hashCode); /// Returns the external transaction Id of the originating subscription, if /// the purchase is a subscription upgrade/downgrade. diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart index e93dd094b8f1..d865e328edbe 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform.dart @@ -33,12 +33,12 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { /// Creates a new InAppPurchaseAndroidPlatform instance, and configures it /// for use. @visibleForTesting - InAppPurchaseAndroidPlatform({ - @visibleForTesting BillingClientManager? manager, - }) : billingClientManager = manager ?? BillingClientManager() { + InAppPurchaseAndroidPlatform({@visibleForTesting BillingClientManager? manager}) + : billingClientManager = manager ?? BillingClientManager() { // Register [InAppPurchaseAndroidPlatformAddition]. - InAppPurchasePlatformAddition.instance = - InAppPurchaseAndroidPlatformAddition(billingClientManager); + InAppPurchasePlatformAddition.instance = InAppPurchaseAndroidPlatformAddition( + billingClientManager, + ); billingClientManager.purchasesUpdatedStream .asyncMap(_getPurchaseDetailsFromResult) @@ -56,8 +56,7 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { StreamController>.broadcast(); @override - late final Stream> purchaseStream = - _purchaseUpdatedController.stream; + late final Stream> purchaseStream = _purchaseUpdatedController.stream; /// The [BillingClient] that's abstracted by [GooglePlayConnection]. /// @@ -76,40 +75,33 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { /// Performs a network query for the details of products available. @override - Future queryProductDetails( - Set identifiers, - ) async { + Future queryProductDetails(Set identifiers) async { List? productResponses; PlatformException? exception; try { - productResponses = - await Future.wait(>[ - billingClientManager.runWithClient( - (BillingClient client) => client.queryProductDetails( - productList: identifiers - .map( - (String productId) => ProductWrapper( - productId: productId, - productType: ProductType.inapp, - ), - ) - .toList(), - ), - ), - billingClientManager.runWithClient( - (BillingClient client) => client.queryProductDetails( - productList: identifiers - .map( - (String productId) => ProductWrapper( - productId: productId, - productType: ProductType.subs, - ), - ) - .toList(), - ), - ), - ]); + productResponses = await Future.wait(>[ + billingClientManager.runWithClient( + (BillingClient client) => client.queryProductDetails( + productList: identifiers + .map( + (String productId) => + ProductWrapper(productId: productId, productType: ProductType.inapp), + ) + .toList(), + ), + ), + billingClientManager.runWithClient( + (BillingClient client) => client.queryProductDetails( + productList: identifiers + .map( + (String productId) => + ProductWrapper(productId: productId, productType: ProductType.subs), + ) + .toList(), + ), + ), + ]); } on PlatformException catch (e) { exception = e; productResponses = [ @@ -134,18 +126,14 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { return response.productDetailsList; }) .expand((ProductDetailsWrapper productDetailWrapper) { - return GooglePlayProductDetails.fromProductDetails( - productDetailWrapper, - ); + return GooglePlayProductDetails.fromProductDetails(productDetailWrapper); }) .toList(); final Set successIDS = productDetailsList .map((ProductDetails productDetails) => productDetails.id) .toSet(); - final List notFoundIDS = identifiers - .difference(successIDS) - .toList(); + final List notFoundIDS = identifiers.difference(successIDS).toList(); return ProductDetailsResponse( productDetails: productDetailsList, notFoundIDs: notFoundIDS, @@ -170,34 +158,26 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { offerToken = purchaseParam.offerToken; } - if (offerToken == null && - purchaseParam.productDetails is GooglePlayProductDetails) { - offerToken = - (purchaseParam.productDetails as GooglePlayProductDetails).offerToken; + if (offerToken == null && purchaseParam.productDetails is GooglePlayProductDetails) { + offerToken = (purchaseParam.productDetails as GooglePlayProductDetails).offerToken; } - final BillingResultWrapper billingResultWrapper = await billingClientManager - .runWithClient( - (BillingClient client) => client.launchBillingFlow( - product: purchaseParam.productDetails.id, - offerToken: offerToken, - accountId: purchaseParam.applicationUserName, - oldProduct: changeSubscriptionParam?.oldPurchaseDetails.productID, - purchaseToken: changeSubscriptionParam - ?.oldPurchaseDetails - .verificationData - .serverVerificationData, - replacementMode: changeSubscriptionParam?.replacementMode, - ), - ); + final BillingResultWrapper billingResultWrapper = await billingClientManager.runWithClient( + (BillingClient client) => client.launchBillingFlow( + product: purchaseParam.productDetails.id, + offerToken: offerToken, + accountId: purchaseParam.applicationUserName, + oldProduct: changeSubscriptionParam?.oldPurchaseDetails.productID, + purchaseToken: + changeSubscriptionParam?.oldPurchaseDetails.verificationData.serverVerificationData, + replacementMode: changeSubscriptionParam?.replacementMode, + ), + ); return billingResultWrapper.responseCode == BillingResponse.ok; } @override - Future buyConsumable({ - required PurchaseParam purchaseParam, - bool autoConsume = true, - }) { + Future buyConsumable({required PurchaseParam purchaseParam, bool autoConsume = true}) { if (autoConsume) { _productIdsToConsume.add(purchaseParam.productDetails.id); } @@ -205,9 +185,7 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { } @override - Future completePurchase( - PurchaseDetails purchase, - ) async { + Future completePurchase(PurchaseDetails purchase) async { assert( purchase is GooglePlayPurchaseDetails, 'On Android, the `purchase` should always be of type `GooglePlayPurchaseDetails`.', @@ -220,9 +198,8 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { } return billingClientManager.runWithClient( - (BillingClient client) => client.acknowledgePurchase( - purchase.verificationData.serverVerificationData, - ), + (BillingClient client) => + client.acknowledgePurchase(purchase.verificationData.serverVerificationData), ); } @@ -240,18 +217,11 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { ]); final Set errorCodeSet = responses - .where( - (PurchasesResultWrapper response) => - response.responseCode != BillingResponse.ok, - ) - .map( - (PurchasesResultWrapper response) => response.responseCode.toString(), - ) + .where((PurchasesResultWrapper response) => response.responseCode != BillingResponse.ok) + .map((PurchasesResultWrapper response) => response.responseCode.toString()) .toSet(); - final String errorMessage = errorCodeSet.isNotEmpty - ? errorCodeSet.join(', ') - : ''; + final String errorMessage = errorCodeSet.isNotEmpty ? errorCodeSet.join(', ') : ''; final List pastPurchases = responses .expand((PurchasesResultWrapper response) => response.purchasesList) @@ -259,10 +229,7 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { (PurchaseWrapper purchaseWrapper) => GooglePlayPurchaseDetails.fromPurchase(purchaseWrapper), ) - .map( - (GooglePlayPurchaseDetails details) => - details..status = PurchaseStatus.restored, - ) + .map((GooglePlayPurchaseDetails details) => details..status = PurchaseStatus.restored) .toList(); if (errorMessage.isNotEmpty) { @@ -276,17 +243,14 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { _purchaseUpdatedController.add(pastPurchases); } - Future _maybeAutoConsumePurchase( - PurchaseDetails purchaseDetails, - ) async { + Future _maybeAutoConsumePurchase(PurchaseDetails purchaseDetails) async { if (!(purchaseDetails.status == PurchaseStatus.purchased && _productIdsToConsume.contains(purchaseDetails.productID))) { return purchaseDetails; } final BillingResultWrapper billingResult = - await (InAppPurchasePlatformAddition.instance! - as InAppPurchaseAndroidPlatformAddition) + await (InAppPurchasePlatformAddition.instance! as InAppPurchaseAndroidPlatformAddition) .consumePurchase(purchaseDetails); final BillingResponse consumedResponse = billingResult.responseCode; if (consumedResponse != BillingResponse.ok) { @@ -316,10 +280,7 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { ); } final List> purchases = resultWrapper.purchasesList - .expand( - (PurchaseWrapper purchase) => - GooglePlayPurchaseDetails.fromPurchase(purchase), - ) + .expand((PurchaseWrapper purchase) => GooglePlayPurchaseDetails.fromPurchase(purchase)) .map((GooglePlayPurchaseDetails purchaseDetails) { purchaseDetails.error = error; if (resultWrapper.responseCode == BillingResponse.userCanceled) { @@ -359,8 +320,9 @@ class InAppPurchaseAndroidPlatform extends InAppPurchasePlatform { /// See: https://unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html @override Future countryCode() async { - final BillingConfigWrapper billingConfig = await billingClientManager - .runWithClient((BillingClient client) => client.getBillingConfig()); + final BillingConfigWrapper billingConfig = await billingClientManager.runWithClient( + (BillingClient client) => client.getBillingConfig(), + ); return billingConfig.countryCode; } diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart index e4d27cdb99bc..4d77bbf7e3be 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/in_app_purchase_android_platform_addition.dart @@ -13,8 +13,7 @@ import 'billing_client_wrappers/billing_config_wrapper.dart'; import 'types/translator.dart'; /// Contains InApp Purchase features that are only available on PlayStore. -class InAppPurchaseAndroidPlatformAddition - extends InAppPurchasePlatformAddition { +class InAppPurchaseAndroidPlatformAddition extends InAppPurchasePlatformAddition { /// Creates a [InAppPurchaseAndroidPlatformAddition] which uses the supplied /// `BillingClientManager` to provide Android specific features. InAppPurchaseAndroidPlatformAddition(this._billingClientManager) { @@ -23,8 +22,7 @@ class InAppPurchaseAndroidPlatformAddition .listen(_userChoiceDetailsStreamController.add); } - final StreamController - _userChoiceDetailsStreamController = + final StreamController _userChoiceDetailsStreamController = StreamController.broadcast(); /// [GooglePlayUserChoiceDetails] emits each time user selects alternative billing. @@ -59,9 +57,7 @@ class InAppPurchaseAndroidPlatformAddition /// /// * [refreshPurchaseVerificationData], for reloading failed /// [PurchaseDetails.verificationData]. - Future queryPastPurchases({ - String? applicationUserName, - }) async { + Future queryPastPurchases({String? applicationUserName}) async { List responses; PlatformException? exception; @@ -97,18 +93,11 @@ class InAppPurchaseAndroidPlatformAddition } final Set errorCodeSet = responses - .where( - (PurchasesResultWrapper response) => - response.responseCode != BillingResponse.ok, - ) - .map( - (PurchasesResultWrapper response) => response.responseCode.toString(), - ) + .where((PurchasesResultWrapper response) => response.responseCode != BillingResponse.ok) + .map((PurchasesResultWrapper response) => response.responseCode.toString()) .toSet(); - final String errorMessage = errorCodeSet.isNotEmpty - ? errorCodeSet.join(', ') - : ''; + final String errorMessage = errorCodeSet.isNotEmpty ? errorCodeSet.join(', ') : ''; final List pastPurchases = responses .expand((PurchasesResultWrapper response) => response.purchasesList) @@ -127,17 +116,10 @@ class InAppPurchaseAndroidPlatformAddition details: exception.details, ); } else if (errorMessage.isNotEmpty) { - error = IAPError( - source: kIAPSource, - code: kRestoredPurchaseErrorCode, - message: errorMessage, - ); + error = IAPError(source: kIAPSource, code: kRestoredPurchaseErrorCode, message: errorMessage); } - return QueryPurchaseDetailsResponse( - pastPurchases: pastPurchases, - error: error, - ); + return QueryPurchaseDetailsResponse(pastPurchases: pastPurchases, error: error); } /// Checks if the specified feature or capability is supported by the Play Store. @@ -154,8 +136,9 @@ class InAppPurchaseAndroidPlatformAddition /// See: https://unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html @Deprecated('Use InAppPurchasePlatfrom.countryCode') Future getCountryCode() async { - final BillingConfigWrapper billingConfig = await _billingClientManager - .runWithClient((BillingClient client) => client.getBillingConfig()); + final BillingConfigWrapper billingConfig = await _billingClientManager.runWithClient( + (BillingClient client) => client.getBillingConfig(), + ); return billingConfig.countryCode; } @@ -164,23 +147,19 @@ class InAppPurchaseAndroidPlatformAddition /// /// See: https://developer.android.com/reference/com/android/billingclient/api/BillingClient#isAlternativeBillingOnlyAvailableAsync(com.android.billingclient.api.AlternativeBillingOnlyAvailabilityListener) Future isAlternativeBillingOnlyAvailable() async { - final BillingResultWrapper wrapper = await _billingClientManager - .runWithClient( - (BillingClient client) => client.isAlternativeBillingOnlyAvailable(), - ); + final BillingResultWrapper wrapper = await _billingClientManager.runWithClient( + (BillingClient client) => client.isAlternativeBillingOnlyAvailable(), + ); return wrapper; } /// Shows the alternative billing only information dialog on top of the calling app. /// /// See: https://developer.android.com/reference/com/android/billingclient/api/BillingClient#showAlternativeBillingOnlyInformationDialog(android.app.Activity,%20com.android.billingclient.api.AlternativeBillingOnlyInformationDialogListener) - Future - showAlternativeBillingOnlyInformationDialog() async { - final BillingResultWrapper wrapper = await _billingClientManager - .runWithClient( - (BillingClient client) => - client.showAlternativeBillingOnlyInformationDialog(), - ); + Future showAlternativeBillingOnlyInformationDialog() async { + final BillingResultWrapper wrapper = await _billingClientManager.runWithClient( + (BillingClient client) => client.showAlternativeBillingOnlyInformationDialog(), + ); return wrapper; } @@ -190,10 +169,9 @@ class InAppPurchaseAndroidPlatformAddition /// See: https://developer.android.com/reference/com/android/billingclient/api/AlternativeBillingOnlyReportingDetails Future createAlternativeBillingOnlyReportingDetails() async { - final AlternativeBillingOnlyReportingDetailsWrapper wrapper = - await _billingClientManager.runWithClient( - (BillingClient client) => - client.createAlternativeBillingOnlyReportingDetails(), + final AlternativeBillingOnlyReportingDetailsWrapper wrapper = await _billingClientManager + .runWithClient( + (BillingClient client) => client.createAlternativeBillingOnlyReportingDetails(), ); return wrapper; } @@ -207,8 +185,6 @@ class InAppPurchaseAndroidPlatformAddition /// Play apis have requirements for when this method can be called. /// See: https://developer.android.com/google/play/billing/alternative/alternative-billing-without-user-choice-in-app Future setBillingChoice(BillingChoiceMode billingChoiceMode) { - return _billingClientManager.reconnectWithBillingChoiceMode( - billingChoiceMode, - ); + return _billingClientManager.reconnectWithBillingChoiceMode(billingChoiceMode); } } diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/messages.g.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/messages.g.dart index 6e100a89f40d..37e57b112e11 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/messages.g.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/messages.g.dart @@ -37,11 +37,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -63,9 +59,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -208,8 +202,7 @@ class PlatformQueryProduct { if (identical(this, other)) { return true; } - return _deepEquals(productId, other.productId) && - _deepEquals(productType, other.productType); + return _deepEquals(productId, other.productId) && _deepEquals(productType, other.productType); } @override @@ -219,10 +212,7 @@ class PlatformQueryProduct { /// Pigeon version of Java AccountIdentifiers. class PlatformAccountIdentifiers { - PlatformAccountIdentifiers({ - this.obfuscatedAccountId, - this.obfuscatedProfileId, - }); + PlatformAccountIdentifiers({this.obfuscatedAccountId, this.obfuscatedProfileId}); String? obfuscatedAccountId; @@ -247,8 +237,7 @@ class PlatformAccountIdentifiers { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformAccountIdentifiers || - other.runtimeType != runtimeType) { + if (other is! PlatformAccountIdentifiers || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -265,10 +254,7 @@ class PlatformAccountIdentifiers { /// Pigeon version of Java BillingResult. class PlatformBillingResult { - PlatformBillingResult({ - required this.responseCode, - required this.debugMessage, - }); + PlatformBillingResult({required this.responseCode, required this.debugMessage}); PlatformBillingResponse responseCode; @@ -342,8 +328,7 @@ class PlatformOneTimePurchaseOfferDetails { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformOneTimePurchaseOfferDetails || - other.runtimeType != runtimeType) { + if (other is! PlatformOneTimePurchaseOfferDetails || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -409,8 +394,7 @@ class PlatformProductDetails { productId: result[2]! as String, productType: result[3]! as PlatformProductType, title: result[4]! as String, - oneTimePurchaseOfferDetails: - result[5] as PlatformOneTimePurchaseOfferDetails?, + oneTimePurchaseOfferDetails: result[5] as PlatformOneTimePurchaseOfferDetails?, subscriptionOfferDetails: (result[6] as List?) ?.cast(), ); @@ -430,10 +414,7 @@ class PlatformProductDetails { _deepEquals(productId, other.productId) && _deepEquals(productType, other.productType) && _deepEquals(title, other.title) && - _deepEquals( - oneTimePurchaseOfferDetails, - other.oneTimePurchaseOfferDetails, - ) && + _deepEquals(oneTimePurchaseOfferDetails, other.oneTimePurchaseOfferDetails) && _deepEquals(subscriptionOfferDetails, other.subscriptionOfferDetails); } @@ -445,10 +426,7 @@ class PlatformProductDetails { /// Pigeon version of ProductDetailsResponseWrapper, which contains the /// components of the Java ProductDetailsResponseListener callback. class PlatformProductDetailsResponse { - PlatformProductDetailsResponse({ - required this.billingResult, - required this.productDetails, - }); + PlatformProductDetailsResponse({required this.billingResult, required this.productDetails}); PlatformBillingResult billingResult; @@ -466,16 +444,14 @@ class PlatformProductDetailsResponse { result as List; return PlatformProductDetailsResponse( billingResult: result[0]! as PlatformBillingResult, - productDetails: (result[1]! as List) - .cast(), + productDetails: (result[1]! as List).cast(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformProductDetailsResponse || - other.runtimeType != runtimeType) { + if (other is! PlatformProductDetailsResponse || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -511,9 +487,7 @@ class PlatformAlternativeBillingOnlyReportingDetailsResponse { return _toList(); } - static PlatformAlternativeBillingOnlyReportingDetailsResponse decode( - Object result, - ) { + static PlatformAlternativeBillingOnlyReportingDetailsResponse decode(Object result) { result as List; return PlatformAlternativeBillingOnlyReportingDetailsResponse( billingResult: result[0]! as PlatformBillingResult, @@ -543,10 +517,7 @@ class PlatformAlternativeBillingOnlyReportingDetailsResponse { /// Pigeon version of BillingConfigWrapper, which contains the components of the /// Java BillingConfigResponseListener callback. class PlatformBillingConfigResponse { - PlatformBillingConfigResponse({ - required this.billingResult, - required this.countryCode, - }); + PlatformBillingConfigResponse({required this.billingResult, required this.countryCode}); PlatformBillingResult billingResult; @@ -571,8 +542,7 @@ class PlatformBillingConfigResponse { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBillingConfigResponse || - other.runtimeType != runtimeType) { + if (other is! PlatformBillingConfigResponse || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -645,8 +615,7 @@ class PlatformBillingFlowParams { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformBillingFlowParams || - other.runtimeType != runtimeType) { + if (other is! PlatformBillingFlowParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -864,10 +833,7 @@ class PlatformPurchase { /// /// See also PendingPurchaseUpdateWrapper on the Dart side. class PlatformPendingPurchaseUpdate { - PlatformPendingPurchaseUpdate({ - required this.products, - required this.purchaseToken, - }); + PlatformPendingPurchaseUpdate({required this.products, required this.purchaseToken}); List products; @@ -892,15 +858,13 @@ class PlatformPendingPurchaseUpdate { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformPendingPurchaseUpdate || - other.runtimeType != runtimeType) { + if (other is! PlatformPendingPurchaseUpdate || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { return true; } - return _deepEquals(products, other.products) && - _deepEquals(purchaseToken, other.purchaseToken); + return _deepEquals(products, other.products) && _deepEquals(purchaseToken, other.purchaseToken); } @override @@ -968,8 +932,7 @@ class PlatformPurchaseHistoryRecord { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformPurchaseHistoryRecord || - other.runtimeType != runtimeType) { + if (other is! PlatformPurchaseHistoryRecord || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -992,10 +955,7 @@ class PlatformPurchaseHistoryRecord { /// Pigeon version of PurchasesHistoryResult, which contains the components of /// the Java PurchaseHistoryResponseListener callback. class PlatformPurchaseHistoryResponse { - PlatformPurchaseHistoryResponse({ - required this.billingResult, - required this.purchases, - }); + PlatformPurchaseHistoryResponse({required this.billingResult, required this.purchases}); PlatformBillingResult billingResult; @@ -1013,16 +973,14 @@ class PlatformPurchaseHistoryResponse { result as List; return PlatformPurchaseHistoryResponse( billingResult: result[0]! as PlatformBillingResult, - purchases: (result[1]! as List) - .cast(), + purchases: (result[1]! as List).cast(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformPurchaseHistoryResponse || - other.runtimeType != runtimeType) { + if (other is! PlatformPurchaseHistoryResponse || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1040,10 +998,7 @@ class PlatformPurchaseHistoryResponse { /// Pigeon version of PurchasesResultWrapper, which contains the components of /// the Java PurchasesResponseListener callback. class PlatformPurchasesResponse { - PlatformPurchasesResponse({ - required this.billingResult, - required this.purchases, - }); + PlatformPurchasesResponse({required this.billingResult, required this.purchases}); PlatformBillingResult billingResult; @@ -1068,8 +1023,7 @@ class PlatformPurchasesResponse { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformPurchasesResponse || - other.runtimeType != runtimeType) { + if (other is! PlatformPurchasesResponse || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1137,8 +1091,7 @@ class PlatformSubscriptionOfferDetails { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformSubscriptionOfferDetails || - other.runtimeType != runtimeType) { + if (other is! PlatformSubscriptionOfferDetails || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1172,11 +1125,7 @@ class PlatformUserChoiceDetails { List products; List _toList() { - return [ - originalExternalTransactionId, - externalTransactionToken, - products, - ]; + return [originalExternalTransactionId, externalTransactionToken, products]; } Object encode() { @@ -1195,17 +1144,13 @@ class PlatformUserChoiceDetails { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformUserChoiceDetails || - other.runtimeType != runtimeType) { + if (other is! PlatformUserChoiceDetails || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { return true; } - return _deepEquals( - originalExternalTransactionId, - other.originalExternalTransactionId, - ) && + return _deepEquals(originalExternalTransactionId, other.originalExternalTransactionId) && _deepEquals(externalTransactionToken, other.externalTransactionToken) && _deepEquals(products, other.products); } @@ -1217,11 +1162,7 @@ class PlatformUserChoiceDetails { /// Pigeon version of UserChoiseDetails.Product. class PlatformUserChoiceProduct { - PlatformUserChoiceProduct({ - required this.id, - this.offerToken, - required this.type, - }); + PlatformUserChoiceProduct({required this.id, this.offerToken, required this.type}); String id; @@ -1249,8 +1190,7 @@ class PlatformUserChoiceProduct { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformUserChoiceProduct || - other.runtimeType != runtimeType) { + if (other is! PlatformUserChoiceProduct || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1279,10 +1219,7 @@ class PlatformInstallmentPlanDetails { int subsequentCommitmentPaymentsCount; List _toList() { - return [ - commitmentPaymentsCount, - subsequentCommitmentPaymentsCount, - ]; + return [commitmentPaymentsCount, subsequentCommitmentPaymentsCount]; } Object encode() { @@ -1300,21 +1237,14 @@ class PlatformInstallmentPlanDetails { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformInstallmentPlanDetails || - other.runtimeType != runtimeType) { + if (other is! PlatformInstallmentPlanDetails || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { return true; } - return _deepEquals( - commitmentPaymentsCount, - other.commitmentPaymentsCount, - ) && - _deepEquals( - subsequentCommitmentPaymentsCount, - other.subsequentCommitmentPaymentsCount, - ); + return _deepEquals(commitmentPaymentsCount, other.commitmentPaymentsCount) && + _deepEquals(subsequentCommitmentPaymentsCount, other.subsequentCommitmentPaymentsCount); } @override @@ -1338,16 +1268,13 @@ class PlatformPendingPurchasesParams { static PlatformPendingPurchasesParams decode(Object result) { result as List; - return PlatformPendingPurchasesParams( - enablePrepaidPlans: result[0]! as bool, - ); + return PlatformPendingPurchasesParams(enablePrepaidPlans: result[0]! as bool); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! PlatformPendingPurchasesParams || - other.runtimeType != runtimeType) { + if (other is! PlatformPendingPurchasesParams || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1407,8 +1334,7 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is PlatformProductDetailsResponse) { buffer.putUint8(141); writeValue(buffer, value.encode()); - } else if (value - is PlatformAlternativeBillingOnlyReportingDetailsResponse) { + } else if (value is PlatformAlternativeBillingOnlyReportingDetailsResponse) { buffer.putUint8(142); writeValue(buffer, value.encode()); } else if (value is PlatformBillingConfigResponse) { @@ -1472,9 +1398,7 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : PlatformBillingChoiceMode.values[value]; case 133: final value = readValue(buffer) as int?; - return value == null - ? null - : PlatformBillingClientFeature.values[value]; + return value == null ? null : PlatformBillingClientFeature.values[value]; case 134: final value = readValue(buffer) as int?; return value == null ? null : PlatformPurchaseState.values[value]; @@ -1494,9 +1418,7 @@ class _PigeonCodec extends StandardMessageCodec { case 141: return PlatformProductDetailsResponse.decode(readValue(buffer)!); case 142: - return PlatformAlternativeBillingOnlyReportingDetailsResponse.decode( - readValue(buffer)!, - ); + return PlatformAlternativeBillingOnlyReportingDetailsResponse.decode(readValue(buffer)!); case 143: return PlatformBillingConfigResponse.decode(readValue(buffer)!); case 144: @@ -1533,13 +1455,11 @@ class InAppPurchaseApi { /// Constructor for [InAppPurchaseApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - InAppPurchaseApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + InAppPurchaseApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -1579,9 +1499,11 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [callbackHandle, billingMode, pendingPurchasesParams], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + callbackHandle, + billingMode, + pendingPurchasesParams, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1604,11 +1526,7 @@ class InAppPurchaseApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Wraps BillingClient#getBillingConfigAsync(GetBillingConfigParams, BillingConfigResponseListener). @@ -1632,9 +1550,7 @@ class InAppPurchaseApi { } /// Wraps BillingClient#launchBillingFlow(Activity, BillingFlowParams). - Future launchBillingFlow( - PlatformBillingFlowParams params, - ) async { + Future launchBillingFlow(PlatformBillingFlowParams params) async { final pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_android.InAppPurchaseApi.launchBillingFlow$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1642,9 +1558,7 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [params], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([params]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1656,9 +1570,7 @@ class InAppPurchaseApi { } /// Wraps BillingClient#acknowledgePurchase(AcknowledgePurchaseParams, AcknowledgePurchaseResponseListener). - Future acknowledgePurchase( - String purchaseToken, - ) async { + Future acknowledgePurchase(String purchaseToken) async { final pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_android.InAppPurchaseApi.acknowledgePurchase$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1666,9 +1578,7 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [purchaseToken], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([purchaseToken]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1688,9 +1598,7 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [purchaseToken], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([purchaseToken]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1702,9 +1610,7 @@ class InAppPurchaseApi { } /// Wraps BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener). - Future queryPurchasesAsync( - PlatformProductType productType, - ) async { + Future queryPurchasesAsync(PlatformProductType productType) async { final pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_android.InAppPurchaseApi.queryPurchasesAsync$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1712,9 +1618,7 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [productType], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([productType]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1736,9 +1640,7 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [productType], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([productType]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1760,9 +1662,7 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [products], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([products]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1782,9 +1682,7 @@ class InAppPurchaseApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [feature], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([feature]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1816,8 +1714,7 @@ class InAppPurchaseApi { } /// Wraps BillingClient#showAlternativeBillingOnlyInformationDialog(). - Future - showAlternativeBillingOnlyInformationDialog() async { + Future showAlternativeBillingOnlyInformationDialog() async { final pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_android.InAppPurchaseApi.showAlternativeBillingOnlyInformationDialog$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1854,8 +1751,7 @@ class InAppPurchaseApi { pigeonVar_channelName, isNullValid: false, ); - return pigeonVar_replyValue! - as PlatformAlternativeBillingOnlyReportingDetailsResponse; + return pigeonVar_replyValue! as PlatformAlternativeBillingOnlyReportingDetailsResponse; } } @@ -1876,9 +1772,7 @@ abstract class InAppPurchaseCallbackApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.in_app_purchase_android.InAppPurchaseCallbackApi.onBillingServiceDisconnected$messageChannelSuffix', @@ -1915,8 +1809,7 @@ abstract class InAppPurchaseCallbackApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final PlatformPurchasesResponse arg_update = - args[0]! as PlatformPurchasesResponse; + final PlatformPurchasesResponse arg_update = args[0]! as PlatformPurchasesResponse; try { api.onPurchasesUpdated(arg_update); return wrapResponse(empty: true); @@ -1941,8 +1834,7 @@ abstract class InAppPurchaseCallbackApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final PlatformUserChoiceDetails arg_details = - args[0]! as PlatformUserChoiceDetails; + final PlatformUserChoiceDetails arg_details = args[0]! as PlatformUserChoiceDetails; try { api.userSelectedalternativeBilling(arg_details); return wrapResponse(empty: true); diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/pigeon_converters.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/pigeon_converters.dart index c3586df9c6a7..e4f6f578a8fd 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/pigeon_converters.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/pigeon_converters.dart @@ -12,12 +12,9 @@ import 'messages.g.dart'; /// Converts a [BillingChoiceMode] to the Pigeon equivalent. PlatformBillingChoiceMode platformBillingChoiceMode(BillingChoiceMode mode) { return switch (mode) { - BillingChoiceMode.playBillingOnly => - PlatformBillingChoiceMode.playBillingOnly, - BillingChoiceMode.alternativeBillingOnly => - PlatformBillingChoiceMode.alternativeBillingOnly, - BillingChoiceMode.userChoiceBilling => - PlatformBillingChoiceMode.userChoiceBilling, + BillingChoiceMode.playBillingOnly => PlatformBillingChoiceMode.playBillingOnly, + BillingChoiceMode.alternativeBillingOnly => PlatformBillingChoiceMode.alternativeBillingOnly, + BillingChoiceMode.userChoiceBilling => PlatformBillingChoiceMode.userChoiceBilling, }; } @@ -35,16 +32,12 @@ ProductDetailsResponseWrapper productDetailsResponseWrapperFromPlatform( ) { return ProductDetailsResponseWrapper( billingResult: resultWrapperFromPlatform(response.billingResult), - productDetailsList: response.productDetails - .map(productDetailsWrapperFromPlatform) - .toList(), + productDetailsList: response.productDetails.map(productDetailsWrapperFromPlatform).toList(), ); } /// Creates a [ProductDetailsWrapper] from the Pigeon equivalent. -ProductDetailsWrapper productDetailsWrapperFromPlatform( - PlatformProductDetails product, -) { +ProductDetailsWrapper productDetailsWrapperFromPlatform(PlatformProductDetails product) { return ProductDetailsWrapper( description: product.description, name: product.name, @@ -61,8 +54,7 @@ ProductDetailsWrapper productDetailsWrapperFromPlatform( } /// Creates a [OneTimePurchaseOfferDetailsWrapper] from the Pigeon equivalent. -OneTimePurchaseOfferDetailsWrapper? -oneTimePurchaseOfferDetailsWrapperFromPlatform( +OneTimePurchaseOfferDetailsWrapper? oneTimePurchaseOfferDetailsWrapperFromPlatform( PlatformOneTimePurchaseOfferDetails? details, ) { if (details == null) { @@ -76,9 +68,7 @@ oneTimePurchaseOfferDetailsWrapperFromPlatform( } /// Creates a [PurchaseHistoryResult] from the Pigeon equivalent. -PurchasesHistoryResult purchaseHistoryResultFromPlatform( - PlatformPurchaseHistoryResponse response, -) { +PurchasesHistoryResult purchaseHistoryResultFromPlatform(PlatformPurchaseHistoryResponse response) { return PurchasesHistoryResult( billingResult: resultWrapperFromPlatform(response.billingResult), purchaseHistoryRecordList: response.purchases @@ -122,22 +112,16 @@ alternativeBillingOnlyReportingDetailsWrapperFromPlatform( PlatformAlternativeBillingOnlyReportingDetailsResponse response, ) { return AlternativeBillingOnlyReportingDetailsWrapper( - responseCode: billingResponseFromPlatform( - response.billingResult.responseCode, - ), + responseCode: billingResponseFromPlatform(response.billingResult.responseCode), debugMessage: response.billingResult.debugMessage, externalTransactionToken: response.externalTransactionToken, ); } /// Creates a [BillingConfigWrapper] from the Pigeon equivalent. -BillingConfigWrapper billingConfigWrapperFromPlatform( - PlatformBillingConfigResponse response, -) { +BillingConfigWrapper billingConfigWrapperFromPlatform(PlatformBillingConfigResponse response) { return BillingConfigWrapper( - responseCode: billingResponseFromPlatform( - response.billingResult.responseCode, - ), + responseCode: billingResponseFromPlatform(response.billingResult.responseCode), debugMessage: response.billingResult.debugMessage, countryCode: response.countryCode, ); @@ -160,9 +144,7 @@ PlatformProductType platformProductTypeFromWrapper(ProductType type) { } /// Creates a [PricingPhaseWrapper] from its Pigeon equivalent. -PricingPhaseWrapper pricingPhaseWrapperFromPlatform( - PlatformPricingPhase phase, -) { +PricingPhaseWrapper pricingPhaseWrapperFromPlatform(PlatformPricingPhase phase) { return PricingPhaseWrapper( billingCycleCount: phase.billingCycleCount, billingPeriod: phase.billingPeriod, @@ -197,9 +179,7 @@ PurchaseWrapper purchaseWrapperFromPlatform(PlatformPurchase purchase) { developerPayload: purchase.developerPayload, obfuscatedAccountId: purchase.accountIdentifiers?.obfuscatedAccountId, obfuscatedProfileId: purchase.accountIdentifiers?.obfuscatedProfileId, - pendingPurchaseUpdate: pendingPurchaseUpdateFromPlatform( - purchase.pendingPurchaseUpdate, - ), + pendingPurchaseUpdate: pendingPurchaseUpdateFromPlatform(purchase.pendingPurchaseUpdate), ); } @@ -218,9 +198,7 @@ PendingPurchaseUpdateWrapper? pendingPurchaseUpdateFromPlatform( } /// Creates a [PurchaseStateWrapper] from the Pigeon equivalent. -PurchaseStateWrapper purchaseStateWrapperFromPlatform( - PlatformPurchaseState state, -) { +PurchaseStateWrapper purchaseStateWrapperFromPlatform(PlatformPurchaseState state) { return switch (state) { PlatformPurchaseState.unspecified => PurchaseStateWrapper.unspecified_state, PlatformPurchaseState.purchased => PurchaseStateWrapper.purchased, @@ -241,8 +219,7 @@ PurchaseStatus purchaseStatusFromWrapper(PurchaseStateWrapper purchaseState) { RecurrenceMode recurrenceModeFromPlatform(PlatformRecurrenceMode mode) { return switch (mode) { PlatformRecurrenceMode.finiteRecurring => RecurrenceMode.finiteRecurring, - PlatformRecurrenceMode.infiniteRecurring => - RecurrenceMode.infiniteRecurring, + PlatformRecurrenceMode.infiniteRecurring => RecurrenceMode.infiniteRecurring, PlatformRecurrenceMode.nonRecurring => RecurrenceMode.nonRecurring, }; } @@ -256,25 +233,17 @@ SubscriptionOfferDetailsWrapper subscriptionOfferDetailsWrapperFromPlatform( offerId: offer.offerId, offerTags: offer.offerTags, offerIdToken: offer.offerToken, - pricingPhases: offer.pricingPhases - .map(pricingPhaseWrapperFromPlatform) - .toList(), - installmentPlanDetails: installmentPlanDetailsFromPlatform( - offer.installmentPlanDetails, - ), + pricingPhases: offer.pricingPhases.map(pricingPhaseWrapperFromPlatform).toList(), + installmentPlanDetails: installmentPlanDetailsFromPlatform(offer.installmentPlanDetails), ); } /// Creates a [UserChoiceDetailsWrapper] from the Pigeon equivalent. -UserChoiceDetailsWrapper userChoiceDetailsFromPlatform( - PlatformUserChoiceDetails details, -) { +UserChoiceDetailsWrapper userChoiceDetailsFromPlatform(PlatformUserChoiceDetails details) { return UserChoiceDetailsWrapper( originalExternalTransactionId: details.originalExternalTransactionId ?? '', externalTransactionToken: details.externalTransactionToken, - products: details.products - .map(userChoiceDetailsProductFromPlatform) - .toList(), + products: details.products.map(userChoiceDetailsProductFromPlatform).toList(), ); } @@ -299,8 +268,7 @@ InstallmentPlanDetailsWrapper? installmentPlanDetailsFromPlatform( return InstallmentPlanDetailsWrapper( commitmentPaymentsCount: details.commitmentPaymentsCount, - subsequentCommitmentPaymentsCount: - details.subsequentCommitmentPaymentsCount, + subsequentCommitmentPaymentsCount: details.subsequentCommitmentPaymentsCount, ); } @@ -308,101 +276,71 @@ InstallmentPlanDetailsWrapper? installmentPlanDetailsFromPlatform( PlatformPendingPurchasesParams pendingPurchasesParamsFromWrapper( PendingPurchasesParamsWrapper params, ) { - return PlatformPendingPurchasesParams( - enablePrepaidPlans: params.enablePrepaidPlans, - ); + return PlatformPendingPurchasesParams(enablePrepaidPlans: params.enablePrepaidPlans); } /// Converts [PlatformBillingResponse] to its public API enum equivalent. -BillingResponse billingResponseFromPlatform( - PlatformBillingResponse responseCode, -) { +BillingResponse billingResponseFromPlatform(PlatformBillingResponse responseCode) { return switch (responseCode) { PlatformBillingResponse.serviceTimeout => BillingResponse.serviceTimeout, - PlatformBillingResponse.featureNotSupported => - BillingResponse.featureNotSupported, - PlatformBillingResponse.serviceDisconnected => - BillingResponse.serviceDisconnected, + PlatformBillingResponse.featureNotSupported => BillingResponse.featureNotSupported, + PlatformBillingResponse.serviceDisconnected => BillingResponse.serviceDisconnected, PlatformBillingResponse.ok => BillingResponse.ok, PlatformBillingResponse.userCanceled => BillingResponse.userCanceled, - PlatformBillingResponse.serviceUnavailable => - BillingResponse.serviceUnavailable, - PlatformBillingResponse.billingUnavailable => - BillingResponse.billingUnavailable, + PlatformBillingResponse.serviceUnavailable => BillingResponse.serviceUnavailable, + PlatformBillingResponse.billingUnavailable => BillingResponse.billingUnavailable, PlatformBillingResponse.itemUnavailable => BillingResponse.itemUnavailable, PlatformBillingResponse.developerError => BillingResponse.developerError, PlatformBillingResponse.error => BillingResponse.error, - PlatformBillingResponse.itemAlreadyOwned => - BillingResponse.itemAlreadyOwned, + PlatformBillingResponse.itemAlreadyOwned => BillingResponse.itemAlreadyOwned, PlatformBillingResponse.itemNotOwned => BillingResponse.itemNotOwned, PlatformBillingResponse.networkError => BillingResponse.networkError, }; } /// Converts a [BillingResponse] to its Pigeon equivalent. -PlatformBillingResponse billingResponseFromWrapper( - BillingResponse responseCode, -) { +PlatformBillingResponse billingResponseFromWrapper(BillingResponse responseCode) { return switch (responseCode) { BillingResponse.serviceTimeout => PlatformBillingResponse.serviceTimeout, - BillingResponse.featureNotSupported => - PlatformBillingResponse.featureNotSupported, - BillingResponse.serviceDisconnected => - PlatformBillingResponse.serviceDisconnected, + BillingResponse.featureNotSupported => PlatformBillingResponse.featureNotSupported, + BillingResponse.serviceDisconnected => PlatformBillingResponse.serviceDisconnected, BillingResponse.ok => PlatformBillingResponse.ok, BillingResponse.userCanceled => PlatformBillingResponse.userCanceled, - BillingResponse.serviceUnavailable => - PlatformBillingResponse.serviceUnavailable, - BillingResponse.billingUnavailable => - PlatformBillingResponse.billingUnavailable, + BillingResponse.serviceUnavailable => PlatformBillingResponse.serviceUnavailable, + BillingResponse.billingUnavailable => PlatformBillingResponse.billingUnavailable, BillingResponse.itemUnavailable => PlatformBillingResponse.itemUnavailable, BillingResponse.developerError => PlatformBillingResponse.developerError, BillingResponse.error => PlatformBillingResponse.error, - BillingResponse.itemAlreadyOwned => - PlatformBillingResponse.itemAlreadyOwned, + BillingResponse.itemAlreadyOwned => PlatformBillingResponse.itemAlreadyOwned, BillingResponse.itemNotOwned => PlatformBillingResponse.itemNotOwned, BillingResponse.networkError => PlatformBillingResponse.networkError, }; } /// Converts [ReplacementMode] enum to its Pigeon equivalent. -PlatformReplacementMode replacementModeFromWrapper( - ReplacementMode replacementMode, -) { +PlatformReplacementMode replacementModeFromWrapper(ReplacementMode replacementMode) { return switch (replacementMode) { - ReplacementMode.unknownReplacementMode => - PlatformReplacementMode.unknownReplacementMode, - ReplacementMode.withTimeProration => - PlatformReplacementMode.withTimeProration, - ReplacementMode.chargeProratedPrice => - PlatformReplacementMode.chargeProratedPrice, - ReplacementMode.withoutProration => - PlatformReplacementMode.withoutProration, + ReplacementMode.unknownReplacementMode => PlatformReplacementMode.unknownReplacementMode, + ReplacementMode.withTimeProration => PlatformReplacementMode.withTimeProration, + ReplacementMode.chargeProratedPrice => PlatformReplacementMode.chargeProratedPrice, + ReplacementMode.withoutProration => PlatformReplacementMode.withoutProration, ReplacementMode.deferred => PlatformReplacementMode.deferred, ReplacementMode.chargeFullPrice => PlatformReplacementMode.chargeFullPrice, }; } /// Converts [BillingClientFeature] enum to its Pigeon equivalent. -PlatformBillingClientFeature billingClientFeatureFromWrapper( - BillingClientFeature feature, -) { +PlatformBillingClientFeature billingClientFeatureFromWrapper(BillingClientFeature feature) { return switch (feature) { BillingClientFeature.alternativeBillingOnly => PlatformBillingClientFeature.alternativeBillingOnly, BillingClientFeature.priceChangeConfirmation => PlatformBillingClientFeature.priceChangeConfirmation, - BillingClientFeature.productDetails => - PlatformBillingClientFeature.productDetails, - BillingClientFeature.subscriptions => - PlatformBillingClientFeature.subscriptions, - BillingClientFeature.subscriptionsUpdate => - PlatformBillingClientFeature.subscriptionsUpdate, - BillingClientFeature.billingConfig => - PlatformBillingClientFeature.billingConfig, - BillingClientFeature.externalOffer => - PlatformBillingClientFeature.externalOffer, - BillingClientFeature.inAppMessaging => - PlatformBillingClientFeature.inAppMessaging, + BillingClientFeature.productDetails => PlatformBillingClientFeature.productDetails, + BillingClientFeature.subscriptions => PlatformBillingClientFeature.subscriptions, + BillingClientFeature.subscriptionsUpdate => PlatformBillingClientFeature.subscriptionsUpdate, + BillingClientFeature.billingConfig => PlatformBillingClientFeature.billingConfig, + BillingClientFeature.externalOffer => PlatformBillingClientFeature.externalOffer, + BillingClientFeature.inAppMessaging => PlatformBillingClientFeature.inAppMessaging, }; } diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/change_subscription_param.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/change_subscription_param.dart index 93b7fd1ad15e..5d5e8d447a01 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/change_subscription_param.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/change_subscription_param.dart @@ -8,10 +8,7 @@ import 'types.dart'; /// This parameter object for upgrading or downgrading an existing subscription. class ChangeSubscriptionParam { /// Creates a new change subscription param object with given data - ChangeSubscriptionParam({ - required this.oldPurchaseDetails, - this.replacementMode, - }); + ChangeSubscriptionParam({required this.oldPurchaseDetails, this.replacementMode}); /// The purchase object of the existing subscription that the user needs to /// upgrade/downgrade from. diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_product_details.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_product_details.dart index 3858c75f0e14..7ec1a558a207 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_product_details.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_product_details.dart @@ -35,8 +35,7 @@ class GooglePlayProductDetails extends ProductDetails { productDetails.oneTimePurchaseOfferDetails!; final String formattedPrice = oneTimePurchaseOfferDetails.formattedPrice; - final double rawPrice = - oneTimePurchaseOfferDetails.priceAmountMicros / 1000000.0; + final double rawPrice = oneTimePurchaseOfferDetails.priceAmountMicros / 1000000.0; final String currencyCode = oneTimePurchaseOfferDetails.priceCurrencyCode; final String? currencySymbol = _extractCurrencySymbol(formattedPrice); @@ -70,8 +69,7 @@ class GooglePlayProductDetails extends ProductDetails { final SubscriptionOfferDetailsWrapper subscriptionOfferDetails = productDetails.subscriptionOfferDetails![subscriptionIndex]; - final PricingPhaseWrapper firstPricingPhase = - subscriptionOfferDetails.pricingPhases.first; + final PricingPhaseWrapper firstPricingPhase = subscriptionOfferDetails.pricingPhases.first; final String formattedPrice = firstPricingPhase.formattedPrice; final double rawPrice = firstPricingPhase.priceAmountMicros / 1000000.0; final String currencyCode = firstPricingPhase.priceCurrencyCode; @@ -98,14 +96,10 @@ class GooglePlayProductDetails extends ProductDetails { /// If [productDetails] is of type [ProductType.subs], a list is returned /// where every element corresponds to a base plan or its offer in /// [productDetails.subscriptionOfferDetails]. - static List fromProductDetails( - ProductDetailsWrapper productDetails, - ) { + static List fromProductDetails(ProductDetailsWrapper productDetails) { if (productDetails.productType == ProductType.inapp) { return [ - GooglePlayProductDetails._fromOneTimePurchaseProductDetails( - productDetails, - ), + GooglePlayProductDetails._fromOneTimePurchaseProductDetails(productDetails), ]; } else { final productDetailList = []; @@ -115,10 +109,7 @@ class GooglePlayProductDetails extends ProductDetails { subscriptionIndex++ ) { productDetailList.add( - GooglePlayProductDetails._fromSubscription( - productDetails, - subscriptionIndex, - ), + GooglePlayProductDetails._fromSubscription(productDetails, subscriptionIndex), ); } @@ -158,10 +149,7 @@ class GooglePlayProductDetails extends ProductDetails { /// The offerToken of the subscription this [GooglePlayProductDetails] /// object was contructed for, or `null` if it was not a subscription. String? get offerToken => - subscriptionIndex != null && - productDetails.subscriptionOfferDetails != null - ? productDetails - .subscriptionOfferDetails![subscriptionIndex!] - .offerIdToken + subscriptionIndex != null && productDetails.subscriptionOfferDetails != null + ? productDetails.subscriptionOfferDetails![subscriptionIndex!].offerIdToken : null; } diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart index 36d33b1e5509..727f54c7baf3 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_purchase_details.dart @@ -26,9 +26,7 @@ class GooglePlayPurchaseDetails extends PurchaseDetails { /// Generates a [List] of [PurchaseDetails] based on an Android [Purchase] object. /// /// The list contains one entry per product. - static List fromPurchase( - PurchaseWrapper purchase, - ) { + static List fromPurchase(PurchaseWrapper purchase) { return purchase.products.map((String productId) { final purchaseDetails = GooglePlayPurchaseDetails( purchaseID: purchase.orderId, @@ -44,11 +42,7 @@ class GooglePlayPurchaseDetails extends PurchaseDetails { ); if (purchaseDetails.status == PurchaseStatus.error) { - purchaseDetails.error = IAPError( - source: kIAPSource, - code: kPurchaseErrorCode, - message: '', - ); + purchaseDetails.error = IAPError(source: kIAPSource, code: kPurchaseErrorCode, message: ''); } return purchaseDetails; diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_user_choice_details.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_user_choice_details.dart index 34cd8c1aba86..b4d53433cd3a 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_user_choice_details.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_user_choice_details.dart @@ -44,11 +44,8 @@ class GooglePlayUserChoiceDetails { } @override - int get hashCode => Object.hash( - originalExternalTransactionId, - externalTransactionToken, - products.hashCode, - ); + int get hashCode => + Object.hash(originalExternalTransactionId, externalTransactionToken, products.hashCode); } /// Data structure representing a UserChoiceDetails product. diff --git a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/translator.dart b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/translator.dart index d2579ea69c6d..466461997206 100644 --- a/packages/in_app_purchase/in_app_purchase_android/lib/src/types/translator.dart +++ b/packages/in_app_purchase/in_app_purchase_android/lib/src/types/translator.dart @@ -16,14 +16,10 @@ class Translator { UserChoiceDetailsWrapper detailsWrapper, ) { return GooglePlayUserChoiceDetails( - originalExternalTransactionId: - detailsWrapper.originalExternalTransactionId, + originalExternalTransactionId: detailsWrapper.originalExternalTransactionId, externalTransactionToken: detailsWrapper.externalTransactionToken, products: detailsWrapper.products - .map( - (UserChoiceDetailsProductWrapper e) => - convertToUserChoiceDetailsProduct(e), - ) + .map((UserChoiceDetailsProductWrapper e) => convertToUserChoiceDetailsProduct(e)) .toList(), ); } diff --git a/packages/in_app_purchase/in_app_purchase_android/pigeons/messages.dart b/packages/in_app_purchase/in_app_purchase_android/pigeons/messages.dart index 7aa6c9e84ceb..4892ec9072ae 100644 --- a/packages/in_app_purchase/in_app_purchase_android/pigeons/messages.dart +++ b/packages/in_app_purchase/in_app_purchase_android/pigeons/messages.dart @@ -8,8 +8,7 @@ import 'package:pigeon/pigeon.dart'; PigeonOptions( dartOut: 'lib/src/messages.g.dart', kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.inapppurchase'), - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/inapppurchase/Messages.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/inapppurchase/Messages.kt', copyrightHeader: 'pigeons/copyright.txt', ), ) @@ -34,10 +33,7 @@ class PlatformAccountIdentifiers { /// Pigeon version of Java BillingResult. class PlatformBillingResult { - PlatformBillingResult({ - required this.responseCode, - required this.debugMessage, - }); + PlatformBillingResult({required this.responseCode, required this.debugMessage}); final PlatformBillingResponse responseCode; final String debugMessage; } @@ -96,10 +92,7 @@ class PlatformProductDetails { /// Pigeon version of ProductDetailsResponseWrapper, which contains the /// components of the Java ProductDetailsResponseListener callback. class PlatformProductDetailsResponse { - PlatformProductDetailsResponse({ - required this.billingResult, - required this.productDetails, - }); + PlatformProductDetailsResponse({required this.billingResult, required this.productDetails}); final PlatformBillingResult billingResult; final List productDetails; @@ -121,10 +114,7 @@ class PlatformAlternativeBillingOnlyReportingDetailsResponse { /// Pigeon version of BillingConfigWrapper, which contains the components of the /// Java BillingConfigResponseListener callback. class PlatformBillingConfigResponse { - PlatformBillingConfigResponse({ - required this.billingResult, - required this.countryCode, - }); + PlatformBillingConfigResponse({required this.billingResult, required this.countryCode}); final PlatformBillingResult billingResult; final String countryCode; @@ -220,10 +210,7 @@ class PlatformPurchase { /// /// See also PendingPurchaseUpdateWrapper on the Dart side. class PlatformPendingPurchaseUpdate { - PlatformPendingPurchaseUpdate({ - required this.products, - required this.purchaseToken, - }); + PlatformPendingPurchaseUpdate({required this.products, required this.purchaseToken}); final List products; final String purchaseToken; @@ -255,10 +242,7 @@ class PlatformPurchaseHistoryRecord { /// Pigeon version of PurchasesHistoryResult, which contains the components of /// the Java PurchaseHistoryResponseListener callback. class PlatformPurchaseHistoryResponse { - PlatformPurchaseHistoryResponse({ - required this.billingResult, - required this.purchases, - }); + PlatformPurchaseHistoryResponse({required this.billingResult, required this.purchases}); final PlatformBillingResult billingResult; final List purchases; @@ -267,10 +251,7 @@ class PlatformPurchaseHistoryResponse { /// Pigeon version of PurchasesResultWrapper, which contains the components of /// the Java PurchasesResponseListener callback. class PlatformPurchasesResponse { - PlatformPurchasesResponse({ - required this.billingResult, - required this.purchases, - }); + PlatformPurchasesResponse({required this.billingResult, required this.purchases}); final PlatformBillingResult billingResult; final List purchases; @@ -314,11 +295,7 @@ class PlatformUserChoiceDetails { /// Pigeon version of UserChoiseDetails.Product. class PlatformUserChoiceProduct { - PlatformUserChoiceProduct({ - required this.id, - required this.offerToken, - required this.type, - }); + PlatformUserChoiceProduct({required this.id, required this.offerToken, required this.type}); final String id; final String? offerToken; @@ -412,21 +389,15 @@ abstract class InAppPurchaseApi { /// Wraps BillingClient#queryPurchasesAsync(QueryPurchaseParams, PurchaseResponseListener). @async - PlatformPurchasesResponse queryPurchasesAsync( - PlatformProductType productType, - ); + PlatformPurchasesResponse queryPurchasesAsync(PlatformProductType productType); /// Wraps BillingClient#queryPurchaseHistoryAsync(QueryPurchaseHistoryParams, PurchaseHistoryResponseListener). @async - PlatformPurchaseHistoryResponse queryPurchaseHistoryAsync( - PlatformProductType productType, - ); + PlatformPurchaseHistoryResponse queryPurchaseHistoryAsync(PlatformProductType productType); /// Wraps BillingClient#queryProductDetailsAsync(QueryProductDetailsParams, ProductDetailsResponseListener). @async - PlatformProductDetailsResponse queryProductDetailsAsync( - List products, - ); + PlatformProductDetailsResponse queryProductDetailsAsync(List products); /// Wraps BillingClient#isFeatureSupported(String). bool isFeatureSupported(PlatformBillingClientFeature feature); diff --git a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_manager_test.dart b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_manager_test.dart index e8d549676bb3..20c092f0d85f 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_manager_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_manager_test.dart @@ -23,18 +23,14 @@ void main() { WidgetsFlutterBinding.ensureInitialized(); mockApi = MockInAppPurchaseApi(); when(mockApi.startConnection(any, any, any)).thenAnswer( - (_) async => PlatformBillingResult( - responseCode: PlatformBillingResponse.ok, - debugMessage: '', - ), + (_) async => + PlatformBillingResult(responseCode: PlatformBillingResponse.ok, debugMessage: ''), ); manager = BillingClientManager( - billingClientFactory: - ( - PurchasesUpdatedListener listener, - UserSelectedAlternativeBillingListener? alternativeBillingListener, - ) => - BillingClient(listener, alternativeBillingListener, api: mockApi), + billingClientFactory: ( + PurchasesUpdatedListener listener, + UserSelectedAlternativeBillingListener? alternativeBillingListener, + ) => BillingClient(listener, alternativeBillingListener, api: mockApi), ); }); @@ -47,10 +43,7 @@ void main() { final connectedCompleter = Completer(); when(mockApi.startConnection(any, any, any)).thenAnswer((_) async { connectedCompleter.complete(); - return PlatformBillingResult( - responseCode: PlatformBillingResponse.ok, - debugMessage: '', - ); + return PlatformBillingResult(responseCode: PlatformBillingResponse.ok, debugMessage: ''); }); final calledCompleter1 = Completer(); @@ -62,9 +55,7 @@ void main() { }), ); unawaited( - manager.runWithClientNonRetryable( - (BillingClient _) async => calledCompleter2.complete(), - ), + manager.runWithClientNonRetryable((BillingClient _) async => calledCompleter2.complete()), ); expect(calledCompleter1.isCompleted, equals(false)); expect(calledCompleter1.isCompleted, equals(false)); @@ -73,97 +64,71 @@ void main() { await expectLater(calledCompleter2.future, completes); }); - test( - 're-connects when client sends onBillingServiceDisconnected', - () async { - // Ensures all asynchronous connected code finishes. - await manager.runWithClientNonRetryable((_) async {}); + test('re-connects when client sends onBillingServiceDisconnected', () async { + // Ensures all asynchronous connected code finishes. + await manager.runWithClientNonRetryable((_) async {}); - manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); - verify(mockApi.startConnection(any, any, any)).called(2); - }, - ); + manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); + verify(mockApi.startConnection(any, any, any)).called(2); + }); - test( - 're-connects when host calls reconnectWithBillingChoiceMode', - () async { - // Ensures all asynchronous connected code finishes. - await manager.runWithClientNonRetryable((_) async {}); + test('re-connects when host calls reconnectWithBillingChoiceMode', () async { + // Ensures all asynchronous connected code finishes. + await manager.runWithClientNonRetryable((_) async {}); - await manager.reconnectWithBillingChoiceMode( - BillingChoiceMode.alternativeBillingOnly, - ); - // Verify that connection was ended. - verify(mockApi.endConnection()).called(1); + await manager.reconnectWithBillingChoiceMode(BillingChoiceMode.alternativeBillingOnly); + // Verify that connection was ended. + verify(mockApi.endConnection()).called(1); - clearInteractions(mockApi); + clearInteractions(mockApi); - /// Fake the disconnect that we would expect from a endConnectionCall. - manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); - // Verify that after connection ended reconnect was called. - final VerificationResult result = verify( - mockApi.startConnection(any, captureAny, any), - ); - expect( - result.captured.single, - PlatformBillingChoiceMode.alternativeBillingOnly, - ); - }, - ); + /// Fake the disconnect that we would expect from a endConnectionCall. + manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); + // Verify that after connection ended reconnect was called. + final VerificationResult result = verify(mockApi.startConnection(any, captureAny, any)); + expect(result.captured.single, PlatformBillingChoiceMode.alternativeBillingOnly); + }); - test( - 're-connects when host calls reconnectWithPendingPurchasesParams', - () async { - // Ensures all asynchronous connected code finishes. - await manager.runWithClientNonRetryable((_) async {}); + test('re-connects when host calls reconnectWithPendingPurchasesParams', () async { + // Ensures all asynchronous connected code finishes. + await manager.runWithClientNonRetryable((_) async {}); - await manager.reconnectWithPendingPurchasesParams( - const PendingPurchasesParamsWrapper(enablePrepaidPlans: true), - ); - // Verify that connection was ended. - verify(mockApi.endConnection()).called(1); + await manager.reconnectWithPendingPurchasesParams( + const PendingPurchasesParamsWrapper(enablePrepaidPlans: true), + ); + // Verify that connection was ended. + verify(mockApi.endConnection()).called(1); - clearInteractions(mockApi); + clearInteractions(mockApi); - /// Fake the disconnect that we would expect from a endConnectionCall. - manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); - // Verify that after connection ended reconnect was called. - final VerificationResult result = verify( - mockApi.startConnection(any, any, captureAny), - ); - expect( - result.captured.single, - isA().having( - (PlatformPendingPurchasesParams params) => - params.enablePrepaidPlans, - 'enablePrepaidPlans', - true, - ), - ); - }, - ); + /// Fake the disconnect that we would expect from a endConnectionCall. + manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); + // Verify that after connection ended reconnect was called. + final VerificationResult result = verify(mockApi.startConnection(any, any, captureAny)); + expect( + result.captured.single, + isA().having( + (PlatformPendingPurchasesParams params) => params.enablePrepaidPlans, + 'enablePrepaidPlans', + true, + ), + ); + }); - test( - 're-connects when operation returns BillingResponse.serviceDisconnected', - () async { - clearInteractions(mockApi); - - var timesCalled = 0; - final BillingResultWrapper result = await manager.runWithClient(( - BillingClient _, - ) async { - timesCalled++; - return BillingResultWrapper( - responseCode: timesCalled == 1 - ? BillingResponse.serviceDisconnected - : BillingResponse.ok, - ); - }); - verify(mockApi.startConnection(any, any, any)).called(1); - expect(timesCalled, equals(2)); - expect(result.responseCode, equals(BillingResponse.ok)); - }, - ); + test('re-connects when operation returns BillingResponse.serviceDisconnected', () async { + clearInteractions(mockApi); + + var timesCalled = 0; + final BillingResultWrapper result = await manager.runWithClient((BillingClient _) async { + timesCalled++; + return BillingResultWrapper( + responseCode: timesCalled == 1 ? BillingResponse.serviceDisconnected : BillingResponse.ok, + ); + }); + verify(mockApi.startConnection(any, any, any)).called(1); + expect(timesCalled, equals(2)); + expect(result.responseCode, equals(BillingResponse.ok)); + }); test('does not re-connect when disposed', () { clearInteractions(mockApi); @@ -172,33 +137,29 @@ void main() { verify(mockApi.endConnection()).called(1); }); - test( - 'Emits UserChoiceDetailsWrapper when onUserChoiceAlternativeBilling is called', - () async { - // Ensures all asynchronous connected code finishes. - await manager.runWithClientNonRetryable((_) async {}); - - const expected = UserChoiceDetailsWrapper( - originalExternalTransactionId: 'TransactionId', - externalTransactionToken: 'TransactionToken', - products: [ - UserChoiceDetailsProductWrapper( - id: 'id1', - offerToken: 'offerToken1', - productType: ProductType.inapp, - ), - UserChoiceDetailsProductWrapper( - id: 'id2', - offerToken: 'offerToken2', - productType: ProductType.inapp, - ), - ], - ); - final Future detailsFuture = - manager.userChoiceDetailsStream.first; - manager.onUserChoiceAlternativeBilling(expected); - expect(await detailsFuture, expected); - }, - ); + test('Emits UserChoiceDetailsWrapper when onUserChoiceAlternativeBilling is called', () async { + // Ensures all asynchronous connected code finishes. + await manager.runWithClientNonRetryable((_) async {}); + + const expected = UserChoiceDetailsWrapper( + originalExternalTransactionId: 'TransactionId', + externalTransactionToken: 'TransactionToken', + products: [ + UserChoiceDetailsProductWrapper( + id: 'id1', + offerToken: 'offerToken1', + productType: ProductType.inapp, + ), + UserChoiceDetailsProductWrapper( + id: 'id2', + offerToken: 'offerToken2', + productType: ProductType.inapp, + ), + ], + ); + final Future detailsFuture = manager.userChoiceDetailsStream.first; + manager.onUserChoiceAlternativeBilling(expected); + expect(await detailsFuture, expected); + }); }); } diff --git a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.dart b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.dart index 2959ea704712..7eeed5be1811 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.dart @@ -42,10 +42,8 @@ void main() { setUp(() { mockApi = MockInAppPurchaseApi(); when(mockApi.startConnection(any, any, any)).thenAnswer( - (_) async => PlatformBillingResult( - responseCode: PlatformBillingResponse.ok, - debugMessage: '', - ), + (_) async => + PlatformBillingResult(responseCode: PlatformBillingResponse.ok, debugMessage: ''), ); billingClient = BillingClient( (PurchasesResultWrapper _) {}, @@ -82,9 +80,7 @@ void main() { debugMessage: debugMessage, ); expect( - await billingClient.startConnection( - onBillingServiceDisconnected: () {}, - ), + await billingClient.startConnection(onBillingServiceDisconnected: () {}), equals(billingResult), ); }); @@ -162,9 +158,7 @@ void main() { await billingClient.startConnection( onBillingServiceDisconnected: () {}, billingChoiceMode: BillingChoiceMode.alternativeBillingOnly, - pendingPurchasesParams: const PendingPurchasesParamsWrapper( - enablePrepaidPlans: true, - ), + pendingPurchasesParams: const PendingPurchasesParamsWrapper(enablePrepaidPlans: true), ); expect( @@ -198,15 +192,11 @@ void main() { ), ); - final ProductDetailsResponseWrapper response = await billingClient - .queryProductDetails( - productList: [ - const ProductWrapper( - productId: 'invalid', - productType: ProductType.inapp, - ), - ], - ); + final ProductDetailsResponseWrapper response = await billingClient.queryProductDetails( + productList: [ + const ProductWrapper(productId: 'invalid', productType: ProductType.inapp), + ], + ); const billingResult = BillingResultWrapper( responseCode: responseCode, @@ -231,15 +221,11 @@ void main() { ), ); - final ProductDetailsResponseWrapper response = await billingClient - .queryProductDetails( - productList: [ - const ProductWrapper( - productId: 'invalid', - productType: ProductType.inapp, - ), - ], - ); + final ProductDetailsResponseWrapper response = await billingClient.queryProductDetails( + productList: [ + const ProductWrapper(productId: 'invalid', productType: ProductType.inapp), + ], + ); const billingResult = BillingResultWrapper( responseCode: responseCode, @@ -274,9 +260,7 @@ void main() { equals(expectedBillingResult), ); - final VerificationResult result = verify( - mockApi.launchBillingFlow(captureAny), - ); + final VerificationResult result = verify(mockApi.launchBillingFlow(captureAny)); final params = result.captured.single as PlatformBillingFlowParams; expect(params.product, equals(productDetails.productId)); expect(params.accountId, equals(accountId)); @@ -312,134 +296,76 @@ void main() { }, ); - test( - 'serializes and deserializes data on change subscription without proration', - () async { - const debugMessage = 'dummy message'; - const BillingResponse responseCode = BillingResponse.ok; - const expectedBillingResult = BillingResultWrapper( - responseCode: responseCode, - debugMessage: debugMessage, - ); - when( - mockApi.launchBillingFlow(any), - ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; - const accountId = 'hashedAccountId'; - const profileId = 'hashedProfileId'; - - expect( - await billingClient.launchBillingFlow( - product: productDetails.productId, - accountId: accountId, - obfuscatedProfileId: profileId, - oldProduct: dummyOldPurchase.products.first, - purchaseToken: dummyOldPurchase.purchaseToken, - ), - equals(expectedBillingResult), - ); - final VerificationResult result = verify( - mockApi.launchBillingFlow(captureAny), - ); - final params = result.captured.single as PlatformBillingFlowParams; - expect(params.product, equals(productDetails.productId)); - expect(params.accountId, equals(accountId)); - expect(params.oldProduct, equals(dummyOldPurchase.products.first)); - expect(params.purchaseToken, equals(dummyOldPurchase.purchaseToken)); - expect(params.obfuscatedProfileId, equals(profileId)); - }, - ); - - test( - 'serializes and deserializes data on change subscription with proration', - () async { - const debugMessage = 'dummy message'; - const BillingResponse responseCode = BillingResponse.ok; - const expectedBillingResult = BillingResultWrapper( - responseCode: responseCode, - debugMessage: debugMessage, - ); - when( - mockApi.launchBillingFlow(any), - ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; - const accountId = 'hashedAccountId'; - const profileId = 'hashedProfileId'; - const ReplacementMode replacementMode = - ReplacementMode.chargeProratedPrice; + test('serializes and deserializes data on change subscription without proration', () async { + const debugMessage = 'dummy message'; + const BillingResponse responseCode = BillingResponse.ok; + const expectedBillingResult = BillingResultWrapper( + responseCode: responseCode, + debugMessage: debugMessage, + ); + when( + mockApi.launchBillingFlow(any), + ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); + const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; + const accountId = 'hashedAccountId'; + const profileId = 'hashedProfileId'; - expect( - await billingClient.launchBillingFlow( - product: productDetails.productId, - accountId: accountId, - obfuscatedProfileId: profileId, - oldProduct: dummyOldPurchase.products.first, - replacementMode: replacementMode, - purchaseToken: dummyOldPurchase.purchaseToken, - ), - equals(expectedBillingResult), - ); - final VerificationResult result = verify( - mockApi.launchBillingFlow(captureAny), - ); - final params = result.captured.single as PlatformBillingFlowParams; - expect(params.product, equals(productDetails.productId)); - expect(params.accountId, equals(accountId)); - expect(params.oldProduct, equals(dummyOldPurchase.products.first)); - expect(params.obfuscatedProfileId, equals(profileId)); - expect(params.purchaseToken, equals(dummyOldPurchase.purchaseToken)); - expect( - params.replacementMode, - replacementModeFromWrapper(replacementMode), - ); - }, - ); + expect( + await billingClient.launchBillingFlow( + product: productDetails.productId, + accountId: accountId, + obfuscatedProfileId: profileId, + oldProduct: dummyOldPurchase.products.first, + purchaseToken: dummyOldPurchase.purchaseToken, + ), + equals(expectedBillingResult), + ); + final VerificationResult result = verify(mockApi.launchBillingFlow(captureAny)); + final params = result.captured.single as PlatformBillingFlowParams; + expect(params.product, equals(productDetails.productId)); + expect(params.accountId, equals(accountId)); + expect(params.oldProduct, equals(dummyOldPurchase.products.first)); + expect(params.purchaseToken, equals(dummyOldPurchase.purchaseToken)); + expect(params.obfuscatedProfileId, equals(profileId)); + }); - test( - 'serializes and deserializes data when using immediateAndChargeFullPrice', - () async { - const debugMessage = 'dummy message'; - const BillingResponse responseCode = BillingResponse.ok; - const expectedBillingResult = BillingResultWrapper( - responseCode: responseCode, - debugMessage: debugMessage, - ); - when( - mockApi.launchBillingFlow(any), - ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; - const accountId = 'hashedAccountId'; - const profileId = 'hashedProfileId'; - const ReplacementMode replacementMode = ReplacementMode.chargeFullPrice; + test('serializes and deserializes data on change subscription with proration', () async { + const debugMessage = 'dummy message'; + const BillingResponse responseCode = BillingResponse.ok; + const expectedBillingResult = BillingResultWrapper( + responseCode: responseCode, + debugMessage: debugMessage, + ); + when( + mockApi.launchBillingFlow(any), + ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); + const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; + const accountId = 'hashedAccountId'; + const profileId = 'hashedProfileId'; + const ReplacementMode replacementMode = ReplacementMode.chargeProratedPrice; - expect( - await billingClient.launchBillingFlow( - product: productDetails.productId, - accountId: accountId, - obfuscatedProfileId: profileId, - oldProduct: dummyOldPurchase.products.first, - replacementMode: replacementMode, - purchaseToken: dummyOldPurchase.purchaseToken, - ), - equals(expectedBillingResult), - ); - final VerificationResult result = verify( - mockApi.launchBillingFlow(captureAny), - ); - final params = result.captured.single as PlatformBillingFlowParams; - expect(params.product, equals(productDetails.productId)); - expect(params.accountId, equals(accountId)); - expect(params.oldProduct, equals(dummyOldPurchase.products.first)); - expect(params.obfuscatedProfileId, equals(profileId)); - expect(params.purchaseToken, equals(dummyOldPurchase.purchaseToken)); - expect( - params.replacementMode, - replacementModeFromWrapper(replacementMode), - ); - }, - ); + expect( + await billingClient.launchBillingFlow( + product: productDetails.productId, + accountId: accountId, + obfuscatedProfileId: profileId, + oldProduct: dummyOldPurchase.products.first, + replacementMode: replacementMode, + purchaseToken: dummyOldPurchase.purchaseToken, + ), + equals(expectedBillingResult), + ); + final VerificationResult result = verify(mockApi.launchBillingFlow(captureAny)); + final params = result.captured.single as PlatformBillingFlowParams; + expect(params.product, equals(productDetails.productId)); + expect(params.accountId, equals(accountId)); + expect(params.oldProduct, equals(dummyOldPurchase.products.first)); + expect(params.obfuscatedProfileId, equals(profileId)); + expect(params.purchaseToken, equals(dummyOldPurchase.purchaseToken)); + expect(params.replacementMode, replacementModeFromWrapper(replacementMode)); + }); - test('handles null accountId', () async { + test('serializes and deserializes data when using immediateAndChargeFullPrice', () async { const debugMessage = 'dummy message'; const BillingResponse responseCode = BillingResponse.ok; const expectedBillingResult = BillingResultWrapper( @@ -450,16 +376,48 @@ void main() { mockApi.launchBillingFlow(any), ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; + const accountId = 'hashedAccountId'; + const profileId = 'hashedProfileId'; + const ReplacementMode replacementMode = ReplacementMode.chargeFullPrice; expect( await billingClient.launchBillingFlow( product: productDetails.productId, + accountId: accountId, + obfuscatedProfileId: profileId, + oldProduct: dummyOldPurchase.products.first, + replacementMode: replacementMode, + purchaseToken: dummyOldPurchase.purchaseToken, ), equals(expectedBillingResult), ); - final VerificationResult result = verify( - mockApi.launchBillingFlow(captureAny), + final VerificationResult result = verify(mockApi.launchBillingFlow(captureAny)); + final params = result.captured.single as PlatformBillingFlowParams; + expect(params.product, equals(productDetails.productId)); + expect(params.accountId, equals(accountId)); + expect(params.oldProduct, equals(dummyOldPurchase.products.first)); + expect(params.obfuscatedProfileId, equals(profileId)); + expect(params.purchaseToken, equals(dummyOldPurchase.purchaseToken)); + expect(params.replacementMode, replacementModeFromWrapper(replacementMode)); + }); + + test('handles null accountId', () async { + const debugMessage = 'dummy message'; + const BillingResponse responseCode = BillingResponse.ok; + const expectedBillingResult = BillingResultWrapper( + responseCode: responseCode, + debugMessage: debugMessage, + ); + when( + mockApi.launchBillingFlow(any), + ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); + const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; + + expect( + await billingClient.launchBillingFlow(product: productDetails.productId), + equals(expectedBillingResult), ); + final VerificationResult result = verify(mockApi.launchBillingFlow(captureAny)); final params = result.captured.single as PlatformBillingFlowParams; expect(params.product, equals(productDetails.productId)); expect(params.accountId, isNull); @@ -482,15 +440,12 @@ void main() { debugMessage: debugMessage, ), purchases: expectedList - .map( - (PurchaseWrapper purchase) => convertToPigeonPurchase(purchase), - ) + .map((PurchaseWrapper purchase) => convertToPigeonPurchase(purchase)) .toList(), ), ); - final PurchasesResultWrapper response = await billingClient - .queryPurchases(ProductType.inapp); + final PurchasesResultWrapper response = await billingClient.queryPurchases(ProductType.inapp); expect(response.billingResult, equals(expectedBillingResult)); expect(response.responseCode, equals(expectedCode)); @@ -514,8 +469,7 @@ void main() { ), ); - final PurchasesResultWrapper response = await billingClient - .queryPurchases(ProductType.inapp); + final PurchasesResultWrapper response = await billingClient.queryPurchases(ProductType.inapp); expect(response.billingResult, equals(expectedBillingResult)); // The top-level response code is hard-coded to "ok", as the underlying @@ -543,8 +497,9 @@ void main() { ), ); - final PurchasesHistoryResult response = await billingClient - .queryPurchaseHistory(ProductType.inapp); + final PurchasesHistoryResult response = await billingClient.queryPurchaseHistory( + ProductType.inapp, + ); expect(response.billingResult, equals(expectedBillingResult)); expect(response.purchaseHistoryRecordList, isEmpty); @@ -564,8 +519,7 @@ void main() { mockApi.consumeAsync(token), ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - final BillingResultWrapper billingResult = await billingClient - .consumeAsync(token); + final BillingResultWrapper billingResult = await billingClient.consumeAsync(token); expect(billingResult, equals(expectedBillingResult)); }); @@ -584,8 +538,7 @@ void main() { mockApi.acknowledgePurchase(token), ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - final BillingResultWrapper billingResult = await billingClient - .acknowledgePurchase(token); + final BillingResultWrapper billingResult = await billingClient.acknowledgePurchase(token); expect(billingResult, equals(expectedBillingResult)); }); @@ -623,8 +576,7 @@ void main() { when( mockApi.getBillingConfigAsync(), ).thenAnswer((_) async => platformBillingConfigFromWrapper(expected)); - final BillingConfigWrapper result = await billingClient - .getBillingConfig(); + final BillingConfigWrapper result = await billingClient.getBillingConfig(); expect(result.countryCode, 'US'); expect(result, expected); }); @@ -642,8 +594,7 @@ void main() { debugMessage: expected.debugMessage!, ), ); - final BillingResultWrapper result = await billingClient - .isAlternativeBillingOnlyAvailable(); + final BillingResultWrapper result = await billingClient.isAlternativeBillingOnlyAvailable(); expect(result, expected); }); }); @@ -655,14 +606,11 @@ void main() { debugMessage: 'debug', externalTransactionToken: 'abc123youandme', ); - when( - mockApi.createAlternativeBillingOnlyReportingDetailsAsync(), - ).thenAnswer( - (_) async => - platformAlternativeBillingOnlyReportingDetailsFromWrapper(expected), + when(mockApi.createAlternativeBillingOnlyReportingDetailsAsync()).thenAnswer( + (_) async => platformAlternativeBillingOnlyReportingDetailsFromWrapper(expected), ); - final AlternativeBillingOnlyReportingDetailsWrapper result = - await billingClient.createAlternativeBillingOnlyReportingDetails(); + final AlternativeBillingOnlyReportingDetailsWrapper result = await billingClient + .createAlternativeBillingOnlyReportingDetails(); expect(result, equals(expected)); }); }); @@ -686,9 +634,7 @@ void main() { }); } -PlatformBillingConfigResponse platformBillingConfigFromWrapper( - BillingConfigWrapper original, -) { +PlatformBillingConfigResponse platformBillingConfigFromWrapper(BillingConfigWrapper original) { return PlatformBillingConfigResponse( billingResult: PlatformBillingResult( responseCode: billingResponseFromWrapper(original.responseCode), diff --git a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.mocks.dart b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.mocks.dart index e8d4c2c38e67..f4bdc0289ea4 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.mocks.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/billing_client_wrapper_test.mocks.dart @@ -22,18 +22,15 @@ import 'package:mockito/src/dummies.dart' as _i3; // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class -class _FakePlatformBillingResult_0 extends _i1.SmartFake - implements _i2.PlatformBillingResult { +class _FakePlatformBillingResult_0 extends _i1.SmartFake implements _i2.PlatformBillingResult { _FakePlatformBillingResult_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakePlatformBillingConfigResponse_1 extends _i1.SmartFake implements _i2.PlatformBillingConfigResponse { - _FakePlatformBillingConfigResponse_1( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakePlatformBillingConfigResponse_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformPurchasesResponse_2 extends _i1.SmartFake @@ -44,22 +41,17 @@ class _FakePlatformPurchasesResponse_2 extends _i1.SmartFake class _FakePlatformPurchaseHistoryResponse_3 extends _i1.SmartFake implements _i2.PlatformPurchaseHistoryResponse { - _FakePlatformPurchaseHistoryResponse_3( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakePlatformPurchaseHistoryResponse_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformProductDetailsResponse_4 extends _i1.SmartFake implements _i2.PlatformProductDetailsResponse { - _FakePlatformProductDetailsResponse_4( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakePlatformProductDetailsResponse_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5 - extends _i1.SmartFake +class _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5 extends _i1.SmartFake implements _i2.PlatformAlternativeBillingOnlyReportingDetailsResponse { _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5( Object parent, @@ -72,322 +64,214 @@ class _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5 /// See the documentation for Mockito's code generation for more information. class MockInAppPurchaseApi extends _i1.Mock implements _i2.InAppPurchaseApi { @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + returnValueForMissingStub: _i3.dummyValue( + this, + Invocation.getter(#pigeonVar_messageChannelSuffix), + ), + ) as String); @override - _i4.Future isReady() => - (super.noSuchMethod( - Invocation.method(#isReady, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isReady() => (super.noSuchMethod( + Invocation.method(#isReady, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override _i4.Future<_i2.PlatformBillingResult> startConnection( int? callbackHandle, _i2.PlatformBillingChoiceMode? billingMode, _i2.PlatformPendingPurchasesParams? pendingPurchasesParams, - ) => - (super.noSuchMethod( - Invocation.method(#startConnection, [ - callbackHandle, - billingMode, - pendingPurchasesParams, - ]), - returnValue: _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#startConnection, [ - callbackHandle, - billingMode, - pendingPurchasesParams, - ]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#startConnection, [ - callbackHandle, - billingMode, - pendingPurchasesParams, - ]), - ), - ), - ) - as _i4.Future<_i2.PlatformBillingResult>); + ) => (super.noSuchMethod( + Invocation.method(#startConnection, [callbackHandle, billingMode, pendingPurchasesParams]), + returnValue: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0( + this, + Invocation.method(#startConnection, [callbackHandle, billingMode, pendingPurchasesParams]), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0( + this, + Invocation.method(#startConnection, [callbackHandle, billingMode, pendingPurchasesParams]), + ), + ), + ) as _i4.Future<_i2.PlatformBillingResult>); @override - _i4.Future endConnection() => - (super.noSuchMethod( - Invocation.method(#endConnection, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future endConnection() => (super.noSuchMethod( + Invocation.method(#endConnection, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformBillingConfigResponse> getBillingConfigAsync() => - (super.noSuchMethod( - Invocation.method(#getBillingConfigAsync, []), - returnValue: _i4.Future<_i2.PlatformBillingConfigResponse>.value( - _FakePlatformBillingConfigResponse_1( - this, - Invocation.method(#getBillingConfigAsync, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformBillingConfigResponse>.value( - _FakePlatformBillingConfigResponse_1( - this, - Invocation.method(#getBillingConfigAsync, []), - ), - ), - ) - as _i4.Future<_i2.PlatformBillingConfigResponse>); + _i4.Future<_i2.PlatformBillingConfigResponse> getBillingConfigAsync() => (super.noSuchMethod( + Invocation.method(#getBillingConfigAsync, []), + returnValue: _i4.Future<_i2.PlatformBillingConfigResponse>.value( + _FakePlatformBillingConfigResponse_1(this, Invocation.method(#getBillingConfigAsync, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformBillingConfigResponse>.value( + _FakePlatformBillingConfigResponse_1(this, Invocation.method(#getBillingConfigAsync, [])), + ), + ) as _i4.Future<_i2.PlatformBillingConfigResponse>); @override - _i4.Future<_i2.PlatformBillingResult> launchBillingFlow( - _i2.PlatformBillingFlowParams? params, - ) => + _i4.Future<_i2.PlatformBillingResult> launchBillingFlow(_i2.PlatformBillingFlowParams? params) => (super.noSuchMethod( - Invocation.method(#launchBillingFlow, [params]), - returnValue: _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#launchBillingFlow, [params]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#launchBillingFlow, [params]), - ), - ), - ) - as _i4.Future<_i2.PlatformBillingResult>); + Invocation.method(#launchBillingFlow, [params]), + returnValue: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0(this, Invocation.method(#launchBillingFlow, [params])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0(this, Invocation.method(#launchBillingFlow, [params])), + ), + ) as _i4.Future<_i2.PlatformBillingResult>); @override _i4.Future<_i2.PlatformBillingResult> acknowledgePurchase( String? purchaseToken, - ) => - (super.noSuchMethod( - Invocation.method(#acknowledgePurchase, [purchaseToken]), - returnValue: _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#acknowledgePurchase, [purchaseToken]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#acknowledgePurchase, [purchaseToken]), - ), - ), - ) - as _i4.Future<_i2.PlatformBillingResult>); + ) => (super.noSuchMethod( + Invocation.method(#acknowledgePurchase, [purchaseToken]), + returnValue: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0(this, Invocation.method(#acknowledgePurchase, [purchaseToken])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0(this, Invocation.method(#acknowledgePurchase, [purchaseToken])), + ), + ) as _i4.Future<_i2.PlatformBillingResult>); @override - _i4.Future<_i2.PlatformBillingResult> consumeAsync(String? purchaseToken) => - (super.noSuchMethod( - Invocation.method(#consumeAsync, [purchaseToken]), - returnValue: _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#consumeAsync, [purchaseToken]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#consumeAsync, [purchaseToken]), - ), - ), - ) - as _i4.Future<_i2.PlatformBillingResult>); + _i4.Future<_i2.PlatformBillingResult> consumeAsync(String? purchaseToken) => (super.noSuchMethod( + Invocation.method(#consumeAsync, [purchaseToken]), + returnValue: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0(this, Invocation.method(#consumeAsync, [purchaseToken])), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0(this, Invocation.method(#consumeAsync, [purchaseToken])), + ), + ) as _i4.Future<_i2.PlatformBillingResult>); @override _i4.Future<_i2.PlatformPurchasesResponse> queryPurchasesAsync( _i2.PlatformProductType? productType, - ) => - (super.noSuchMethod( - Invocation.method(#queryPurchasesAsync, [productType]), - returnValue: _i4.Future<_i2.PlatformPurchasesResponse>.value( - _FakePlatformPurchasesResponse_2( - this, - Invocation.method(#queryPurchasesAsync, [productType]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformPurchasesResponse>.value( - _FakePlatformPurchasesResponse_2( - this, - Invocation.method(#queryPurchasesAsync, [productType]), - ), - ), - ) - as _i4.Future<_i2.PlatformPurchasesResponse>); + ) => (super.noSuchMethod( + Invocation.method(#queryPurchasesAsync, [productType]), + returnValue: _i4.Future<_i2.PlatformPurchasesResponse>.value( + _FakePlatformPurchasesResponse_2( + this, + Invocation.method(#queryPurchasesAsync, [productType]), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformPurchasesResponse>.value( + _FakePlatformPurchasesResponse_2( + this, + Invocation.method(#queryPurchasesAsync, [productType]), + ), + ), + ) as _i4.Future<_i2.PlatformPurchasesResponse>); @override _i4.Future<_i2.PlatformPurchaseHistoryResponse> queryPurchaseHistoryAsync( _i2.PlatformProductType? productType, - ) => - (super.noSuchMethod( - Invocation.method(#queryPurchaseHistoryAsync, [productType]), - returnValue: _i4.Future<_i2.PlatformPurchaseHistoryResponse>.value( - _FakePlatformPurchaseHistoryResponse_3( - this, - Invocation.method(#queryPurchaseHistoryAsync, [productType]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformPurchaseHistoryResponse>.value( - _FakePlatformPurchaseHistoryResponse_3( - this, - Invocation.method(#queryPurchaseHistoryAsync, [ - productType, - ]), - ), - ), - ) - as _i4.Future<_i2.PlatformPurchaseHistoryResponse>); + ) => (super.noSuchMethod( + Invocation.method(#queryPurchaseHistoryAsync, [productType]), + returnValue: _i4.Future<_i2.PlatformPurchaseHistoryResponse>.value( + _FakePlatformPurchaseHistoryResponse_3( + this, + Invocation.method(#queryPurchaseHistoryAsync, [productType]), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformPurchaseHistoryResponse>.value( + _FakePlatformPurchaseHistoryResponse_3( + this, + Invocation.method(#queryPurchaseHistoryAsync, [productType]), + ), + ), + ) as _i4.Future<_i2.PlatformPurchaseHistoryResponse>); @override _i4.Future<_i2.PlatformProductDetailsResponse> queryProductDetailsAsync( List<_i2.PlatformQueryProduct>? products, - ) => - (super.noSuchMethod( - Invocation.method(#queryProductDetailsAsync, [products]), - returnValue: _i4.Future<_i2.PlatformProductDetailsResponse>.value( - _FakePlatformProductDetailsResponse_4( - this, - Invocation.method(#queryProductDetailsAsync, [products]), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformProductDetailsResponse>.value( - _FakePlatformProductDetailsResponse_4( - this, - Invocation.method(#queryProductDetailsAsync, [products]), - ), - ), - ) - as _i4.Future<_i2.PlatformProductDetailsResponse>); + ) => (super.noSuchMethod( + Invocation.method(#queryProductDetailsAsync, [products]), + returnValue: _i4.Future<_i2.PlatformProductDetailsResponse>.value( + _FakePlatformProductDetailsResponse_4( + this, + Invocation.method(#queryProductDetailsAsync, [products]), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformProductDetailsResponse>.value( + _FakePlatformProductDetailsResponse_4( + this, + Invocation.method(#queryProductDetailsAsync, [products]), + ), + ), + ) as _i4.Future<_i2.PlatformProductDetailsResponse>); @override - _i4.Future isFeatureSupported( - _i2.PlatformBillingClientFeature? feature, - ) => + _i4.Future isFeatureSupported(_i2.PlatformBillingClientFeature? feature) => (super.noSuchMethod( - Invocation.method(#isFeatureSupported, [feature]), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + Invocation.method(#isFeatureSupported, [feature]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future<_i2.PlatformBillingResult> - isAlternativeBillingOnlyAvailableAsync() => + _i4.Future<_i2.PlatformBillingResult> isAlternativeBillingOnlyAvailableAsync() => (super.noSuchMethod( + Invocation.method(#isAlternativeBillingOnlyAvailableAsync, []), + returnValue: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0( + this, Invocation.method(#isAlternativeBillingOnlyAvailableAsync, []), - returnValue: _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method(#isAlternativeBillingOnlyAvailableAsync, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method( - #isAlternativeBillingOnlyAvailableAsync, - [], - ), - ), - ), - ) - as _i4.Future<_i2.PlatformBillingResult>); + ), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0( + this, + Invocation.method(#isAlternativeBillingOnlyAvailableAsync, []), + ), + ), + ) as _i4.Future<_i2.PlatformBillingResult>); @override - _i4.Future<_i2.PlatformBillingResult> - showAlternativeBillingOnlyInformationDialog() => + _i4.Future<_i2.PlatformBillingResult> showAlternativeBillingOnlyInformationDialog() => (super.noSuchMethod( + Invocation.method(#showAlternativeBillingOnlyInformationDialog, []), + returnValue: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0( + this, + Invocation.method(#showAlternativeBillingOnlyInformationDialog, []), + ), + ), + returnValueForMissingStub: _i4.Future<_i2.PlatformBillingResult>.value( + _FakePlatformBillingResult_0( + this, Invocation.method(#showAlternativeBillingOnlyInformationDialog, []), - returnValue: _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method( - #showAlternativeBillingOnlyInformationDialog, - [], - ), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.PlatformBillingResult>.value( - _FakePlatformBillingResult_0( - this, - Invocation.method( - #showAlternativeBillingOnlyInformationDialog, - [], - ), - ), - ), - ) - as _i4.Future<_i2.PlatformBillingResult>); + ), + ), + ) as _i4.Future<_i2.PlatformBillingResult>); @override _i4.Future<_i2.PlatformAlternativeBillingOnlyReportingDetailsResponse> - createAlternativeBillingOnlyReportingDetailsAsync() => - (super.noSuchMethod( - Invocation.method( - #createAlternativeBillingOnlyReportingDetailsAsync, - [], - ), - returnValue: - _i4.Future< - _i2.PlatformAlternativeBillingOnlyReportingDetailsResponse - >.value( - _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5( - this, - Invocation.method( - #createAlternativeBillingOnlyReportingDetailsAsync, - [], - ), - ), - ), - returnValueForMissingStub: - _i4.Future< - _i2.PlatformAlternativeBillingOnlyReportingDetailsResponse - >.value( - _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5( - this, - Invocation.method( - #createAlternativeBillingOnlyReportingDetailsAsync, - [], - ), - ), - ), - ) - as _i4.Future< - _i2.PlatformAlternativeBillingOnlyReportingDetailsResponse - >); + createAlternativeBillingOnlyReportingDetailsAsync() => (super.noSuchMethod( + Invocation.method(#createAlternativeBillingOnlyReportingDetailsAsync, []), + returnValue: _i4.Future<_i2.PlatformAlternativeBillingOnlyReportingDetailsResponse>.value( + _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5( + this, + Invocation.method(#createAlternativeBillingOnlyReportingDetailsAsync, []), + ), + ), + returnValueForMissingStub: + _i4.Future<_i2.PlatformAlternativeBillingOnlyReportingDetailsResponse>.value( + _FakePlatformAlternativeBillingOnlyReportingDetailsResponse_5( + this, + Invocation.method(#createAlternativeBillingOnlyReportingDetailsAsync, []), + ), + ), + ) as _i4.Future<_i2.PlatformAlternativeBillingOnlyReportingDetailsResponse>); } diff --git a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_details_wrapper_test.dart b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_details_wrapper_test.dart index a2277eaff969..841fadab007e 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_details_wrapper_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_details_wrapper_test.dart @@ -23,17 +23,13 @@ void main() { group('ProductDetailsResponseWrapper', () { test('toProductDetails() should return correct Product object', () { const ProductDetailsWrapper wrapper = dummyOneTimeProductDetails; - final GooglePlayProductDetails product = - GooglePlayProductDetails.fromProductDetails( - dummyOneTimeProductDetails, - ).first; + final GooglePlayProductDetails product = GooglePlayProductDetails.fromProductDetails( + dummyOneTimeProductDetails, + ).first; expect(product.title, wrapper.title); expect(product.description, wrapper.description); expect(product.id, wrapper.productId); - expect( - product.price, - wrapper.oneTimePurchaseOfferDetails?.formattedPrice, - ); + expect(product.price, wrapper.oneTimePurchaseOfferDetails?.formattedPrice); expect(product.productDetails, wrapper); }); }); @@ -106,10 +102,7 @@ void main() { ), ], ); - expect( - firstProductDetailsInstance == secondProductDetailsInstance, - isTrue, - ); + expect(firstProductDetailsInstance == secondProductDetailsInstance, isTrue); }); test('operator == of BillingResultWrapper works fine', () { diff --git a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart index 5ed23eb6f559..9be1dec24343 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/purchase_wrapper_test.dart @@ -53,15 +53,13 @@ const PurchaseWrapper dummyUnacknowledgedPurchase = PurchaseWrapper( void main() { group('PurchaseWrapper', () { test('fromPurchase() should return correct PurchaseDetail object', () { - final List details = - GooglePlayPurchaseDetails.fromPurchase(dummyMultipleProductsPurchase); + final List details = GooglePlayPurchaseDetails.fromPurchase( + dummyMultipleProductsPurchase, + ); expect(details[0].purchaseID, dummyMultipleProductsPurchase.orderId); expect(details[0].productID, dummyMultipleProductsPurchase.products[0]); - expect( - details[0].transactionDate, - dummyMultipleProductsPurchase.purchaseTime.toString(), - ); + expect(details[0].transactionDate, dummyMultipleProductsPurchase.purchaseTime.toString()); expect(details[0].verificationData, isNotNull); expect(details[0].verificationData.source, kIAPSource); expect( @@ -77,10 +75,7 @@ void main() { expect(details[1].purchaseID, dummyMultipleProductsPurchase.orderId); expect(details[1].productID, dummyMultipleProductsPurchase.products[1]); - expect( - details[1].transactionDate, - dummyMultipleProductsPurchase.purchaseTime.toString(), - ); + expect(details[1].transactionDate, dummyMultipleProductsPurchase.purchaseTime.toString()); expect(details[1].verificationData, isNotNull); expect(details[1].verificationData.source, kIAPSource); expect( @@ -98,24 +93,17 @@ void main() { test( 'fromPurchase() should return set pendingCompletePurchase to true for unacknowledged purchase', () { - final GooglePlayPurchaseDetails details = - GooglePlayPurchaseDetails.fromPurchase( - dummyUnacknowledgedPurchase, - ).first; + final GooglePlayPurchaseDetails details = GooglePlayPurchaseDetails.fromPurchase( + dummyUnacknowledgedPurchase, + ).first; expect(details.purchaseID, dummyPurchase.orderId); expect(details.productID, dummyPurchase.products.first); expect(details.transactionDate, dummyPurchase.purchaseTime.toString()); expect(details.verificationData, isNotNull); expect(details.verificationData.source, kIAPSource); - expect( - details.verificationData.localVerificationData, - dummyPurchase.originalJson, - ); - expect( - details.verificationData.serverVerificationData, - dummyPurchase.purchaseToken, - ); + expect(details.verificationData.localVerificationData, dummyPurchase.originalJson); + expect(details.verificationData.serverVerificationData, dummyPurchase.purchaseToken); expect(details.billingClientPurchase, dummyUnacknowledgedPurchase); expect(details.pendingCompletePurchase, true); }, diff --git a/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_addition_test.dart b/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_addition_test.dart index 48a31577cbf6..e2c70de2b73f 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_addition_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_addition_test.dart @@ -28,18 +28,14 @@ void main() { widgets.WidgetsFlutterBinding.ensureInitialized(); mockApi = MockInAppPurchaseApi(); when(mockApi.startConnection(any, any, any)).thenAnswer( - (_) async => PlatformBillingResult( - responseCode: PlatformBillingResponse.ok, - debugMessage: '', - ), + (_) async => + PlatformBillingResult(responseCode: PlatformBillingResponse.ok, debugMessage: ''), ); manager = BillingClientManager( - billingClientFactory: - ( - PurchasesUpdatedListener listener, - UserSelectedAlternativeBillingListener? alternativeBillingListener, - ) => - BillingClient(listener, alternativeBillingListener, api: mockApi), + billingClientFactory: ( + PurchasesUpdatedListener listener, + UserSelectedAlternativeBillingListener? alternativeBillingListener, + ) => BillingClient(listener, alternativeBillingListener, api: mockApi), ); iapAndroidPlatformAddition = InAppPurchaseAndroidPlatformAddition(manager); }); @@ -55,10 +51,8 @@ void main() { when( mockApi.consumeAsync(any), ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - final BillingResultWrapper billingResultWrapper = - await iapAndroidPlatformAddition.consumePurchase( - GooglePlayPurchaseDetails.fromPurchase(dummyPurchase).first, - ); + final BillingResultWrapper billingResultWrapper = await iapAndroidPlatformAddition + .consumePurchase(GooglePlayPurchaseDetails.fromPurchase(dummyPurchase).first); expect(billingResultWrapper, equals(expectedBillingResult)); }); @@ -76,8 +70,7 @@ void main() { when( mockApi.getBillingConfigAsync(), ).thenAnswer((_) async => platformBillingConfigFromWrapper(expected)); - final String countryCode = await iapAndroidPlatformAddition - .getCountryCode(); + final String countryCode = await iapAndroidPlatformAddition.getCountryCode(); expect(countryCode, equals(expectedCountryCode)); }); @@ -86,35 +79,24 @@ void main() { group('setBillingChoice', () { test('setAlternativeBillingOnlyState', () async { clearInteractions(mockApi); - await iapAndroidPlatformAddition.setBillingChoice( - BillingChoiceMode.alternativeBillingOnly, - ); + await iapAndroidPlatformAddition.setBillingChoice(BillingChoiceMode.alternativeBillingOnly); // Fake the disconnect that we would expect from a endConnectionCall. manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); // Verify that after connection ended reconnect was called. - final VerificationResult result = verify( - mockApi.startConnection(any, captureAny, any), - ); + final VerificationResult result = verify(mockApi.startConnection(any, captureAny, any)); expect(result.callCount, equals(2)); - expect( - result.captured.last, - PlatformBillingChoiceMode.alternativeBillingOnly, - ); + expect(result.captured.last, PlatformBillingChoiceMode.alternativeBillingOnly); }); test('setPlayBillingState', () async { clearInteractions(mockApi); - await iapAndroidPlatformAddition.setBillingChoice( - BillingChoiceMode.playBillingOnly, - ); + await iapAndroidPlatformAddition.setBillingChoice(BillingChoiceMode.playBillingOnly); // Fake the disconnect that we would expect from a endConnectionCall. manager.client.hostCallbackHandler.onBillingServiceDisconnected(0); // Verify that after connection ended reconnect was called. - final VerificationResult result = verify( - mockApi.startConnection(any, captureAny, any), - ); + final VerificationResult result = verify(mockApi.startConnection(any, captureAny, any)); expect(result.callCount, equals(2)); expect(result.captured.last, PlatformBillingChoiceMode.playBillingOnly); }); @@ -172,16 +154,14 @@ void main() { responseCode: responseCode, debugMessage: debugMessage, ), - purchases: [ - convertToPigeonPurchase(dummyPurchase), - ], + purchases: [convertToPigeonPurchase(dummyPurchase)], ), ); // Since queryPastPurchases makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead // of 1. - final QueryPurchaseDetailsResponse response = - await iapAndroidPlatformAddition.queryPastPurchases(); + final QueryPurchaseDetailsResponse response = await iapAndroidPlatformAddition + .queryPastPurchases(); expect(response.error, isNull); expect(response.pastPurchases.first.purchaseID, dummyPurchase.orderId); }); @@ -194,15 +174,13 @@ void main() { details: {'info': 'error_info'}, ); }); - final QueryPurchaseDetailsResponse response = - await iapAndroidPlatformAddition.queryPastPurchases(); + final QueryPurchaseDetailsResponse response = await iapAndroidPlatformAddition + .queryPastPurchases(); expect(response.pastPurchases, isEmpty); expect(response.error, isNotNull); expect(response.error!.code, 'error_code'); expect(response.error!.message, 'error_message'); - expect(response.error!.details, { - 'info': 'error_info', - }); + expect(response.error!.details, {'info': 'error_info'}); }); }); }); @@ -212,8 +190,9 @@ void main() { when( mockApi.isFeatureSupported(PlatformBillingClientFeature.subscriptions), ).thenAnswer((_) async => false); - final bool isSupported = await iapAndroidPlatformAddition - .isFeatureSupported(BillingClientFeature.subscriptions); + final bool isSupported = await iapAndroidPlatformAddition.isFeatureSupported( + BillingClientFeature.subscriptions, + ); expect(isSupported, isFalse); }); @@ -221,8 +200,9 @@ void main() { when( mockApi.isFeatureSupported(PlatformBillingClientFeature.subscriptions), ).thenAnswer((_) async => true); - final bool isSupported = await iapAndroidPlatformAddition - .isFeatureSupported(BillingClientFeature.subscriptions); + final bool isSupported = await iapAndroidPlatformAddition.isFeatureSupported( + BillingClientFeature.subscriptions, + ); expect(isSupported, isTrue); }); }); @@ -248,10 +228,7 @@ void main() { ], ); manager.onUserChoiceAlternativeBilling(expected); - expect( - await futureDetails, - Translator.convertToUserChoiceDetails(expected), - ); + expect(await futureDetails, Translator.convertToUserChoiceDetails(expected)); }); }); } diff --git a/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_test.dart b/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_test.dart index c29edc9e861e..88f0cd601f02 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/in_app_purchase_android_platform_test.dart @@ -20,32 +20,31 @@ import 'billing_client_wrappers/product_details_wrapper_test.dart'; import 'billing_client_wrappers/purchase_wrapper_test.dart'; import 'test_conversion_utils.dart'; -const ProductDetailsWrapper dummySubscriptionProductDetails = - ProductDetailsWrapper( - description: 'description', - name: 'name', - productId: 'productId', - productType: ProductType.subs, - title: 'title', - subscriptionOfferDetails: [ - SubscriptionOfferDetailsWrapper( - basePlanId: 'basePlanId', - offerTags: ['offerTags'], - offerId: 'offerId', - offerIdToken: 'offerToken', - pricingPhases: [ - PricingPhaseWrapper( - billingCycleCount: 4, - billingPeriod: 'billingPeriod', - formattedPrice: r'$100', - priceAmountMicros: 100000000, - priceCurrencyCode: 'USD', - recurrenceMode: RecurrenceMode.finiteRecurring, - ), - ], +const ProductDetailsWrapper dummySubscriptionProductDetails = ProductDetailsWrapper( + description: 'description', + name: 'name', + productId: 'productId', + productType: ProductType.subs, + title: 'title', + subscriptionOfferDetails: [ + SubscriptionOfferDetailsWrapper( + basePlanId: 'basePlanId', + offerTags: ['offerTags'], + offerId: 'offerId', + offerIdToken: 'offerToken', + pricingPhases: [ + PricingPhaseWrapper( + billingCycleCount: 4, + billingPeriod: 'billingPeriod', + formattedPrice: r'$100', + priceAmountMicros: 100000000, + priceCurrencyCode: 'USD', + recurrenceMode: RecurrenceMode.finiteRecurring, ), ], - ); + ), + ], +); void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -58,23 +57,15 @@ void main() { mockApi = MockInAppPurchaseApi(); when(mockApi.startConnection(any, any, any)).thenAnswer( - (_) async => PlatformBillingResult( - responseCode: PlatformBillingResponse.ok, - debugMessage: '', - ), + (_) async => + PlatformBillingResult(responseCode: PlatformBillingResponse.ok, debugMessage: ''), ); iapAndroidPlatform = InAppPurchaseAndroidPlatform( manager: BillingClientManager( - billingClientFactory: - ( - PurchasesUpdatedListener listener, - UserSelectedAlternativeBillingListener? - alternativeBillingListener, - ) => BillingClient( - listener, - alternativeBillingListener, - api: mockApi, - ), + billingClientFactory: ( + PurchasesUpdatedListener listener, + UserSelectedAlternativeBillingListener? alternativeBillingListener, + ) => BillingClient(listener, alternativeBillingListener, api: mockApi), ), ); InAppPurchasePlatform.instance = iapAndroidPlatform; @@ -92,38 +83,31 @@ void main() { verify(mockApi.startConnection(any, any, any)).called(2); }); - test( - 're-connects when operation returns BillingResponse.clientDisconnected', - () async { + test('re-connects when operation returns BillingResponse.clientDisconnected', () async { + when(mockApi.acknowledgePurchase(any)).thenAnswer( + (_) async => PlatformBillingResult( + responseCode: PlatformBillingResponse.serviceDisconnected, + debugMessage: 'disconnected', + ), + ); + when(mockApi.startConnection(any, any, any)).thenAnswer((_) async { + // Change the acknowledgePurchase response to success for the next call. when(mockApi.acknowledgePurchase(any)).thenAnswer( (_) async => PlatformBillingResult( - responseCode: PlatformBillingResponse.serviceDisconnected, + responseCode: PlatformBillingResponse.ok, debugMessage: 'disconnected', ), ); - when(mockApi.startConnection(any, any, any)).thenAnswer((_) async { - // Change the acknowledgePurchase response to success for the next call. - when(mockApi.acknowledgePurchase(any)).thenAnswer( - (_) async => PlatformBillingResult( - responseCode: PlatformBillingResponse.ok, - debugMessage: 'disconnected', - ), - ); - return PlatformBillingResult( - responseCode: PlatformBillingResponse.ok, - debugMessage: '', - ); - }); - final PurchaseDetails purchase = GooglePlayPurchaseDetails.fromPurchase( - dummyUnacknowledgedPurchase, - ).first; - final BillingResultWrapper result = await iapAndroidPlatform - .completePurchase(purchase); - verify(mockApi.acknowledgePurchase(any)).called(2); - verify(mockApi.startConnection(any, any, any)).called(2); - expect(result.responseCode, equals(BillingResponse.ok)); - }, - ); + return PlatformBillingResult(responseCode: PlatformBillingResponse.ok, debugMessage: ''); + }); + final PurchaseDetails purchase = GooglePlayPurchaseDetails.fromPurchase( + dummyUnacknowledgedPurchase, + ).first; + final BillingResultWrapper result = await iapAndroidPlatform.completePurchase(purchase); + verify(mockApi.acknowledgePurchase(any)).called(2); + verify(mockApi.startConnection(any, any, any)).called(2); + expect(result.responseCode, equals(BillingResponse.ok)); + }); }); group('isAvailable', () { @@ -152,8 +136,9 @@ void main() { ), ); - final ProductDetailsResponse response = await iapAndroidPlatform - .queryProductDetails({''}); + final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails({ + '', + }); expect(response.productDetails, isEmpty); }); @@ -173,16 +158,11 @@ void main() { ); // Since queryProductDetails makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead // of 1. - final ProductDetailsResponse response = await iapAndroidPlatform - .queryProductDetails({'valid'}); - expect( - response.productDetails.first.title, - dummyOneTimeProductDetails.title, - ); - expect( - response.productDetails.first.description, - dummyOneTimeProductDetails.description, - ); + final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails({ + 'valid', + }); + expect(response.productDetails.first.title, dummyOneTimeProductDetails.title); + expect(response.productDetails.first.description, dummyOneTimeProductDetails.description); expect( response.productDetails.first.price, dummyOneTimeProductDetails.oneTimePurchaseOfferDetails?.formattedPrice, @@ -206,36 +186,33 @@ void main() { ); // Since queryProductDetails makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead // of 1. - final ProductDetailsResponse response = await iapAndroidPlatform - .queryProductDetails({'invalid'}); + final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails({ + 'invalid', + }); expect(response.notFoundIDs.first, 'invalid'); }); - test( - 'should have error stored in the response when platform exception is thrown', - () async { - when(mockApi.queryProductDetailsAsync(any)).thenAnswer((_) async { - throw PlatformException( - code: 'error_code', - message: 'error_message', - details: {'info': 'error_info'}, - ); - }); - // Since queryProductDetails makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead - // of 1. - final ProductDetailsResponse response = await iapAndroidPlatform - .queryProductDetails({'invalid'}); - expect(response.notFoundIDs, ['invalid']); - expect(response.productDetails, isEmpty); - expect(response.error, isNotNull); - expect(response.error!.source, kIAPSource); - expect(response.error!.code, 'error_code'); - expect(response.error!.message, 'error_message'); - expect(response.error!.details, { - 'info': 'error_info', - }); - }, - ); + test('should have error stored in the response when platform exception is thrown', () async { + when(mockApi.queryProductDetailsAsync(any)).thenAnswer((_) async { + throw PlatformException( + code: 'error_code', + message: 'error_message', + details: {'info': 'error_info'}, + ); + }); + // Since queryProductDetails makes 2 platform method calls (one for each ProductType), the result will contain 2 dummyWrapper instead + // of 1. + final ProductDetailsResponse response = await iapAndroidPlatform.queryProductDetails({ + 'invalid', + }); + expect(response.notFoundIDs, ['invalid']); + expect(response.productDetails, isEmpty); + expect(response.error, isNotNull); + expect(response.error!.source, kIAPSource); + expect(response.error!.code, 'error_code'); + expect(response.error!.message, 'error_message'); + expect(response.error!.details, {'info': 'error_info'}); + }); }); group('restorePurchases', () { @@ -253,24 +230,17 @@ void main() { throwsA( isA() .having((PlatformException e) => e.code, 'code', 'error_code') - .having( - (PlatformException e) => e.message, - 'message', - 'error_message', - ) - .having( - (PlatformException e) => e.details, - 'details', - {'info': 'error_info'}, - ), + .having((PlatformException e) => e.message, 'message', 'error_message') + .having((PlatformException e) => e.details, 'details', { + 'info': 'error_info', + }), ), ); }); test('returns ProductDetailsResponseWrapper', () async { final completer = Completer>(); - final Stream> stream = - iapAndroidPlatform.purchaseStream; + final Stream> stream = iapAndroidPlatform.purchaseStream; late StreamSubscription> subscription; subscription = stream.listen((List purchaseDetailsList) { @@ -305,14 +275,8 @@ void main() { expect(purchase.productID, dummyPurchase.products.first); expect(purchase.purchaseID, dummyPurchase.orderId); - expect( - purchase.verificationData.localVerificationData, - dummyPurchase.originalJson, - ); - expect( - purchase.verificationData.serverVerificationData, - dummyPurchase.purchaseToken, - ); + expect(purchase.verificationData.localVerificationData, dummyPurchase.originalJson); + expect(purchase.verificationData.serverVerificationData, dummyPurchase.purchaseToken); expect(purchase.verificationData.source, kIAPSource); expect(purchase.transactionDate, dummyPurchase.purchaseTime.toString()); expect(purchase.billingClientPurchase, dummyPurchase); @@ -322,75 +286,66 @@ void main() { }); group('make payment', () { - test( - 'buy non consumable subscribe offer, serializes and deserializes data', - () async { - const ProductDetailsWrapper productDetails = - dummySubscriptionProductDetails; - const accountId = 'hashedAccountId'; - const debugMessage = 'dummy message'; - const BillingResponse sentCode = BillingResponse.ok; - const expectedBillingResult = BillingResultWrapper( - responseCode: sentCode, - debugMessage: debugMessage, - ); - - when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { - // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [ - PlatformPurchase( - orderId: 'orderID1', - products: [productDetails.productId], - isAutoRenewing: false, - packageName: 'package', - purchaseTime: 1231231231, - purchaseToken: 'token', - signature: 'sign', - originalJson: 'json', - developerPayload: 'dummy payload', - isAcknowledged: true, - purchaseState: PlatformPurchaseState.purchased, - quantity: 1, - ), - ], - ), - ); + test('buy non consumable subscribe offer, serializes and deserializes data', () async { + const ProductDetailsWrapper productDetails = dummySubscriptionProductDetails; + const accountId = 'hashedAccountId'; + const debugMessage = 'dummy message'; + const BillingResponse sentCode = BillingResponse.ok; + const expectedBillingResult = BillingResultWrapper( + responseCode: sentCode, + debugMessage: debugMessage, + ); - return convertToPigeonResult(expectedBillingResult); - }); - final completer = Completer(); - PurchaseDetails purchaseDetails; - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; - late StreamSubscription> subscription; - subscription = purchaseStream.listen((List details) { - purchaseDetails = details.first; - completer.complete(purchaseDetails); - subscription.cancel(); - }, onDone: () {}); - final purchaseParam = GooglePlayPurchaseParam( - offerToken: - productDetails.subscriptionOfferDetails?.first.offerIdToken, - productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, - ).first, - applicationUserName: accountId, - ); - final bool launchResult = await iapAndroidPlatform.buyNonConsumable( - purchaseParam: purchaseParam, + when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { + // Mock java update purchase callback. + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [ + PlatformPurchase( + orderId: 'orderID1', + products: [productDetails.productId], + isAutoRenewing: false, + packageName: 'package', + purchaseTime: 1231231231, + purchaseToken: 'token', + signature: 'sign', + originalJson: 'json', + developerPayload: 'dummy payload', + isAcknowledged: true, + purchaseState: PlatformPurchaseState.purchased, + quantity: 1, + ), + ], + ), ); - final PurchaseDetails result = await completer.future; - expect(launchResult, isTrue); - expect(result.purchaseID, 'orderID1'); - expect(result.status, PurchaseStatus.purchased); - expect(result.productID, productDetails.productId); - }, - ); + return convertToPigeonResult(expectedBillingResult); + }); + final completer = Completer(); + PurchaseDetails purchaseDetails; + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; + late StreamSubscription> subscription; + subscription = purchaseStream.listen((List details) { + purchaseDetails = details.first; + completer.complete(purchaseDetails); + subscription.cancel(); + }, onDone: () {}); + final purchaseParam = GooglePlayPurchaseParam( + offerToken: productDetails.subscriptionOfferDetails?.first.offerIdToken, + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, + applicationUserName: accountId, + ); + final bool launchResult = await iapAndroidPlatform.buyNonConsumable( + purchaseParam: purchaseParam, + ); + + final PurchaseDetails result = await completer.future; + expect(launchResult, isTrue); + expect(result.purchaseID, 'orderID1'); + expect(result.status, PurchaseStatus.purchased); + expect(result.productID, productDetails.productId); + }); test('buy non consumable, serializes and deserializes data', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; @@ -404,35 +359,33 @@ void main() { when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [ - PlatformPurchase( - orderId: 'orderID1', - products: [productDetails.productId], - isAutoRenewing: false, - packageName: 'package', - purchaseTime: 1231231231, - purchaseToken: 'token', - signature: 'sign', - originalJson: 'json', - developerPayload: 'dummy payload', - isAcknowledged: true, - purchaseState: PlatformPurchaseState.purchased, - quantity: 1, - ), - ], + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [ + PlatformPurchase( + orderId: 'orderID1', + products: [productDetails.productId], + isAutoRenewing: false, + packageName: 'package', + purchaseTime: 1231231231, + purchaseToken: 'token', + signature: 'sign', + originalJson: 'json', + developerPayload: 'dummy payload', + isAcknowledged: true, + purchaseState: PlatformPurchaseState.purchased, + quantity: 1, ), - ); + ], + ), + ); return convertToPigeonResult(expectedBillingResult); }); final completer = Completer(); PurchaseDetails purchaseDetails; - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription> subscription; subscription = purchaseStream.listen((List details) { purchaseDetails = details.first; @@ -440,9 +393,7 @@ void main() { subscription.cancel(); }, onDone: () {}); final purchaseParam = GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, - ).first, + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId, ); final bool launchResult = await iapAndroidPlatform.buyNonConsumable( @@ -468,20 +419,18 @@ void main() { when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [], - ), - ); + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [], + ), + ); return convertToPigeonResult(expectedBillingResult); }); final completer = Completer(); PurchaseDetails purchaseDetails; - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription> subscription; subscription = purchaseStream.listen((List details) { purchaseDetails = details.first; @@ -489,9 +438,7 @@ void main() { subscription.cancel(); }, onDone: () {}); final purchaseParam = GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, - ).first, + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId, ); await iapAndroidPlatform.buyNonConsumable(purchaseParam: purchaseParam); @@ -503,144 +450,126 @@ void main() { expect(result.purchaseID, isEmpty); }); - test( - 'buy consumable with auto consume, serializes and deserializes data', - () async { - const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; - const accountId = 'hashedAccountId'; - const debugMessage = 'dummy message'; - const BillingResponse sentCode = BillingResponse.ok; - const expectedBillingResult = BillingResultWrapper( - responseCode: sentCode, - debugMessage: debugMessage, + test('buy consumable with auto consume, serializes and deserializes data', () async { + const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; + const accountId = 'hashedAccountId'; + const debugMessage = 'dummy message'; + const BillingResponse sentCode = BillingResponse.ok; + const expectedBillingResult = BillingResultWrapper( + responseCode: sentCode, + debugMessage: debugMessage, + ); + + when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { + // Mock java update purchase callback. + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [ + PlatformPurchase( + orderId: 'orderID1', + products: [productDetails.productId], + isAutoRenewing: false, + packageName: 'package', + purchaseTime: 1231231231, + purchaseToken: 'token', + signature: 'sign', + originalJson: 'json', + developerPayload: 'dummy payload', + isAcknowledged: true, + purchaseState: PlatformPurchaseState.purchased, + quantity: 1, + ), + ], + ), ); - when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { - // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [ - PlatformPurchase( - orderId: 'orderID1', - products: [productDetails.productId], - isAutoRenewing: false, - packageName: 'package', - purchaseTime: 1231231231, - purchaseToken: 'token', - signature: 'sign', - originalJson: 'json', - developerPayload: 'dummy payload', - isAcknowledged: true, - purchaseState: PlatformPurchaseState.purchased, - quantity: 1, - ), - ], - ), - ); + return convertToPigeonResult(expectedBillingResult); + }); + final consumeCompleter = Completer(); + // adding call back for consume purchase + const BillingResponse expectedCode = BillingResponse.ok; + const expectedBillingResultForConsume = BillingResultWrapper( + responseCode: expectedCode, + debugMessage: debugMessage, + ); + when(mockApi.consumeAsync(any)).thenAnswer((Invocation invocation) async { + final purchaseToken = invocation.positionalArguments.first as String; + consumeCompleter.complete(purchaseToken); + return convertToPigeonResult(expectedBillingResultForConsume); + }); - return convertToPigeonResult(expectedBillingResult); - }); - final consumeCompleter = Completer(); - // adding call back for consume purchase - const BillingResponse expectedCode = BillingResponse.ok; - const expectedBillingResultForConsume = BillingResultWrapper( - responseCode: expectedCode, - debugMessage: debugMessage, - ); - when(mockApi.consumeAsync(any)).thenAnswer(( - Invocation invocation, - ) async { - final purchaseToken = invocation.positionalArguments.first as String; - consumeCompleter.complete(purchaseToken); - return convertToPigeonResult(expectedBillingResultForConsume); - }); + final completer = Completer(); + PurchaseDetails purchaseDetails; + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; + late StreamSubscription> subscription; + subscription = purchaseStream.listen((List details) { + purchaseDetails = details.first; + completer.complete(purchaseDetails); + subscription.cancel(); + }, onDone: () {}); + final purchaseParam = GooglePlayPurchaseParam( + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, + applicationUserName: accountId, + ); + final bool launchResult = await iapAndroidPlatform.buyConsumable( + purchaseParam: purchaseParam, + ); - final completer = Completer(); - PurchaseDetails purchaseDetails; - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; - late StreamSubscription> subscription; - subscription = purchaseStream.listen((List details) { - purchaseDetails = details.first; - completer.complete(purchaseDetails); - subscription.cancel(); - }, onDone: () {}); - final purchaseParam = GooglePlayPurchaseParam( + // Verify that the result has succeeded + final result = await completer.future as GooglePlayPurchaseDetails; + expect(launchResult, isTrue); + expect(result.billingClientPurchase, isNotNull); + expect(result.billingClientPurchase.purchaseToken, await consumeCompleter.future); + expect(result.status, PurchaseStatus.purchased); + expect(result.error, isNull); + }); + + test('buyNonConsumable propagates failures to launch the billing flow', () async { + const debugMessage = 'dummy message'; + const BillingResponse sentCode = BillingResponse.error; + const expectedBillingResult = BillingResultWrapper( + responseCode: sentCode, + debugMessage: debugMessage, + ); + when( + mockApi.launchBillingFlow(any), + ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); + + final bool result = await iapAndroidPlatform.buyNonConsumable( + purchaseParam: GooglePlayPurchaseParam( productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, + dummyOneTimeProductDetails, ).first, - applicationUserName: accountId, - ); - final bool launchResult = await iapAndroidPlatform.buyConsumable( - purchaseParam: purchaseParam, - ); - - // Verify that the result has succeeded - final result = await completer.future as GooglePlayPurchaseDetails; - expect(launchResult, isTrue); - expect(result.billingClientPurchase, isNotNull); - expect( - result.billingClientPurchase.purchaseToken, - await consumeCompleter.future, - ); - expect(result.status, PurchaseStatus.purchased); - expect(result.error, isNull); - }, - ); + ), + ); - test( - 'buyNonConsumable propagates failures to launch the billing flow', - () async { - const debugMessage = 'dummy message'; - const BillingResponse sentCode = BillingResponse.error; - const expectedBillingResult = BillingResultWrapper( - responseCode: sentCode, - debugMessage: debugMessage, - ); - when( - mockApi.launchBillingFlow(any), - ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - - final bool result = await iapAndroidPlatform.buyNonConsumable( - purchaseParam: GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - dummyOneTimeProductDetails, - ).first, - ), - ); + // Verify that the failure has been converted and returned + expect(result, isFalse); + }); - // Verify that the failure has been converted and returned - expect(result, isFalse); - }, - ); + test('buyConsumable propagates failures to launch the billing flow', () async { + const debugMessage = 'dummy message'; + const BillingResponse sentCode = BillingResponse.developerError; + const expectedBillingResult = BillingResultWrapper( + responseCode: sentCode, + debugMessage: debugMessage, + ); + when( + mockApi.launchBillingFlow(any), + ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - test( - 'buyConsumable propagates failures to launch the billing flow', - () async { - const debugMessage = 'dummy message'; - const BillingResponse sentCode = BillingResponse.developerError; - const expectedBillingResult = BillingResultWrapper( - responseCode: sentCode, - debugMessage: debugMessage, - ); - when( - mockApi.launchBillingFlow(any), - ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - - final bool result = await iapAndroidPlatform.buyConsumable( - purchaseParam: GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - dummyOneTimeProductDetails, - ).first, - ), - ); + final bool result = await iapAndroidPlatform.buyConsumable( + purchaseParam: GooglePlayPurchaseParam( + productDetails: GooglePlayProductDetails.fromProductDetails( + dummyOneTimeProductDetails, + ).first, + ), + ); - // Verify that the failure has been converted and returned - expect(result, isFalse); - }, - ); + // Verify that the failure has been converted and returned + expect(result, isFalse); + }); test('adds consumption failures to PurchaseDetails objects', () async { const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; @@ -653,28 +582,27 @@ void main() { ); when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [ - PlatformPurchase( - orderId: 'orderID1', - products: [productDetails.productId], - isAutoRenewing: false, - packageName: 'package', - purchaseTime: 1231231231, - purchaseToken: 'token', - signature: 'sign', - originalJson: 'json', - developerPayload: 'dummy payload', - isAcknowledged: true, - purchaseState: PlatformPurchaseState.purchased, - quantity: 1, - ), - ], + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [ + PlatformPurchase( + orderId: 'orderID1', + products: [productDetails.productId], + isAutoRenewing: false, + packageName: 'package', + purchaseTime: 1231231231, + purchaseToken: 'token', + signature: 'sign', + originalJson: 'json', + developerPayload: 'dummy payload', + isAcknowledged: true, + purchaseState: PlatformPurchaseState.purchased, + quantity: 1, ), - ); + ], + ), + ); return convertToPigeonResult(expectedBillingResult); }); @@ -693,8 +621,7 @@ void main() { final completer = Completer(); PurchaseDetails purchaseDetails; - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription> subscription; subscription = purchaseStream.listen((List details) { purchaseDetails = details.first; @@ -702,9 +629,7 @@ void main() { subscription.cancel(); }, onDone: () {}); final purchaseParam = GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, - ).first, + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId, ); await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); @@ -712,89 +637,74 @@ void main() { // Verify that the result has an error for the failed consumption final result = await completer.future as GooglePlayPurchaseDetails; expect(result.billingClientPurchase, isNotNull); - expect( - result.billingClientPurchase.purchaseToken, - await consumeCompleter.future, - ); + expect(result.billingClientPurchase.purchaseToken, await consumeCompleter.future); expect(result.status, PurchaseStatus.error); expect(result.error, isNotNull); expect(result.error!.code, kConsumptionFailedErrorCode); }); - test( - 'buy consumable without auto consume, consume api should not receive calls', - () async { - const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; - const accountId = 'hashedAccountId'; - const debugMessage = 'dummy message'; - const BillingResponse sentCode = BillingResponse.developerError; - const expectedBillingResult = BillingResultWrapper( - responseCode: sentCode, - debugMessage: debugMessage, - ); - - when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { - // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [ - PlatformPurchase( - orderId: 'orderID1', - products: [productDetails.productId], - isAutoRenewing: false, - packageName: 'package', - purchaseTime: 1231231231, - purchaseToken: 'token', - signature: 'sign', - originalJson: 'json', - developerPayload: 'dummy payload', - isAcknowledged: true, - purchaseState: PlatformPurchaseState.purchased, - quantity: 1, - ), - ], - ), - ); + test('buy consumable without auto consume, consume api should not receive calls', () async { + const ProductDetailsWrapper productDetails = dummyOneTimeProductDetails; + const accountId = 'hashedAccountId'; + const debugMessage = 'dummy message'; + const BillingResponse sentCode = BillingResponse.developerError; + const expectedBillingResult = BillingResultWrapper( + responseCode: sentCode, + debugMessage: debugMessage, + ); - return convertToPigeonResult(expectedBillingResult); - }); - final consumeCompleter = Completer(); - // adding call back for consume purchase - const BillingResponse expectedCode = BillingResponse.ok; - const expectedBillingResultForConsume = BillingResultWrapper( - responseCode: expectedCode, - debugMessage: debugMessage, + when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { + // Mock java update purchase callback. + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [ + PlatformPurchase( + orderId: 'orderID1', + products: [productDetails.productId], + isAutoRenewing: false, + packageName: 'package', + purchaseTime: 1231231231, + purchaseToken: 'token', + signature: 'sign', + originalJson: 'json', + developerPayload: 'dummy payload', + isAcknowledged: true, + purchaseState: PlatformPurchaseState.purchased, + quantity: 1, + ), + ], + ), ); - when(mockApi.consumeAsync(any)).thenAnswer(( - Invocation invocation, - ) async { - final purchaseToken = invocation.positionalArguments.first as String; - consumeCompleter.complete(purchaseToken); - return convertToPigeonResult(expectedBillingResultForConsume); - }); - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; - late StreamSubscription> subscription; - subscription = purchaseStream.listen((_) { - consumeCompleter.complete(null); - subscription.cancel(); - }, onDone: () {}); - final purchaseParam = GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, - ).first, - applicationUserName: accountId, - ); - await iapAndroidPlatform.buyConsumable( - purchaseParam: purchaseParam, - autoConsume: false, - ); - expect(null, await consumeCompleter.future); - }, - ); + return convertToPigeonResult(expectedBillingResult); + }); + final consumeCompleter = Completer(); + // adding call back for consume purchase + const BillingResponse expectedCode = BillingResponse.ok; + const expectedBillingResultForConsume = BillingResultWrapper( + responseCode: expectedCode, + debugMessage: debugMessage, + ); + when(mockApi.consumeAsync(any)).thenAnswer((Invocation invocation) async { + final purchaseToken = invocation.positionalArguments.first as String; + consumeCompleter.complete(purchaseToken); + return convertToPigeonResult(expectedBillingResultForConsume); + }); + + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; + late StreamSubscription> subscription; + subscription = purchaseStream.listen((_) { + consumeCompleter.complete(null); + subscription.cancel(); + }, onDone: () {}); + final purchaseParam = GooglePlayPurchaseParam( + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, + applicationUserName: accountId, + ); + await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam, autoConsume: false); + expect(null, await consumeCompleter.future); + }); test( 'should get canceled purchase status when response code is BillingResponse.userCanceled', @@ -809,28 +719,27 @@ void main() { ); when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [ - PlatformPurchase( - orderId: 'orderID1', - products: [productDetails.productId], - isAutoRenewing: false, - packageName: 'package', - purchaseTime: 1231231231, - purchaseToken: 'token', - signature: 'sign', - originalJson: 'json', - developerPayload: 'dummy payload', - isAcknowledged: true, - purchaseState: PlatformPurchaseState.purchased, - quantity: 1, - ), - ], + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [ + PlatformPurchase( + orderId: 'orderID1', + products: [productDetails.productId], + isAutoRenewing: false, + packageName: 'package', + purchaseTime: 1231231231, + purchaseToken: 'token', + signature: 'sign', + originalJson: 'json', + developerPayload: 'dummy payload', + isAcknowledged: true, + purchaseState: PlatformPurchaseState.purchased, + quantity: 1, ), - ); + ], + ), + ); return convertToPigeonResult(expectedBillingResult); }); @@ -841,9 +750,7 @@ void main() { responseCode: expectedCode, debugMessage: debugMessage, ); - when(mockApi.consumeAsync(any)).thenAnswer(( - Invocation invocation, - ) async { + when(mockApi.consumeAsync(any)).thenAnswer((Invocation invocation) async { final purchaseToken = invocation.positionalArguments.first as String; consumeCompleter.complete(purchaseToken); return convertToPigeonResult(expectedBillingResultForConsume); @@ -851,8 +758,7 @@ void main() { final completer = Completer(); PurchaseDetails purchaseDetails; - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription> subscription; subscription = purchaseStream.listen((List details) { purchaseDetails = details.first; @@ -860,9 +766,7 @@ void main() { subscription.cancel(); }, onDone: () {}); final purchaseParam = GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, - ).first, + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId, ); await iapAndroidPlatform.buyConsumable(purchaseParam: purchaseParam); @@ -886,21 +790,19 @@ void main() { ); when(mockApi.launchBillingFlow(any)).thenAnswer((_) async { // Mock java update purchase callback. - iapAndroidPlatform.billingClientManager.client.hostCallbackHandler - .onPurchasesUpdated( - PlatformPurchasesResponse( - billingResult: convertToPigeonResult(expectedBillingResult), - purchases: [], - ), - ); + iapAndroidPlatform.billingClientManager.client.hostCallbackHandler.onPurchasesUpdated( + PlatformPurchasesResponse( + billingResult: convertToPigeonResult(expectedBillingResult), + purchases: [], + ), + ); return convertToPigeonResult(expectedBillingResult); }); final completer = Completer(); PurchaseDetails purchaseDetails; - final Stream> purchaseStream = - iapAndroidPlatform.purchaseStream; + final Stream> purchaseStream = iapAndroidPlatform.purchaseStream; late StreamSubscription> subscription; subscription = purchaseStream.listen((List details) { purchaseDetails = details.first; @@ -908,9 +810,7 @@ void main() { subscription.cancel(); }, onDone: () {}); final purchaseParam = GooglePlayPurchaseParam( - productDetails: GooglePlayProductDetails.fromProductDetails( - productDetails, - ).first, + productDetails: GooglePlayProductDetails.fromProductDetails(productDetails).first, applicationUserName: accountId, changeSubscriptionParam: ChangeSubscriptionParam( oldPurchaseDetails: GooglePlayPurchaseDetails.fromPurchase( @@ -938,15 +838,15 @@ void main() { when( mockApi.acknowledgePurchase(any), ).thenAnswer((_) async => convertToPigeonResult(expectedBillingResult)); - final PurchaseDetails purchaseDetails = - GooglePlayPurchaseDetails.fromPurchase( - dummyUnacknowledgedPurchase, - ).first; + final PurchaseDetails purchaseDetails = GooglePlayPurchaseDetails.fromPurchase( + dummyUnacknowledgedPurchase, + ).first; final completer = Completer(); purchaseDetails.status = PurchaseStatus.purchased; if (purchaseDetails.pendingCompletePurchase) { - final BillingResultWrapper billingResultWrapper = - await iapAndroidPlatform.completePurchase(purchaseDetails); + final BillingResultWrapper billingResultWrapper = await iapAndroidPlatform.completePurchase( + purchaseDetails, + ); expect(billingResultWrapper, equals(expectedBillingResult)); completer.complete(billingResultWrapper); } @@ -970,10 +870,7 @@ void main() { expect(countryCode, equals(expectedCountryCode)); // Ensure deprecated code keeps working until removed. - expect( - await iapAndroidPlatform.getCountryCode(), - equals(expectedCountryCode), - ); + expect(await iapAndroidPlatform.getCountryCode(), equals(expectedCountryCode)); }); }); } diff --git a/packages/in_app_purchase/in_app_purchase_android/test/test_conversion_utils.dart b/packages/in_app_purchase/in_app_purchase_android/test/test_conversion_utils.dart index b80ab3574580..856cb897d5eb 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/test_conversion_utils.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/test_conversion_utils.dart @@ -34,9 +34,7 @@ PlatformPurchase convertToPigeonPurchase(PurchaseWrapper purchase) { purchaseState: _convertToPigeonPurchaseState(purchase.purchaseState), // For some reason quantity is not in PurchaseWrapper. quantity: 99, - accountIdentifiers: - purchase.obfuscatedAccountId != null || - purchase.obfuscatedProfileId != null + accountIdentifiers: purchase.obfuscatedAccountId != null || purchase.obfuscatedProfileId != null ? PlatformAccountIdentifiers( obfuscatedAccountId: purchase.obfuscatedAccountId, obfuscatedProfileId: purchase.obfuscatedProfileId, @@ -46,9 +44,7 @@ PlatformPurchase convertToPigeonPurchase(PurchaseWrapper purchase) { } /// Creates a [PlatformProductDetails] from the corresponding [ProductDetailsWrapper]. -PlatformProductDetails convertToPigeonProductDetails( - ProductDetailsWrapper details, -) { +PlatformProductDetails convertToPigeonProductDetails(ProductDetailsWrapper details) { return PlatformProductDetails( description: details.description, name: details.name, @@ -72,9 +68,7 @@ PlatformSubscriptionOfferDetails convertToPigeonSubscriptionOfferDetails( offerId: details.offerId, offerToken: details.offerIdToken, offerTags: details.offerTags, - pricingPhases: details.pricingPhases - .map(convertToPigeonPricingPhase) - .toList(), + pricingPhases: details.pricingPhases.map(convertToPigeonPricingPhase).toList(), ); } @@ -89,8 +83,7 @@ PlatformPricingPhase convertToPigeonPricingPhase(PricingPhaseWrapper phase) { ); } -PlatformOneTimePurchaseOfferDetails? -_convertToPigeonOneTimePurchaseOfferDetails( +PlatformOneTimePurchaseOfferDetails? _convertToPigeonOneTimePurchaseOfferDetails( OneTimePurchaseOfferDetailsWrapper? offer, ) { if (offer == null) { @@ -104,9 +97,7 @@ _convertToPigeonOneTimePurchaseOfferDetails( } /// Creates a [PlatformPurchaseState] from the Dart wrapper equivalent. -PlatformPurchaseState _convertToPigeonPurchaseState( - PurchaseStateWrapper state, -) { +PlatformPurchaseState _convertToPigeonPurchaseState(PurchaseStateWrapper state) { return switch (state) { PurchaseStateWrapper.unspecified_state => PlatformPurchaseState.unspecified, PurchaseStateWrapper.purchased => PlatformPurchaseState.purchased, @@ -117,8 +108,7 @@ PlatformPurchaseState _convertToPigeonPurchaseState( PlatformRecurrenceMode _convertToPigeonRecurrenceMode(RecurrenceMode mode) { return switch (mode) { RecurrenceMode.finiteRecurring => PlatformRecurrenceMode.finiteRecurring, - RecurrenceMode.infiniteRecurring => - PlatformRecurrenceMode.infiniteRecurring, + RecurrenceMode.infiniteRecurring => PlatformRecurrenceMode.infiniteRecurring, RecurrenceMode.nonRecurring => PlatformRecurrenceMode.nonRecurring, }; } diff --git a/packages/in_app_purchase/in_app_purchase_android/test/types/translator_test.dart b/packages/in_app_purchase/in_app_purchase_android/test/types/translator_test.dart index 0d96b456d560..50a10d13a2c6 100644 --- a/packages/in_app_purchase/in_app_purchase_android/test/types/translator_test.dart +++ b/packages/in_app_purchase/in_app_purchase_android/test/types/translator_test.dart @@ -10,14 +10,8 @@ import 'package:test/test.dart'; void main() { group('Translator ', () { test('convertToPlayProductType', () { - expect( - Translator.convertToPlayProductType(ProductType.inapp), - GooglePlayProductType.inapp, - ); - expect( - Translator.convertToPlayProductType(ProductType.subs), - GooglePlayProductType.subs, - ); + expect(Translator.convertToPlayProductType(ProductType.inapp), GooglePlayProductType.inapp); + expect(Translator.convertToPlayProductType(ProductType.subs), GooglePlayProductType.subs); expect(GooglePlayProductType.values.length, ProductType.values.length); }); @@ -52,17 +46,13 @@ void main() { const expected = GooglePlayUserChoiceDetails( originalExternalTransactionId: 'originalExternalTransactionId', externalTransactionToken: 'externalTransactionToken', - products: [ - expectedProduct1, - expectedProduct2, - ], + products: [expectedProduct1, expectedProduct2], ); expect( Translator.convertToUserChoiceDetails( UserChoiceDetailsWrapper( - originalExternalTransactionId: - expected.originalExternalTransactionId, + originalExternalTransactionId: expected.originalExternalTransactionId, externalTransactionToken: expected.externalTransactionToken, products: [ UserChoiceDetailsProductWrapper( diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_error.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_error.dart index f57aef1135db..e4e191cbe88d 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_error.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_error.dart @@ -11,12 +11,7 @@ /// * [PurchaseDetails] for error happened in purchase. class IAPError { /// Creates a new IAP error object with the given error details. - IAPError({ - required this.source, - required this.code, - required this.message, - this.details, - }); + IAPError({required this.source, required this.code, required this.message, this.details}); /// Which source is the error on. final String source; diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_exception.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_exception.dart index f938008cce6a..b225b71eb3ef 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_exception.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/errors/in_app_purchase_exception.dart @@ -7,11 +7,7 @@ class InAppPurchaseException implements Exception { /// Creates a [InAppPurchaseException] with the specified source and error /// [code] and optional [message]. - InAppPurchaseException({ - required this.source, - required this.code, - this.message, - }); + InAppPurchaseException({required this.source, required this.code, this.message}); /// An error code. final String code; diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform.dart index eac2a80e214f..2474e490bb7d 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/in_app_purchase_platform.dart @@ -62,8 +62,7 @@ abstract class InAppPurchasePlatform extends PlatformInterface { throw UnimplementedError('purchaseStream has not been implemented.'); /// Returns `true` if the payment platform is ready and available. - Future isAvailable() => - throw UnimplementedError('isAvailable() has not been implemented.'); + Future isAvailable() => throw UnimplementedError('isAvailable() has not been implemented.'); /// Query product details for the given set of IDs. /// @@ -71,9 +70,7 @@ abstract class InAppPurchasePlatform extends PlatformInterface { /// Connect](https://appstoreconnect.apple.com/) for iOS and [Google Play /// Console](https://play.google.com/) for Android. Future queryProductDetails(Set identifiers) => - throw UnimplementedError( - 'queryProductDetails() had not been implemented.', - ); + throw UnimplementedError('queryProductDetails() had not been implemented.'); /// Buy a non consumable product or subscription. /// @@ -147,10 +144,8 @@ abstract class InAppPurchasePlatform extends PlatformInterface { /// /// Calling this method for non consumable items will cause unwanted /// behaviors! - Future buyConsumable({ - required PurchaseParam purchaseParam, - bool autoConsume = true, - }) => throw UnimplementedError('buyConsumable() has not been implemented.'); + Future buyConsumable({required PurchaseParam purchaseParam, bool autoConsume = true}) => + throw UnimplementedError('buyConsumable() has not been implemented.'); /// Mark that purchased content has been delivered to the user. /// diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details_response.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details_response.dart index 4376a0cb1354..1f8d15da61d6 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details_response.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/product_details_response.dart @@ -10,11 +10,7 @@ import 'product_details.dart'; /// A list of [ProductDetails] can be obtained from the this response. class ProductDetailsResponse { /// Creates a new [ProductDetailsResponse] with the provided response details. - ProductDetailsResponse({ - required this.productDetails, - required this.notFoundIDs, - this.error, - }); + ProductDetailsResponse({required this.productDetails, required this.notFoundIDs, this.error}); /// Each [ProductDetails] uniquely matches one valid identifier in [identifiers] of [InAppPurchasePlatform.queryProductDetails]. final List productDetails; diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart index 350fd26d1b88..03efd97f6845 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/test/in_app_purchase_platform_test.dart @@ -32,105 +32,65 @@ void main() { InAppPurchasePlatform.instance = MockInAppPurchasePlatform(); }); - test( - 'Default implementation of purchaseStream should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.purchaseStream, - throwsUnimplementedError, - ); - }, - ); - - test( - 'Default implementation of isAvailable should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.isAvailable(), - throwsUnimplementedError, - ); - }, - ); - - test( - 'Default implementation of queryProductDetails should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.queryProductDetails({''}), - throwsUnimplementedError, - ); - }, - ); - - test( - 'Default implementation of buyNonConsumable should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.buyNonConsumable( - purchaseParam: MockPurchaseParam(), - ), - throwsUnimplementedError, - ); - }, - ); - - test( - 'Default implementation of buyConsumable should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.buyConsumable( - purchaseParam: MockPurchaseParam(), - ), - throwsUnimplementedError, - ); - }, - ); - - test( - 'Default implementation of completePurchase should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.completePurchase(MockPurchaseDetails()), - throwsUnimplementedError, - ); - }, - ); - - test( - 'Default implementation of restorePurchases should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.restorePurchases(), - throwsUnimplementedError, - ); - }, - ); - - test( - 'Default implementation of countryCode should throw unimplemented error', - () { - final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); - - expect( - () => inAppPurchasePlatform.countryCode(), - throwsUnimplementedError, - ); - }, - ); + test('Default implementation of purchaseStream should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect(() => inAppPurchasePlatform.purchaseStream, throwsUnimplementedError); + }); + + test('Default implementation of isAvailable should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect(() => inAppPurchasePlatform.isAvailable(), throwsUnimplementedError); + }); + + test('Default implementation of queryProductDetails should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect( + () => inAppPurchasePlatform.queryProductDetails({''}), + throwsUnimplementedError, + ); + }); + + test('Default implementation of buyNonConsumable should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect( + () => inAppPurchasePlatform.buyNonConsumable(purchaseParam: MockPurchaseParam()), + throwsUnimplementedError, + ); + }); + + test('Default implementation of buyConsumable should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect( + () => inAppPurchasePlatform.buyConsumable(purchaseParam: MockPurchaseParam()), + throwsUnimplementedError, + ); + }); + + test('Default implementation of completePurchase should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect( + () => inAppPurchasePlatform.completePurchase(MockPurchaseDetails()), + throwsUnimplementedError, + ); + }); + + test('Default implementation of restorePurchases should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect(() => inAppPurchasePlatform.restorePurchases(), throwsUnimplementedError); + }); + + test('Default implementation of countryCode should throw unimplemented error', () { + final inAppPurchasePlatform = ExtendsInAppPurchasePlatform(); + + expect(() => inAppPurchasePlatform.countryCode(), throwsUnimplementedError); + }); }); group('$InAppPurchasePlatformAddition', () { @@ -143,13 +103,11 @@ void main() { }); test('Can be implemented.', () { - InAppPurchasePlatformAddition.instance = - ImplementsInAppPurchasePlatformAddition(); + InAppPurchasePlatformAddition.instance = ImplementsInAppPurchasePlatformAddition(); }); test('InAppPurchasePlatformAddition Can be extended', () { - InAppPurchasePlatformAddition.instance = - ExtendsInAppPurchasePlatformAddition(); + InAppPurchasePlatformAddition.instance = ExtendsInAppPurchasePlatformAddition(); }); test('Can not be a `InAppPurchasePlatform`', () { @@ -163,15 +121,13 @@ void main() { test('Provider can provide', () { ImplementsInAppPurchasePlatformAdditionProvider.register(); final provider = ImplementsInAppPurchasePlatformAdditionProvider(); - final InAppPurchasePlatformAddition? addition = provider - .getPlatformAddition(); + final InAppPurchasePlatformAddition? addition = provider.getPlatformAddition(); expect(addition.runtimeType, ExtendsInAppPurchasePlatformAddition); }); test('Provider can provide `null`', () { final provider = ImplementsInAppPurchasePlatformAdditionProvider(); - final InAppPurchasePlatformAddition? addition = provider - .getPlatformAddition(); + final InAppPurchasePlatformAddition? addition = provider.getPlatformAddition(); expect(addition, isNull); }); }); @@ -194,20 +150,17 @@ class MockPurchaseParam extends Mock implements PurchaseParam {} class MockPurchaseDetails extends Mock implements PurchaseDetails {} -class ImplementsInAppPurchasePlatformAddition - implements InAppPurchasePlatformAddition { +class ImplementsInAppPurchasePlatformAddition implements InAppPurchasePlatformAddition { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } -class ExtendsInAppPurchasePlatformAddition - extends InAppPurchasePlatformAddition {} +class ExtendsInAppPurchasePlatformAddition extends InAppPurchasePlatformAddition {} class ImplementsInAppPurchasePlatformAdditionProvider implements InAppPurchasePlatformAdditionProvider { static void register() { - InAppPurchasePlatformAddition.instance = - ExtendsInAppPurchasePlatformAddition(); + InAppPurchasePlatformAddition.instance = ExtendsInAppPurchasePlatformAddition(); } @override @@ -216,6 +169,5 @@ class ImplementsInAppPurchasePlatformAdditionProvider } } -class ExtendsInAppPurchasePlatformAdditionIsPlatformInterface - extends InAppPurchasePlatform +class ExtendsInAppPurchasePlatformAdditionIsPlatformInterface extends InAppPurchasePlatform implements ExtendsInAppPurchasePlatformAddition {} diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/errors/in_app_purchase_exception_test.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/errors/in_app_purchase_exception_test.dart index 1b376a8422fa..dad777b2d5d6 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/errors/in_app_purchase_exception_test.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/errors/in_app_purchase_exception_test.dart @@ -17,9 +17,6 @@ void main() { final actual = exception.toString(); // Assert - expect( - actual, - 'InAppPurchaseException(error_code, dummy message, dummy_source)', - ); + expect(actual, 'InAppPurchaseException(error_code, dummy message, dummy_source)'); }); } diff --git a/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/types/product_details_test.dart b/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/types/product_details_test.dart index 86a7d25b66b1..eb7e9d7a3439 100644 --- a/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/types/product_details_test.dart +++ b/packages/in_app_purchase/in_app_purchase_platform_interface/test/src/types/product_details_test.dart @@ -7,27 +7,24 @@ import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_inte void main() { group('Constructor Tests', () { - test( - 'fromSkProduct should correctly parse data from a SKProductWrapper instance.', - () { - final productDetails = ProductDetails( - id: 'id', - title: 'title', - description: 'description', - price: '13.37', - currencyCode: 'USD', - currencySymbol: r'$', - rawPrice: 13.37, - ); + test('fromSkProduct should correctly parse data from a SKProductWrapper instance.', () { + final productDetails = ProductDetails( + id: 'id', + title: 'title', + description: 'description', + price: '13.37', + currencyCode: 'USD', + currencySymbol: r'$', + rawPrice: 13.37, + ); - expect(productDetails.id, 'id'); - expect(productDetails.title, 'title'); - expect(productDetails.description, 'description'); - expect(productDetails.rawPrice, 13.37); - expect(productDetails.currencyCode, 'USD'); - expect(productDetails.currencySymbol, r'$'); - }, - ); + expect(productDetails.id, 'id'); + expect(productDetails.title, 'title'); + expect(productDetails.description, 'description'); + expect(productDetails.rawPrice, 13.37); + expect(productDetails.currencyCode, 'USD'); + expect(productDetails.currencySymbol, r'$'); + }); }); group('PurchaseStatus Tests', () { diff --git a/packages/in_app_purchase/in_app_purchase_storekit/example/integration_test/in_app_purchase_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/example/integration_test/in_app_purchase_test.dart index b9f5b08cee57..aba38bf2c8da 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/example/integration_test/in_app_purchase_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/example/integration_test/in_app_purchase_test.dart @@ -10,12 +10,9 @@ import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - testWidgets('Can create InAppPurchaseStoreKit instance', ( - WidgetTester tester, - ) async { + testWidgets('Can create InAppPurchaseStoreKit instance', (WidgetTester tester) async { InAppPurchaseStoreKitPlatform.registerPlatform(); - final InAppPurchasePlatform androidPlatform = - InAppPurchasePlatform.instance; + final InAppPurchasePlatform androidPlatform = InAppPurchasePlatform.instance; expect(androidPlatform, isNotNull); }); } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/example/lib/consumable_store.dart b/packages/in_app_purchase/in_app_purchase_storekit/example/lib/consumable_store.dart index fb53bebdfe78..33718a44028a 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/example/lib/consumable_store.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/example/lib/consumable_store.dart @@ -32,8 +32,7 @@ class ConsumableStore { /// Returns the list of consumables from the store. static Future> load() async { - return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ?? - []; + return (await SharedPreferences.getInstance()).getStringList(_kPrefKey) ?? []; } static Future _doSave(String id) async { diff --git a/packages/in_app_purchase/in_app_purchase_storekit/example/lib/main.dart b/packages/in_app_purchase/in_app_purchase_storekit/example/lib/main.dart index 3a0e5a449ac9..8f8c012dccaa 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/example/lib/main.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/example/lib/main.dart @@ -41,8 +41,7 @@ class _MyAppState extends State<_MyApp> { final InAppPurchaseStoreKitPlatform _iapStoreKitPlatform = InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform; final InAppPurchaseStoreKitPlatformAddition _iapStoreKitPlatformAddition = - InAppPurchasePlatformAddition.instance! - as InAppPurchaseStoreKitPlatformAddition; + InAppPurchasePlatformAddition.instance! as InAppPurchaseStoreKitPlatformAddition; late StreamSubscription> _subscription; List _notFoundIds = []; List _products = []; @@ -55,8 +54,7 @@ class _MyAppState extends State<_MyApp> { @override void initState() { - final Stream> purchaseUpdated = - _iapStoreKitPlatform.purchaseStream; + final Stream> purchaseUpdated = _iapStoreKitPlatform.purchaseStream; _subscription = purchaseUpdated.listen( (List purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); @@ -91,8 +89,8 @@ class _MyAppState extends State<_MyApp> { return; } - final ProductDetailsResponse productDetailResponse = - await _iapStoreKitPlatform.queryProductDetails(_kProductIds.toSet()); + final ProductDetailsResponse productDetailResponse = await _iapStoreKitPlatform + .queryProductDetails(_kProductIds.toSet()); if (productDetailResponse.error != null) { setState(() { _queryProductError = productDetailResponse.error!.message; @@ -159,10 +157,7 @@ class _MyAppState extends State<_MyApp> { stack.add( const Stack( children: [ - Opacity( - opacity: 0.3, - child: ModalBarrier(dismissible: false, color: Colors.grey), - ), + Opacity(opacity: 0.3, child: ModalBarrier(dismissible: false, color: Colors.grey)), Center(child: CircularProgressIndicator()), ], ), @@ -184,13 +179,9 @@ class _MyAppState extends State<_MyApp> { final Widget storeHeader = ListTile( leading: Icon( _isAvailable ? Icons.check : Icons.block, - color: _isAvailable - ? Colors.green - : ThemeData.light().colorScheme.error, - ), - title: Text( - 'The store is ${_isAvailable ? 'available' : 'unavailable'}.', + color: _isAvailable ? Colors.green : ThemeData.light().colorScheme.error, ), + title: Text('The store is ${_isAvailable ? 'available' : 'unavailable'}.'), ); final children = [storeHeader]; @@ -214,26 +205,17 @@ class _MyAppState extends State<_MyApp> { Widget _buildProductList() { if (_loading) { return const Card( - child: ListTile( - leading: CircularProgressIndicator(), - title: Text('Fetching products...'), - ), + child: ListTile(leading: CircularProgressIndicator(), title: Text('Fetching products...')), ); } if (!_isAvailable) { return const Card(); } const productHeader = ListTile( - title: Text( - 'Products for Sale', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), - ), + title: Text('Products for Sale', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ); const promoHeader = ListTile( - title: Text( - 'Products in promo', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), - ), + title: Text('Products in promo', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), ); final productList = []; if (_notFoundIds.isNotEmpty) { @@ -280,17 +262,11 @@ class _MyAppState extends State<_MyApp> { foregroundColor: Colors.white, ), onPressed: () { - final purchaseParam = PurchaseParam( - productDetails: productDetails, - ); + final purchaseParam = PurchaseParam(productDetails: productDetails); if (productDetails.id == _kConsumableId) { - _iapStoreKitPlatform.buyConsumable( - purchaseParam: purchaseParam, - ); + _iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); } else { - _iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + _iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); } }, child: Text(productDetails.price), @@ -301,11 +277,7 @@ class _MyAppState extends State<_MyApp> { return Column( children: [ - Card( - child: Column( - children: [productHeader, const Divider(), ...productList], - ), - ), + Card(child: Column(children: [productHeader, const Divider(), ...productList])), Card( child: Column( children: [ @@ -313,19 +285,15 @@ class _MyAppState extends State<_MyApp> { const Divider(), FutureBuilder>( future: _buildPromoList(), - builder: - ( - BuildContext context, - AsyncSnapshot> snapshot, - ) { - final List? data = snapshot.data; - - if (data != null) { - return Column(children: data); - } - - return const SizedBox.shrink(); - }, + builder: (BuildContext context, AsyncSnapshot> snapshot) { + final List? data = snapshot.data; + + if (data != null) { + return Column(children: data); + } + + return const SizedBox.shrink(); + }, ), ], ), @@ -338,15 +306,16 @@ class _MyAppState extends State<_MyApp> { final promoList = []; for (final ProductDetails detail in _products) { if (detail is AppStoreProduct2Details) { - final SK2SubscriptionInfo? subscription = - detail.sk2Product.subscription; + final SK2SubscriptionInfo? subscription = detail.sk2Product.subscription; final List offers = subscription?.promotionalOffers ?? []; for (final offer in offers) { if (offer.type == SK2SubscriptionOfferType.winBack) { - final bool eligible = await _iapStoreKitPlatform - .isWinBackOfferEligible(detail.id, offer.id ?? ''); + final bool eligible = await _iapStoreKitPlatform.isWinBackOfferEligible( + detail.id, + offer.id ?? '', + ); if (!eligible) { continue; @@ -360,10 +329,7 @@ class _MyAppState extends State<_MyApp> { return promoList; } - ListTile _buildPromoTile( - ProductDetails productDetails, - SK2SubscriptionOffer offer, - ) { + ListTile _buildPromoTile(ProductDetails productDetails, SK2SubscriptionOffer offer) { return ListTile( title: Text('${productDetails.title} [${offer.type.name}]'), subtitle: Text(productDetails.description), @@ -503,9 +469,7 @@ class _MyAppState extends State<_MyApp> { purchaseDetailsList.forEach(_handleReportedPurchaseState); } - Future _handleReportedPurchaseState( - PurchaseDetails purchaseDetails, - ) async { + Future _handleReportedPurchaseState(PurchaseDetails purchaseDetails) async { if (purchaseDetails.status == PurchaseStatus.pending) { showPendingUI(); } else { diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/channel.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/channel.dart index ae589f40e738..84959ca2c07b 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/channel.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/channel.dart @@ -5,9 +5,7 @@ import 'package:flutter/services.dart'; /// Method channel for the plugin's platform<-->Dart calls. -const MethodChannel channel = MethodChannel( - 'plugins.flutter.io/in_app_purchase', -); +const MethodChannel channel = MethodChannel('plugins.flutter.io/in_app_purchase'); /// Method channel used to deliver the payment queue delegate system calls to /// Dart. diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_apis.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_apis.dart index 0895118a20fe..424c27814c51 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_apis.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_apis.dart @@ -25,10 +25,7 @@ InAppPurchase2API hostApi2 = InAppPurchase2API(); /// Set up pigeon API. @visibleForTesting -void setInAppPurchaseHostApis({ - InAppPurchaseAPI? api, - InAppPurchase2API? api2, -}) { +void setInAppPurchaseHostApis({InAppPurchaseAPI? api, InAppPurchase2API? api2}) { if (api != null) { hostApi = api; } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform.dart index 05c0262027e3..3d438922adc8 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform.dart @@ -51,15 +51,13 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { /// Callback handler for transaction status changes for StoreKit2 transactions @visibleForTesting - static SK2TransactionObserverWrapper get sk2TransactionObserver => - _sk2transactionObserver; + static SK2TransactionObserverWrapper get sk2TransactionObserver => _sk2transactionObserver; /// Registers this class as the default instance of [InAppPurchasePlatform]. static void registerPlatform() { // Register the [InAppPurchaseStoreKitPlatformAddition] containing // StoreKit-specific functionality. - InAppPurchasePlatformAddition.instance = - InAppPurchaseStoreKitPlatformAddition(); + InAppPurchasePlatformAddition.instance = InAppPurchaseStoreKitPlatformAddition(); // Register the platform-specific implementation of the idiomatic // InAppPurchase API. @@ -68,11 +66,10 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { _skPaymentQueueWrapper = SKPaymentQueueWrapper(); if (_useStoreKit2) { - final updateController2 = - StreamController>.broadcast( - onListen: () => SK2Transaction.startListeningToTransactions(), - onCancel: () => SK2Transaction.stopListeningToTransactions(), - ); + final updateController2 = StreamController>.broadcast( + onListen: () => SK2Transaction.startListeningToTransactions(), + onCancel: () => SK2Transaction.stopListeningToTransactions(), + ); _sk2transactionObserver = SK2TransactionObserverWrapper( transactionsCreatedController: updateController2, ); @@ -80,13 +77,10 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { } else { // Create a purchaseUpdatedController and notify the native side when to // start of stop sending updates. - final updateController = - StreamController>.broadcast( - onListen: () => - _skPaymentQueueWrapper.startObservingTransactionQueue(), - onCancel: () => - _skPaymentQueueWrapper.stopObservingTransactionQueue(), - ); + final updateController = StreamController>.broadcast( + onListen: () => _skPaymentQueueWrapper.startObservingTransactionQueue(), + onCancel: () => _skPaymentQueueWrapper.stopObservingTransactionQueue(), + ); _sk1transactionObserver = _TransactionObserver(updateController); _skPaymentQueueWrapper.setTransactionObserver(observer); } @@ -165,39 +159,27 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { appAccountToken: purchaseParam.applicationUserName, quantity: purchaseParam.quantity, winBackOfferId: purchaseParam.winBackOfferId, - promotionalOffer: _convertPromotionalOffer( - purchaseParam.promotionalOffer, - ), + promotionalOffer: _convertPromotionalOffer(purchaseParam.promotionalOffer), ); } else { options = SK2ProductPurchaseOptions( - quantity: purchaseParam is AppStorePurchaseParam - ? purchaseParam.quantity - : 1, + quantity: purchaseParam is AppStorePurchaseParam ? purchaseParam.quantity : 1, appAccountToken: purchaseParam.applicationUserName, ); } - await SK2Product.purchase( - purchaseParam.productDetails.id, - options: options, - ); + await SK2Product.purchase(purchaseParam.productDetails.id, options: options); return true; } await _skPaymentQueueWrapper.addPayment( SKPaymentWrapper( productIdentifier: purchaseParam.productDetails.id, - quantity: purchaseParam is AppStorePurchaseParam - ? purchaseParam.quantity - : 1, + quantity: purchaseParam is AppStorePurchaseParam ? purchaseParam.quantity : 1, applicationUsername: purchaseParam.applicationUserName, simulatesAskToBuyInSandbox: - purchaseParam is AppStorePurchaseParam && - purchaseParam.simulatesAskToBuyInSandbox, - paymentDiscount: purchaseParam is AppStorePurchaseParam - ? purchaseParam.discount - : null, + purchaseParam is AppStorePurchaseParam && purchaseParam.simulatesAskToBuyInSandbox, + paymentDiscount: purchaseParam is AppStorePurchaseParam ? purchaseParam.discount : null, ), ); @@ -223,10 +205,7 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { } @override - Future buyConsumable({ - required PurchaseParam purchaseParam, - bool autoConsume = true, - }) { + Future buyConsumable({required PurchaseParam purchaseParam, bool autoConsume = true}) { assert(autoConsume, 'On iOS, we should always auto consume'); return buyNonConsumable(purchaseParam: purchaseParam); } @@ -257,9 +236,7 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { queue: _skPaymentQueueWrapper, applicationUserName: applicationUserName, ) - .whenComplete( - () => _sk1transactionObserver.cleanUpRestoredTransactions(), - ); + .whenComplete(() => _sk1transactionObserver.cleanUpRestoredTransactions()); } /// Query the product detail list. @@ -268,9 +245,7 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { /// To get detailed Store Kit product list, use [SkProductResponseWrapper.startProductRequest] /// to get the [SKProductResponseWrapper]. @override - Future queryProductDetails( - Set identifiers, - ) async { + Future queryProductDetails(Set identifiers) async { if (_useStoreKit2) { var products = []; Set invalidProductIdentifiers; @@ -289,8 +264,7 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { List productDetails; productDetails = products .map( - (SK2Product productWrapper) => - AppStoreProduct2Details.fromSK2Product(productWrapper), + (SK2Product productWrapper) => AppStoreProduct2Details.fromSK2Product(productWrapper), ) .toList(); final response = ProductDetailsResponse( @@ -322,8 +296,7 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { var productDetails = []; productDetails = response.products .map( - (SKProductWrapper productWrapper) => - AppStoreProductDetails.fromSKProduct(productWrapper), + (SKProductWrapper productWrapper) => AppStoreProductDetails.fromSKProduct(productWrapper), ) .toList(); List invalidIdentifiers = response.invalidProductIdentifiers; @@ -393,9 +366,7 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { ); } - final bool eligibility = await SK2Product.isIntroductoryOfferEligible( - productId, - ); + final bool eligibility = await SK2Product.isIntroductoryOfferEligible(productId); return eligibility; } @@ -419,20 +390,13 @@ class InAppPurchaseStoreKitPlatform extends InAppPurchasePlatform { ); } - final bool eligibility = await SK2Product.isWinBackOfferEligible( - productId, - offerId, - ); + final bool eligibility = await SK2Product.isWinBackOfferEligible(productId, offerId); return eligibility; } } -enum _TransactionRestoreState { - notRunning, - waitingForTransactions, - receivedTransaction, -} +enum _TransactionRestoreState { notRunning, waitingForTransactions, receivedTransaction } class _TransactionObserver implements SKTransactionObserverWrapper { _TransactionObserver(this.purchaseUpdatedController); @@ -441,8 +405,7 @@ class _TransactionObserver implements SKTransactionObserverWrapper { Completer? _restoreCompleter; late String _receiptData; - _TransactionRestoreState _transactionRestoreState = - _TransactionRestoreState.notRunning; + _TransactionRestoreState _transactionRestoreState = _TransactionRestoreState.notRunning; Future restoreTransactions({ required SKPaymentQueueWrapper queue, @@ -459,16 +422,12 @@ class _TransactionObserver implements SKTransactionObserverWrapper { } @override - void updatedTransactions({ - required List transactions, - }) { + void updatedTransactions({required List transactions}) { _handleTransationUpdates(transactions); } @override - void removedTransactions({ - required List transactions, - }) {} + void removedTransactions({required List transactions}) {} /// Triggered when there is an error while restoring transactions. @override @@ -484,8 +443,7 @@ class _TransactionObserver implements SKTransactionObserverWrapper { // If no restored transactions were received during the restore session // emit an empty list of purchase details to inform listeners that the // restore session finished without any results. - if (_transactionRestoreState == - _TransactionRestoreState.waitingForTransactions) { + if (_transactionRestoreState == _TransactionRestoreState.waitingForTransactions) { purchaseUpdatedController.add([]); } @@ -510,15 +468,11 @@ class _TransactionObserver implements SKTransactionObserverWrapper { return _receiptData; } - Future _handleTransationUpdates( - List transactions, - ) async { - if (_transactionRestoreState == - _TransactionRestoreState.waitingForTransactions && + Future _handleTransationUpdates(List transactions) async { + if (_transactionRestoreState == _TransactionRestoreState.waitingForTransactions && transactions.any( (SKPaymentTransactionWrapper transaction) => - transaction.transactionState == - SKPaymentTransactionStateWrapper.restored, + transaction.transactionState == SKPaymentTransactionStateWrapper.restored, )) { _transactionRestoreState = _TransactionRestoreState.receivedTransaction; } @@ -527,10 +481,7 @@ class _TransactionObserver implements SKTransactionObserverWrapper { final List purchases = transactions .map( (SKPaymentTransactionWrapper transaction) => - AppStorePurchaseDetails.fromSKTransaction( - transaction, - receiptData, - ), + AppStorePurchaseDetails.fromSKTransaction(transaction, receiptData), ) .toList(); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform_addition.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform_addition.dart index cd80a5ced25f..b92d74014da2 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform_addition.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/in_app_purchase_storekit_platform_addition.dart @@ -9,8 +9,7 @@ import '../store_kit_2_wrappers.dart'; import '../store_kit_wrappers.dart'; /// Contains InApp Purchase features that are only available on iOS. -class InAppPurchaseStoreKitPlatformAddition - extends InAppPurchasePlatformAddition { +class InAppPurchaseStoreKitPlatformAddition extends InAppPurchasePlatformAddition { /// Synchronizes your app’s transaction information and subscription status /// with information from the App Store. /// Storekit 2 only @@ -69,6 +68,5 @@ class InAppPurchaseStoreKitPlatformAddition /// `SKPaymentQueueDelegateWrapper.shouldShowPriceConsent()` method was called. /// /// See documentation of StoreKit's [`-[SKPaymentQueue showPriceConsentIfNeeded]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/3521327-showpriceconsentifneeded?language=objc). - Future showPriceConsentIfNeeded() => - SKPaymentQueueWrapper().showPriceConsentIfNeeded(); + Future showPriceConsentIfNeeded() => SKPaymentQueueWrapper().showPriceConsentIfNeeded(); } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/messages.g.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/messages.g.dart index 47447273c965..202b4b0bd9b7 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/messages.g.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -149,8 +147,7 @@ class SKPaymentTransactionMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SKPaymentTransactionMessage || - other.runtimeType != runtimeType) { + if (other is! SKPaymentTransactionMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -314,8 +311,7 @@ class SKPaymentDiscountMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SKPaymentDiscountMessage || - other.runtimeType != runtimeType) { + if (other is! SKPaymentDiscountMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -346,10 +342,7 @@ class SKStorefrontMessage { static SKStorefrontMessage decode(Object result) { result as List; - return SKStorefrontMessage( - countryCode: result[0]! as String, - identifier: result[1]! as String, - ); + return SKStorefrontMessage(countryCode: result[0]! as String, identifier: result[1]! as String); } @override @@ -395,8 +388,7 @@ class SKProductsResponseMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SKProductsResponseMessage || - other.runtimeType != runtimeType) { + if (other is! SKProductsResponseMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -470,8 +462,7 @@ class SKProductMessage { price: result[5]! as String, subscriptionPeriod: result[6] as SKProductSubscriptionPeriodMessage?, introductoryPrice: result[7] as SKProductDiscountMessage?, - discounts: (result[8] as List?) - ?.cast(), + discounts: (result[8] as List?)?.cast(), ); } @@ -599,8 +590,7 @@ class SKProductDiscountMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SKProductDiscountMessage || - other.runtimeType != runtimeType) { + if (other is! SKProductDiscountMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -615,10 +605,7 @@ class SKProductDiscountMessage { } class SKProductSubscriptionPeriodMessage { - SKProductSubscriptionPeriodMessage({ - required this.numberOfUnits, - required this.unit, - }); + SKProductSubscriptionPeriodMessage({required this.numberOfUnits, required this.unit}); int numberOfUnits; @@ -643,8 +630,7 @@ class SKProductSubscriptionPeriodMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SKProductSubscriptionPeriodMessage || - other.runtimeType != runtimeType) { + if (other is! SKProductSubscriptionPeriodMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -717,24 +703,16 @@ class _PigeonCodec extends StandardMessageCodec { switch (type) { case 129: final int? value = readValue(buffer) as int?; - return value == null - ? null - : SKPaymentTransactionStateMessage.values[value]; + return value == null ? null : SKPaymentTransactionStateMessage.values[value]; case 130: final int? value = readValue(buffer) as int?; - return value == null - ? null - : SKProductDiscountTypeMessage.values[value]; + return value == null ? null : SKProductDiscountTypeMessage.values[value]; case 131: final int? value = readValue(buffer) as int?; - return value == null - ? null - : SKProductDiscountPaymentModeMessage.values[value]; + return value == null ? null : SKProductDiscountPaymentModeMessage.values[value]; case 132: final int? value = readValue(buffer) as int?; - return value == null - ? null - : SKSubscriptionPeriodUnitMessage.values[value]; + return value == null ? null : SKSubscriptionPeriodUnitMessage.values[value]; case 133: return SKPaymentTransactionMessage.decode(readValue(buffer)!); case 134: @@ -765,13 +743,11 @@ class InAppPurchaseAPI { /// Constructor for [InAppPurchaseAPI]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - InAppPurchaseAPI({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + InAppPurchaseAPI({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -782,15 +758,13 @@ class InAppPurchaseAPI { Future canMakePayments() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.canMakePayments$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -812,15 +786,13 @@ class InAppPurchaseAPI { Future> transactions() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.transactions$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -835,23 +807,20 @@ class InAppPurchaseAPI { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } Future storefront() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.storefront$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -873,17 +842,13 @@ class InAppPurchaseAPI { Future addPayment(Map paymentMap) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.addPayment$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [paymentMap], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([paymentMap]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -897,22 +862,18 @@ class InAppPurchaseAPI { } } - Future startProductRequest( - List productIdentifiers, - ) async { + Future startProductRequest(List productIdentifiers) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startProductRequest$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [productIdentifiers], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + productIdentifiers, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -934,17 +895,13 @@ class InAppPurchaseAPI { Future finishTransaction(Map finishMap) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.finishTransaction$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [finishMap], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([finishMap]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -961,17 +918,15 @@ class InAppPurchaseAPI { Future restoreTransactions(String? applicationUserName) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.restoreTransactions$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [applicationUserName], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + applicationUserName, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -988,15 +943,13 @@ class InAppPurchaseAPI { Future presentCodeRedemptionSheet() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.presentCodeRedemptionSheet$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1013,15 +966,13 @@ class InAppPurchaseAPI { Future retrieveReceiptData() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.retrieveReceiptData$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1038,17 +989,15 @@ class InAppPurchaseAPI { Future refreshReceipt({Map? receiptProperties}) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.refreshReceipt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [receiptProperties], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + receiptProperties, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1065,15 +1014,13 @@ class InAppPurchaseAPI { Future startObservingPaymentQueue() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startObservingPaymentQueue$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1090,15 +1037,13 @@ class InAppPurchaseAPI { Future stopObservingPaymentQueue() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.stopObservingPaymentQueue$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1115,15 +1060,13 @@ class InAppPurchaseAPI { Future registerPaymentQueueDelegate() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.registerPaymentQueueDelegate$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1140,15 +1083,13 @@ class InAppPurchaseAPI { Future removePaymentQueueDelegate() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.removePaymentQueueDelegate$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1165,15 +1106,13 @@ class InAppPurchaseAPI { Future showPriceConsentIfNeeded() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.showPriceConsentIfNeeded$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1190,15 +1129,13 @@ class InAppPurchaseAPI { Future supportsStoreKit2() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.supportsStoreKit2$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/sk2_pigeon.g.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/sk2_pigeon.g.dart index 8b20981d7d80..f978b505f71c 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/sk2_pigeon.g.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/sk2_pigeon.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -66,20 +60,11 @@ enum SK2ProductTypeMessage { enum SK2SubscriptionOfferTypeMessage { introductory, promotional, winBack } -enum SK2SubscriptionOfferPaymentModeMessage { - payAsYouGo, - payUpFront, - freeTrial, -} +enum SK2SubscriptionOfferPaymentModeMessage { payAsYouGo, payUpFront, freeTrial } enum SK2SubscriptionPeriodUnitMessage { day, week, month, year } -enum SK2ProductPurchaseResultMessage { - success, - unverified, - userCancelled, - pending, -} +enum SK2ProductPurchaseResultMessage { success, unverified, userCancelled, pending } /// The status of a purchase transaction. /// Used to communicate the result state to Dart layer via purchaseStream. @@ -142,8 +127,7 @@ class SK2SubscriptionOfferMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SK2SubscriptionOfferMessage || - other.runtimeType != runtimeType) { + if (other is! SK2SubscriptionOfferMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -185,8 +169,7 @@ class SK2SubscriptionPeriodMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SK2SubscriptionPeriodMessage || - other.runtimeType != runtimeType) { + if (other is! SK2SubscriptionPeriodMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -217,11 +200,7 @@ class SK2SubscriptionInfoMessage { SK2SubscriptionPeriodMessage subscriptionPeriod; List _toList() { - return [ - promotionalOffers, - subscriptionGroupID, - subscriptionPeriod, - ]; + return [promotionalOffers, subscriptionGroupID, subscriptionPeriod]; } Object encode() { @@ -231,8 +210,7 @@ class SK2SubscriptionInfoMessage { static SK2SubscriptionInfoMessage decode(Object result) { result as List; return SK2SubscriptionInfoMessage( - promotionalOffers: (result[0] as List?)! - .cast(), + promotionalOffers: (result[0] as List?)!.cast(), subscriptionGroupID: result[1]! as String, subscriptionPeriod: result[2]! as SK2SubscriptionPeriodMessage, ); @@ -241,8 +219,7 @@ class SK2SubscriptionInfoMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SK2SubscriptionInfoMessage || - other.runtimeType != runtimeType) { + if (other is! SK2SubscriptionInfoMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -343,10 +320,7 @@ class SK2ProductMessage { } class SK2PriceLocaleMessage { - SK2PriceLocaleMessage({ - required this.currencyCode, - required this.currencySymbol, - }); + SK2PriceLocaleMessage({required this.currencyCode, required this.currencySymbol}); String currencyCode; @@ -424,8 +398,7 @@ class SK2SubscriptionOfferSignatureMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SK2SubscriptionOfferSignatureMessage || - other.runtimeType != runtimeType) { + if (other is! SK2SubscriptionOfferSignatureMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -461,16 +434,14 @@ class SK2SubscriptionOfferPurchaseMessage { result as List; return SK2SubscriptionOfferPurchaseMessage( promotionalOfferId: result[0]! as String, - promotionalOfferSignature: - result[1]! as SK2SubscriptionOfferSignatureMessage, + promotionalOfferSignature: result[1]! as SK2SubscriptionOfferSignatureMessage, ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SK2SubscriptionOfferPurchaseMessage || - other.runtimeType != runtimeType) { + if (other is! SK2SubscriptionOfferPurchaseMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -501,12 +472,7 @@ class SK2ProductPurchaseOptionsMessage { String? winBackOfferId; List _toList() { - return [ - appAccountToken, - quantity, - promotionalOffer, - winBackOfferId, - ]; + return [appAccountToken, quantity, promotionalOffer, winBackOfferId]; } Object encode() { @@ -526,8 +492,7 @@ class SK2ProductPurchaseOptionsMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SK2ProductPurchaseOptionsMessage || - other.runtimeType != runtimeType) { + if (other is! SK2ProductPurchaseOptionsMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -745,24 +710,16 @@ class _PigeonCodec extends StandardMessageCodec { return value == null ? null : SK2ProductTypeMessage.values[value]; case 130: final value = readValue(buffer) as int?; - return value == null - ? null - : SK2SubscriptionOfferTypeMessage.values[value]; + return value == null ? null : SK2SubscriptionOfferTypeMessage.values[value]; case 131: final value = readValue(buffer) as int?; - return value == null - ? null - : SK2SubscriptionOfferPaymentModeMessage.values[value]; + return value == null ? null : SK2SubscriptionOfferPaymentModeMessage.values[value]; case 132: final value = readValue(buffer) as int?; - return value == null - ? null - : SK2SubscriptionPeriodUnitMessage.values[value]; + return value == null ? null : SK2SubscriptionPeriodUnitMessage.values[value]; case 133: final value = readValue(buffer) as int?; - return value == null - ? null - : SK2ProductPurchaseResultMessage.values[value]; + return value == null ? null : SK2ProductPurchaseResultMessage.values[value]; case 134: final value = readValue(buffer) as int?; return value == null ? null : SK2PurchaseStatusMessage.values[value]; @@ -796,13 +753,11 @@ class InAppPurchase2API { /// Constructor for [InAppPurchase2API]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - InAppPurchase2API({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + InAppPurchase2API({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -845,9 +800,7 @@ class InAppPurchase2API { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [identifiers], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([identifiers]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -863,8 +816,7 @@ class InAppPurchase2API { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } @@ -879,9 +831,7 @@ class InAppPurchase2API { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [id, options], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([id, options]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -909,9 +859,10 @@ class InAppPurchase2API { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [productId, offerId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + productId, + offerId, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -939,9 +890,7 @@ class InAppPurchase2API { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [productId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([productId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -985,8 +934,7 @@ class InAppPurchase2API { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } @@ -1014,8 +962,7 @@ class InAppPurchase2API { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as List?)! - .cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } @@ -1027,9 +974,7 @@ class InAppPurchase2API { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [id], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([id]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1175,9 +1120,7 @@ abstract class InAppPurchase2CallbackAPI { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchase2CallbackAPI.onTransactionsUpdated$messageChannelSuffix', @@ -1193,8 +1136,8 @@ abstract class InAppPurchase2CallbackAPI { 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchase2CallbackAPI.onTransactionsUpdated was null.', ); final List args = (message as List?)!; - final List? arg_newTransactions = - (args[0] as List?)?.cast(); + final List? arg_newTransactions = (args[0] as List?) + ?.cast(); assert( arg_newTransactions != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchase2CallbackAPI.onTransactionsUpdated was null, expected non-null List.', diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_product_wrapper.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_product_wrapper.dart index 8baffa757439..c9d6a4fb775c 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_product_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_product_wrapper.dart @@ -254,19 +254,13 @@ class SK2PriceLocale { /// Convert this instance of [SK2PriceLocale] to [SK2PriceLocaleMessage] SK2PriceLocaleMessage convertToPigeon() { - return SK2PriceLocaleMessage( - currencyCode: currencyCode, - currencySymbol: currencySymbol, - ); + return SK2PriceLocaleMessage(currencyCode: currencyCode, currencySymbol: currencySymbol); } } extension on SK2PriceLocaleMessage { SK2PriceLocale convertFromPigeon() { - return SK2PriceLocale( - currencyCode: currencyCode, - currencySymbol: currencySymbol, - ); + return SK2PriceLocale(currencyCode: currencyCode, currencySymbol: currencySymbol); } } @@ -323,14 +317,10 @@ class SK2ProductPurchaseOptions { extension on SK2ProductPurchaseResultMessage { SK2ProductPurchaseResult convertFromPigeon() { return switch (this) { - SK2ProductPurchaseResultMessage.success => - SK2ProductPurchaseResult.success, - SK2ProductPurchaseResultMessage.userCancelled => - SK2ProductPurchaseResult.userCancelled, - SK2ProductPurchaseResultMessage.pending => - SK2ProductPurchaseResult.pending, - SK2ProductPurchaseResultMessage.unverified => - SK2ProductPurchaseResult.unverified, + SK2ProductPurchaseResultMessage.success => SK2ProductPurchaseResult.success, + SK2ProductPurchaseResultMessage.userCancelled => SK2ProductPurchaseResult.userCancelled, + SK2ProductPurchaseResultMessage.pending => SK2ProductPurchaseResult.pending, + SK2ProductPurchaseResultMessage.unverified => SK2ProductPurchaseResult.unverified, }; } } @@ -380,9 +370,7 @@ class SK2Product { /// If any of the identifiers are invalid or can't be found, they are excluded /// from the returned list. static Future> products(List identifiers) async { - final List productsMsg = await hostApi2.products( - identifiers, - ); + final List productsMsg = await hostApi2.products(identifiers); if (productsMsg.isEmpty && identifiers.isNotEmpty) { throw PlatformException( code: 'storekit_no_response', @@ -421,14 +409,8 @@ class SK2Product { } /// Checks if the user is eligible for a specific win back offer. - static Future isWinBackOfferEligible( - String productId, - String offerId, - ) async { - final bool result = await hostApi2.isWinBackOfferEligible( - productId, - offerId, - ); + static Future isWinBackOfferEligible(String productId, String offerId) async { + final bool result = await hostApi2.isWinBackOfferEligible(productId, offerId); return result; } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_transaction_wrapper.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_transaction_wrapper.dart index 551d4ed0836e..660242745942 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_transaction_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_2_wrappers/sk2_transaction_wrapper.dart @@ -94,8 +94,7 @@ class SK2Transaction { /// https://developer.apple.com/documentation/storekit/transaction/unfinished /// A sequence that emits unfinished transactions for the customer. static Future> unfinishedTransactions() async { - final List msgs = await hostApi2 - .unfinishedTransactions(); + final List msgs = await hostApi2.unfinishedTransactions(); final List transactions = msgs .map((SK2TransactionMessage e) => e.convertFromPigeon()) .toList(); @@ -173,9 +172,7 @@ class SK2TransactionObserverWrapper implements InAppPurchase2CallbackAPI { @override void onTransactionsUpdated(List newTransactions) { transactionsCreatedController.add( - newTransactions - .map((SK2TransactionMessage e) => e.convertToDetails()) - .toList(), + newTransactions.map((SK2TransactionMessage e) => e.convertToDetails()).toList(), ); } } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.dart index 54d176a46a7c..c8c3e79d5b65 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.dart @@ -24,17 +24,13 @@ class SKTransactionStatusConverter return SKPaymentTransactionStateWrapper.unspecified; } return $enumDecode( - _$SKPaymentTransactionStateWrapperEnumMap - .cast(), + _$SKPaymentTransactionStateWrapperEnumMap.cast(), json, ); } /// Converts an [SKPaymentTransactionStateWrapper] to a [PurchaseStatus]. - PurchaseStatus toPurchaseStatus( - SKPaymentTransactionStateWrapper object, - SKError? error, - ) { + PurchaseStatus toPurchaseStatus(SKPaymentTransactionStateWrapper object, SKError? error) { switch (object) { case SKPaymentTransactionStateWrapper.purchasing: case SKPaymentTransactionStateWrapper.deferred: @@ -66,8 +62,7 @@ class SKTransactionStatusConverter /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@SKSubscriptionPeriodUnitConverter()`. -class SKSubscriptionPeriodUnitConverter - implements JsonConverter { +class SKSubscriptionPeriodUnitConverter implements JsonConverter { /// Default const constructor. const SKSubscriptionPeriodUnitConverter(); @@ -77,15 +72,13 @@ class SKSubscriptionPeriodUnitConverter return SKSubscriptionPeriodUnit.day; } return $enumDecode( - _$SKSubscriptionPeriodUnitEnumMap - .cast(), + _$SKSubscriptionPeriodUnitEnumMap.cast(), json, ); } @override - int toJson(SKSubscriptionPeriodUnit object) => - _$SKSubscriptionPeriodUnitEnumMap[object]!; + int toJson(SKSubscriptionPeriodUnit object) => _$SKSubscriptionPeriodUnitEnumMap[object]!; } /// Serializer for [SKProductDiscountPaymentMode]. @@ -103,15 +96,13 @@ class SKProductDiscountPaymentModeConverter return SKProductDiscountPaymentMode.payAsYouGo; } return $enumDecode( - _$SKProductDiscountPaymentModeEnumMap - .cast(), + _$SKProductDiscountPaymentModeEnumMap.cast(), json, ); } @override - int toJson(SKProductDiscountPaymentMode object) => - _$SKProductDiscountPaymentModeEnumMap[object]!; + int toJson(SKProductDiscountPaymentMode object) => _$SKProductDiscountPaymentModeEnumMap[object]!; } // Define a class so we generate serializer helper methods for the enums @@ -128,8 +119,7 @@ class _SerializedEnums { /// /// Use these in `@JsonSerializable()` classes by annotating them with /// `@SKProductDiscountTypeConverter()`. -class SKProductDiscountTypeConverter - implements JsonConverter { +class SKProductDiscountTypeConverter implements JsonConverter { /// Default const constructor. const SKProductDiscountTypeConverter(); @@ -145,6 +135,5 @@ class SKProductDiscountTypeConverter } @override - int toJson(SKProductDiscountType object) => - _$SKProductDiscountTypeEnumMap[object]!; + int toJson(SKProductDiscountType object) => _$SKProductDiscountTypeEnumMap[object]!; } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.g.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.g.dart index 25a4d28db792..ff9c4b259f72 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.g.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/enum_converters.g.dart @@ -7,19 +7,13 @@ part of 'enum_converters.dart'; // ************************************************************************** _SerializedEnums _$SerializedEnumsFromJson(Map json) => _SerializedEnums() - ..response = $enumDecode( - _$SKPaymentTransactionStateWrapperEnumMap, - json['response'], - ) + ..response = $enumDecode(_$SKPaymentTransactionStateWrapperEnumMap, json['response']) ..unit = $enumDecode(_$SKSubscriptionPeriodUnitEnumMap, json['unit']) ..discountPaymentMode = $enumDecode( _$SKProductDiscountPaymentModeEnumMap, json['discountPaymentMode'], ) - ..discountType = $enumDecode( - _$SKProductDiscountTypeEnumMap, - json['discountType'], - ); + ..discountType = $enumDecode(_$SKProductDiscountTypeEnumMap, json['discountType']); const _$SKPaymentTransactionStateWrapperEnumMap = { SKPaymentTransactionStateWrapper.purchasing: 0, diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.dart index d36041d6ec32..927815d104c7 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.dart @@ -52,12 +52,10 @@ class SKPaymentQueueWrapper { /// Calls [`-[SKPaymentQueue transactions]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1506026-transactions?language=objc). Future> transactions() async { - final List pigeonMsgs = await hostApi - .transactions(); + final List pigeonMsgs = await hostApi.transactions(); return pigeonMsgs .map( - (SKPaymentTransactionMessage? msg) => - SKPaymentTransactionWrapper.convertFromPigeon(msg!), + (SKPaymentTransactionMessage? msg) => SKPaymentTransactionWrapper.convertFromPigeon(msg!), ) .toList(); } @@ -81,16 +79,14 @@ class SKPaymentQueueWrapper { /// /// Call this method when the first listener is subscribed to the /// [InAppPurchaseStoreKitPlatform.purchaseStream]. - Future startObservingTransactionQueue() => - hostApi.startObservingPaymentQueue(); + Future startObservingTransactionQueue() => hostApi.startObservingPaymentQueue(); /// Instructs the iOS implementation to remove the transaction observer and /// stop listening to it. /// /// Call this when there are no longer any listeners subscribed to the /// [InAppPurchaseStoreKitPlatform.purchaseStream]. - Future stopObservingTransactionQueue() => - hostApi.stopObservingPaymentQueue(); + Future stopObservingTransactionQueue() => hostApi.stopObservingPaymentQueue(); /// Sets an implementation of the [SKPaymentQueueDelegateWrapper]. /// @@ -108,9 +104,7 @@ class SKPaymentQueueWrapper { paymentQueueDelegateChannel.setMethodCallHandler(null); } else { await hostApi.registerPaymentQueueDelegate(); - paymentQueueDelegateChannel.setMethodCallHandler( - handlePaymentQueueDelegateCallbacks, - ); + paymentQueueDelegateChannel.setMethodCallHandler(handlePaymentQueueDelegateCallbacks); } _paymentQueueDelegate = delegate; @@ -156,9 +150,7 @@ class SKPaymentQueueWrapper { /// /// This method calls StoreKit's [`-[SKPaymentQueue /// finishTransaction:]`](https://developer.apple.com/documentation/storekit/skpaymentqueue/1506003-finishtransaction?language=objc). - Future finishTransaction( - SKPaymentTransactionWrapper transaction, - ) async { + Future finishTransaction(SKPaymentTransactionWrapper transaction) async { final Map requestMap = transaction.toFinishMap(); await hostApi.finishTransaction(requestMap); } @@ -223,16 +215,18 @@ class SKPaymentQueueWrapper { switch (call.method) { case 'updatedTransactions': { - final List transactions = - _getTransactionList(call.arguments as List); + final List transactions = _getTransactionList( + call.arguments as List, + ); return Future(() { observer.updatedTransactions(transactions: transactions); }); } case 'removedTransactions': { - final List transactions = - _getTransactionList(call.arguments as List); + final List transactions = _getTransactionList( + call.arguments as List, + ); return Future(() { observer.removedTransactions(transactions: transactions); }); @@ -256,18 +250,13 @@ class SKPaymentQueueWrapper { { final arguments = call.arguments as Map; final payment = SKPaymentWrapper.fromJson( - (arguments['payment']! as Map) - .cast(), + (arguments['payment']! as Map).cast(), ); final product = SKProductWrapper.fromJson( - (arguments['product']! as Map) - .cast(), + (arguments['product']! as Map).cast(), ); return Future(() { - if (observer.shouldAddStorePayment( - payment: payment, - product: product, - )) { + if (observer.shouldAddStorePayment(payment: payment, product: product)) { SKPaymentQueueWrapper().addPayment(payment); } }); @@ -282,14 +271,10 @@ class SKPaymentQueueWrapper { } // Get transaction wrapper object list from arguments. - List _getTransactionList( - List transactionsData, - ) { + List _getTransactionList(List transactionsData) { return transactionsData.map((dynamic map) { return SKPaymentTransactionWrapper.fromJson( - Map.castFrom( - map as Map, - ), + Map.castFrom(map as Map), ); }).toList(); } @@ -311,12 +296,10 @@ class SKPaymentQueueWrapper { case 'shouldContinueTransaction': final arguments = call.arguments as Map; final transaction = SKPaymentTransactionWrapper.fromJson( - (arguments['transaction']! as Map) - .cast(), + (arguments['transaction']! as Map).cast(), ); final storefront = SKStorefrontWrapper.fromJson( - (arguments['storefront']! as Map) - .cast(), + (arguments['storefront']! as Map).cast(), ); return delegate.shouldContinueTransaction(transaction, storefront); case 'shouldShowPriceConsent': @@ -326,8 +309,7 @@ class SKPaymentQueueWrapper { } throw PlatformException( code: 'no_such_callback', - message: - 'Did not recognize the payment queue delegate callback ${call.method}.', + message: 'Did not recognize the payment queue delegate callback ${call.method}.', ); } } @@ -338,11 +320,7 @@ class SKPaymentQueueWrapper { @JsonSerializable() class SKError { /// Creates a new [SKError] object with the provided information. - const SKError({ - required this.code, - required this.domain, - required this.userInfo, - }); + const SKError({required this.code, required this.domain, required this.userInfo}); /// Constructs an instance of this from a key-value map of data. /// @@ -381,10 +359,7 @@ class SKError { return other is SKError && other.code == code && other.domain == domain && - const DeepCollectionEquality.unordered().equals( - other.userInfo, - userInfo, - ); + const DeepCollectionEquality.unordered().equals(other.userInfo, userInfo); } @override @@ -529,9 +504,7 @@ class SKPaymentWrapper { quantity: msg.quantity, simulatesAskToBuyInSandbox: msg.simulatesAskToBuyInSandbox, requestData: msg.requestData, - paymentDiscount: SKPaymentDiscountWrapper.convertFromPigeon( - msg.paymentDiscount, - ), + paymentDiscount: SKPaymentDiscountWrapper.convertFromPigeon(msg.paymentDiscount), ); } } @@ -630,13 +603,10 @@ class SKPaymentDiscountWrapper { } @override - int get hashCode => - Object.hash(identifier, keyIdentifier, nonce, signature, timestamp); + int get hashCode => Object.hash(identifier, keyIdentifier, nonce, signature, timestamp); /// Converts [SKPaymentDiscountMessage] into the dart equivalent - static SKPaymentDiscountWrapper? convertFromPigeon( - SKPaymentDiscountMessage? msg, - ) { + static SKPaymentDiscountWrapper? convertFromPigeon(SKPaymentDiscountMessage? msg) { if (msg == null) { return null; } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.g.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.g.dart index 9e8080cba5c9..c9b40f4674e8 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.g.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.g.dart @@ -9,8 +9,7 @@ part of 'sk_payment_queue_wrapper.dart'; SKError _$SKErrorFromJson(Map json) => SKError( code: (json['code'] as num?)?.toInt() ?? 0, domain: json['domain'] as String? ?? '', - userInfo: - (json['userInfo'] as Map?)?.map((k, e) => MapEntry(k as String, e)) ?? {}, + userInfo: (json['userInfo'] as Map?)?.map((k, e) => MapEntry(k as String, e)) ?? {}, ); SKPaymentWrapper _$SKPaymentWrapperFromJson(Map json) => SKPaymentWrapper( @@ -18,8 +17,7 @@ SKPaymentWrapper _$SKPaymentWrapperFromJson(Map json) => SKPaymentWrapper( applicationUsername: json['applicationUsername'] as String?, requestData: json['requestData'] as String?, quantity: (json['quantity'] as num?)?.toInt() ?? 0, - simulatesAskToBuyInSandbox: - json['simulatesAskToBuyInSandbox'] as bool? ?? false, + simulatesAskToBuyInSandbox: json['simulatesAskToBuyInSandbox'] as bool? ?? false, paymentDiscount: json['paymentDiscount'] == null ? null : SKPaymentDiscountWrapper.fromJson( @@ -27,31 +25,28 @@ SKPaymentWrapper _$SKPaymentWrapperFromJson(Map json) => SKPaymentWrapper( ), ); -Map _$SKPaymentWrapperToJson(SKPaymentWrapper instance) => - { - 'productIdentifier': instance.productIdentifier, - 'applicationUsername': instance.applicationUsername, - 'requestData': instance.requestData, - 'quantity': instance.quantity, - 'simulatesAskToBuyInSandbox': instance.simulatesAskToBuyInSandbox, - 'paymentDiscount': instance.paymentDiscount, - }; +Map _$SKPaymentWrapperToJson(SKPaymentWrapper instance) => { + 'productIdentifier': instance.productIdentifier, + 'applicationUsername': instance.applicationUsername, + 'requestData': instance.requestData, + 'quantity': instance.quantity, + 'simulatesAskToBuyInSandbox': instance.simulatesAskToBuyInSandbox, + 'paymentDiscount': instance.paymentDiscount, +}; -SKPaymentDiscountWrapper _$SKPaymentDiscountWrapperFromJson(Map json) => - SKPaymentDiscountWrapper( - identifier: json['identifier'] as String, - keyIdentifier: json['keyIdentifier'] as String, - nonce: json['nonce'] as String, - signature: json['signature'] as String, - timestamp: (json['timestamp'] as num).toInt(), - ); +SKPaymentDiscountWrapper _$SKPaymentDiscountWrapperFromJson(Map json) => SKPaymentDiscountWrapper( + identifier: json['identifier'] as String, + keyIdentifier: json['keyIdentifier'] as String, + nonce: json['nonce'] as String, + signature: json['signature'] as String, + timestamp: (json['timestamp'] as num).toInt(), +); -Map _$SKPaymentDiscountWrapperToJson( - SKPaymentDiscountWrapper instance, -) => { - 'identifier': instance.identifier, - 'keyIdentifier': instance.keyIdentifier, - 'nonce': instance.nonce, - 'signature': instance.signature, - 'timestamp': instance.timestamp, -}; +Map _$SKPaymentDiscountWrapperToJson(SKPaymentDiscountWrapper instance) => + { + 'identifier': instance.identifier, + 'keyIdentifier': instance.keyIdentifier, + 'nonce': instance.nonce, + 'signature': instance.signature, + 'timestamp': instance.timestamp, + }; diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.dart index 0cb50bf2024a..27e716345046 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.dart @@ -21,14 +21,10 @@ part 'sk_payment_transaction_wrappers.g.dart'; /// This class is a Dart wrapper around [SKTransactionObserver](https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver?language=objc). abstract class SKTransactionObserverWrapper { /// Triggered when any transactions are updated. - void updatedTransactions({ - required List transactions, - }); + void updatedTransactions({required List transactions}); /// Triggered when any transactions are removed from the payment queue. - void removedTransactions({ - required List transactions, - }); + void removedTransactions({required List transactions}); /// Triggered when there is an error while restoring transactions. void restoreCompletedTransactionsFailed({required SKError error}); @@ -98,9 +94,7 @@ enum SKPaymentTransactionStateWrapper { unspecified; /// Converts [SKPaymentTransactionStateMessages] into the dart equivalent - static SKPaymentTransactionStateWrapper convertFromPigeon( - SKPaymentTransactionStateMessage msg, - ) { + static SKPaymentTransactionStateWrapper convertFromPigeon(SKPaymentTransactionStateMessage msg) { switch (msg) { case SKPaymentTransactionStateMessage.purchased: return SKPaymentTransactionStateWrapper.purchased; @@ -232,14 +226,10 @@ class SKPaymentTransactionWrapper { }; /// Converts [SKPaymentTransactionMessages] into the dart equivalent - static SKPaymentTransactionWrapper convertFromPigeon( - SKPaymentTransactionMessage msg, - ) { + static SKPaymentTransactionWrapper convertFromPigeon(SKPaymentTransactionMessage msg) { return SKPaymentTransactionWrapper( payment: SKPaymentWrapper.convertFromPigeon(msg.payment), - transactionState: SKPaymentTransactionStateWrapper.convertFromPigeon( - msg.transactionState, - ), + transactionState: SKPaymentTransactionStateWrapper.convertFromPigeon(msg.transactionState), originalTransaction: msg.originalTransaction == null ? null : convertFromPigeon(msg.originalTransaction!), diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart index 6aaf95685781..ab2f388a6080 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_transaction_wrappers.g.dart @@ -8,9 +8,7 @@ part of 'sk_payment_transaction_wrappers.dart'; SKPaymentTransactionWrapper _$SKPaymentTransactionWrapperFromJson(Map json) => SKPaymentTransactionWrapper( - payment: SKPaymentWrapper.fromJson( - Map.from(json['payment'] as Map), - ), + payment: SKPaymentWrapper.fromJson(Map.from(json['payment'] as Map)), transactionState: const SKTransactionStatusConverter().fromJson( (json['transactionState'] as num?)?.toInt(), ), @@ -26,15 +24,12 @@ SKPaymentTransactionWrapper _$SKPaymentTransactionWrapperFromJson(Map json) => : SKError.fromJson(Map.from(json['error'] as Map)), ); -Map _$SKPaymentTransactionWrapperToJson( - SKPaymentTransactionWrapper instance, -) => { - 'transactionState': const SKTransactionStatusConverter().toJson( - instance.transactionState, - ), - 'payment': instance.payment, - 'originalTransaction': instance.originalTransaction, - 'transactionTimeStamp': instance.transactionTimeStamp, - 'transactionIdentifier': instance.transactionIdentifier, - 'error': instance.error, -}; +Map _$SKPaymentTransactionWrapperToJson(SKPaymentTransactionWrapper instance) => + { + 'transactionState': const SKTransactionStatusConverter().toJson(instance.transactionState), + 'payment': instance.payment, + 'originalTransaction': instance.originalTransaction, + 'transactionTimeStamp': instance.transactionTimeStamp, + 'transactionIdentifier': instance.transactionIdentifier, + 'error': instance.error, + }; diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.dart index 6e6d42a6d334..60c46e01292c 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.dart @@ -25,10 +25,7 @@ class SkProductResponseWrapper { // TODO(stuartmorgan): Temporarily ignore const warning in other parts of the // federated package, and remove this. // ignore: prefer_const_constructors_in_immutables - SkProductResponseWrapper({ - required this.products, - required this.invalidProductIdentifiers, - }); + SkProductResponseWrapper({required this.products, required this.invalidProductIdentifiers}); /// Constructing an instance from a map from the Objective-C layer. /// @@ -72,9 +69,7 @@ class SkProductResponseWrapper { int get hashCode => Object.hash(products, invalidProductIdentifiers); /// Convert from [SkProductResponseMessage] to [SkProductResponseWrapper] - static SkProductResponseWrapper convertFromPigeon( - SKProductsResponseMessage msg, - ) { + static SkProductResponseWrapper convertFromPigeon(SKProductsResponseMessage msg) { return SkProductResponseWrapper( products: msg.products! .map((SKProductMessage e) => SKProductWrapper.convertFromPigeon(e)) @@ -85,9 +80,7 @@ class SkProductResponseWrapper { /// Convert from [SkProductResponseWrapper] to [SkProductResponseWrapper] @visibleForTesting - static SKProductsResponseMessage convertToPigeon( - SkProductResponseWrapper wrapper, - ) { + static SKProductsResponseMessage convertToPigeon(SkProductResponseWrapper wrapper) { return SKProductsResponseMessage( products: wrapper.products .map((SKProductWrapper e) => SKProductWrapper.convertToPigeon(e)) @@ -120,9 +113,7 @@ enum SKSubscriptionPeriodUnit { year; /// Convert from [SKSubscriptionPeriodUnitMessage] to [SKSubscriptionPeriodUnit] - static SKSubscriptionPeriodUnit convertFromPigeon( - SKSubscriptionPeriodUnitMessage msg, - ) { + static SKSubscriptionPeriodUnit convertFromPigeon(SKSubscriptionPeriodUnitMessage msg) { switch (msg) { case SKSubscriptionPeriodUnitMessage.day: return SKSubscriptionPeriodUnit.day; @@ -137,9 +128,7 @@ enum SKSubscriptionPeriodUnit { /// Convert from [SKSubscriptionPeriodUnit] to [SKSubscriptionPeriodUnitMessage] @visibleForTesting - static SKSubscriptionPeriodUnitMessage convertToPigeon( - SKSubscriptionPeriodUnit msg, - ) { + static SKSubscriptionPeriodUnitMessage convertToPigeon(SKSubscriptionPeriodUnit msg) { switch (msg) { case SKSubscriptionPeriodUnit.day: return SKSubscriptionPeriodUnitMessage.day; @@ -164,17 +153,12 @@ class SKProductSubscriptionPeriodWrapper { // TODO(stuartmorgan): Temporarily ignore const warning in other parts of the // federated package, and remove this. // ignore: prefer_const_constructors_in_immutables - SKProductSubscriptionPeriodWrapper({ - required this.numberOfUnits, - required this.unit, - }); + SKProductSubscriptionPeriodWrapper({required this.numberOfUnits, required this.unit}); /// Constructing an instance from a map from the Objective-C layer. /// /// This method should only be used with `map` values returned by [SKProductDiscountWrapper.fromJson] or [SKProductWrapper.fromJson]. - factory SKProductSubscriptionPeriodWrapper.fromJson( - Map? map, - ) { + factory SKProductSubscriptionPeriodWrapper.fromJson(Map? map) { if (map == null) { return SKProductSubscriptionPeriodWrapper( numberOfUnits: 0, @@ -255,9 +239,7 @@ enum SKProductDiscountPaymentMode { unspecified; /// Convert from [SKProductDiscountPaymentModeMessage] to [SKProductDiscountPaymentModeWrapper] - static SKProductDiscountPaymentMode convertFromPigeon( - SKProductDiscountPaymentModeMessage msg, - ) { + static SKProductDiscountPaymentMode convertFromPigeon(SKProductDiscountPaymentModeMessage msg) { switch (msg) { case SKProductDiscountPaymentModeMessage.payAsYouGo: return SKProductDiscountPaymentMode.payAsYouGo; @@ -272,9 +254,7 @@ enum SKProductDiscountPaymentMode { /// Convert from [SKProductDiscountPaymentModeMessage] to [SKProductDiscountPaymentMode] @visibleForTesting - static SKProductDiscountPaymentModeMessage convertToPigeon( - SKProductDiscountPaymentMode wrapper, - ) { + static SKProductDiscountPaymentModeMessage convertToPigeon(SKProductDiscountPaymentMode wrapper) { switch (wrapper) { case SKProductDiscountPaymentMode.payAsYouGo: return SKProductDiscountPaymentModeMessage.payAsYouGo; @@ -306,9 +286,7 @@ enum SKProductDiscountType { subscription; /// Convert from [SKProductDiscountTypeMessage] to [SKProductDiscountType] - static SKProductDiscountType convertFromPigeon( - SKProductDiscountTypeMessage msg, - ) { + static SKProductDiscountType convertFromPigeon(SKProductDiscountTypeMessage msg) { switch (msg) { case SKProductDiscountTypeMessage.introductory: return SKProductDiscountType.introductory; @@ -319,9 +297,7 @@ enum SKProductDiscountType { /// Convert from [SKProductDiscountType] to [SKProductDiscountTypeMessage] @visibleForTesting - static SKProductDiscountTypeMessage convertToPigeon( - SKProductDiscountType wrapper, - ) { + static SKProductDiscountTypeMessage convertToPigeon(SKProductDiscountType wrapper) { switch (wrapper) { case SKProductDiscountType.introductory: return SKProductDiscountTypeMessage.introductory; @@ -421,16 +397,12 @@ class SKProductDiscountWrapper { ); /// Convert from [SKProductDiscountMessage] to [SKProductDiscountWrapper] - static SKProductDiscountWrapper convertFromPigeon( - SKProductDiscountMessage msg, - ) { + static SKProductDiscountWrapper convertFromPigeon(SKProductDiscountMessage msg) { return SKProductDiscountWrapper( price: msg.price, priceLocale: SKPriceLocaleWrapper.convertFromPigeon(msg.priceLocale), numberOfPeriods: msg.numberOfPeriods, - paymentMode: SKProductDiscountPaymentMode.convertFromPigeon( - msg.paymentMode, - ), + paymentMode: SKProductDiscountPaymentMode.convertFromPigeon(msg.paymentMode), subscriptionPeriod: SKProductSubscriptionPeriodWrapper.convertFromPigeon( msg.subscriptionPeriod, ), @@ -441,16 +413,12 @@ class SKProductDiscountWrapper { /// Convert from [SKProductDiscountWrapper] to [SKProductDiscountMessage] @visibleForTesting - static SKProductDiscountMessage convertToPigeon( - SKProductDiscountWrapper wrapper, - ) { + static SKProductDiscountMessage convertToPigeon(SKProductDiscountWrapper wrapper) { return SKProductDiscountMessage( price: wrapper.price, priceLocale: SKPriceLocaleWrapper.convertToPigeon(wrapper.priceLocale), numberOfPeriods: wrapper.numberOfPeriods, - paymentMode: SKProductDiscountPaymentMode.convertToPigeon( - wrapper.paymentMode, - ), + paymentMode: SKProductDiscountPaymentMode.convertToPigeon(wrapper.paymentMode), subscriptionPeriod: SKProductSubscriptionPeriodWrapper.convertToPigeon( wrapper.subscriptionPeriod, ), @@ -588,19 +556,14 @@ class SKProductWrapper { price: msg.price, subscriptionGroupIdentifier: msg.subscriptionGroupIdentifier, subscriptionPeriod: msg.subscriptionPeriod != null - ? SKProductSubscriptionPeriodWrapper.convertFromPigeon( - msg.subscriptionPeriod!, - ) + ? SKProductSubscriptionPeriodWrapper.convertFromPigeon(msg.subscriptionPeriod!) : null, introductoryPrice: msg.introductoryPrice != null ? SKProductDiscountWrapper.convertFromPigeon(msg.introductoryPrice!) : null, discounts: msg.discounts != null ? msg.discounts! - .map( - (SKProductDiscountMessage e) => - SKProductDiscountWrapper.convertFromPigeon(e), - ) + .map((SKProductDiscountMessage e) => SKProductDiscountWrapper.convertFromPigeon(e)) .toList() : [], ); @@ -616,18 +579,13 @@ class SKProductWrapper { price: wrapper.price, subscriptionGroupIdentifier: wrapper.subscriptionGroupIdentifier, subscriptionPeriod: wrapper.subscriptionPeriod != null - ? SKProductSubscriptionPeriodWrapper.convertToPigeon( - wrapper.subscriptionPeriod!, - ) + ? SKProductSubscriptionPeriodWrapper.convertToPigeon(wrapper.subscriptionPeriod!) : null, introductoryPrice: wrapper.introductoryPrice != null ? SKProductDiscountWrapper.convertToPigeon(wrapper.introductoryPrice!) : null, discounts: wrapper.discounts - .map( - (SKProductDiscountWrapper e) => - SKProductDiscountWrapper.convertToPigeon(e), - ) + .map((SKProductDiscountWrapper e) => SKProductDiscountWrapper.convertToPigeon(e)) .toList(), ); } @@ -656,11 +614,7 @@ class SKPriceLocaleWrapper { /// This method should only be used with `map` values returned by [SKProductWrapper.fromJson] and [SKProductDiscountWrapper.fromJson]. factory SKPriceLocaleWrapper.fromJson(Map? map) { if (map == null) { - return SKPriceLocaleWrapper( - currencyCode: '', - currencySymbol: '', - countryCode: '', - ); + return SKPriceLocaleWrapper(currencyCode: '', currencySymbol: '', countryCode: ''); } return _$SKPriceLocaleWrapperFromJson(map); } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.g.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.g.dart index acbfb2d861f3..09a69b1d60d5 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.g.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.g.dart @@ -6,54 +6,38 @@ part of 'sk_product_wrapper.dart'; // JsonSerializableGenerator // ************************************************************************** -SkProductResponseWrapper _$SkProductResponseWrapperFromJson(Map json) => - SkProductResponseWrapper( - products: - (json['products'] as List?) - ?.map( - (e) => SKProductWrapper.fromJson( - Map.from(e as Map), - ), - ) - .toList() ?? - [], - invalidProductIdentifiers: - (json['invalidProductIdentifiers'] as List?) - ?.map((e) => e as String) - .toList() ?? - [], +SkProductResponseWrapper _$SkProductResponseWrapperFromJson(Map json) => SkProductResponseWrapper( + products: + (json['products'] as List?) + ?.map((e) => SKProductWrapper.fromJson(Map.from(e as Map))) + .toList() ?? + [], + invalidProductIdentifiers: + (json['invalidProductIdentifiers'] as List?)?.map((e) => e as String).toList() ?? [], +); + +SKProductSubscriptionPeriodWrapper _$SKProductSubscriptionPeriodWrapperFromJson(Map json) => + SKProductSubscriptionPeriodWrapper( + numberOfUnits: (json['numberOfUnits'] as num?)?.toInt() ?? 0, + unit: const SKSubscriptionPeriodUnitConverter().fromJson((json['unit'] as num?)?.toInt()), ); -SKProductSubscriptionPeriodWrapper _$SKProductSubscriptionPeriodWrapperFromJson( - Map json, -) => SKProductSubscriptionPeriodWrapper( - numberOfUnits: (json['numberOfUnits'] as num?)?.toInt() ?? 0, - unit: const SKSubscriptionPeriodUnitConverter().fromJson( - (json['unit'] as num?)?.toInt(), +SKProductDiscountWrapper _$SKProductDiscountWrapperFromJson(Map json) => SKProductDiscountWrapper( + price: json['price'] as String? ?? '', + priceLocale: SKPriceLocaleWrapper.fromJson( + (json['priceLocale'] as Map?)?.map((k, e) => MapEntry(k as String, e)), ), + numberOfPeriods: (json['numberOfPeriods'] as num?)?.toInt() ?? 0, + paymentMode: const SKProductDiscountPaymentModeConverter().fromJson( + (json['paymentMode'] as num?)?.toInt(), + ), + subscriptionPeriod: SKProductSubscriptionPeriodWrapper.fromJson( + (json['subscriptionPeriod'] as Map?)?.map((k, e) => MapEntry(k as String, e)), + ), + identifier: json['identifier'] as String?, + type: const SKProductDiscountTypeConverter().fromJson((json['type'] as num?)?.toInt()), ); -SKProductDiscountWrapper _$SKProductDiscountWrapperFromJson(Map json) => - SKProductDiscountWrapper( - price: json['price'] as String? ?? '', - priceLocale: SKPriceLocaleWrapper.fromJson( - (json['priceLocale'] as Map?)?.map((k, e) => MapEntry(k as String, e)), - ), - numberOfPeriods: (json['numberOfPeriods'] as num?)?.toInt() ?? 0, - paymentMode: const SKProductDiscountPaymentModeConverter().fromJson( - (json['paymentMode'] as num?)?.toInt(), - ), - subscriptionPeriod: SKProductSubscriptionPeriodWrapper.fromJson( - (json['subscriptionPeriod'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), - ), - identifier: json['identifier'] as String?, - type: const SKProductDiscountTypeConverter().fromJson( - (json['type'] as num?)?.toInt(), - ), - ); - SKProductWrapper _$SKProductWrapperFromJson(Map json) => SKProductWrapper( productIdentifier: json['productIdentifier'] as String? ?? '', localizedTitle: json['localizedTitle'] as String? ?? '', @@ -66,9 +50,7 @@ SKProductWrapper _$SKProductWrapperFromJson(Map json) => SKProductWrapper( subscriptionPeriod: json['subscriptionPeriod'] == null ? null : SKProductSubscriptionPeriodWrapper.fromJson( - (json['subscriptionPeriod'] as Map?)?.map( - (k, e) => MapEntry(k as String, e), - ), + (json['subscriptionPeriod'] as Map?)?.map((k, e) => MapEntry(k as String, e)), ), introductoryPrice: json['introductoryPrice'] == null ? null @@ -77,18 +59,13 @@ SKProductWrapper _$SKProductWrapperFromJson(Map json) => SKProductWrapper( ), discounts: (json['discounts'] as List?) - ?.map( - (e) => SKProductDiscountWrapper.fromJson( - Map.from(e as Map), - ), - ) + ?.map((e) => SKProductDiscountWrapper.fromJson(Map.from(e as Map))) .toList() ?? [], ); -SKPriceLocaleWrapper _$SKPriceLocaleWrapperFromJson(Map json) => - SKPriceLocaleWrapper( - currencySymbol: json['currencySymbol'] as String? ?? '', - currencyCode: json['currencyCode'] as String? ?? '', - countryCode: json['countryCode'] as String? ?? '', - ); +SKPriceLocaleWrapper _$SKPriceLocaleWrapperFromJson(Map json) => SKPriceLocaleWrapper( + currencySymbol: json['currencySymbol'] as String? ?? '', + currencyCode: json['currencyCode'] as String? ?? '', + countryCode: json['countryCode'] as String? ?? '', +); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_request_maker.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_request_maker.dart index be73348dbe9a..4fa22a503dc8 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_request_maker.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_request_maker.dart @@ -25,11 +25,10 @@ class SKRequestMaker { /// /// [SkProductResponseWrapper] is returned if there is no error during the request. /// A [PlatformException] is thrown if the platform code making the request fails. - Future startProductRequest( - List productIdentifiers, - ) async { - final SKProductsResponseMessage productResponsePigeon = await hostApi - .startProductRequest(productIdentifiers); + Future startProductRequest(List productIdentifiers) async { + final SKProductsResponseMessage productResponsePigeon = await hostApi.startProductRequest( + productIdentifiers, + ); // should products be null or [] ? if (productResponsePigeon.products == null) { @@ -51,9 +50,7 @@ class SKRequestMaker { /// * isExpired: whether the receipt is expired. /// * isRevoked: whether the receipt has been revoked. /// * isVolumePurchase: whether the receipt is a Volume Purchase Plan receipt. - Future startRefreshReceiptRequest({ - Map? receiptProperties, - }) { + Future startRefreshReceiptRequest({Map? receiptProperties}) { return hostApi.refreshReceipt(receiptProperties: receiptProperties); } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.dart index c0da3a94bb79..4b2ae9c0e588 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.dart @@ -64,9 +64,6 @@ class SKStorefrontWrapper { /// Converts the pigeon equivalent to an instance of SKStorefrontWrapper static SKStorefrontWrapper convertFromPigeon(SKStorefrontMessage msg) { - return SKStorefrontWrapper( - countryCode: msg.countryCode, - identifier: msg.identifier, - ); + return SKStorefrontWrapper(countryCode: msg.countryCode, identifier: msg.identifier); } } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.g.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.g.dart index bb71ee2919be..37035b24e94d 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.g.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_storefront_wrapper.g.dart @@ -6,15 +6,12 @@ part of 'sk_storefront_wrapper.dart'; // JsonSerializableGenerator // ************************************************************************** -SKStorefrontWrapper _$SKStorefrontWrapperFromJson(Map json) => - SKStorefrontWrapper( - countryCode: json['countryCode'] as String, - identifier: json['identifier'] as String, - ); +SKStorefrontWrapper _$SKStorefrontWrapperFromJson(Map json) => SKStorefrontWrapper( + countryCode: json['countryCode'] as String, + identifier: json['identifier'] as String, +); -Map _$SKStorefrontWrapperToJson( - SKStorefrontWrapper instance, -) => { +Map _$SKStorefrontWrapperToJson(SKStorefrontWrapper instance) => { 'countryCode': instance.countryCode, 'identifier': instance.identifier, }; diff --git a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/sk2_purchase_param.dart b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/sk2_purchase_param.dart index d2946f640806..501196a000a7 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/sk2_purchase_param.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/lib/src/types/sk2_purchase_param.dart @@ -35,17 +35,11 @@ class Sk2PurchaseParam extends PurchaseParam { }) { switch (offer.type) { case SK2SubscriptionOfferType.winBack: - return Sk2PurchaseParam( - productDetails: productDetails, - winBackOfferId: offer.id, - ); + return Sk2PurchaseParam(productDetails: productDetails, winBackOfferId: offer.id); case SK2SubscriptionOfferType.promotional: return Sk2PurchaseParam( productDetails: productDetails, - promotionalOffer: SK2PromotionalOffer( - offerId: offer.id ?? '', - signature: signature!, - ), + promotionalOffer: SK2PromotionalOffer(offerId: offer.id ?? '', signature: signature!), ); case SK2SubscriptionOfferType.introductory: return Sk2PurchaseParam(productDetails: productDetails); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/pigeons/messages.dart b/packages/in_app_purchase/in_app_purchase_storekit/pigeons/messages.dart index 95b215cb5b61..9e45715230d6 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/pigeons/messages.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/pigeons/messages.dart @@ -93,11 +93,7 @@ class SKPaymentMessage { } class SKErrorMessage { - const SKErrorMessage({ - required this.code, - required this.domain, - required this.userInfo, - }); + const SKErrorMessage({required this.code, required this.domain, required this.userInfo}); final int code; final String domain; @@ -121,10 +117,7 @@ class SKPaymentDiscountMessage { } class SKStorefrontMessage { - const SKStorefrontMessage({ - required this.countryCode, - required this.identifier, - }); + const SKStorefrontMessage({required this.countryCode, required this.identifier}); final String countryCode; final String identifier; @@ -226,10 +219,7 @@ enum SKProductDiscountPaymentModeMessage { } class SKProductSubscriptionPeriodMessage { - SKProductSubscriptionPeriodMessage({ - required this.numberOfUnits, - required this.unit, - }); + SKProductSubscriptionPeriodMessage({required this.numberOfUnits, required this.unit}); final int numberOfUnits; final SKSubscriptionPeriodUnitMessage unit; @@ -249,9 +239,7 @@ abstract class InAppPurchaseAPI { void addPayment(Map paymentMap); @async - SKProductsResponseMessage startProductRequest( - List productIdentifiers, - ); + SKProductsResponseMessage startProductRequest(List productIdentifiers); void finishTransaction(Map finishMap); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/pigeons/sk2_pigeon.dart b/packages/in_app_purchase/in_app_purchase_storekit/pigeons/sk2_pigeon.dart index f318ec5277e0..be8eaa007396 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/pigeons/sk2_pigeon.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/pigeons/sk2_pigeon.dart @@ -28,11 +28,7 @@ enum SK2ProductTypeMessage { enum SK2SubscriptionOfferTypeMessage { introductory, promotional, winBack } -enum SK2SubscriptionOfferPaymentModeMessage { - payAsYouGo, - payUpFront, - freeTrial, -} +enum SK2SubscriptionOfferPaymentModeMessage { payAsYouGo, payUpFront, freeTrial } class SK2SubscriptionOfferMessage { const SK2SubscriptionOfferMessage({ @@ -120,10 +116,7 @@ class SK2ProductMessage { } class SK2PriceLocaleMessage { - SK2PriceLocaleMessage({ - required this.currencyCode, - required this.currencySymbol, - }); + SK2PriceLocaleMessage({required this.currencyCode, required this.currencySymbol}); final String currencyCode; final String currencySymbol; @@ -200,23 +193,14 @@ class SK2TransactionMessage { } class SK2ErrorMessage { - const SK2ErrorMessage({ - required this.code, - required this.domain, - required this.userInfo, - }); + const SK2ErrorMessage({required this.code, required this.domain, required this.userInfo}); final int code; final String domain; final Map? userInfo; } -enum SK2ProductPurchaseResultMessage { - success, - unverified, - userCancelled, - pending, -} +enum SK2ProductPurchaseResultMessage { success, unverified, userCancelled, pending } /// The status of a purchase transaction. /// Used to communicate the result state to Dart layer via purchaseStream. @@ -245,10 +229,7 @@ abstract class InAppPurchase2API { // https://developer.apple.com/documentation/storekit/product/3791971-purchase @async - SK2ProductPurchaseResultMessage purchase( - String id, { - SK2ProductPurchaseOptionsMessage? options, - }); + SK2ProductPurchaseResultMessage purchase(String id, {SK2ProductPurchaseOptionsMessage? options}); @async bool isWinBackOfferEligible(String productId, String offerId); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/fakes/fake_storekit_platform.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/fakes/fake_storekit_platform.dart index 517670f8c8ae..f8e84f847d8e 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/fakes/fake_storekit_platform.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/fakes/fake_storekit_platform.dart @@ -39,9 +39,7 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { validProductIDs = {'123', '456', '789'}; validProducts = {}; for (final String validID in validProductIDs) { - final Map productWrapperMap = buildProductMap( - dummyProductWrapper, - ); + final Map productWrapperMap = buildProductMap(dummyProductWrapper); productWrapperMap['productIdentifier'] = validID; if (validID == '456') { productWrapperMap['priceLocale'] = buildLocaleMap(noSymbolLocale); @@ -67,10 +65,7 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { _countryIdentifier = 'LL'; } - SKPaymentTransactionWrapper createPendingTransaction( - String id, { - int quantity = 1, - }) { + SKPaymentTransactionWrapper createPendingTransaction(String id, {int quantity = 1}) { return SKPaymentTransactionWrapper( transactionIdentifier: '', payment: SKPaymentWrapper(productIdentifier: id, quantity: quantity), @@ -85,26 +80,17 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { int quantity = 1, }) { return SKPaymentTransactionWrapper( - payment: SKPaymentWrapper( - productIdentifier: productId, - quantity: quantity, - ), + payment: SKPaymentWrapper(productIdentifier: productId, quantity: quantity), transactionState: SKPaymentTransactionStateWrapper.purchased, transactionTimeStamp: 123123.121, transactionIdentifier: transactionId, ); } - SKPaymentTransactionWrapper createFailedTransaction( - String productId, { - int quantity = 1, - }) { + SKPaymentTransactionWrapper createFailedTransaction(String productId, {int quantity = 1}) { return SKPaymentTransactionWrapper( transactionIdentifier: '', - payment: SKPaymentWrapper( - productIdentifier: productId, - quantity: quantity, - ), + payment: SKPaymentWrapper(productIdentifier: productId, quantity: quantity), transactionState: SKPaymentTransactionStateWrapper.failed, transactionTimeStamp: 123123.121, error: const SKError( @@ -122,10 +108,7 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { }) { return SKPaymentTransactionWrapper( transactionIdentifier: '', - payment: SKPaymentWrapper( - productIdentifier: productId, - quantity: quantity, - ), + payment: SKPaymentWrapper(productIdentifier: productId, quantity: quantity), transactionState: SKPaymentTransactionStateWrapper.failed, transactionTimeStamp: 123123.121, error: SKError( @@ -142,10 +125,7 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { int quantity = 1, }) { return SKPaymentTransactionWrapper( - payment: SKPaymentWrapper( - productIdentifier: productId, - quantity: quantity, - ), + payment: SKPaymentWrapper(productIdentifier: productId, quantity: quantity), transactionState: SKPaymentTransactionStateWrapper.restored, transactionTimeStamp: 123123.121, transactionIdentifier: transactionId, @@ -164,8 +144,7 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { // Keep the received paymentDiscount parameter when testing payment with discount. if (paymentMap['applicationUsername']! == 'userWithDiscount') { - final discountArgument = - paymentMap['paymentDiscount'] as Map?; + final discountArgument = paymentMap['paymentDiscount'] as Map?; if (discountArgument != null) { discountReceived = discountArgument.cast(); } else { @@ -182,48 +161,42 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { transactions: [transaction], ); if (testTransactionFail) { - final SKPaymentTransactionWrapper transactionFailed = - createFailedTransaction(id, quantity: quantity); + final SKPaymentTransactionWrapper transactionFailed = createFailedTransaction( + id, + quantity: quantity, + ); InAppPurchaseStoreKitPlatform.observer.updatedTransactions( transactions: [transactionFailed], ); } else if (testTransactionCancel > 0) { - final SKPaymentTransactionWrapper transactionCanceled = - createCanceledTransaction( - id, - testTransactionCancel, - quantity: quantity, - ); + final SKPaymentTransactionWrapper transactionCanceled = createCanceledTransaction( + id, + testTransactionCancel, + quantity: quantity, + ); InAppPurchaseStoreKitPlatform.observer.updatedTransactions( transactions: [transactionCanceled], ); } else { - final SKPaymentTransactionWrapper transactionFinished = - createPurchasedTransaction( - id, - transaction.transactionIdentifier ?? '', - quantity: quantity, - ); + final SKPaymentTransactionWrapper transactionFinished = createPurchasedTransaction( + id, + transaction.transactionIdentifier ?? '', + quantity: quantity, + ); InAppPurchaseStoreKitPlatform.observer.updatedTransactions( transactions: [transactionFinished], ); } } - void setStoreFrontInfo({ - required String countryCode, - required String identifier, - }) { + void setStoreFrontInfo({required String countryCode, required String identifier}) { _countryCode = countryCode; _countryIdentifier = identifier; } @override Future storefront() async { - return SKStorefrontMessage( - countryCode: _countryCode, - identifier: _countryIdentifier, - ); + return SKStorefrontMessage(countryCode: _countryCode, identifier: _countryIdentifier); } @override @@ -257,18 +230,13 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { return; } if (!testRestoredTransactionsNull) { - InAppPurchaseStoreKitPlatform.observer.updatedTransactions( - transactions: transactionList, - ); + InAppPurchaseStoreKitPlatform.observer.updatedTransactions(transactions: transactionList); } - InAppPurchaseStoreKitPlatform.observer - .paymentQueueRestoreCompletedTransactionsFinished(); + InAppPurchaseStoreKitPlatform.observer.paymentQueueRestoreCompletedTransactionsFinished(); } @override - Future startProductRequest( - List productIdentifiers, - ) { + Future startProductRequest(List productIdentifiers) { if (queryProductException != null) { throw queryProductException!; } @@ -360,8 +328,7 @@ class FakeStoreKit2Platform implements InAppPurchase2API { /// Simulates purchase result for testing non-success scenarios. /// Set to userCancelled, pending, or unverified to test those cases. - SK2ProductPurchaseResultMessage simulatedPurchaseResult = - SK2ProductPurchaseResultMessage.success; + SK2ProductPurchaseResultMessage simulatedPurchaseResult = SK2ProductPurchaseResultMessage.success; void reset() { validProductIDs = {'123', '456'}; @@ -445,8 +412,9 @@ class FakeStoreKit2Platform implements InAppPurchase2API { jsonRepresentation: 'jsonRepresentation', status: SK2PurchaseStatusMessage.purchased, ); - InAppPurchaseStoreKitPlatform.sk2TransactionObserver - .onTransactionsUpdated([transaction]); + InAppPurchaseStoreKitPlatform.sk2TransactionObserver.onTransactionsUpdated( + [transaction], + ); case SK2ProductPurchaseResultMessage.pending: // Create minimal message for pending status (without purchaseDate) final pendingTransaction = SK2TransactionMessage( @@ -455,8 +423,9 @@ class FakeStoreKit2Platform implements InAppPurchase2API { productId: id, status: SK2PurchaseStatusMessage.pending, ); - InAppPurchaseStoreKitPlatform.sk2TransactionObserver - .onTransactionsUpdated([pendingTransaction]); + InAppPurchaseStoreKitPlatform.sk2TransactionObserver.onTransactionsUpdated( + [pendingTransaction], + ); case SK2ProductPurchaseResultMessage.userCancelled: // Create minimal message for cancelled status (without purchaseDate) final cancelledTransaction = SK2TransactionMessage( @@ -465,15 +434,12 @@ class FakeStoreKit2Platform implements InAppPurchase2API { productId: id, status: SK2PurchaseStatusMessage.cancelled, ); - InAppPurchaseStoreKitPlatform.sk2TransactionObserver - .onTransactionsUpdated([ - cancelledTransaction, - ]); + InAppPurchaseStoreKitPlatform.sk2TransactionObserver.onTransactionsUpdated( + [cancelledTransaction], + ); } - return Future.value( - simulatedPurchaseResult, - ); + return Future.value(simulatedPurchaseResult); } @override @@ -521,9 +487,7 @@ class FakeStoreKit2Platform implements InAppPurchase2API { @override Future restorePurchases() async { - InAppPurchaseStoreKitPlatform.sk2TransactionObserver.onTransactionsUpdated( - transactionList, - ); + InAppPurchaseStoreKitPlatform.sk2TransactionObserver.onTransactionsUpdated(transactionList); } @override diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_2_platform_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_2_platform_test.dart index f143f84f41a3..883a6c468698 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_2_platform_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_2_platform_test.dart @@ -32,16 +32,12 @@ void main() { late InAppPurchaseStoreKitPlatform iapStoreKitPlatform; setUpAll(() { - setInAppPurchaseHostApis( - api: fakeStoreKitPlatform, - api2: fakeStoreKit2Platform, - ); + setInAppPurchaseHostApis(api: fakeStoreKitPlatform, api2: fakeStoreKit2Platform); }); setUp(() { InAppPurchaseStoreKitPlatform.registerPlatform(); - iapStoreKitPlatform = - InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform; + iapStoreKitPlatform = InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform; fakeStoreKit2Platform.reset(); }); @@ -56,8 +52,11 @@ void main() { group('query product list', () { test('should get product list and correct invalid identifiers', () async { final connection = InAppPurchaseStoreKitPlatform(); - final ProductDetailsResponse response = await connection - .queryProductDetails({'123', '456', '789'}); + final ProductDetailsResponse response = await connection.queryProductDetails({ + '123', + '456', + '789', + }); final List products = response.productDetails; expect(products.first.id, '123'); expect(products[1].id, '456'); @@ -66,26 +65,26 @@ void main() { expect(response.productDetails.first.currencySymbol, r'$'); expect(response.productDetails[1].currencySymbol, r'$'); }); - test( - 'if query products throws error, should get error object in the response', - () async { - fakeStoreKit2Platform.queryProductException = PlatformException( - code: 'error_code', - message: 'error_message', - details: {'info': 'error_info'}, - ); - final connection = InAppPurchaseStoreKitPlatform(); - final ProductDetailsResponse response = await connection - .queryProductDetails({'123', '456', '789'}); - expect(response.productDetails, []); - expect(response.notFoundIDs, ['123', '456', '789']); - expect(response.error, isNotNull); - expect(response.error!.source, kIAPSource); - expect(response.error!.code, 'error_code'); - expect(response.error!.message, 'error_message'); - expect(response.error!.details, {'info': 'error_info'}); - }, - ); + test('if query products throws error, should get error object in the response', () async { + fakeStoreKit2Platform.queryProductException = PlatformException( + code: 'error_code', + message: 'error_message', + details: {'info': 'error_info'}, + ); + final connection = InAppPurchaseStoreKitPlatform(); + final ProductDetailsResponse response = await connection.queryProductDetails({ + '123', + '456', + '789', + }); + expect(response.productDetails, []); + expect(response.notFoundIDs, ['123', '456', '789']); + expect(response.error, isNotNull); + expect(response.error!.source, kIAPSource); + expect(response.error!.code, 'error_code'); + expect(response.error!.message, 'error_message'); + expect(response.error!.details, {'info': 'error_info'}); + }); }); group('make payment', () { @@ -94,13 +93,10 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); if (purchaseDetailsList.first.status == PurchaseStatus.purchased) { completer.complete(details); @@ -108,14 +104,10 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), applicationUserName: 'appName', ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); final List result = await completer.future; expect(result.length, 1); @@ -130,13 +122,10 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); if (purchaseDetailsList.first.status == PurchaseStatus.purchased) { completer.complete(details); @@ -144,9 +133,7 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), applicationUserName: 'appName', ); await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); @@ -159,16 +146,11 @@ void main() { test('buying consumable, should throw when autoConsume is false', () async { final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), applicationUserName: 'appName', ); expect( - () => iapStoreKitPlatform.buyConsumable( - purchaseParam: purchaseParam, - autoConsume: false, - ), + () => iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam, autoConsume: false), throwsA(isInstanceOf()), ); }); @@ -178,13 +160,10 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late final StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); if (purchaseDetailsList.first.status == PurchaseStatus.purchased) { completer.complete(details); @@ -192,9 +171,7 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), applicationUserName: 'appName', ); await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); @@ -202,26 +179,15 @@ void main() { final List result = await completer.future; expect(result.length, 1); expect(result.first.productID, dummyProductWrapper.id); - expect( - result.first.verificationData.serverVerificationData, - 'receiptData', - ); - expect( - result.first.verificationData.localVerificationData, - 'jsonRepresentation', - ); - expect( - (result.first as SK2PurchaseDetails).appAccountToken, - 'appAccountToken', - ); + expect(result.first.verificationData.serverVerificationData, 'receiptData'); + expect(result.first.verificationData.localVerificationData, 'jsonRepresentation'); + expect((result.first as SK2PurchaseDetails).appAccountToken, 'appAccountToken'); }, ); test('should process Sk2PurchaseParam with winBackOfferId only', () async { final purchaseParam = Sk2PurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), applicationUserName: 'testUser', winBackOfferId: 'winBack123', ); @@ -237,224 +203,158 @@ void main() { expect(lastPurchaseOptions.promotionalOffer, isNull); }); - test( - 'should process Sk2PurchaseParam with promotionalOffer only', - () async { - final fakeSignature = SK2SubscriptionOfferSignature( - keyID: 'key123', - signature: 'signature123', - nonce: 'nonce123', - timestamp: 1234567890, - ); + test('should process Sk2PurchaseParam with promotionalOffer only', () async { + final fakeSignature = SK2SubscriptionOfferSignature( + keyID: 'key123', + signature: 'signature123', + nonce: 'nonce123', + timestamp: 1234567890, + ); - final purchaseParam = Sk2PurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), - applicationUserName: 'testUser', - quantity: 2, - promotionalOffer: SK2PromotionalOffer( - signature: fakeSignature, - offerId: 'promo123', - ), - ); + final purchaseParam = Sk2PurchaseParam( + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), + applicationUserName: 'testUser', + quantity: 2, + promotionalOffer: SK2PromotionalOffer(signature: fakeSignature, offerId: 'promo123'), + ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); - final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = - fakeStoreKit2Platform.lastPurchaseOptions!; + final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = + fakeStoreKit2Platform.lastPurchaseOptions!; - expect(lastPurchaseOptions.appAccountToken, 'testUser'); - expect(lastPurchaseOptions.quantity, 2); - expect( - lastPurchaseOptions.promotionalOffer!.promotionalOfferId, - 'promo123', - ); - expect( - lastPurchaseOptions.promotionalOffer!.promotionalOfferSignature.keyID, - 'key123', - ); - expect(lastPurchaseOptions.winBackOfferId, isNull); - }, - ); + expect(lastPurchaseOptions.appAccountToken, 'testUser'); + expect(lastPurchaseOptions.quantity, 2); + expect(lastPurchaseOptions.promotionalOffer!.promotionalOfferId, 'promo123'); + expect(lastPurchaseOptions.promotionalOffer!.promotionalOfferSignature.keyID, 'key123'); + expect(lastPurchaseOptions.winBackOfferId, isNull); + }); - test( - 'should process Sk2PurchaseParam with no winBackOfferId or promotionalOffer', - () async { - final purchaseParam = Sk2PurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), - applicationUserName: 'testUser', - ); + test('should process Sk2PurchaseParam with no winBackOfferId or promotionalOffer', () async { + final purchaseParam = Sk2PurchaseParam( + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), + applicationUserName: 'testUser', + ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); - final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = - fakeStoreKit2Platform.lastPurchaseOptions!; + final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = + fakeStoreKit2Platform.lastPurchaseOptions!; - expect(lastPurchaseOptions.appAccountToken, 'testUser'); - expect(lastPurchaseOptions.quantity, 1); - expect(lastPurchaseOptions.winBackOfferId, isNull); - expect(lastPurchaseOptions.promotionalOffer, isNull); - }, - ); + expect(lastPurchaseOptions.appAccountToken, 'testUser'); + expect(lastPurchaseOptions.quantity, 1); + expect(lastPurchaseOptions.winBackOfferId, isNull); + expect(lastPurchaseOptions.promotionalOffer, isNull); + }); - test( - 'should pass quantity for consumable product with Sk2PurchaseParam', - () async { - final purchaseParam = Sk2PurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), - quantity: 3, - applicationUserName: 'testUser', - ); + test('should pass quantity for consumable product with Sk2PurchaseParam', () async { + final purchaseParam = Sk2PurchaseParam( + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), + quantity: 3, + applicationUserName: 'testUser', + ); - await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); + await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); - final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = - fakeStoreKit2Platform.lastPurchaseOptions!; + final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = + fakeStoreKit2Platform.lastPurchaseOptions!; - expect(lastPurchaseOptions.appAccountToken, 'testUser'); - expect(lastPurchaseOptions.quantity, 3); - expect(lastPurchaseOptions.winBackOfferId, isNull); - expect(lastPurchaseOptions.promotionalOffer, isNull); - }, - ); + expect(lastPurchaseOptions.appAccountToken, 'testUser'); + expect(lastPurchaseOptions.quantity, 3); + expect(lastPurchaseOptions.winBackOfferId, isNull); + expect(lastPurchaseOptions.promotionalOffer, isNull); + }); - test( - 'should default to quantity = 1 when not provided in Sk2PurchaseParam', - () async { - final purchaseParam = Sk2PurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), - applicationUserName: 'testUser', - ); + test('should default to quantity = 1 when not provided in Sk2PurchaseParam', () async { + final purchaseParam = Sk2PurchaseParam( + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), + applicationUserName: 'testUser', + ); - await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); + await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); - final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = - fakeStoreKit2Platform.lastPurchaseOptions!; + final SK2ProductPurchaseOptionsMessage lastPurchaseOptions = + fakeStoreKit2Platform.lastPurchaseOptions!; - expect(lastPurchaseOptions.quantity, 1); - }, - ); + expect(lastPurchaseOptions.quantity, 1); + }); - test( - 'user cancelled purchase should emit canceled status to purchaseStream', - () async { - fakeStoreKit2Platform.simulatedPurchaseResult = - SK2ProductPurchaseResultMessage.userCancelled; + test('user cancelled purchase should emit canceled status to purchaseStream', () async { + fakeStoreKit2Platform.simulatedPurchaseResult = SK2ProductPurchaseResultMessage.userCancelled; - final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final completer = Completer>(); + final Stream> stream = iapStoreKitPlatform.purchaseStream; - late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { - completer.complete(purchaseDetailsList); - subscription.cancel(); - }); + late StreamSubscription> subscription; + subscription = stream.listen((List purchaseDetailsList) { + completer.complete(purchaseDetailsList); + subscription.cancel(); + }); - final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), - applicationUserName: 'appName', - ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + final purchaseParam = AppStorePurchaseParam( + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), + applicationUserName: 'appName', + ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); - final List result = await completer.future; - expect(result.length, 1); - expect(result.first.productID, dummyProductWrapper.id); - expect(result.first.status, PurchaseStatus.canceled); - expect(result.first.pendingCompletePurchase, false); - }, - ); + final List result = await completer.future; + expect(result.length, 1); + expect(result.first.productID, dummyProductWrapper.id); + expect(result.first.status, PurchaseStatus.canceled); + expect(result.first.pendingCompletePurchase, false); + }); - test( - 'pending purchase should emit pending status to purchaseStream', - () async { - fakeStoreKit2Platform.simulatedPurchaseResult = - SK2ProductPurchaseResultMessage.pending; + test('pending purchase should emit pending status to purchaseStream', () async { + fakeStoreKit2Platform.simulatedPurchaseResult = SK2ProductPurchaseResultMessage.pending; - final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final completer = Completer>(); + final Stream> stream = iapStoreKitPlatform.purchaseStream; - late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { - completer.complete(purchaseDetailsList); - subscription.cancel(); - }); + late StreamSubscription> subscription; + subscription = stream.listen((List purchaseDetailsList) { + completer.complete(purchaseDetailsList); + subscription.cancel(); + }); - final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), - applicationUserName: 'appName', - ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + final purchaseParam = AppStorePurchaseParam( + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), + applicationUserName: 'appName', + ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); - final List result = await completer.future; - expect(result.length, 1); - expect(result.first.productID, dummyProductWrapper.id); - expect(result.first.status, PurchaseStatus.pending); - expect(result.first.pendingCompletePurchase, false); - }, - ); + final List result = await completer.future; + expect(result.length, 1); + expect(result.first.productID, dummyProductWrapper.id); + expect(result.first.status, PurchaseStatus.pending); + expect(result.first.pendingCompletePurchase, false); + }); - test( - 'unverified purchase should receive transaction with purchased status', - () async { - fakeStoreKit2Platform.simulatedPurchaseResult = - SK2ProductPurchaseResultMessage.unverified; + test('unverified purchase should receive transaction with purchased status', () async { + fakeStoreKit2Platform.simulatedPurchaseResult = SK2ProductPurchaseResultMessage.unverified; - final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final completer = Completer>(); + final Stream> stream = iapStoreKitPlatform.purchaseStream; - late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { - completer.complete(purchaseDetailsList); - subscription.cancel(); - }); + late StreamSubscription> subscription; + subscription = stream.listen((List purchaseDetailsList) { + completer.complete(purchaseDetailsList); + subscription.cancel(); + }); - final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProduct2Details.fromSK2Product( - dummyProductWrapper, - ), - applicationUserName: 'appName', - ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + final purchaseParam = AppStorePurchaseParam( + productDetails: AppStoreProduct2Details.fromSK2Product(dummyProductWrapper), + applicationUserName: 'appName', + ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); - final List result = await completer.future; - expect(result.length, 1); - expect(result.first.productID, dummyProductWrapper.id); - // Native side sends the transaction for unverified case - // The transaction comes with purchased status from native side - expect(result.first.status, PurchaseStatus.purchased); - expect(result.first.pendingCompletePurchase, true); - }, - ); + final List result = await completer.future; + expect(result.length, 1); + expect(result.first.productID, dummyProductWrapper.id); + // Native side sends the transaction for unverified case + // The transaction comes with purchased status from native side + expect(result.first.status, PurchaseStatus.purchased); + expect(result.first.pendingCompletePurchase, true); + }); }); group('restore purchases', () { @@ -466,8 +366,7 @@ void main() { fakeStoreKit2Platform.createRestoredTransaction('foo', 'RT2'), ); final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; subscription = stream.listen((List purchaseDetailsList) { @@ -482,8 +381,7 @@ void main() { expect(details.length, 2); for (var i = 0; i < fakeStoreKit2Platform.transactionList.length; i++) { - final SK2TransactionMessage expected = - fakeStoreKit2Platform.transactionList[i]; + final SK2TransactionMessage expected = fakeStoreKit2Platform.transactionList[i]; final PurchaseDetails actual = details[i]; expect(actual.purchaseID, expected.id.toString()); @@ -515,9 +413,7 @@ void main() { test('should return true when offer is eligible', () async { fakeStoreKit2Platform.validProductIDs = {'sub1'}; - fakeStoreKit2Platform.eligibleWinBackOffers['sub1'] = { - 'winback1', - }; + fakeStoreKit2Platform.eligibleWinBackOffers['sub1'] = {'winback1'}; fakeStoreKit2Platform.validProducts['sub1'] = SK2Product( id: 'sub1', displayName: 'Subscription', @@ -536,10 +432,7 @@ void main() { priceLocale: SK2PriceLocale(currencyCode: 'USD', currencySymbol: r'$'), ); - final bool result = await iapStoreKitPlatform.isWinBackOfferEligible( - 'sub1', - 'winback1', - ); + final bool result = await iapStoreKitPlatform.isWinBackOfferEligible('sub1', 'winback1'); expect(result, isTrue); }); @@ -565,20 +458,14 @@ void main() { priceLocale: SK2PriceLocale(currencyCode: 'USD', currencySymbol: r'$'), ); - final bool result = await iapStoreKitPlatform.isWinBackOfferEligible( - 'sub1', - 'winback1', - ); + final bool result = await iapStoreKitPlatform.isWinBackOfferEligible('sub1', 'winback1'); expect(result, isFalse); }); test('should throw product not found error for invalid product', () async { expect( - () => iapStoreKitPlatform.isWinBackOfferEligible( - 'invalid_product', - 'winback1', - ), + () => iapStoreKitPlatform.isWinBackOfferEligible('invalid_product', 'winback1'), throwsA( isA().having( (PlatformException e) => e.code, @@ -589,56 +476,44 @@ void main() { ); }); - test( - 'should throw subscription error for non-subscription product', - () async { - fakeStoreKit2Platform.validProductIDs = {'consumable1'}; - fakeStoreKit2Platform.validProducts['consumable1'] = SK2Product( - id: 'consumable1', - displayName: 'Coins', - displayPrice: r'$0.99', - description: 'Game currency', - price: 0.99, - type: SK2ProductType.consumable, - priceLocale: SK2PriceLocale( - currencyCode: 'USD', - currencySymbol: r'$', - ), - ); + test('should throw subscription error for non-subscription product', () async { + fakeStoreKit2Platform.validProductIDs = {'consumable1'}; + fakeStoreKit2Platform.validProducts['consumable1'] = SK2Product( + id: 'consumable1', + displayName: 'Coins', + displayPrice: r'$0.99', + description: 'Game currency', + price: 0.99, + type: SK2ProductType.consumable, + priceLocale: SK2PriceLocale(currencyCode: 'USD', currencySymbol: r'$'), + ); - expect( - () => iapStoreKitPlatform.isWinBackOfferEligible( - 'consumable1', - 'winback1', - ), - throwsA( - isA().having( - (PlatformException e) => e.code, - 'code', - 'storekit2_not_subscription', - ), + expect( + () => iapStoreKitPlatform.isWinBackOfferEligible('consumable1', 'winback1'), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'storekit2_not_subscription', ), - ); - }, - ); + ), + ); + }); - test( - 'should throw platform exception when StoreKit2 is not supported', - () async { - await InAppPurchaseStoreKitPlatform.enableStoreKit1(); - - expect( - () => iapStoreKitPlatform.isWinBackOfferEligible('sub1', 'winback1'), - throwsA( - isA().having( - (PlatformException e) => e.code, - 'code', - 'storekit2_not_enabled', - ), + test('should throw platform exception when StoreKit2 is not supported', () async { + await InAppPurchaseStoreKitPlatform.enableStoreKit1(); + + expect( + () => iapStoreKitPlatform.isWinBackOfferEligible('sub1', 'winback1'), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'storekit2_not_enabled', ), - ); - }, - ); + ), + ); + }); }); group('introductory offers eligibility', () { @@ -672,50 +547,40 @@ void main() { priceLocale: SK2PriceLocale(currencyCode: 'USD', currencySymbol: r'$'), ); - final bool result = await iapStoreKitPlatform.isIntroductoryOfferEligible( - 'sub1', - ); + final bool result = await iapStoreKitPlatform.isIntroductoryOfferEligible('sub1'); expect(result, isTrue); }); - test( - 'should return false when introductory offer is not eligible', - () async { - fakeStoreKit2Platform.validProductIDs = {'sub1'}; - fakeStoreKit2Platform.eligibleIntroductoryOffers['sub1'] = false; - fakeStoreKit2Platform.validProducts['sub1'] = SK2Product( - id: 'sub1', - displayName: 'Subscription', - displayPrice: r'$9.99', - description: 'Monthly subscription', - price: 9.99, - type: SK2ProductType.autoRenewable, - subscription: const SK2SubscriptionInfo( - subscriptionGroupID: 'group1', - promotionalOffers: [], - subscriptionPeriod: SK2SubscriptionPeriod( - value: 1, - unit: SK2SubscriptionPeriodUnit.month, - ), - ), - priceLocale: SK2PriceLocale( - currencyCode: 'USD', - currencySymbol: r'$', + test('should return false when introductory offer is not eligible', () async { + fakeStoreKit2Platform.validProductIDs = {'sub1'}; + fakeStoreKit2Platform.eligibleIntroductoryOffers['sub1'] = false; + fakeStoreKit2Platform.validProducts['sub1'] = SK2Product( + id: 'sub1', + displayName: 'Subscription', + displayPrice: r'$9.99', + description: 'Monthly subscription', + price: 9.99, + type: SK2ProductType.autoRenewable, + subscription: const SK2SubscriptionInfo( + subscriptionGroupID: 'group1', + promotionalOffers: [], + subscriptionPeriod: SK2SubscriptionPeriod( + value: 1, + unit: SK2SubscriptionPeriodUnit.month, ), - ); + ), + priceLocale: SK2PriceLocale(currencyCode: 'USD', currencySymbol: r'$'), + ); - final bool result = await iapStoreKitPlatform - .isIntroductoryOfferEligible('sub1'); + final bool result = await iapStoreKitPlatform.isIntroductoryOfferEligible('sub1'); - expect(result, isFalse); - }, - ); + expect(result, isFalse); + }); test('should throw product not found error for invalid product', () async { expect( - () => - iapStoreKitPlatform.isIntroductoryOfferEligible('invalid_product'), + () => iapStoreKitPlatform.isIntroductoryOfferEligible('invalid_product'), throwsA( isA().having( (PlatformException e) => e.code, @@ -726,80 +591,65 @@ void main() { ); }); - test( - 'should throw subscription error for non-subscription product', - () async { - fakeStoreKit2Platform.validProductIDs = {'consumable1'}; - fakeStoreKit2Platform.validProducts['consumable1'] = SK2Product( - id: 'consumable1', - displayName: 'Coins', - displayPrice: r'$0.99', - description: 'Game currency', - price: 0.99, - type: SK2ProductType.consumable, - priceLocale: SK2PriceLocale( - currencyCode: 'USD', - currencySymbol: r'$', - ), - ); + test('should throw subscription error for non-subscription product', () async { + fakeStoreKit2Platform.validProductIDs = {'consumable1'}; + fakeStoreKit2Platform.validProducts['consumable1'] = SK2Product( + id: 'consumable1', + displayName: 'Coins', + displayPrice: r'$0.99', + description: 'Game currency', + price: 0.99, + type: SK2ProductType.consumable, + priceLocale: SK2PriceLocale(currencyCode: 'USD', currencySymbol: r'$'), + ); - expect( - () => iapStoreKitPlatform.isIntroductoryOfferEligible('consumable1'), - throwsA( - isA().having( - (PlatformException e) => e.code, - 'code', - 'storekit2_not_subscription', - ), + expect( + () => iapStoreKitPlatform.isIntroductoryOfferEligible('consumable1'), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'storekit2_not_subscription', ), - ); - }, - ); + ), + ); + }); - test( - 'should throw platform exception when StoreKit2 is not supported', - () async { - await InAppPurchaseStoreKitPlatform.enableStoreKit1(); - - expect( - () => iapStoreKitPlatform.isIntroductoryOfferEligible('sub1'), - throwsA( - isA().having( - (PlatformException e) => e.code, - 'code', - 'storekit2_not_enabled', - ), + test('should throw platform exception when StoreKit2 is not supported', () async { + await InAppPurchaseStoreKitPlatform.enableStoreKit1(); + + expect( + () => iapStoreKitPlatform.isIntroductoryOfferEligible('sub1'), + throwsA( + isA().having( + (PlatformException e) => e.code, + 'code', + 'storekit2_not_enabled', ), - ); - }, - ); + ), + ); + }); }); group('unfinished transactions', () { test('should return unfinished transactions', () async { - final List transactions = - await SK2Transaction.unfinishedTransactions(); + final List transactions = await SK2Transaction.unfinishedTransactions(); expect(transactions, isNotEmpty); expect(transactions.first.id, '123'); expect(transactions.first.productId, 'product_id'); }); - test( - 'should expose receiptData (JWS) in unfinished transactions', - () async { - final List transactions = - await SK2Transaction.unfinishedTransactions(); + test('should expose receiptData (JWS) in unfinished transactions', () async { + final List transactions = await SK2Transaction.unfinishedTransactions(); - expect(transactions, isNotEmpty); - expect(transactions.first.receiptData, isNotNull); - expect(transactions.first.receiptData, 'fake_jws_representation'); - }, - ); + expect(transactions, isNotEmpty); + expect(transactions.first.receiptData, isNotNull); + expect(transactions.first.receiptData, 'fake_jws_representation'); + }); test('should expose appAccountToken in unfinished transactions', () async { - final List transactions = - await SK2Transaction.unfinishedTransactions(); + final List transactions = await SK2Transaction.unfinishedTransactions(); expect(transactions, isNotEmpty); expect(transactions.first.appAccountToken, isNotNull); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart index b73b62681392..4e6b75424293 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_addtion_test.dart @@ -20,18 +20,14 @@ void main() { group('present code redemption sheet', () { test('null', () async { - expect( - InAppPurchaseStoreKitPlatformAddition().presentCodeRedemptionSheet(), - completes, - ); + expect(InAppPurchaseStoreKitPlatformAddition().presentCodeRedemptionSheet(), completes); }); }); group('refresh receipt data', () { test('should refresh receipt data', () async { - final PurchaseVerificationData? receiptData = - await InAppPurchaseStoreKitPlatformAddition() - .refreshPurchaseVerificationData(); + final PurchaseVerificationData? receiptData = await InAppPurchaseStoreKitPlatformAddition() + .refreshPurchaseVerificationData(); expect(receiptData, isNotNull); expect(receiptData!.source, kIAPSource); expect(receiptData.localVerificationData, 'refreshed receipt data'); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart index b22a023058bf..6a71a79e4a1c 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/in_app_purchase_storekit_platform_test.dart @@ -28,8 +28,7 @@ void main() { setUp(() { InAppPurchaseStoreKitPlatform.enableStoreKit1(); InAppPurchaseStoreKitPlatform.registerPlatform(); - iapStoreKitPlatform = - InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform; + iapStoreKitPlatform = InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform; fakeStoreKitPlatform.reset(); }); @@ -44,8 +43,12 @@ void main() { group('query product list', () { test('should get product list and correct invalid identifiers', () async { final connection = InAppPurchaseStoreKitPlatform(); - final ProductDetailsResponse response = await connection - .queryProductDetails({'123', '456', '789', '999'}); + final ProductDetailsResponse response = await connection.queryProductDetails({ + '123', + '456', + '789', + '999', + }); final List products = response.productDetails; expect(products.first.id, '123'); expect(products[1].id, '456'); @@ -57,26 +60,26 @@ void main() { expect(response.productDetails[1].currencySymbol, 'EUR'); }); - test( - 'if query products throws error, should get error object in the response', - () async { - fakeStoreKitPlatform.queryProductException = PlatformException( - code: 'error_code', - message: 'error_message', - details: {'info': 'error_info'}, - ); - final connection = InAppPurchaseStoreKitPlatform(); - final ProductDetailsResponse response = await connection - .queryProductDetails({'123', '456', '789'}); - expect(response.productDetails, []); - expect(response.notFoundIDs, ['123', '456', '789']); - expect(response.error, isNotNull); - expect(response.error!.source, kIAPSource); - expect(response.error!.code, 'error_code'); - expect(response.error!.message, 'error_message'); - expect(response.error!.details, {'info': 'error_info'}); - }, - ); + test('if query products throws error, should get error object in the response', () async { + fakeStoreKitPlatform.queryProductException = PlatformException( + code: 'error_code', + message: 'error_message', + details: {'info': 'error_info'}, + ); + final connection = InAppPurchaseStoreKitPlatform(); + final ProductDetailsResponse response = await connection.queryProductDetails({ + '123', + '456', + '789', + }); + expect(response.productDetails, []); + expect(response.notFoundIDs, ['123', '456', '789']); + expect(response.error, isNotNull); + expect(response.error!.source, kIAPSource); + expect(response.error!.code, 'error_code'); + expect(response.error!.message, 'error_message'); + expect(response.error!.details, {'info': 'error_info'}); + }); }); group('restore purchases', () { @@ -90,8 +93,7 @@ void main() { fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'), ); final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; subscription = stream.listen((List purchaseDetailsList) { @@ -106,21 +108,14 @@ void main() { expect(details.length, 2); for (var i = 0; i < fakeStoreKitPlatform.transactionList.length; i++) { - final SKPaymentTransactionWrapper expected = - fakeStoreKitPlatform.transactionList[i]; + final SKPaymentTransactionWrapper expected = fakeStoreKitPlatform.transactionList[i]; final PurchaseDetails actual = details[i]; expect(actual.purchaseID, expected.transactionIdentifier); expect(actual.verificationData, isNotNull); expect(actual.status, PurchaseStatus.restored); - expect( - actual.verificationData.localVerificationData, - fakeStoreKitPlatform.receiptData, - ); - expect( - actual.verificationData.serverVerificationData, - fakeStoreKitPlatform.receiptData, - ); + expect(actual.verificationData.localVerificationData, fakeStoreKitPlatform.receiptData); + expect(actual.verificationData.serverVerificationData, fakeStoreKitPlatform.receiptData); expect(actual.pendingCompletePurchase, true); } }); @@ -130,13 +125,10 @@ void main() { () async { fakeStoreKitPlatform.testRestoredTransactionsNull = true; final completer = Completer?>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { expect(purchaseDetailsList.isEmpty, true); subscription.cancel(); completer.complete(); @@ -161,8 +153,7 @@ void main() { fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'), ); final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; subscription = stream.listen((List purchaseDetailsList) { @@ -175,8 +166,7 @@ void main() { final List details = await completer.future; expect(details.length, 3); for (var i = 0; i < fakeStoreKitPlatform.transactionList.length; i++) { - final SKPaymentTransactionWrapper expected = - fakeStoreKitPlatform.transactionList[i]; + final SKPaymentTransactionWrapper expected = fakeStoreKitPlatform.transactionList[i]; final PurchaseDetails actual = details[i]; expect(actual.purchaseID, expected.transactionIdentifier); @@ -188,14 +178,8 @@ void main() { expected.error, ), ); - expect( - actual.verificationData.localVerificationData, - fakeStoreKitPlatform.receiptData, - ); - expect( - actual.verificationData.serverVerificationData, - fakeStoreKitPlatform.receiptData, - ); + expect(actual.verificationData.localVerificationData, fakeStoreKitPlatform.receiptData); + expect(actual.verificationData.serverVerificationData, fakeStoreKitPlatform.receiptData); expect(actual.pendingCompletePurchase, true); } }); @@ -208,14 +192,11 @@ void main() { fakeStoreKitPlatform.createPurchasedTransaction('foo', 'bar'), ); final completer = Completer>>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; final purchaseDetails = >[]; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { purchaseDetails.add(purchaseDetailsList); if (purchaseDetails.length == 2) { @@ -228,8 +209,7 @@ void main() { expect(details.length, 2); expect(details[0], >[]); for (var i = 0; i < fakeStoreKitPlatform.transactionList.length; i++) { - final SKPaymentTransactionWrapper expected = - fakeStoreKitPlatform.transactionList[i]; + final SKPaymentTransactionWrapper expected = fakeStoreKitPlatform.transactionList[i]; final PurchaseDetails actual = details[1][i]; expect(actual.purchaseID, expected.transactionIdentifier); @@ -241,54 +221,42 @@ void main() { expected.error, ), ); - expect( - actual.verificationData.localVerificationData, - fakeStoreKitPlatform.receiptData, - ); - expect( - actual.verificationData.serverVerificationData, - fakeStoreKitPlatform.receiptData, - ); + expect(actual.verificationData.localVerificationData, fakeStoreKitPlatform.receiptData); + expect(actual.verificationData.serverVerificationData, fakeStoreKitPlatform.receiptData); expect(actual.pendingCompletePurchase, true); } }, ); - test( - 'receipt error should populate null to verificationData.data', - () async { - fakeStoreKitPlatform.transactionList.insert( - 0, - fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'), - ); - fakeStoreKitPlatform.transactionList.insert( - 1, - fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'), - ); - fakeStoreKitPlatform.receiptData = null; - final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + test('receipt error should populate null to verificationData.data', () async { + fakeStoreKitPlatform.transactionList.insert( + 0, + fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT1'), + ); + fakeStoreKitPlatform.transactionList.insert( + 1, + fakeStoreKitPlatform.createRestoredTransaction('foo', 'RT2'), + ); + fakeStoreKitPlatform.receiptData = null; + final completer = Completer>(); + final Stream> stream = iapStoreKitPlatform.purchaseStream; - late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { - if (purchaseDetailsList.first.status == PurchaseStatus.restored) { - completer.complete(purchaseDetailsList); - subscription.cancel(); - } - }); + late StreamSubscription> subscription; + subscription = stream.listen((List purchaseDetailsList) { + if (purchaseDetailsList.first.status == PurchaseStatus.restored) { + completer.complete(purchaseDetailsList); + subscription.cancel(); + } + }); - await iapStoreKitPlatform.restorePurchases(); - final List details = await completer.future; + await iapStoreKitPlatform.restorePurchases(); + final List details = await completer.future; - for (final purchase in details) { - expect(purchase.verificationData.localVerificationData, isEmpty); - expect(purchase.verificationData.serverVerificationData, isEmpty); - } - }, - ); + for (final purchase in details) { + expect(purchase.verificationData.localVerificationData, isEmpty); + expect(purchase.verificationData.serverVerificationData, isEmpty); + } + }); test('test restore error', () { fakeStoreKitPlatform.testRestoredError = const SKError( @@ -303,11 +271,9 @@ void main() { isA() .having((SKError error) => error.code, 'code', 123) .having((SKError error) => error.domain, 'domain', 'error_test') - .having( - (SKError error) => error.userInfo, - 'userInfo', - {'message': 'errorMessage'}, - ), + .having((SKError error) => error.userInfo, 'userInfo', { + 'message': 'errorMessage', + }), ), ); }); @@ -319,13 +285,10 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); if (purchaseDetailsList.first.status == PurchaseStatus.purchased) { completer.complete(details); @@ -333,14 +296,10 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'appName', ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); final List result = await completer.future; expect(result.length, 2); @@ -353,13 +312,10 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); if (purchaseDetailsList.first.status == PurchaseStatus.purchased) { completer.complete(details); @@ -367,9 +323,7 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'appName', ); await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); @@ -382,16 +336,11 @@ void main() { test('buying consumable, should throw when autoConsume is false', () async { final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'appName', ); expect( - () => iapStoreKitPlatform.buyConsumable( - purchaseParam: purchaseParam, - autoConsume: false, - ), + () => iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam, autoConsume: false), throwsA(isInstanceOf()), ); }); @@ -402,8 +351,7 @@ void main() { final completer = Completer(); late IAPError error; - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); @@ -416,9 +364,7 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'appName', ); await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); @@ -427,9 +373,7 @@ void main() { expect(completerError.code, 'purchase_error'); expect(completerError.source, kIAPSource); expect(completerError.message, 'ios_domain'); - expect(completerError.details, { - 'message': 'an error message', - }); + expect(completerError.details, {'message': 'an error message'}); }); test( @@ -439,12 +383,9 @@ void main() { final details = []; final completer = Completer(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); for (final purchaseDetails in purchaseDetailsList) { if (purchaseDetails.status == PurchaseStatus.canceled) { @@ -454,14 +395,10 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'appName', ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); final PurchaseStatus purchaseStatus = await completer.future; expect(purchaseStatus, PurchaseStatus.canceled); @@ -475,12 +412,9 @@ void main() { final details = []; final completer = Completer(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); for (final purchaseDetails in purchaseDetailsList) { if (purchaseDetails.status == PurchaseStatus.canceled) { @@ -490,14 +424,10 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'appName', ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); final PurchaseStatus purchaseStatus = await completer.future; expect(purchaseStatus, PurchaseStatus.canceled); @@ -509,12 +439,9 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); for (final purchaseDetails in purchaseDetailsList) { if (purchaseDetails.pendingCompletePurchase) { @@ -524,22 +451,15 @@ void main() { } } }); - final productDetails = AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ); + final productDetails = AppStoreProductDetails.fromSKProduct(dummyProductWrapper); final purchaseParam = AppStorePurchaseParam( productDetails: productDetails, quantity: 5, applicationUserName: 'appName', ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); await completer.future; - expect( - fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, - 5, - ); + expect(fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, 5); }, ); @@ -548,12 +468,9 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); for (final purchaseDetails in purchaseDetailsList) { if (purchaseDetails.pendingCompletePurchase) { @@ -563,9 +480,7 @@ void main() { } } }); - final productDetails = AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ); + final productDetails = AppStoreProductDetails.fromSKProduct(dummyProductWrapper); final purchaseParam = AppStorePurchaseParam( productDetails: productDetails, quantity: 5, @@ -573,10 +488,7 @@ void main() { ); await iapStoreKitPlatform.buyConsumable(purchaseParam: purchaseParam); await completer.future; - expect( - fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, - 5, - ); + expect(fakeStoreKitPlatform.finishedTransactions.first.payment.quantity, 5); }, ); @@ -585,13 +497,10 @@ void main() { () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; - subscription = stream.listen(( - List purchaseDetailsList, - ) { + subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); if (purchaseDetailsList.first.status == PurchaseStatus.purchased) { completer.complete(details); @@ -599,23 +508,16 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'userWithDiscount', discount: dummyPaymentDiscountWrapper, ); - await iapStoreKitPlatform.buyNonConsumable( - purchaseParam: purchaseParam, - ); + await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); final List result = await completer.future; expect(result.length, 2); expect(result.first.productID, dummyProductWrapper.productIdentifier); - expect( - fakeStoreKitPlatform.discountReceived, - dummyPaymentDiscountWrapper.toMap(), - ); + expect(fakeStoreKitPlatform.discountReceived, dummyPaymentDiscountWrapper.toMap()); }, ); }); @@ -624,8 +526,7 @@ void main() { test('should complete purchase', () async { final details = []; final completer = Completer>(); - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; late StreamSubscription> subscription; subscription = stream.listen((List purchaseDetailsList) { details.addAll(purchaseDetailsList); @@ -638,9 +539,7 @@ void main() { } }); final purchaseParam = AppStorePurchaseParam( - productDetails: AppStoreProductDetails.fromSKProduct( - dummyProductWrapper, - ), + productDetails: AppStoreProductDetails.fromSKProduct(dummyProductWrapper), applicationUserName: 'appName', ); await iapStoreKitPlatform.buyNonConsumable(purchaseParam: purchaseParam); @@ -653,14 +552,15 @@ void main() { group('purchase stream', () { test('Should only have active queue when purchaseStream has listeners', () { - final Stream> stream = - iapStoreKitPlatform.purchaseStream; + final Stream> stream = iapStoreKitPlatform.purchaseStream; expect(fakeStoreKitPlatform.queueIsActive, false); - final StreamSubscription> subscription1 = stream - .listen((List event) {}); + final StreamSubscription> subscription1 = stream.listen( + (List event) {}, + ); expect(fakeStoreKitPlatform.queueIsActive, true); - final StreamSubscription> subscription2 = stream - .listen((List event) {}); + final StreamSubscription> subscription2 = stream.listen( + (List event) {}, + ); expect(fakeStoreKitPlatform.queueIsActive, true); subscription1.cancel(); expect(fakeStoreKitPlatform.queueIsActive, true); @@ -672,10 +572,7 @@ void main() { group('billing configuration', () { test('country_code', () async { const expectedCountryCode = 'CA'; - fakeStoreKitPlatform.setStoreFrontInfo( - countryCode: expectedCountryCode, - identifier: 'ABC', - ); + fakeStoreKitPlatform.setStoreFrontInfo(countryCode: expectedCountryCode, identifier: 'ABC'); final String countryCode = await iapStoreKitPlatform.countryCode(); expect(countryCode, expectedCountryCode); // Ensure deprecated code keeps working until removed. diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/pigeon_converter_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/pigeon_converter_test.dart index 9276e0a122b5..8dd3432f3c55 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/pigeon_converter_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/pigeon_converter_test.dart @@ -45,15 +45,12 @@ void main() { ); test('test SKPriceLocale pigeon converters', () { - final SKPriceLocaleMessage msg = SKPriceLocaleWrapper.convertToPigeon( - locale, - ); + final SKPriceLocaleMessage msg = SKPriceLocaleWrapper.convertToPigeon(locale); expect(msg.currencySymbol, r'$'); expect(msg.currencyCode, 'USD'); expect(msg.countryCode, 'USA'); - final SKPriceLocaleWrapper convertedWrapper = - SKPriceLocaleWrapper.convertFromPigeon(msg); + final SKPriceLocaleWrapper convertedWrapper = SKPriceLocaleWrapper.convertFromPigeon(msg); expect(convertedWrapper, locale); }); @@ -68,16 +65,16 @@ void main() { }); test('test SKProductDiscount pigeon converters', () { - final SKProductDiscountMessage msg = - SKProductDiscountWrapper.convertToPigeon(discount); + final SKProductDiscountMessage msg = SKProductDiscountWrapper.convertToPigeon(discount); expect(msg.price, '0.99'); expect(msg.numberOfPeriods, 1); expect(msg.paymentMode, SKProductDiscountPaymentModeMessage.payUpFront); expect(msg.identifier, 'discount'); expect(msg.type, SKProductDiscountTypeMessage.subscription); - final SKProductDiscountWrapper convertedWrapper = - SKProductDiscountWrapper.convertFromPigeon(msg); + final SKProductDiscountWrapper convertedWrapper = SKProductDiscountWrapper.convertFromPigeon( + msg, + ); expect(convertedWrapper, discount); }); @@ -89,19 +86,18 @@ void main() { expect(msg.price, '3.99'); expect(msg.discounts?.length, 1); - final SKProductWrapper convertedWrapper = - SKProductWrapper.convertFromPigeon(msg); + final SKProductWrapper convertedWrapper = SKProductWrapper.convertFromPigeon(msg); expect(convertedWrapper, product); }); test('test SKProductResponse pigeon converters', () { - final SKProductsResponseMessage msg = - SkProductResponseWrapper.convertToPigeon(productResponse); + final SKProductsResponseMessage msg = SkProductResponseWrapper.convertToPigeon(productResponse); expect(msg.products?.length, 1); expect(msg.invalidProductIdentifiers, ['invalid_identifier']); - final SkProductResponseWrapper convertedWrapper = - SkProductResponseWrapper.convertFromPigeon(msg); + final SkProductResponseWrapper convertedWrapper = SkProductResponseWrapper.convertFromPigeon( + msg, + ); expect(convertedWrapper, productResponse); }); diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart index 4e5609a41fbb..b881b38cb702 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart @@ -28,26 +28,14 @@ void main() { group('sk_request_maker', () { test('get products method channel', () async { - final SkProductResponseWrapper productResponseWrapper = - await SKRequestMaker().startProductRequest(['xxx']); + final SkProductResponseWrapper productResponseWrapper = await SKRequestMaker() + .startProductRequest(['xxx']); expect(productResponseWrapper.products, isNotEmpty); - expect( - productResponseWrapper.products.first.priceLocale.currencySymbol, - r'$', - ); + expect(productResponseWrapper.products.first.priceLocale.currencySymbol, r'$'); - expect( - productResponseWrapper.products.first.priceLocale.currencySymbol, - isNot('A'), - ); - expect( - productResponseWrapper.products.first.priceLocale.currencyCode, - 'USD', - ); - expect( - productResponseWrapper.products.first.priceLocale.countryCode, - 'US', - ); + expect(productResponseWrapper.products.first.priceLocale.currencySymbol, isNot('A')); + expect(productResponseWrapper.products.first.priceLocale.currencyCode, 'USD'); + expect(productResponseWrapper.products.first.priceLocale.countryCode, 'US'); expect(productResponseWrapper.invalidProductIdentifiers, isNotEmpty); expect(fakeStoreKitPlatform.startProductRequestParam, ['xxx']); @@ -55,10 +43,7 @@ void main() { test('get products method channel should throw exception', () async { fakeStoreKitPlatform.getProductRequestFailTest = true; - expect( - SKRequestMaker().startProductRequest(['xxx']), - throwsException, - ); + expect(SKRequestMaker().startProductRequest(['xxx']), throwsException); fakeStoreKitPlatform.getProductRequestFailTest = false; }); @@ -68,9 +53,7 @@ void main() { receiptProperties: {'isExpired': true}, ); expect(fakeStoreKitPlatform.refreshReceiptCount, receiptCountBefore + 1); - expect(fakeStoreKitPlatform.refreshReceiptParam, { - 'isExpired': true, - }); + expect(fakeStoreKitPlatform.refreshReceiptParam, {'isExpired': true}); }); test('should get null receipt if any exceptions are raised', () async { @@ -83,13 +66,10 @@ void main() { }); group('sk_receipt_manager', () { - test( - 'should get receipt (faking it by returning a `receipt data` string)', - () async { - final String receiptData = await SKReceiptManager.retrieveReceiptData(); - expect(receiptData, 'receipt data'); - }, - ); + test('should get receipt (faking it by returning a `receipt data` string)', () async { + final String receiptData = await SKReceiptManager.retrieveReceiptData(); + expect(receiptData, 'receipt data'); + }); }); group('sk_payment_queue', () { @@ -112,15 +92,9 @@ void main() { expect(await SKPaymentQueueWrapper().transactions(), isNotEmpty); }); - test( - 'throws if observer is not set for payment queue before adding payment', - () async { - expect( - SKPaymentQueueWrapper().addPayment(dummyPayment), - throwsAssertionError, - ); - }, - ); + test('throws if observer is not set for payment queue before adding payment', () async { + expect(SKPaymentQueueWrapper().addPayment(dummyPayment), throwsAssertionError); + }); test('should add payment to the payment queue', () async { final queue = SKPaymentQueueWrapper(); @@ -146,10 +120,7 @@ void main() { final observer = TestPaymentTransactionObserver(); queue.setTransactionObserver(observer); await queue.restoreTransactions(applicationUserName: 'aUserID'); - expect( - fakeStoreKitPlatform.applicationNameHasTransactionRestored, - 'aUserID', - ); + expect(fakeStoreKitPlatform.applicationNameHasTransactionRestored, 'aUserID'); }); test('startObservingTransactionQueue should call methodChannel', () async { @@ -221,9 +192,7 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { @override Future addPayment(Map paymentMap) async { - payments.add( - SKPaymentWrapper.fromJson(Map.from(paymentMap)), - ); + payments.add(SKPaymentWrapper.fromJson(Map.from(paymentMap))); } @override @@ -233,15 +202,13 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { @override Future storefront() async { - return SKStorefrontMessage( - countryCode: 'USA', - identifier: 'unique_identifier', - ); + return SKStorefrontMessage(countryCode: 'USA', identifier: 'unique_identifier'); } @override - Future> transactions() async => - [dummyTransactionMessage]; + Future> transactions() async => [ + dummyTransactionMessage, + ]; @override Future finishTransaction(Map finishMap) async { @@ -259,14 +226,10 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { } @override - Future startProductRequest( - List productIdentifiers, - ) async { + Future startProductRequest(List productIdentifiers) async { startProductRequestParam = productIdentifiers; if (getProductRequestFailTest) { - return Future.value( - SKProductsResponseMessage(), - ); + return Future.value(SKProductsResponseMessage()); } return dummyProductResponseMessage; } @@ -302,9 +265,7 @@ class FakeStoreKitPlatform implements InAppPurchaseAPI { @override Future refreshReceipt({Map? receiptProperties}) { refreshReceiptCount++; - refreshReceiptParam = Map.castFrom( - receiptProperties!, - ); + refreshReceiptParam = Map.castFrom(receiptProperties!); return Future.sync(() {}); } @@ -331,14 +292,10 @@ class TestPaymentQueueDelegate extends SKPaymentQueueDelegateWrapper {} class TestPaymentTransactionObserver extends SKTransactionObserverWrapper { @override - void updatedTransactions({ - required List transactions, - }) {} + void updatedTransactions({required List transactions}) {} @override - void removedTransactions({ - required List transactions, - }) {} + void removedTransactions({required List transactions}) {} @override void restoreCompletedTransactionsFailed({required SKError error}) {} diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_payment_queue_delegate_api_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_payment_queue_delegate_api_test.dart index 6f0467197b0f..3805135d35e5 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_payment_queue_delegate_api_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_payment_queue_delegate_api_test.dart @@ -26,14 +26,9 @@ void main() { await queue.setDelegate(testDelegate); final arguments = { - 'storefront': { - 'countryCode': 'USA', - 'identifier': 'unique_identifier', - }, + 'storefront': {'countryCode': 'USA', 'identifier': 'unique_identifier'}, 'transaction': { - 'payment': { - 'productIdentifier': 'product_identifier', - }, + 'payment': {'productIdentifier': 'product_identifier'}, }, }; @@ -81,9 +76,7 @@ void main() { MethodCall('restoreCompletedTransactionsFailed', arguments), ); - expect(testObserver.log, { - equals('restoreCompletedTransactionsFailed'), - }); + expect(testObserver.log, {equals('restoreCompletedTransactionsFailed')}); }, ); } @@ -92,16 +85,12 @@ class TestTransactionObserverWrapper extends SKTransactionObserverWrapper { final List log = []; @override - void updatedTransactions({ - required List transactions, - }) { + void updatedTransactions({required List transactions}) { log.add('updatedTransactions'); } @override - void removedTransactions({ - required List transactions, - }) { + void removedTransactions({required List transactions}) { log.add('removedTransactions'); } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_product_test.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_product_test.dart index dfdd6e6be1e6..2645d842458f 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_product_test.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_product_test.dart @@ -11,110 +11,72 @@ import 'sk_test_stub_objects.dart'; void main() { group('product related object wrapper test', () { - test( - 'SKProductSubscriptionPeriodWrapper should have property values consistent with map', - () { - final wrapper = SKProductSubscriptionPeriodWrapper.fromJson( - buildSubscriptionPeriodMap(dummySubscription), - ); - expect(wrapper, equals(dummySubscription)); - }, - ); + test('SKProductSubscriptionPeriodWrapper should have property values consistent with map', () { + final wrapper = SKProductSubscriptionPeriodWrapper.fromJson( + buildSubscriptionPeriodMap(dummySubscription), + ); + expect(wrapper, equals(dummySubscription)); + }); test( 'SKProductSubscriptionPeriodWrapper should have properties to be default values if map is empty', () { - final wrapper = SKProductSubscriptionPeriodWrapper.fromJson( - const {}, - ); + final wrapper = SKProductSubscriptionPeriodWrapper.fromJson(const {}); expect(wrapper.numberOfUnits, 0); expect(wrapper.unit, SKSubscriptionPeriodUnit.day); }, ); - test( - 'SKProductDiscountWrapper should have property values consistent with map', - () { - final wrapper = SKProductDiscountWrapper.fromJson( - buildDiscountMap(dummyDiscount), - ); - expect(wrapper, equals(dummyDiscount)); - }, - ); + test('SKProductDiscountWrapper should have property values consistent with map', () { + final wrapper = SKProductDiscountWrapper.fromJson(buildDiscountMap(dummyDiscount)); + expect(wrapper, equals(dummyDiscount)); + }); test('SKProductDiscountWrapper missing identifier and type should have ' 'property values consistent with map', () { final wrapper = SKProductDiscountWrapper.fromJson( - buildDiscountMapMissingIdentifierAndType( - dummyDiscountMissingIdentifierAndType, - ), + buildDiscountMapMissingIdentifierAndType(dummyDiscountMissingIdentifierAndType), ); expect(wrapper, equals(dummyDiscountMissingIdentifierAndType)); }); - test( - 'SKProductDiscountWrapper should have properties to be default if map is empty', - () { - final wrapper = SKProductDiscountWrapper.fromJson( - const {}, - ); - expect(wrapper.price, ''); - expect( - wrapper.priceLocale, - SKPriceLocaleWrapper( - currencyCode: '', - currencySymbol: '', - countryCode: '', - ), - ); - expect(wrapper.numberOfPeriods, 0); - expect(wrapper.paymentMode, SKProductDiscountPaymentMode.payAsYouGo); - expect( - wrapper.subscriptionPeriod, - SKProductSubscriptionPeriodWrapper( - numberOfUnits: 0, - unit: SKSubscriptionPeriodUnit.day, - ), - ); - }, - ); + test('SKProductDiscountWrapper should have properties to be default if map is empty', () { + final wrapper = SKProductDiscountWrapper.fromJson(const {}); + expect(wrapper.price, ''); + expect( + wrapper.priceLocale, + SKPriceLocaleWrapper(currencyCode: '', currencySymbol: '', countryCode: ''), + ); + expect(wrapper.numberOfPeriods, 0); + expect(wrapper.paymentMode, SKProductDiscountPaymentMode.payAsYouGo); + expect( + wrapper.subscriptionPeriod, + SKProductSubscriptionPeriodWrapper(numberOfUnits: 0, unit: SKSubscriptionPeriodUnit.day), + ); + }); - test( - 'SKProductWrapper should have property values consistent with map', - () { - final wrapper = SKProductWrapper.fromJson( - buildProductMap(dummyProductWrapper), - ); - expect(wrapper, equals(dummyProductWrapper)); - }, - ); + test('SKProductWrapper should have property values consistent with map', () { + final wrapper = SKProductWrapper.fromJson(buildProductMap(dummyProductWrapper)); + expect(wrapper, equals(dummyProductWrapper)); + }); - test( - 'SKProductWrapper should have properties to be default if map is empty', - () { - final wrapper = SKProductWrapper.fromJson(const {}); - expect(wrapper.productIdentifier, ''); - expect(wrapper.localizedTitle, ''); - expect(wrapper.localizedDescription, ''); - expect( - wrapper.priceLocale, - SKPriceLocaleWrapper( - currencyCode: '', - currencySymbol: '', - countryCode: '', - ), - ); - expect(wrapper.subscriptionGroupIdentifier, null); - expect(wrapper.price, ''); - expect(wrapper.subscriptionPeriod, null); - expect(wrapper.discounts, []); - }, - ); + test('SKProductWrapper should have properties to be default if map is empty', () { + final wrapper = SKProductWrapper.fromJson(const {}); + expect(wrapper.productIdentifier, ''); + expect(wrapper.localizedTitle, ''); + expect(wrapper.localizedDescription, ''); + expect( + wrapper.priceLocale, + SKPriceLocaleWrapper(currencyCode: '', currencySymbol: '', countryCode: ''), + ); + expect(wrapper.subscriptionGroupIdentifier, null); + expect(wrapper.price, ''); + expect(wrapper.subscriptionPeriod, null); + expect(wrapper.discounts, []); + }); test('toProductDetails() should return correct Product object', () { - final wrapper = SKProductWrapper.fromJson( - buildProductMap(dummyProductWrapper), - ); + final wrapper = SKProductWrapper.fromJson(buildProductMap(dummyProductWrapper)); final product = AppStoreProductDetails.fromSKProduct(wrapper); expect(product.title, wrapper.localizedTitle); expect(product.description, wrapper.localizedDescription); @@ -134,17 +96,13 @@ void main() { 'products': >[], 'invalidProductIdentifiers': [], }; - final wrapper = SkProductResponseWrapper.fromJson( - productResponseMapEmptyList, - ); + final wrapper = SkProductResponseWrapper.fromJson(productResponseMapEmptyList); expect(wrapper.products.length, 0); expect(wrapper.invalidProductIdentifiers.length, 0); }); test('LocaleWrapper should have property values consistent with map', () { - final wrapper = SKPriceLocaleWrapper.fromJson( - buildLocaleMap(dollarLocale), - ); + final wrapper = SKPriceLocaleWrapper.fromJson(buildLocaleMap(dollarLocale)); expect(wrapper, equals(dollarLocale)); }); }); @@ -155,30 +113,21 @@ void main() { expect(payment, equals(dummyPayment)); }); - test( - 'SKPaymentWrapper should have propery values consistent with .toMap()', - () { - final Map mapResult = dummyPaymentWithDiscount.toMap(); - expect( - mapResult['productIdentifier'], - dummyPaymentWithDiscount.productIdentifier, - ); - expect( - mapResult['applicationUsername'], - dummyPaymentWithDiscount.applicationUsername, - ); - expect(mapResult['requestData'], dummyPaymentWithDiscount.requestData); - expect(mapResult['quantity'], dummyPaymentWithDiscount.quantity); - expect( - mapResult['simulatesAskToBuyInSandbox'], - dummyPaymentWithDiscount.simulatesAskToBuyInSandbox, - ); - expect( - mapResult['paymentDiscount'], - equals(dummyPaymentWithDiscount.paymentDiscount?.toMap()), - ); - }, - ); + test('SKPaymentWrapper should have propery values consistent with .toMap()', () { + final Map mapResult = dummyPaymentWithDiscount.toMap(); + expect(mapResult['productIdentifier'], dummyPaymentWithDiscount.productIdentifier); + expect(mapResult['applicationUsername'], dummyPaymentWithDiscount.applicationUsername); + expect(mapResult['requestData'], dummyPaymentWithDiscount.requestData); + expect(mapResult['quantity'], dummyPaymentWithDiscount.quantity); + expect( + mapResult['simulatesAskToBuyInSandbox'], + dummyPaymentWithDiscount.simulatesAskToBuyInSandbox, + ); + expect( + mapResult['paymentDiscount'], + equals(dummyPaymentWithDiscount.paymentDiscount?.toMap()), + ); + }); test('Should construct correct SKError from json', () { final error = SKError.fromJson(buildErrorMap(dummyError)); @@ -193,10 +142,7 @@ void main() { }); test('toPurchaseDetails() should return correct PurchaseDetail object', () { - final details = AppStorePurchaseDetails.fromSKTransaction( - dummyTransaction, - 'receipt data', - ); + final details = AppStorePurchaseDetails.fromSKTransaction(dummyTransaction, 'receipt data'); expect(dummyTransaction.transactionIdentifier, details.purchaseID); expect(dummyTransaction.payment.productIdentifier, details.productID); expect(dummyTransaction.transactionTimeStamp, isNotNull); @@ -243,10 +189,7 @@ void main() { expect(map['quantity'], dummyPayment.quantity); - expect( - map['simulatesAskToBuyInSandbox'], - dummyPayment.simulatesAskToBuyInSandbox, - ); + expect(map['simulatesAskToBuyInSandbox'], dummyPayment.simulatesAskToBuyInSandbox); }); }); } diff --git a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_test_stub_objects.dart b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_test_stub_objects.dart index cd8ceb1f6ca3..3ee4346758b6 100644 --- a/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_test_stub_objects.dart +++ b/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_test_stub_objects.dart @@ -36,30 +36,27 @@ const SKError dummyError = SKError( userInfo: {'key': 'value'}, ); -final SKPaymentTransactionWrapper dummyOriginalTransaction = - SKPaymentTransactionWrapper( - transactionState: SKPaymentTransactionStateWrapper.purchased, - payment: dummyPayment, - transactionTimeStamp: 1231231231.00, - transactionIdentifier: '123123', - error: dummyError, - ); +final SKPaymentTransactionWrapper dummyOriginalTransaction = SKPaymentTransactionWrapper( + transactionState: SKPaymentTransactionStateWrapper.purchased, + payment: dummyPayment, + transactionTimeStamp: 1231231231.00, + transactionIdentifier: '123123', + error: dummyError, +); -final SKPaymentTransactionWrapper dummyTransaction = - SKPaymentTransactionWrapper( - transactionState: SKPaymentTransactionStateWrapper.purchased, - payment: dummyPayment, - originalTransaction: dummyOriginalTransaction, - transactionTimeStamp: 1231231231.00, - transactionIdentifier: '123123', - error: dummyError, - ); +final SKPaymentTransactionWrapper dummyTransaction = SKPaymentTransactionWrapper( + transactionState: SKPaymentTransactionStateWrapper.purchased, + payment: dummyPayment, + originalTransaction: dummyOriginalTransaction, + transactionTimeStamp: 1231231231.00, + transactionIdentifier: '123123', + error: dummyError, +); -final SKPaymentTransactionMessage dummyTransactionMessage = - SKPaymentTransactionMessage( - payment: dummyPaymentMessage, - transactionState: SKPaymentTransactionStateMessage.purchased, - ); +final SKPaymentTransactionMessage dummyTransactionMessage = SKPaymentTransactionMessage( + payment: dummyPaymentMessage, + transactionState: SKPaymentTransactionStateMessage.purchased, +); final SKPriceLocaleWrapper dollarLocale = SKPriceLocaleWrapper( currencySymbol: r'$', @@ -79,11 +76,10 @@ final SKPriceLocaleWrapper noSymbolLocale = SKPriceLocaleWrapper( countryCode: 'UK', ); -final SKProductSubscriptionPeriodWrapper dummySubscription = - SKProductSubscriptionPeriodWrapper( - numberOfUnits: 1, - unit: SKSubscriptionPeriodUnit.month, - ); +final SKProductSubscriptionPeriodWrapper dummySubscription = SKProductSubscriptionPeriodWrapper( + numberOfUnits: 1, + unit: SKSubscriptionPeriodUnit.month, +); final SKProductSubscriptionPeriodMessage dummySubscriptionMessage = SKProductSubscriptionPeriodMessage( @@ -111,16 +107,15 @@ final SKProductDiscountMessage dummyDiscountMessage = SKProductDiscountMessage( type: SKProductDiscountTypeMessage.subscription, ); -final SKProductDiscountWrapper dummyDiscountMissingIdentifierAndType = - SKProductDiscountWrapper( - price: '1.0', - priceLocale: dollarLocale, - numberOfPeriods: 1, - paymentMode: SKProductDiscountPaymentMode.payUpFront, - subscriptionPeriod: dummySubscription, - identifier: null, - type: SKProductDiscountType.introductory, - ); +final SKProductDiscountWrapper dummyDiscountMissingIdentifierAndType = SKProductDiscountWrapper( + price: '1.0', + priceLocale: dollarLocale, + numberOfPeriods: 1, + paymentMode: SKProductDiscountPaymentMode.payUpFront, + subscriptionPeriod: dummySubscription, + identifier: null, + type: SKProductDiscountType.introductory, +); final SKProductWrapper dummyProductWrapper = SKProductWrapper( productIdentifier: 'id', @@ -146,17 +141,15 @@ final SKProductMessage dummyProductMessage = SKProductMessage( discounts: [dummyDiscountMessage], ); -final SkProductResponseWrapper dummyProductResponseWrapper = - SkProductResponseWrapper( - products: [dummyProductWrapper], - invalidProductIdentifiers: const ['123'], - ); +final SkProductResponseWrapper dummyProductResponseWrapper = SkProductResponseWrapper( + products: [dummyProductWrapper], + invalidProductIdentifiers: const ['123'], +); -final SKProductsResponseMessage dummyProductResponseMessage = - SKProductsResponseMessage( - products: [dummyProductMessage], - invalidProductIdentifiers: const ['123'], - ); +final SKProductsResponseMessage dummyProductResponseMessage = SKProductsResponseMessage( + products: [dummyProductMessage], + invalidProductIdentifiers: const ['123'], +); Map buildLocaleMap(SKPriceLocaleWrapper local) { return { @@ -166,9 +159,7 @@ Map buildLocaleMap(SKPriceLocaleWrapper local) { }; } -Map? buildSubscriptionPeriodMap( - SKProductSubscriptionPeriodWrapper? sub, -) { +Map? buildSubscriptionPeriodMap(SKProductSubscriptionPeriodWrapper? sub) { if (sub == null) { return null; } @@ -183,30 +174,20 @@ Map buildDiscountMap(SKProductDiscountWrapper discount) { 'price': discount.price, 'priceLocale': buildLocaleMap(discount.priceLocale), 'numberOfPeriods': discount.numberOfPeriods, - 'paymentMode': SKProductDiscountPaymentMode.values.indexOf( - discount.paymentMode, - ), - 'subscriptionPeriod': buildSubscriptionPeriodMap( - discount.subscriptionPeriod, - ), + 'paymentMode': SKProductDiscountPaymentMode.values.indexOf(discount.paymentMode), + 'subscriptionPeriod': buildSubscriptionPeriodMap(discount.subscriptionPeriod), 'identifier': discount.identifier, 'type': SKProductDiscountType.values.indexOf(discount.type), }; } -Map buildDiscountMapMissingIdentifierAndType( - SKProductDiscountWrapper discount, -) { +Map buildDiscountMapMissingIdentifierAndType(SKProductDiscountWrapper discount) { return { 'price': discount.price, 'priceLocale': buildLocaleMap(discount.priceLocale), 'numberOfPeriods': discount.numberOfPeriods, - 'paymentMode': SKProductDiscountPaymentMode.values.indexOf( - discount.paymentMode, - ), - 'subscriptionPeriod': buildSubscriptionPeriodMap( - discount.subscriptionPeriod, - ), + 'paymentMode': SKProductDiscountPaymentMode.values.indexOf(discount.paymentMode), + 'subscriptionPeriod': buildSubscriptionPeriodMap(discount.subscriptionPeriod), }; } @@ -218,17 +199,13 @@ Map buildProductMap(SKProductWrapper product) { 'priceLocale': buildLocaleMap(product.priceLocale), 'subscriptionGroupIdentifier': product.subscriptionGroupIdentifier, 'price': product.price, - 'subscriptionPeriod': buildSubscriptionPeriodMap( - product.subscriptionPeriod, - ), + 'subscriptionPeriod': buildSubscriptionPeriodMap(product.subscriptionPeriod), 'introductoryPrice': buildDiscountMap(product.introductoryPrice!), 'discounts': [buildDiscountMap(product.introductoryPrice!)], }; } -Map buildProductResponseMap( - SkProductResponseWrapper response, -) { +Map buildProductResponseMap(SkProductResponseWrapper response) { final List productsMap = response.products .map((SKProductWrapper product) => buildProductMap(product)) .toList(); @@ -239,16 +216,10 @@ Map buildProductResponseMap( } Map buildErrorMap(SKError error) { - return { - 'code': error.code, - 'domain': error.domain, - 'userInfo': error.userInfo, - }; + return {'code': error.code, 'domain': error.domain, 'userInfo': error.userInfo}; } -Map buildTransactionMap( - SKPaymentTransactionWrapper transaction, -) { +Map buildTransactionMap(SKPaymentTransactionWrapper transaction) { final map = { 'transactionState': SKPaymentTransactionStateWrapper.values.indexOf( SKPaymentTransactionStateWrapper.purchased, @@ -264,9 +235,7 @@ Map buildTransactionMap( return map; } -Map buildTransactionMessage( - SKPaymentTransactionWrapper transaction, -) { +Map buildTransactionMessage(SKPaymentTransactionWrapper transaction) { final map = { 'transactionState': SKPaymentTransactionStateWrapper.values.indexOf( SKPaymentTransactionStateWrapper.purchased, diff --git a/packages/interactive_media_ads/example/lib/main.dart b/packages/interactive_media_ads/example/lib/main.dart index ab6c3b86649e..b9e4ab468a3c 100644 --- a/packages/interactive_media_ads/example/lib/main.dart +++ b/packages/interactive_media_ads/example/lib/main.dart @@ -47,14 +47,10 @@ class _HomeScreenState extends State { ), ]; - void _pushVideoAdExampleWithAdTagUrl({ - required String adType, - required String adTagUrl, - }) { + void _pushVideoAdExampleWithAdTagUrl({required String adType, required String adTagUrl}) { Navigator.of(context).push( MaterialPageRoute( - builder: (_) => - VideoAdExampleScreen(adType: adType, adTagUrl: adTagUrl), + builder: (_) => VideoAdExampleScreen(adType: adType, adTagUrl: adTagUrl), ), ); } @@ -62,10 +58,7 @@ class _HomeScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('IMA Test App'), - backgroundColor: Colors.blue, - ), + appBar: AppBar(title: const Text('IMA Test App'), backgroundColor: Colors.blue), body: Center( child: ListView.separated( padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 60), @@ -74,10 +67,7 @@ class _HomeScreenState extends State { itemBuilder: (_, int index) { final (String adType, String adTagUrl) = _testAdTagUrls[index]; return ElevatedButton( - onPressed: () => _pushVideoAdExampleWithAdTagUrl( - adType: adType, - adTagUrl: adTagUrl, - ), + onPressed: () => _pushVideoAdExampleWithAdTagUrl(adType: adType, adTagUrl: adTagUrl), child: Text(adType), ); }, diff --git a/packages/interactive_media_ads/example/lib/readme_example.dart b/packages/interactive_media_ads/example/lib/readme_example.dart index 0165be8a58e4..7fcac1185bb6 100644 --- a/packages/interactive_media_ads/example/lib/readme_example.dart +++ b/packages/interactive_media_ads/example/lib/readme_example.dart @@ -8,6 +8,7 @@ import 'package:flutter/material.dart'; // #docregion imports import 'package:interactive_media_ads/interactive_media_ads.dart'; import 'package:video_player/video_player.dart'; + // #enddocregion imports // #docregion example_widget @@ -20,8 +21,7 @@ class AdExampleWidget extends StatefulWidget { State createState() => _AdExampleWidgetState(); } -class _AdExampleWidgetState extends State - with WidgetsBindingObserver { +class _AdExampleWidgetState extends State with WidgetsBindingObserver { // IMA sample tag for a pre-, mid-, and post-roll, single inline video ad. See more IMA sample // tags at https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/tags static const String _adTagUrl = @@ -51,8 +51,7 @@ class _AdExampleWidgetState extends State // Provides the SDK with the current playback progress of the content video. // This is required to support mid-roll ads. - final ContentProgressProvider _contentProgressProvider = - ContentProgressProvider(); + final ContentProgressProvider _contentProgressProvider = ContentProgressProvider(); // #enddocregion example_widget // #docregion ad_and_content_players @@ -114,9 +113,7 @@ class _AdExampleWidgetState extends State // #docregion ad_and_content_players _contentVideoController = VideoPlayerController.networkUrl( - Uri.parse( - 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', - ), + Uri.parse('https://storage.googleapis.com/gvabox/media/samples/stock.mp4'), ) ..addListener(() { if (_contentVideoController.value.isCompleted) { @@ -129,6 +126,7 @@ class _AdExampleWidgetState extends State setState(() {}); }); } + // #enddocregion ad_and_content_players @override @@ -143,8 +141,7 @@ class _AdExampleWidgetState extends State // because it corresponds to `Activity.onPause`. This state is also // triggered before resume, so this will only pause the Ad if the app is // in the process of being sent to the background. - if (!_shouldShowContentVideo && - _lastLifecycleState == AppLifecycleState.resumed) { + if (!_shouldShowContentVideo && _lastLifecycleState == AppLifecycleState.resumed) { _adsManager?.pause(); } case AppLifecycleState.hidden: @@ -157,10 +154,7 @@ class _AdExampleWidgetState extends State // #docregion request_ads Future _requestAds(AdDisplayContainer container) { return _adsLoader.requestAds( - AdsRequest( - adTagUrl: _adTagUrl, - contentProgressProvider: _contentProgressProvider, - ), + AdsRequest(adTagUrl: _adTagUrl, contentProgressProvider: _contentProgressProvider), ); } @@ -170,20 +164,19 @@ class _AdExampleWidgetState extends State }); if (_adsManager != null) { - _contentProgressTimer = Timer.periodic( - const Duration(milliseconds: 200), - (Timer timer) async { - if (_contentVideoController.value.isInitialized) { - final Duration? progress = await _contentVideoController.position; - if (progress != null) { - await _contentProgressProvider.setProgress( - progress: progress, - duration: _contentVideoController.value.duration, - ); - } + _contentProgressTimer = Timer.periodic(const Duration(milliseconds: 200), ( + Timer timer, + ) async { + if (_contentVideoController.value.isInitialized) { + final Duration? progress = await _contentVideoController.position; + if (progress != null) { + await _contentProgressProvider.setProgress( + progress: progress, + duration: _contentVideoController.value.duration, + ); } - }, - ); + } + }); } await _contentVideoController.play(); @@ -197,6 +190,7 @@ class _AdExampleWidgetState extends State _contentProgressTimer = null; return _contentVideoController.pause(); } + // #enddocregion request_ads // #docregion dispose @@ -210,6 +204,7 @@ class _AdExampleWidgetState extends State WidgetsBinding.instance.removeObserver(this); // #docregion dispose } + // #enddocregion dispose // #docregion example_widget @@ -231,15 +226,13 @@ class _AdExampleWidgetState extends State // loaded and can't be removed between ads. This handles clicks for // ads. _adDisplayContainer, - if (_shouldShowContentVideo) - VideoPlayer(_contentVideoController), + if (_shouldShowContentVideo) VideoPlayer(_contentVideoController), ], ), ), ), ), - floatingActionButton: - _contentVideoController.value.isInitialized && _shouldShowContentVideo + floatingActionButton: _contentVideoController.value.isInitialized && _shouldShowContentVideo ? FloatingActionButton( onPressed: () { setState(() { @@ -248,11 +241,7 @@ class _AdExampleWidgetState extends State : _contentVideoController.play(); }); }, - child: Icon( - _contentVideoController.value.isPlaying - ? Icons.pause - : Icons.play_arrow, - ), + child: Icon(_contentVideoController.value.isPlaying ? Icons.pause : Icons.play_arrow), ) : null, ); diff --git a/packages/interactive_media_ads/example/lib/video_ad_example_screen.dart b/packages/interactive_media_ads/example/lib/video_ad_example_screen.dart index 7684cfbaf3b8..0e2536401f0a 100644 --- a/packages/interactive_media_ads/example/lib/video_ad_example_screen.dart +++ b/packages/interactive_media_ads/example/lib/video_ad_example_screen.dart @@ -32,8 +32,7 @@ class VideoAdExampleScreen extends StatefulWidget { State createState() => _VideoAdExampleScreenState(); } -class _VideoAdExampleScreenState extends State - with WidgetsBindingObserver { +class _VideoAdExampleScreenState extends State with WidgetsBindingObserver { // The AdsLoader instance exposes the request ads method. late final AdsLoader _adsLoader; @@ -56,8 +55,7 @@ class _VideoAdExampleScreenState extends State // Provides the SDK with the current playback progress of the content video. // This is required to support mid-roll ads. - final ContentProgressProvider _contentProgressProvider = - ContentProgressProvider(); + final ContentProgressProvider _contentProgressProvider = ContentProgressProvider(); late final CompanionAdSlot companionAd = CompanionAdSlot( size: CompanionAdSlotSize.fixed(width: 300, height: 250), @@ -100,11 +98,7 @@ class _VideoAdExampleScreenState extends State ), ); - manager.init( - settings: AdsRenderingSettings( - enablePreloading: widget.enablePreloading, - ), - ); + manager.init(settings: AdsRenderingSettings(enablePreloading: widget.enablePreloading)); }, onAdsLoadError: (AdsLoadErrorData data) { debugPrint('OnAdsLoadError: ${data.error.message}'); @@ -126,9 +120,7 @@ class _VideoAdExampleScreenState extends State _contentVideoController = VideoPlayerController.networkUrl( - Uri.parse( - 'https://storage.googleapis.com/gvabox/media/samples/stock.mp4', - ), + Uri.parse('https://storage.googleapis.com/gvabox/media/samples/stock.mp4'), ) ..addListener(() { if (_contentVideoController.value.isCompleted) { @@ -154,8 +146,7 @@ class _VideoAdExampleScreenState extends State // because it corresponds to `Activity.onPause`. This state is also // triggered before resume, so this will only pause the Ad if the app is // in the process of being sent to the background. - if (!_shouldShowContentVideo && - _lastLifecycleState == AppLifecycleState.resumed) { + if (!_shouldShowContentVideo && _lastLifecycleState == AppLifecycleState.resumed) { _adsManager?.pause(); } case AppLifecycleState.hidden: @@ -167,10 +158,7 @@ class _VideoAdExampleScreenState extends State Future _requestAds(AdDisplayContainer container) { return _adsLoader.requestAds( - AdsRequest( - adTagUrl: widget.adTagUrl, - contentProgressProvider: _contentProgressProvider, - ), + AdsRequest(adTagUrl: widget.adTagUrl, contentProgressProvider: _contentProgressProvider), ); } @@ -184,20 +172,19 @@ class _VideoAdExampleScreenState extends State }); if (_adsManager != null) { - _contentProgressTimer = Timer.periodic( - const Duration(milliseconds: 200), - (Timer timer) async { - if (_contentVideoController.value.isInitialized) { - final Duration? progress = await _contentVideoController.position; - if (progress != null) { - await _contentProgressProvider.setProgress( - progress: progress, - duration: _contentVideoController.value.duration, - ); - } + _contentProgressTimer = Timer.periodic(const Duration(milliseconds: 200), ( + Timer timer, + ) async { + if (_contentVideoController.value.isInitialized) { + final Duration? progress = await _contentVideoController.position; + if (progress != null) { + await _contentProgressProvider.setProgress( + progress: progress, + duration: _contentVideoController.value.duration, + ); } - }, - ); + } + }); } await _contentVideoController.play(); @@ -224,19 +211,13 @@ class _VideoAdExampleScreenState extends State @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('IMA Test App'), - backgroundColor: Colors.blue, - ), + appBar: AppBar(title: const Text('IMA Test App'), backgroundColor: Colors.blue), body: Center( child: Column( spacing: 80, mainAxisAlignment: MainAxisAlignment.center, children: [ - Text( - widget.adType, - style: Theme.of(context).textTheme.headlineMedium, - ), + Text(widget.adType, style: Theme.of(context).textTheme.headlineMedium), SizedBox( width: 300, child: !_contentVideoController.value.isInitialized @@ -249,25 +230,19 @@ class _VideoAdExampleScreenState extends State // loaded and can't be removed between ads. This handles clicks for // ads. _adDisplayContainer, - if (_shouldShowContentVideo) - VideoPlayer(_contentVideoController), + if (_shouldShowContentVideo) VideoPlayer(_contentVideoController), ], ), ), ), ColoredBox( color: Colors.green, - child: SizedBox( - width: 300, - height: 250, - child: companionAd.buildWidget(context), - ), + child: SizedBox(width: 300, height: 250, child: companionAd.buildWidget(context)), ), ], ), ), - floatingActionButton: - _contentVideoController.value.isInitialized && _shouldShowContentVideo + floatingActionButton: _contentVideoController.value.isInitialized && _shouldShowContentVideo ? FloatingActionButton( onPressed: () { setState(() { @@ -276,11 +251,7 @@ class _VideoAdExampleScreenState extends State : _contentVideoController.play(); }); }, - child: Icon( - _contentVideoController.value.isPlaying - ? Icons.pause - : Icons.play_arrow, - ), + child: Icon(_contentVideoController.value.isPlaying ? Icons.pause : Icons.play_arrow), ) : null, ); diff --git a/packages/interactive_media_ads/lib/interactive_media_ads.dart b/packages/interactive_media_ads/lib/interactive_media_ads.dart index e86e00f19952..c7652e081ff6 100644 --- a/packages/interactive_media_ads/lib/interactive_media_ads.dart +++ b/packages/interactive_media_ads/lib/interactive_media_ads.dart @@ -8,8 +8,7 @@ export 'src/ads_loader.dart'; export 'src/ads_manager_delegate.dart'; export 'src/ads_rendering_settings.dart'; export 'src/ads_request.dart'; -export 'src/android/android_interactive_media_ads.dart' - show AndroidInteractiveMediaAds; +export 'src/android/android_interactive_media_ads.dart' show AndroidInteractiveMediaAds; export 'src/companion_ad_slot.dart'; export 'src/content_progress_provider.dart'; export 'src/ima_settings.dart'; diff --git a/packages/interactive_media_ads/lib/src/ad.dart b/packages/interactive_media_ads/lib/src/ad.dart index 32454800baeb..fbecbec618f4 100644 --- a/packages/interactive_media_ads/lib/src/ad.dart +++ b/packages/interactive_media_ads/lib/src/ad.dart @@ -36,9 +36,8 @@ class Ad { /// The companions for the current ad while using DAI. /// /// Returns an empty list in any other scenario. - List get companionAds => List.unmodifiable( - platform.companionAds.map(CompanionAd.fromPlatform), - ); + List get companionAds => + List.unmodifiable(platform.companionAds.map(CompanionAd.fromPlatform)); /// The content type of the currently selected creative, or null if no /// creative is selected or the content type is unavailable. @@ -85,9 +84,8 @@ class Ad { Set get uiElements => platform.uiElements; /// The list of all universal ad IDs for this ad. - List get universalAdIds => List.unmodifiable( - platform.universalAdIds.map(UniversalAdId.fromPlatform), - ); + List get universalAdIds => + List.unmodifiable(platform.universalAdIds.map(UniversalAdId.fromPlatform)); /// The VAST bitrate in Kbps of the selected creative. int get vastMediaBitrate => platform.vastMediaBitrate; diff --git a/packages/interactive_media_ads/lib/src/ad_display_container.dart b/packages/interactive_media_ads/lib/src/ad_display_container.dart index be6933fff08c..ec948a95b193 100644 --- a/packages/interactive_media_ads/lib/src/ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/ad_display_container.dart @@ -43,13 +43,9 @@ class AdDisplayContainer extends StatelessWidget { key: key, params: PlatformAdDisplayContainerCreationParams( onContainerAdded: (PlatformAdDisplayContainer container) { - onContainerAdded( - AdDisplayContainer.fromPlatform(platform: container), - ); + onContainerAdded(AdDisplayContainer.fromPlatform(platform: container)); }, - companionSlots: companionSlots.map( - (CompanionAdSlot slot) => slot.platform, - ), + companionSlots: companionSlots.map((CompanionAdSlot slot) => slot.platform), layoutDirection: layoutDirection, ), ); @@ -84,10 +80,7 @@ class AdDisplayContainer extends StatelessWidget { AdDisplayContainer.fromPlatformCreationParams({ Key? key, required PlatformAdDisplayContainerCreationParams params, - }) : this.fromPlatform( - key: key, - platform: PlatformAdDisplayContainer(params), - ); + }) : this.fromPlatform(key: key, platform: PlatformAdDisplayContainer(params)); /// Constructs an [AdDisplayContainer] from a specific platform /// implementation. @@ -102,10 +95,9 @@ class AdDisplayContainer extends StatelessWidget { platform.params.onContainerAdded; /// List of companion ad slots. - Iterable get companionSlots => - platform.params.companionSlots.map( - (PlatformCompanionAdSlot slot) => CompanionAdSlot.fromPlatform(slot), - ); + Iterable get companionSlots => platform.params.companionSlots.map( + (PlatformCompanionAdSlot slot) => CompanionAdSlot.fromPlatform(slot), + ); /// The layout direction to use for the embedded AdDisplayContainer. TextDirection get layoutDirection => platform.params.layoutDirection; diff --git a/packages/interactive_media_ads/lib/src/ads_loader.dart b/packages/interactive_media_ads/lib/src/ads_loader.dart index 6bbf7d1676fe..48c38f0f0d7e 100644 --- a/packages/interactive_media_ads/lib/src/ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/ads_loader.dart @@ -92,8 +92,7 @@ class AdsLoader { final PlatformAdsLoader platform; /// Defines general SDK settings. - ImaSettings get settings => - ImaSettings.fromPlatform(platform.params.settings); + ImaSettings get settings => ImaSettings.fromPlatform(platform.params.settings); /// Signals to the SDK that the content has completed. Future contentComplete() { diff --git a/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart b/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart index 8ecb4623e5e9..6de2faf0c025 100644 --- a/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart +++ b/packages/interactive_media_ads/lib/src/ads_manager_delegate.dart @@ -38,8 +38,7 @@ class AdsManagerDelegate { void Function(AdErrorEvent event)? onAdErrorEvent, }) : this.fromPlatformCreationParams( PlatformAdsManagerDelegateCreationParams( - onAdEvent: (PlatformAdEvent event) => - onAdEvent?.call(AdEvent._fromPlatform(event)), + onAdEvent: (PlatformAdEvent event) => onAdEvent?.call(AdEvent._fromPlatform(event)), onAdErrorEvent: onAdErrorEvent, ), ); @@ -71,9 +70,8 @@ class AdsManagerDelegate { /// ); /// ``` /// {@endtemplate} - AdsManagerDelegate.fromPlatformCreationParams( - PlatformAdsManagerDelegateCreationParams params, - ) : this.fromPlatform(PlatformAdsManagerDelegate(params)); + AdsManagerDelegate.fromPlatformCreationParams(PlatformAdsManagerDelegateCreationParams params) + : this.fromPlatform(PlatformAdsManagerDelegate(params)); /// Constructs a [AdsManagerDelegate] from a specific platform implementation. AdsManagerDelegate.fromPlatform(this.platform); @@ -87,8 +85,7 @@ class AdsManagerDelegate { /// Invoked when there was an error playing the ad. Log the error and resume /// playing content. - void Function(AdErrorEvent event)? get onAdErrorEvent => - platform.params.onAdErrorEvent; + void Function(AdErrorEvent event)? get onAdErrorEvent => platform.params.onAdErrorEvent; } /// Simple data class used to transport ad playback information. diff --git a/packages/interactive_media_ads/lib/src/ads_request.dart b/packages/interactive_media_ads/lib/src/ads_request.dart index 0ba8cdde35bf..dea8b976ae0d 100644 --- a/packages/interactive_media_ads/lib/src/ads_request.dart +++ b/packages/interactive_media_ads/lib/src/ads_request.dart @@ -82,8 +82,7 @@ class AdsRequest { /// A [ContentProgressProvider] instance to allow scheduling of ad breaks /// based on content progress (cue points). - ContentProgressProvider? get contentProgressProvider => - platform.contentProgressProvider != null + ContentProgressProvider? get contentProgressProvider => platform.contentProgressProvider != null ? ContentProgressProvider.fromPlatform(platform.contentProgressProvider!) : null; @@ -110,8 +109,7 @@ class AdsRequest { /// Specifies the maximum amount of time to wait, after calling requestAds, /// before requesting the ad tag URL. - Duration? get liveStreamPrefetchMaxWaitTime => - platform.liveStreamPrefetchMaxWaitTime; + Duration? get liveStreamPrefetchMaxWaitTime => platform.liveStreamPrefetchMaxWaitTime; /// Specifies the VAST load timeout in milliseconds for a single wrapper. Duration? get vastLoadTimeout => platform.vastLoadTimeout; diff --git a/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart b/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart index c0e6d17ba8c6..2dd0f5c41654 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ad_display_container.dart @@ -23,8 +23,7 @@ final class AndroidAdDisplayContainerCreationParams required super.onContainerAdded, super.companionSlots, @visibleForTesting PlatformViewsServiceProxy? platformViewsProxy, - }) : _platformViewsProxy = - platformViewsProxy ?? const PlatformViewsServiceProxy(), + }) : _platformViewsProxy = platformViewsProxy ?? const PlatformViewsServiceProxy(), super(); /// Creates a [AndroidAdDisplayContainerCreationParams] from an instance of @@ -85,8 +84,7 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { /// Methods that must be triggered to update the IMA SDK of the state of /// playback of an ad. @internal - final Set videoAdPlayerCallbacks = - {}; + final Set videoAdPlayerCallbacks = {}; // Handles ad playback callbacks from the IMA SDK. For a player to be used for // ad playback, the callbacks in this class must be implemented. This also @@ -104,8 +102,7 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { ima.AdDisplayContainer? adDisplayContainer; // Queue of ads to be played. - final Queue _loadedAdMediaInfoQueue = - Queue(); + final Queue _loadedAdMediaInfoQueue = Queue(); // The saved ad position, used to resume ad playback following an ad // click-through. @@ -158,9 +155,7 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { // The `VideoView` is replaced to clear the last frame of the last loaded // ad. See https://stackoverflow.com/questions/25660994/clear-video-frame-from-surfaceview-on-video-complete. _frameLayout.removeView(_videoView); - _videoView = _setUpVideoView( - WeakReference(this), - ); + _videoView = _setUpVideoView(WeakReference(this)); _frameLayout.addView(_videoView); _clearMediaPlayer(); @@ -178,29 +173,27 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { void _startAdProgressTracking() { // Stop any previous ad tracking. _stopAdProgressTracking(); - _adProgressTimer = Timer.periodic( - const Duration(milliseconds: _progressPollingMs), - (Timer timer) async { - final int videoCurrentPosition = await _videoView.getCurrentPosition(); - if (_adDuration case final int adDuration) { - final currentProgress = ima.VideoProgressUpdate( - currentTimeMs: videoCurrentPosition, - durationMs: adDuration, - ); + _adProgressTimer = Timer.periodic(const Duration(milliseconds: _progressPollingMs), ( + Timer timer, + ) async { + final int videoCurrentPosition = await _videoView.getCurrentPosition(); + if (_adDuration case final int adDuration) { + final currentProgress = ima.VideoProgressUpdate( + currentTimeMs: videoCurrentPosition, + durationMs: adDuration, + ); - await Future.wait(>[ - _videoAdPlayer.setAdProgress(currentProgress), - - if (_loadedAdMediaInfoQueue.firstOrNull - case final ima.AdMediaInfo loadedAdMediaInfo) - ...videoAdPlayerCallbacks.map( - (ima.VideoAdPlayerCallback callback) => - callback.onAdProgress(loadedAdMediaInfo, currentProgress), - ), - ]); - } - }, - ); + await Future.wait(>[ + _videoAdPlayer.setAdProgress(currentProgress), + + if (_loadedAdMediaInfoQueue.firstOrNull case final ima.AdMediaInfo loadedAdMediaInfo) + ...videoAdPlayerCallbacks.map( + (ima.VideoAdPlayerCallback callback) => + callback.onAdProgress(loadedAdMediaInfo, currentProgress), + ), + ]); + } + }); } // Stops updating the IMA SDK the progress of the currently playing ad. @@ -223,17 +216,14 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { // This value is created in a static method because the callback methods for // any wrapped classes must not reference the encapsulating object. This is to // prevent a circular reference that prevents garbage collection. - static ima.VideoView _setUpVideoView( - WeakReference weakThis, - ) { + static ima.VideoView _setUpVideoView(WeakReference weakThis) { return ima.VideoView( onCompletion: (_, __) { final AndroidAdDisplayContainer? container = weakThis.target; if (container != null) { container._clearMediaPlayer(); container._stopAdProgressTracking(); - for (final ima.VideoAdPlayerCallback callback - in container.videoAdPlayerCallbacks) { + for (final ima.VideoAdPlayerCallback callback in container.videoAdPlayerCallbacks) { callback.onEnded(container._loadedAdMediaInfoQueue.first); } } @@ -257,8 +247,7 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { final AndroidAdDisplayContainer? container = weakThis.target; if (container != null) { container._clearMediaPlayer(); - for (final ima.VideoAdPlayerCallback callback - in container.videoAdPlayerCallbacks) { + for (final ima.VideoAdPlayerCallback callback in container.videoAdPlayerCallbacks) { callback.onError(container._loadedAdMediaInfoQueue.first); } } @@ -269,9 +258,7 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { // This value is created in a static method because the callback methods for // any wrapped classes must not reference the encapsulating object. This is to // prevent a circular reference that prevents garbage collection. - static ima.VideoAdPlayer _setUpVideoAdPlayer( - WeakReference weakThis, - ) { + static ima.VideoAdPlayer _setUpVideoAdPlayer(WeakReference weakThis) { return ima.VideoAdPlayer( addCallback: (_, ima.VideoAdPlayerCallback callback) { weakThis.target?.videoAdPlayerCallbacks.add(callback); @@ -296,12 +283,10 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { // app is returned to the foreground. container._startPlayerWhenVideoIsPrepared = false; await player.pause(); - container._savedAdPosition = await container._videoView - .getCurrentPosition(); + container._savedAdPosition = await container._videoView.getCurrentPosition(); container._stopAdProgressTracking(); await Future.wait(>[ - for (final ima.VideoAdPlayerCallback callback - in container.videoAdPlayerCallbacks) + for (final ima.VideoAdPlayerCallback callback in container.videoAdPlayerCallbacks) callback.onPause(container._loadedAdMediaInfoQueue.first), ]); } @@ -311,19 +296,14 @@ base class AndroidAdDisplayContainer extends PlatformAdDisplayContainer { if (container != null) { assert(container._loadedAdMediaInfoQueue.first == adMediaInfo); - container._videoView.setAudioFocusRequest( - ima.AudioManagerAudioFocus.gain, - ); + container._videoView.setAudioFocusRequest(ima.AudioManagerAudioFocus.gain); if (container._mediaPlayer != null) { - container._mediaPlayer!.start().then( - (_) => container._startAdProgressTracking(), - ); + container._mediaPlayer!.start().then((_) => container._startAdProgressTracking()); } container._startPlayerWhenVideoIsPrepared = true; - for (final ima.VideoAdPlayerCallback callback - in container.videoAdPlayerCallbacks) { + for (final ima.VideoAdPlayerCallback callback in container.videoAdPlayerCallbacks) { if (container._savedAdPosition == 0) { callback.onPlay(adMediaInfo); } else { @@ -393,8 +373,7 @@ class _AdPlayerState extends State<_AdPlayer> with WidgetsBindingObserver { Widget build(BuildContext context) { return AndroidViewWidget( view: widget.container._frameLayout, - platformViewsServiceProxy: - widget.container._androidParams._platformViewsProxy, + platformViewsServiceProxy: widget.container._androidParams._platformViewsProxy, layoutDirection: widget.container._androidParams.layoutDirection, onPlatformViewCreated: () async { final ima.AdDisplayContainer nativeContainer = @@ -402,15 +381,11 @@ class _AdPlayerState extends State<_AdPlayer> with WidgetsBindingObserver { widget.container._frameLayout, widget.container._videoAdPlayer, ); - final Iterable nativeCompanionSlots = - await Future.wait( - widget.container._androidParams.companionSlots.map(( - PlatformCompanionAdSlot slot, - ) { - return (slot as AndroidCompanionAdSlot) - .getNativeCompanionAdSlot(); - }), - ); + final Iterable nativeCompanionSlots = await Future.wait( + widget.container._androidParams.companionSlots.map((PlatformCompanionAdSlot slot) { + return (slot as AndroidCompanionAdSlot).getNativeCompanionAdSlot(); + }), + ); await nativeContainer.setCompanionSlots(nativeCompanionSlots.toList()); widget.container.adDisplayContainer = nativeContainer; diff --git a/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart b/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart index 0dcd067b1eca..884a066402a8 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ads_loader.dart @@ -15,8 +15,7 @@ import 'enum_converter_utils.dart'; import 'interactive_media_ads.g.dart' as ima; /// Android implementation of [PlatformAdsLoaderCreationParams]. -final class AndroidAdsLoaderCreationParams - extends PlatformAdsLoaderCreationParams { +final class AndroidAdsLoaderCreationParams extends PlatformAdsLoaderCreationParams { /// Constructs a [AndroidAdsLoaderCreationParams]. const AndroidAdsLoaderCreationParams({ required super.settings, @@ -45,8 +44,7 @@ base class AndroidAdsLoader extends PlatformAdsLoader { AndroidAdsLoader(super.params) : assert(params.container is AndroidAdDisplayContainer), assert( - (params.container as AndroidAdDisplayContainer).adDisplayContainer != - null, + (params.container as AndroidAdDisplayContainer).adDisplayContainer != null, 'Ensure the AdDisplayContainer has been added to the Widget tree before creating an AdsLoader.', ), super.implementation() { @@ -59,18 +57,14 @@ base class AndroidAdsLoader extends PlatformAdsLoader { late final AndroidAdsLoaderCreationParams _androidParams = params is AndroidAdsLoaderCreationParams ? params as AndroidAdsLoaderCreationParams - : AndroidAdsLoaderCreationParams.fromPlatformAdsLoaderCreationParams( - params, - ); + : AndroidAdsLoaderCreationParams.fromPlatformAdsLoaderCreationParams(params); @override Future contentComplete() async { final Set callbacks = (params.container as AndroidAdDisplayContainer).videoAdPlayerCallbacks; await Future.wait( - callbacks.map( - (ima.VideoAdPlayerCallback callback) => callback.onContentComplete(), - ), + callbacks.map((ima.VideoAdPlayerCallback callback) => callback.onContentComplete()), ); } @@ -99,21 +93,16 @@ base class AndroidAdsLoader extends PlatformAdsLoader { androidRequest.setContentKeywords(contentKeywords), if (request.contentTitle case final String contentTitle) androidRequest.setContentTitle(contentTitle), - if (request.liveStreamPrefetchMaxWaitTime - case final Duration liveStreamPrefetchMaxWaitTime) + if (request.liveStreamPrefetchMaxWaitTime case final Duration liveStreamPrefetchMaxWaitTime) androidRequest.setLiveStreamPrefetchSeconds( - liveStreamPrefetchMaxWaitTime.inMilliseconds / - Duration.millisecondsPerSecond, + liveStreamPrefetchMaxWaitTime.inMilliseconds / Duration.millisecondsPerSecond, ), if (request.vastLoadTimeout case final Duration vastLoadTimeout) - androidRequest.setVastLoadTimeout( - vastLoadTimeout.inMilliseconds.toDouble(), - ), + androidRequest.setVastLoadTimeout(vastLoadTimeout.inMilliseconds.toDouble()), if (request.contentProgressProvider case final PlatformContentProgressProvider contentProgressProvider) androidRequest.setContentProgressProvider( - (contentProgressProvider as AndroidContentProgressProvider) - .progressProvider, + (contentProgressProvider as AndroidContentProgressProvider).progressProvider, ), adsLoader.requestAds(androidRequest), ]); @@ -138,10 +127,7 @@ base class AndroidAdsLoader extends PlatformAdsLoader { // This value is created in a static method because the callback methods for // any wrapped classes must not reference the encapsulating object. This is to // prevent a circular reference that prevents garbage collection. - static void _addListeners( - WeakReference weakThis, - ima.AdsLoader adsLoader, - ) { + static void _addListeners(WeakReference weakThis, ima.AdsLoader adsLoader) { adsLoader ..addAdsLoadedListener( ima.AdsLoadedListener( diff --git a/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart b/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart index a7fab6e24687..0d83b2d48ca1 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ads_manager.dart @@ -20,9 +20,7 @@ class AndroidAdsManager extends PlatformAdsManager { super( adCuePoints: List.unmodifiable( manager.adCuePoints.map((double seconds) { - return Duration( - milliseconds: (seconds * Duration.millisecondsPerSecond).round(), - ); + return Duration(milliseconds: (seconds * Duration.millisecondsPerSecond).round()); }), ), ); @@ -49,9 +47,7 @@ class AndroidAdsManager extends PlatformAdsManager { } @override - Future setAdsManagerDelegate( - PlatformAdsManagerDelegate delegate, - ) async { + Future setAdsManagerDelegate(PlatformAdsManagerDelegate delegate) async { _managerDelegate = delegate; _addListeners(WeakReference(this)); } @@ -91,8 +87,7 @@ class AndroidAdsManager extends PlatformAdsManager { weakThis.target?._managerDelegate?.params.onAdEvent?.call( PlatformAdEvent( type: toInterfaceEventType(event.type), - adData: - event.adData?.cast() ?? {}, + adData: event.adData?.cast() ?? {}, ad: event.ad != null ? _asPlatformAd(event.ad!) : null, ), ); @@ -137,17 +132,11 @@ PlatformAd _asPlatformAd(ima.Ad ad) { description: ad.description, duration: ad.duration == -1 ? null - : Duration( - milliseconds: (ad.duration * Duration.millisecondsPerSecond) - .round(), - ), + : Duration(milliseconds: (ad.duration * Duration.millisecondsPerSecond).round()), height: ad.height, skipTimeOffset: ad.skipTimeOffset == -1 ? null - : Duration( - milliseconds: (ad.skipTimeOffset * Duration.millisecondsPerSecond) - .round(), - ), + : Duration(milliseconds: (ad.skipTimeOffset * Duration.millisecondsPerSecond).round()), surveyUrl: ad.surveyUrl, title: ad.title, traffickingParameters: ad.traffickingParameters, @@ -176,15 +165,10 @@ PlatformAdPodInfo _asPlatformAdInfo(ima.AdPodInfo adPodInfo) { adPosition: adPodInfo.adPosition, maxDuration: adPodInfo.maxDuration == -1 ? null - : Duration( - milliseconds: - (adPodInfo.maxDuration * Duration.millisecondsPerSecond) - .round(), - ), + : Duration(milliseconds: (adPodInfo.maxDuration * Duration.millisecondsPerSecond).round()), podIndex: adPodInfo.podIndex, timeOffset: Duration( - milliseconds: (adPodInfo.timeOffset * Duration.millisecondsPerSecond) - .round(), + milliseconds: (adPodInfo.timeOffset * Duration.millisecondsPerSecond).round(), ), totalAds: adPodInfo.totalAds, isBumper: adPodInfo.isBumper, @@ -200,15 +184,9 @@ PlatformCompanionAd _asPlatformCompanionAd(ima.CompanionAd ad) { ); } -PlatformUniversalAdId _asPlatformUniversalAdId( - ima.UniversalAdId universalAdId, -) { +PlatformUniversalAdId _asPlatformUniversalAdId(ima.UniversalAdId universalAdId) { return PlatformUniversalAdId( - adIdValue: universalAdId.adIdValue == 'unknown' - ? null - : universalAdId.adIdValue, - adIdRegistry: universalAdId.adIdRegistry == 'unknown' - ? null - : universalAdId.adIdRegistry, + adIdValue: universalAdId.adIdValue == 'unknown' ? null : universalAdId.adIdValue, + adIdRegistry: universalAdId.adIdRegistry == 'unknown' ? null : universalAdId.adIdRegistry, ); } diff --git a/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart b/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart index 60dcf11caa40..7dfdf5298703 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ads_rendering_settings.dart @@ -56,19 +56,15 @@ base class AndroidAdsRenderingSettings extends PlatformAdsRenderingSettings { ima.AdsRenderingSettings nativeSettings, ) async { await Future.wait(>[ - if (_androidParams.bitrate != null) - nativeSettings.setBitrateKbps(params.bitrate!), + if (_androidParams.bitrate != null) nativeSettings.setBitrateKbps(params.bitrate!), if (_androidParams.enablePreloading != null) nativeSettings.setEnablePreloading(_androidParams.enablePreloading!), - nativeSettings.setLoadVideoTimeout( - _androidParams.loadVideoTimeout.inMilliseconds, - ), + nativeSettings.setLoadVideoTimeout(_androidParams.loadVideoTimeout.inMilliseconds), if (_androidParams.mimeTypes != null) nativeSettings.setMimeTypes(_androidParams.mimeTypes!), if (_androidParams.playAdsAfterTime != null) nativeSettings.setPlayAdsAfterTime( - _androidParams.playAdsAfterTime!.inMicroseconds / - Duration.microsecondsPerSecond, + _androidParams.playAdsAfterTime!.inMicroseconds / Duration.microsecondsPerSecond, ), if (_androidParams.uiElements != null) nativeSettings.setUiElements( diff --git a/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart b/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart index 23c21b733494..7d31d6656c7b 100644 --- a/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart +++ b/packages/interactive_media_ads/lib/src/android/android_companion_ad_slot.dart @@ -13,15 +13,13 @@ import 'interactive_media_ads.g.dart' as ima; import 'platform_views_service_proxy.dart'; /// Android implementation of [PlatformCompanionAdSlotCreationParams]. -final class AndroidCompanionAdSlotCreationParams - extends PlatformCompanionAdSlotCreationParams { +final class AndroidCompanionAdSlotCreationParams extends PlatformCompanionAdSlotCreationParams { /// Constructs an [AndroidCompanionAdSlotCreationParams]. const AndroidCompanionAdSlotCreationParams({ required super.size, super.onClicked, @visibleForTesting PlatformViewsServiceProxy? platformViewsProxy, - }) : _platformViewsProxy = - platformViewsProxy ?? const PlatformViewsServiceProxy(), + }) : _platformViewsProxy = platformViewsProxy ?? const PlatformViewsServiceProxy(), super(); /// Creates a [AndroidCompanionAdSlotCreationParams] from an instance of @@ -45,8 +43,7 @@ base class AndroidCompanionAdSlot extends PlatformCompanionAdSlot { /// Constructs an [AndroidCompanionAdSlot]. AndroidCompanionAdSlot(super.params) : super.implementation(); - late final AndroidCompanionAdSlotCreationParams _androidParams = - _initAndroidParams(params); + late final AndroidCompanionAdSlotCreationParams _androidParams = _initAndroidParams(params); // ViewGroup used to display the Ad. late final ima.ViewGroup _frameLayout = ima.FrameLayout(); @@ -80,23 +77,17 @@ base class AndroidCompanionAdSlot extends PlatformCompanionAdSlot { } Future _initCompanionAdSlot() async { - final ima.CompanionAdSlot adSlot = await ima.ImaSdkFactory.instance - .createCompanionAdSlot(); + final ima.CompanionAdSlot adSlot = await ima.ImaSdkFactory.instance.createCompanionAdSlot(); await Future.wait(>[ adSlot.setContainer(_frameLayout), switch (params.size) { - final CompanionAdSlotSizeFixed size => adSlot.setSize( - size.width, - size.height, - ), + final CompanionAdSlotSizeFixed size => adSlot.setSize(size.width, size.height), CompanionAdSlotSizeFluid() => adSlot.setFluidSize(), }, if (params.onClicked != null) adSlot.addClickListener( - _createAdSlotClickListener( - WeakReference(this), - ), + _createAdSlotClickListener(WeakReference(this)), ), ]); diff --git a/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart b/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart index 21423431966b..ba762315fb2c 100644 --- a/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart +++ b/packages/interactive_media_ads/lib/src/android/android_content_progress_provider.dart @@ -10,8 +10,7 @@ import '../platform_interface/platform_content_progress_provider.dart'; import 'interactive_media_ads.g.dart' as ima; /// Android implementation of [PlatformContentProgressProvider]. -base class AndroidContentProgressProvider - extends PlatformContentProgressProvider { +base class AndroidContentProgressProvider extends PlatformContentProgressProvider { /// Constructs an [AndroidContentProgressProvider]. AndroidContentProgressProvider(super.params) : super.implementation(); @@ -19,14 +18,10 @@ base class AndroidContentProgressProvider /// /// This allows the SDK to track progress of the content video. @internal - late final ima.ContentProgressProvider progressProvider = - ima.ContentProgressProvider(); + late final ima.ContentProgressProvider progressProvider = ima.ContentProgressProvider(); @override - Future setProgress({ - required Duration progress, - required Duration duration, - }) async { + Future setProgress({required Duration progress, required Duration duration}) async { return progressProvider.setContentProgress( ima.VideoProgressUpdate( currentTimeMs: progress.inMilliseconds, diff --git a/packages/interactive_media_ads/lib/src/android/android_ima_settings.dart b/packages/interactive_media_ads/lib/src/android/android_ima_settings.dart index 7a42e512059e..3ee771dfb8ad 100644 --- a/packages/interactive_media_ads/lib/src/android/android_ima_settings.dart +++ b/packages/interactive_media_ads/lib/src/android/android_ima_settings.dart @@ -69,8 +69,7 @@ final class AndroidImaSettings extends PlatformImaSettings { } Future _createSettings() async { - final ImaSdkSettings settings = await ImaSdkFactory.instance - .createImaSdkSettings(); + final ImaSdkSettings settings = await ImaSdkFactory.instance.createImaSdkSettings(); if (params.language case final String language) { await settings.setLanguage(language); } diff --git a/packages/interactive_media_ads/lib/src/android/android_interactive_media_ads.dart b/packages/interactive_media_ads/lib/src/android/android_interactive_media_ads.dart index 7df8eefd3044..0ca717b928af 100644 --- a/packages/interactive_media_ads/lib/src/android/android_interactive_media_ads.dart +++ b/packages/interactive_media_ads/lib/src/android/android_interactive_media_ads.dart @@ -33,9 +33,7 @@ final class AndroidInteractiveMediaAds extends InteractiveMediaAdsPlatform { } @override - AndroidAdsLoader createPlatformAdsLoader( - PlatformAdsLoaderCreationParams params, - ) { + AndroidAdsLoader createPlatformAdsLoader(PlatformAdsLoaderCreationParams params) { return AndroidAdsLoader(params); } @@ -68,9 +66,7 @@ final class AndroidInteractiveMediaAds extends InteractiveMediaAdsPlatform { } @override - AndroidImaSettings createPlatformImaSettings( - PlatformImaSettingsCreationParams params, - ) { + AndroidImaSettings createPlatformImaSettings(PlatformImaSettingsCreationParams params) { return AndroidImaSettings(params); } } diff --git a/packages/interactive_media_ads/lib/src/android/android_view_widget.dart b/packages/interactive_media_ads/lib/src/android/android_view_widget.dart index 4c58c1dbf0f8..e9507a1b894f 100644 --- a/packages/interactive_media_ads/lib/src/android/android_view_widget.dart +++ b/packages/interactive_media_ads/lib/src/android/android_view_widget.dart @@ -29,8 +29,7 @@ class AndroidViewWidget extends StatelessWidget { }); /// The unique identifier for the view type to be embedded. - static const String _viewType = - 'interactive_media_ads.packages.flutter.dev/view'; + static const String _viewType = 'interactive_media_ads.packages.flutter.dev/view'; /// The reference to the Android native view that should be shown. final ima.View view; @@ -53,15 +52,13 @@ class AndroidViewWidget extends StatelessWidget { Widget build(BuildContext context) { return PlatformViewLink( viewType: _viewType, - surfaceFactory: - (BuildContext context, PlatformViewController controller) { - return AndroidViewSurface( - controller: controller as AndroidViewController, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - gestureRecognizers: - const >{}, - ); - }, + surfaceFactory: (BuildContext context, PlatformViewController controller) { + return AndroidViewSurface( + controller: controller as AndroidViewController, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + gestureRecognizers: const >{}, + ); + }, onCreatePlatformView: (PlatformViewCreationParams params) { return _initAndroidView(params) ..addOnPlatformViewCreatedListener((int id) { @@ -74,9 +71,7 @@ class AndroidViewWidget extends StatelessWidget { } AndroidViewController _initAndroidView(PlatformViewCreationParams params) { - final int? identifier = ima.PigeonInstanceManager.instance.getIdentifier( - view, - ); + final int? identifier = ima.PigeonInstanceManager.instance.getIdentifier(view); if (displayWithHybridComposition) { return platformViewsServiceProxy.initExpensiveAndroidView( diff --git a/packages/interactive_media_ads/lib/src/android/enum_converter_utils.dart b/packages/interactive_media_ads/lib/src/android/enum_converter_utils.dart index 1733f69a05d0..f482b615a360 100644 --- a/packages/interactive_media_ads/lib/src/android/enum_converter_utils.dart +++ b/packages/interactive_media_ads/lib/src/android/enum_converter_utils.dart @@ -22,8 +22,7 @@ AdEventType toInterfaceEventType(ima.AdEventType type) { ima.AdEventType.allAdsCompleted => AdEventType.allAdsCompleted, ima.AdEventType.completed => AdEventType.complete, ima.AdEventType.contentPauseRequested => AdEventType.contentPauseRequested, - ima.AdEventType.contentResumeRequested => - AdEventType.contentResumeRequested, + ima.AdEventType.contentResumeRequested => AdEventType.contentResumeRequested, ima.AdEventType.loaded => AdEventType.loaded, ima.AdEventType.clicked => AdEventType.clicked, ima.AdEventType.adBreakEnded => AdEventType.adBreakEnded, @@ -36,8 +35,7 @@ AdEventType toInterfaceEventType(ima.AdEventType type) { ima.AdEventType.adProgress => AdEventType.adProgress, ima.AdEventType.cuepointsChanged => AdEventType.cuepointsChanged, ima.AdEventType.firstQuartile => AdEventType.firstQuartile, - ima.AdEventType.iconFallbackImageClosed => - AdEventType.iconFallbackImageClosed, + ima.AdEventType.iconFallbackImageClosed => AdEventType.iconFallbackImageClosed, ima.AdEventType.iconTapped => AdEventType.iconTapped, ima.AdEventType.log => AdEventType.log, ima.AdEventType.midpoint => AdEventType.midpoint, @@ -56,32 +54,24 @@ AdEventType toInterfaceEventType(ima.AdEventType type) { AdErrorCode toInterfaceErrorCode(ima.AdErrorCode code) { return switch (code) { ima.AdErrorCode.adsPlayerWasNotProvided => AdErrorCode.adsPlayerNotProvided, - ima.AdErrorCode.adsRequestNetworkError => - AdErrorCode.adsRequestNetworkError, - ima.AdErrorCode.companionAdLoadingFailed => - AdErrorCode.companionAdLoadingFailed, + ima.AdErrorCode.adsRequestNetworkError => AdErrorCode.adsRequestNetworkError, + ima.AdErrorCode.companionAdLoadingFailed => AdErrorCode.companionAdLoadingFailed, ima.AdErrorCode.failedToRequestAds => AdErrorCode.failedToRequestAds, ima.AdErrorCode.internalError => AdErrorCode.internalError, ima.AdErrorCode.invalidArguments => AdErrorCode.invalidArguments, - ima.AdErrorCode.overlayAdLoadingFailed => - AdErrorCode.overlayAdLoadingFailed, - ima.AdErrorCode.overlayAdPlayingFailed => - AdErrorCode.overlayAdPlayingFailed, - ima.AdErrorCode.playlistNoContentTracking => - AdErrorCode.playlistNoContentTracking, - ima.AdErrorCode.unexpectedAdsLoadedEvent => - AdErrorCode.unexpectedAdsLoadedEvent, + ima.AdErrorCode.overlayAdLoadingFailed => AdErrorCode.overlayAdLoadingFailed, + ima.AdErrorCode.overlayAdPlayingFailed => AdErrorCode.overlayAdPlayingFailed, + ima.AdErrorCode.playlistNoContentTracking => AdErrorCode.playlistNoContentTracking, + ima.AdErrorCode.unexpectedAdsLoadedEvent => AdErrorCode.unexpectedAdsLoadedEvent, ima.AdErrorCode.unknownAdResponse => AdErrorCode.unknownAdResponse, ima.AdErrorCode.unknownError => AdErrorCode.unknownError, ima.AdErrorCode.vastAssetNotFound => AdErrorCode.vastAssetNotFound, ima.AdErrorCode.vastEmptyResponse => AdErrorCode.vastEmptyResponse, - ima.AdErrorCode.vastLinearAssetMismatch => - AdErrorCode.vastLinearAssetMismatch, + ima.AdErrorCode.vastLinearAssetMismatch => AdErrorCode.vastLinearAssetMismatch, ima.AdErrorCode.vastLoadTimeout => AdErrorCode.vastLoadTimeout, ima.AdErrorCode.vastMalformedResponse => AdErrorCode.vastMalformedResponse, ima.AdErrorCode.vastMediaLoadTimeout => AdErrorCode.vastMediaLoadTimeout, - ima.AdErrorCode.vastNonlinearAssetMismatch => - AdErrorCode.vastNonlinearAssetMismatch, + ima.AdErrorCode.vastNonlinearAssetMismatch => AdErrorCode.vastNonlinearAssetMismatch, ima.AdErrorCode.vastNoAdsAfterWrapper => AdErrorCode.vastNoAdsAfterWrapper, ima.AdErrorCode.vastTooManyRedirects => AdErrorCode.vastTooManyRedirects, ima.AdErrorCode.vastTraffickingError => AdErrorCode.vastTraffickingError, diff --git a/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart b/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart index a04465afd2d8..f8b1d0e5ea6d 100644 --- a/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart +++ b/packages/interactive_media_ads/lib/src/android/interactive_media_ads.g.dart @@ -21,11 +21,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -48,10 +44,7 @@ class PigeonOverrides { static ContentProgressProvider Function()? contentProgressProvider_new; /// Overrides [VideoProgressUpdate.new]. - static VideoProgressUpdate Function({ - required int currentTimeMs, - required int durationMs, - })? + static VideoProgressUpdate Function({required int currentTimeMs, required int durationMs})? videoProgressUpdate_new; /// Overrides [FrameLayout.new]. @@ -59,25 +52,16 @@ class PigeonOverrides { /// Overrides [VideoView.new]. static VideoView Function({ - required void Function( - VideoView pigeon_instance, - MediaPlayer player, - int what, - int extra, - ) + required void Function(VideoView pigeon_instance, MediaPlayer player, int what, int extra) onError, - Future Function(VideoView pigeon_instance, MediaPlayer player)? - onPrepared, + Future Function(VideoView pigeon_instance, MediaPlayer player)? onPrepared, void Function(VideoView pigeon_instance, MediaPlayer player)? onCompletion, })? videoView_new; /// Overrides [VideoAdPlayer.new]. static VideoAdPlayer Function({ - required void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - ) + required void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback) addCallback, required void Function( VideoAdPlayer pigeon_instance, @@ -85,58 +69,37 @@ class PigeonOverrides { AdPodInfo adPodInfo, ) loadAd, - required Future Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) - pauseAd, - required void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) - playAd, + required Future Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) pauseAd, + required void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) playAd, required void Function(VideoAdPlayer pigeon_instance) release, - required void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - ) + required void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback) removeCallback, - required void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) - stopAd, + required void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) stopAd, })? videoAdPlayer_new; /// Overrides [AdsLoadedListener.new]. static AdsLoadedListener Function({ - required void Function( - AdsLoadedListener pigeon_instance, - AdsManagerLoadedEvent event, - ) + required void Function(AdsLoadedListener pigeon_instance, AdsManagerLoadedEvent event) onAdsManagerLoaded, })? adsLoadedListener_new; /// Overrides [AdErrorListener.new]. static AdErrorListener Function({ - required void Function(AdErrorListener pigeon_instance, AdErrorEvent event) - onAdError, + required void Function(AdErrorListener pigeon_instance, AdErrorEvent event) onAdError, })? adErrorListener_new; /// Overrides [AdEventListener.new]. static AdEventListener Function({ - required void Function(AdEventListener pigeon_instance, AdEvent event) - onAdEvent, + required void Function(AdEventListener pigeon_instance, AdEvent event) onAdEvent, })? adEventListener_new; /// Overrides [CompanionAdSlotClickListener.new]. static CompanionAdSlotClickListener Function({ - required void Function(CompanionAdSlotClickListener pigeon_instance) - onCompanionAdClick, + required void Function(CompanionAdSlotClickListener pigeon_instance) onCompanionAdClick, })? companionAdSlotClickListener_new; @@ -178,8 +141,7 @@ abstract class PigeonInternalProxyApiBaseClass { PigeonInternalProxyApiBaseClass({ this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + }) : pigeon_instanceManager = pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -249,8 +211,8 @@ class PigeonInstanceManager { // by calling instanceManager.getIdentifier() inside of `==` while this was a // HashMap). final Expando _identifiers = Expando(); - final Map> - _weakInstances = >{}; + final Map> _weakInstances = + >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -265,8 +227,7 @@ class PigeonInstanceManager { return PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); } WidgetsFlutterBinding.ensureInitialized(); - final _PigeonInternalInstanceManagerApi api = - _PigeonInternalInstanceManagerApi(); + final _PigeonInternalInstanceManagerApi api = _PigeonInternalInstanceManagerApi(); // Clears the native `PigeonInstanceManager` on the initial use of the Dart one. api.clear(); final PigeonInstanceManager instanceManager = PigeonInstanceManager( @@ -274,104 +235,42 @@ class PigeonInstanceManager { api.removeStrongReference(identifier); }, ); - _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager, - ); - BaseDisplayContainer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdDisplayContainer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdsLoader.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdsManagerLoadedEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdErrorEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdsRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ContentProgressProvider.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdsManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - BaseManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ImaSdkFactory.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ImaSdkSettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoProgressUpdate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdMediaInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdPodInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - FrameLayout.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ViewGroup.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoView.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + _PigeonInternalInstanceManagerApi.setUpMessageHandlers(instanceManager: instanceManager); + BaseDisplayContainer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdDisplayContainer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdsLoader.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdsManagerLoadedEvent.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdErrorEvent.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdError.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdsRequest.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ContentProgressProvider.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdsManager.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + BaseManager.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdEvent.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ImaSdkFactory.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ImaSdkSettings.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoProgressUpdate.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdMediaInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdPodInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + FrameLayout.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ViewGroup.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoView.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); View.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); - MediaPlayer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoAdPlayerCallback.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - VideoAdPlayer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdsLoadedListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdErrorListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdEventListener.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdsRenderingSettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - AdProgressInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - CompanionAd.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - UniversalAdId.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + MediaPlayer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoAdPlayerCallback.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + VideoAdPlayer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdsLoadedListener.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdErrorListener.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdEventListener.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdsRenderingSettings.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + AdProgressInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + CompanionAd.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + UniversalAdId.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); Ad.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); CompanionAdSlotClickListener.pigeon_setUpMessageHandlers( pigeon_instanceManager: instanceManager, ); - CompanionAdSlot.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + CompanionAdSlot.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); AdSlot.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); return instanceManager; } @@ -389,9 +288,7 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = WeakReference( - instance, - ); + _weakInstances[identifier] = WeakReference(instance); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -452,21 +349,15 @@ class PigeonInstanceManager { /// /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. - T? getInstanceWithWeakReference( - int identifier, - ) { - final PigeonInternalProxyApiBaseClass? weakInstance = - _weakInstances[identifier]?.target; + T? getInstanceWithWeakReference(int identifier) { + final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; if (weakInstance == null) { - final PigeonInternalProxyApiBaseClass? strongInstance = - _strongInstances[identifier]; + final PigeonInternalProxyApiBaseClass? strongInstance = _strongInstances[identifier]; if (strongInstance != null) { - final PigeonInternalProxyApiBaseClass copy = strongInstance - .pigeon_copy(); + final PigeonInternalProxyApiBaseClass copy = strongInstance.pigeon_copy(); _identifiers[copy] = identifier; - _weakInstances[identifier] = - WeakReference(copy); + _weakInstances[identifier] = WeakReference(copy); _finalizer.attach(copy, identifier, detach: copy); return copy as T; } @@ -488,10 +379,7 @@ class PigeonInstanceManager { /// /// Throws assertion error if the instance or its identifier has already been /// added. - void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, - int identifier, - ) { + void addHostCreatedInstance(PigeonInternalProxyApiBaseClass instance, int identifier) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -502,8 +390,7 @@ class PigeonInstanceManager { /// Whether this manager contains the given [identifier]. bool containsIdentifier(int identifier) { - return _weakInstances.containsKey(identifier) || - _strongInstances.containsKey(identifier); + return _weakInstances.containsKey(identifier) || _strongInstances.containsKey(identifier); } int _nextUniqueIdentifier() { @@ -552,9 +439,7 @@ class _PigeonInternalInstanceManagerApi { 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', ); try { - (instanceManager ?? PigeonInstanceManager.instance).remove( - arg_identifier!, - ); + (instanceManager ?? PigeonInstanceManager.instance).remove(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -576,9 +461,7 @@ class _PigeonInternalInstanceManagerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [identifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([identifier]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -637,9 +520,7 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager.getInstanceWithWeakReference( - readValue(buffer)! as int, - ); + return instanceManager.getInstanceWithWeakReference(readValue(buffer)! as int); default: return super.readValueOfType(type, buffer); } @@ -944,10 +825,8 @@ class BaseDisplayContainer extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecBaseDisplayContainer = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecBaseDisplayContainer = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -955,10 +834,9 @@ class BaseDisplayContainer extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, BaseDisplayContainer Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -981,15 +859,14 @@ class BaseDisplayContainer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseDisplayContainer.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - BaseDisplayContainer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + BaseDisplayContainer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1017,9 +894,10 @@ class BaseDisplayContainer extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, companionSlots], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + companionSlots, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1052,10 +930,8 @@ class AdDisplayContainer extends BaseDisplayContainer { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - AdDisplayContainer.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + AdDisplayContainer.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -1063,10 +939,9 @@ class AdDisplayContainer extends BaseDisplayContainer { PigeonInstanceManager? pigeon_instanceManager, AdDisplayContainer Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1089,15 +964,14 @@ class AdDisplayContainer extends BaseDisplayContainer { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdDisplayContainer.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdDisplayContainer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AdDisplayContainer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1130,10 +1004,7 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - AdsLoader.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + AdsLoader.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAdsLoader = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -1144,10 +1015,9 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AdsLoader Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1170,15 +1040,14 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoader.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdsLoader.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AdsLoader.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1194,8 +1063,7 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { /// Registers a listener for errors that occur during the ads request. Future addAdErrorListener(AdErrorListener listener) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsLoader; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.addAdErrorListener'; @@ -1204,9 +1072,7 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, listener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, listener]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1223,8 +1089,7 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { /// Registers a listener for the ads manager loaded event. Future addAdsLoadedListener(AdsLoadedListener listener) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsLoader; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.addAdsLoadedListener'; @@ -1233,9 +1098,7 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, listener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, listener]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1252,19 +1115,15 @@ class AdsLoader extends PigeonInternalProxyApiBaseClass { /// Requests ads from a server. Future requestAds(AdsRequest request) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsLoader; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.requestAds'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsLoader.requestAds'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, request], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, request]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1313,10 +1172,9 @@ class AdsManagerLoadedEvent extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AdsManagerLoadedEvent Function(AdsManager? manager)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1340,16 +1198,15 @@ class AdsManagerLoadedEvent extends PigeonInternalProxyApiBaseClass { ); final AdsManager? arg_manager = (args[1] as AdsManager?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_manager) ?? - AdsManagerLoadedEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - manager: arg_manager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_manager) ?? + AdsManagerLoadedEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + manager: arg_manager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1397,10 +1254,9 @@ class AdErrorEvent extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AdErrorEvent Function(AdError error)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1428,16 +1284,15 @@ class AdErrorEvent extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorEvent.pigeon_newInstance was null, expected non-null AdError.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_error!) ?? - AdErrorEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - error: arg_error!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_error!) ?? + AdErrorEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + error: arg_error!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1503,10 +1358,9 @@ class AdError extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1549,24 +1403,23 @@ class AdError extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdError.pigeon_newInstance was null, expected non-null String.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_errorCode!, - arg_errorCodeNumber!, - arg_errorType!, - arg_message!, - ) ?? - AdError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - errorCode: arg_errorCode!, - errorCodeNumber: arg_errorCodeNumber!, - errorType: arg_errorType!, - message: arg_message!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_errorCode!, + arg_errorCodeNumber!, + arg_errorType!, + arg_message!, + ) ?? + AdError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + errorCode: arg_errorCode!, + errorCodeNumber: arg_errorCodeNumber!, + errorType: arg_errorType!, + message: arg_message!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1602,10 +1455,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - AdsRequest.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + AdsRequest.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAdsRequest = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -1616,10 +1466,9 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AdsRequest Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1642,15 +1491,14 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRequest.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdsRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AdsRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1666,19 +1514,15 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Sets the URL from which ads will be requested. Future setAdTagUrl(String adTagUrl) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdTagUrl'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdTagUrl'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adTagUrl], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, adTagUrl]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1695,11 +1539,8 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Attaches a ContentProgressProvider instance to allow scheduling ad breaks /// based on content progress (cue points). - Future setContentProgressProvider( - ContentProgressProvider provider, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + Future setContentProgressProvider(ContentProgressProvider provider) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentProgressProvider'; @@ -1708,9 +1549,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, provider], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, provider]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1731,8 +1570,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Not calling this function leaves the setting as unknown. Note: Changing /// this setting will have no impact on ad playback. Future setAdWillAutoPlay(bool willAutoPlay) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdWillAutoPlay'; @@ -1741,9 +1579,10 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, willAutoPlay], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + willAutoPlay, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1764,8 +1603,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Not calling this function leaves the setting as unknown. Note: Changing /// this setting will have no impact on ad playback. Future setAdWillPlayMuted(bool willPlayMuted) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdWillPlayMuted'; @@ -1774,9 +1612,10 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, willPlayMuted], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + willPlayMuted, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1794,8 +1633,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Specifies a VAST, VMAP, or ad rules response to be used instead of making /// a request through an ad tag URL. Future setAdsResponse(String cannedAdResponse) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setAdsResponse'; @@ -1804,9 +1642,10 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, cannedAdResponse], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + cannedAdResponse, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1826,8 +1665,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// This optional parameter is used by AdX requests. It is recommended for AdX /// users. Future setContentDuration(double duration) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentDuration'; @@ -1836,9 +1674,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, duration], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, duration]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1858,8 +1694,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// This optional parameter is used by AdX requests and is recommended for AdX /// users. Future setContentKeywords(List keywords) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentKeywords'; @@ -1868,9 +1703,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, keywords], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, keywords]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1890,8 +1723,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Used in AdX requests. This optional parameter is used by AdX requests and /// is recommended for AdX users. Future setContentTitle(String title) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContentTitle'; @@ -1900,9 +1732,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, title], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, title]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1923,8 +1753,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// Not calling this function leaves the setting as unknown. Note: Changing /// this setting will have no impact on ad playback. Future setContinuousPlayback(bool continuousPlayback) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setContinuousPlayback'; @@ -1933,9 +1762,10 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, continuousPlayback], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + continuousPlayback, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1956,8 +1786,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// This can be used to stagger requests during a live-stream event, in order /// to mitigate spikes in the number of requests. Future setLiveStreamPrefetchSeconds(double prefetchTime) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setLiveStreamPrefetchSeconds'; @@ -1966,9 +1795,10 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, prefetchTime], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + prefetchTime, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1988,8 +1818,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { /// This parameter is optional and will override the default timeout, /// currently set to 5000ms. Future setVastLoadTimeout(double timeout) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsRequest.setVastLoadTimeout'; @@ -1998,9 +1827,7 @@ class AdsRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, timeout], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, timeout]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2042,12 +1869,8 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { } @protected - ContentProgressProvider.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + ContentProgressProvider.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecContentProgressProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -2058,9 +1881,9 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2087,10 +1910,8 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecContentProgressProvider = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecContentProgressProvider = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -2098,10 +1919,9 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ContentProgressProvider Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2124,15 +1944,14 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.ContentProgressProvider.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ContentProgressProvider.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ContentProgressProvider.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2161,9 +1980,7 @@ class ContentProgressProvider extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, update], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, update]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2217,10 +2034,9 @@ class AdsManager extends BaseManager { PigeonInstanceManager? pigeon_instanceManager, AdsManager Function(List adCuePoints)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2242,23 +2058,21 @@ class AdsManager extends BaseManager { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance was null, expected non-null int.', ); - final List? arg_adCuePoints = (args[1] as List?) - ?.cast(); + final List? arg_adCuePoints = (args[1] as List?)?.cast(); assert( arg_adCuePoints != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsManager.pigeon_newInstance was null, expected non-null List.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adCuePoints!) ?? - AdsManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adCuePoints: arg_adCuePoints!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_adCuePoints!) ?? + AdsManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adCuePoints: arg_adCuePoints!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2274,8 +2088,7 @@ class AdsManager extends BaseManager { /// Discards current ad break and resumes content. Future discardAdBreak() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsManager.discardAdBreak'; @@ -2284,9 +2097,7 @@ class AdsManager extends BaseManager { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2303,19 +2114,15 @@ class AdsManager extends BaseManager { /// Pauses the current ad. Future pause() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdsManager.pause'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsManager.pause'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2332,19 +2139,15 @@ class AdsManager extends BaseManager { /// Starts playing the ads. Future start() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdsManager.start'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsManager.start'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2361,19 +2164,15 @@ class AdsManager extends BaseManager { /// Resumes the current ad. Future resume() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdsManager.resume'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsManager.resume'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2393,19 +2192,15 @@ class AdsManager extends BaseManager { /// `AdsManager.skip()` only skips ads if IMA does not render the 'Skip ad' /// button. Future skip() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdsManager.skip'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsManager.skip'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2439,10 +2234,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - BaseManager.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + BaseManager.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecBaseManager = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -2453,10 +2245,9 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, BaseManager Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2479,15 +2270,14 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.BaseManager.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - BaseManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + BaseManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2504,8 +2294,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Registers a listener for errors that occur during the ad or stream /// initialization and playback. Future addAdErrorListener(AdErrorListener errorListener) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.addAdErrorListener'; @@ -2514,9 +2303,10 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, errorListener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + errorListener, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2534,8 +2324,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Registers a listener for ad events that occur during ad or stream /// initialization and playback. Future addAdEventListener(AdEventListener adEventListener) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.addAdEventListener'; @@ -2544,9 +2333,10 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adEventListener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adEventListener, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2564,19 +2354,15 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Stops the ad and all tracking, then releases all assets that were loaded /// to play the ad. Future destroy() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.BaseManager.destroy'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.destroy'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2593,19 +2379,15 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Initializes the ad experience on the manager. Future init(AdsRenderingSettings? settings) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.BaseManager.init'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.init'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, settings], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, settings]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2622,19 +2404,15 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Generic focus endpoint that puts focus on the skip button if present. Future focus() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.BaseManager.focus'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.focus'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2651,8 +2429,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Returns the latest AdProgressInfo for the current playing ad. Future getAdProgressInfo() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.getAdProgressInfo'; @@ -2661,9 +2438,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2680,8 +2455,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Get currently playing ad. Future getCurrentAd() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.getCurrentAd'; @@ -2690,9 +2464,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2709,8 +2481,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Removes a listener for error events. Future removeAdErrorListener(AdErrorListener errorListener) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.removeAdErrorListener'; @@ -2719,9 +2490,10 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, errorListener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + errorListener, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2738,8 +2510,7 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { /// Removes a listener for ad events. Future removeAdEventListener(AdEventListener adEventListener) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecBaseManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecBaseManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.BaseManager.removeAdEventListener'; @@ -2748,9 +2519,10 @@ class BaseManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adEventListener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adEventListener, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2804,13 +2576,11 @@ class AdEvent extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - AdEvent Function(AdEventType type, Map? adData, Ad? ad)? - pigeon_newInstance, + AdEvent Function(AdEventType type, Map? adData, Ad? ad)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2837,22 +2607,21 @@ class AdEvent extends PigeonInternalProxyApiBaseClass { arg_type != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEvent.pigeon_newInstance was null, expected non-null AdEventType.', ); - final Map? arg_adData = - (args[2] as Map?)?.cast(); + final Map? arg_adData = (args[2] as Map?) + ?.cast(); final Ad? arg_ad = (args[3] as Ad?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_type!, arg_adData, arg_ad) ?? - AdEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - adData: arg_adData, - ad: arg_ad, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_type!, arg_adData, arg_ad) ?? + AdEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + adData: arg_adData, + ad: arg_ad, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2887,18 +2656,14 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - ImaSdkFactory.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + ImaSdkFactory.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecImaSdkFactory = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static final ImaSdkFactory _instance = pigeonVar_instance(); - static ImaSdkFactory get instance => - PigeonOverrides.imaSdkFactory_instance ?? _instance; + static ImaSdkFactory get instance => PigeonOverrides.imaSdkFactory_instance ?? _instance; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -2906,10 +2671,9 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ImaSdkFactory Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2932,15 +2696,14 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ImaSdkFactory.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ImaSdkFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2956,12 +2719,14 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { static ImaSdkFactory pigeonVar_instance() { final ImaSdkFactory pigeonVar_instance = ImaSdkFactory.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.instance'; @@ -2970,9 +2735,9 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2996,15 +2761,11 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, }) async { if (PigeonOverrides.imaSdkFactory_createAdDisplayContainer != null) { - return PigeonOverrides.imaSdkFactory_createAdDisplayContainer!( - container, - player, - ); + return PigeonOverrides.imaSdkFactory_createAdDisplayContainer!(container, player); } - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdDisplayContainer'; @@ -3013,9 +2774,10 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [container, player], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + container, + player, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3037,8 +2799,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { /// Creates a CompanionAdSlot for the SDK to fill with companion ads. Future createCompanionAdSlot() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkFactory; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createCompanionAdSlot'; @@ -3047,9 +2808,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3071,8 +2830,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { /// Creates an `ImaSdkSettings` object for configuring the IMA SDK. Future createImaSdkSettings() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkFactory; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createImaSdkSettings'; @@ -3081,9 +2839,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3105,12 +2861,8 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { /// Creates an `AdsLoader` for requesting ads using the specified settings /// object. - Future createAdsLoader( - ImaSdkSettings settings, - AdDisplayContainer container, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkFactory; + Future createAdsLoader(ImaSdkSettings settings, AdDisplayContainer container) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdsLoader'; @@ -3119,9 +2871,11 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, settings, container], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + settings, + container, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3143,8 +2897,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { /// Creates an AdsRequest object to contain the data used to request ads. Future createAdsRequest() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkFactory; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdsRequest'; @@ -3153,9 +2906,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3178,8 +2929,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { /// Creates an `AdsRenderingSettings` object to give the AdsManager parameters /// that control the rendering of ads. Future createAdsRenderingSettings() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkFactory; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkFactory.createAdsRenderingSettings'; @@ -3188,9 +2938,7 @@ class ImaSdkFactory extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3228,10 +2976,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - ImaSdkSettings.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + ImaSdkSettings.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecImaSdkSettings = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -3242,10 +2987,9 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ImaSdkSettings Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3268,15 +3012,14 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ImaSdkSettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ImaSdkSettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3292,8 +3035,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// Sets whether to automatically play VMAP and ad rules ad breaks. Future setAutoPlayAdBreaks(bool autoPlayAdBreaks) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setAutoPlayAdBreaks'; @@ -3302,9 +3044,10 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, autoPlayAdBreaks], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + autoPlayAdBreaks, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3321,8 +3064,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// Enables and disables the debug mode, which is disabled by default. Future setDebugMode(bool debugMode) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setDebugMode'; @@ -3331,9 +3073,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, debugMode], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, debugMode]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3354,8 +3094,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// will remain constant until the next ad request. Calling this method again /// will reset any feature flags for the next ad request. Future setFeatureFlags(Map featureFlags) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setFeatureFlags'; @@ -3364,9 +3103,10 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, featureFlags], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + featureFlags, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3389,8 +3129,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// Once the AdsLoader object has been created, using this setter will have no /// effect. Future setLanguage(String language) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setLanguage'; @@ -3399,9 +3138,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, language], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, language]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3421,8 +3158,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// /// The default is 4. Future setMaxRedirects(int maxRedirects) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setMaxRedirects'; @@ -3431,9 +3167,10 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, maxRedirects], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + maxRedirects, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3453,8 +3190,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// Player type greater than 20 characters will be truncated. The player type /// specified should be short and unique. Future setPlayerType(String playerType) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setPlayerType'; @@ -3463,9 +3199,10 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, playerType], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + playerType, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3484,8 +3221,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// /// Player versions greater than 20 characters will be truncated. Future setPlayerVersion(String playerVersion) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setPlayerVersion'; @@ -3494,9 +3230,10 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, playerVersion], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + playerVersion, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3513,19 +3250,15 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// Sets the publisher provided ID used for tracking. Future setPpid(String ppid) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setPpid'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setPpid'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, ppid], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, ppid]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3545,8 +3278,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { /// A session ID must be a UUID, or an empty string if the SDK should not send /// a session ID. Future setSessionId(String sessionId) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecImaSdkSettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImaSdkSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ImaSdkSettings.setSessionId'; @@ -3555,9 +3287,7 @@ class ImaSdkSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, sessionId], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, sessionId]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3612,10 +3342,8 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { required int currentTimeMs, required int durationMs, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoProgressUpdate; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoProgressUpdate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_defaultConstructor'; @@ -3624,9 +3352,11 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, currentTimeMs, durationMs], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + currentTimeMs, + durationMs, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3648,26 +3378,19 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - VideoProgressUpdate.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + VideoProgressUpdate.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecVideoProgressUpdate = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecVideoProgressUpdate = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Value to use for cases when progress is not yet defined, such as video /// initialization. - static final VideoProgressUpdate _videoTimeNotReady = - pigeonVar_videoTimeNotReady(); + static final VideoProgressUpdate _videoTimeNotReady = pigeonVar_videoTimeNotReady(); /// Value to use for cases when progress is not yet defined, such as video /// initialization. static VideoProgressUpdate get videoTimeNotReady => - PigeonOverrides.videoProgressUpdate_videoTimeNotReady ?? - _videoTimeNotReady; + PigeonOverrides.videoProgressUpdate_videoTimeNotReady ?? _videoTimeNotReady; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -3675,10 +3398,9 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, VideoProgressUpdate Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3701,15 +3423,14 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoProgressUpdate.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoProgressUpdate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3724,14 +3445,15 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { } static VideoProgressUpdate pigeonVar_videoTimeNotReady() { - final VideoProgressUpdate pigeonVar_instance = - VideoProgressUpdate.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final VideoProgressUpdate pigeonVar_instance = VideoProgressUpdate.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoProgressUpdate.videoTimeNotReady'; @@ -3740,9 +3462,9 @@ class VideoProgressUpdate extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3791,10 +3513,9 @@ class AdMediaInfo extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AdMediaInfo Function(String url)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3822,16 +3543,15 @@ class AdMediaInfo extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdMediaInfo.pigeon_newInstance was null, expected non-null String.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_url!) ?? - AdMediaInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - url: arg_url!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_url!) ?? + AdMediaInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + url: arg_url!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3916,10 +3636,9 @@ class AdPodInfo extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3972,28 +3691,27 @@ class AdPodInfo extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdPodInfo.pigeon_newInstance was null, expected non-null bool.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adPosition!, - arg_maxDuration!, - arg_podIndex!, - arg_timeOffset!, - arg_totalAds!, - arg_isBumper!, - ) ?? - AdPodInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adPosition: arg_adPosition!, - maxDuration: arg_maxDuration!, - podIndex: arg_podIndex!, - timeOffset: arg_timeOffset!, - totalAds: arg_totalAds!, - isBumper: arg_isBumper!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_adPosition!, + arg_maxDuration!, + arg_podIndex!, + arg_timeOffset!, + arg_totalAds!, + arg_isBumper!, + ) ?? + AdPodInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adPosition: arg_adPosition!, + maxDuration: arg_maxDuration!, + podIndex: arg_podIndex!, + timeOffset: arg_timeOffset!, + totalAds: arg_totalAds!, + isBumper: arg_isBumper!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4041,14 +3759,10 @@ class FrameLayout extends ViewGroup { } @protected - FrameLayout.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecFrameLayout; + FrameLayout.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFrameLayout; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_defaultConstructor'; @@ -4057,9 +3771,9 @@ class FrameLayout extends ViewGroup { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4081,10 +3795,8 @@ class FrameLayout extends ViewGroup { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - FrameLayout.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + FrameLayout.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecFrameLayout = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -4095,10 +3807,9 @@ class FrameLayout extends ViewGroup { PigeonInstanceManager? pigeon_instanceManager, FrameLayout Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4121,15 +3832,14 @@ class FrameLayout extends ViewGroup { 'Argument for dev.flutter.pigeon.interactive_media_ads.FrameLayout.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - FrameLayout.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + FrameLayout.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4161,10 +3871,8 @@ class ViewGroup extends View { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - ViewGroup.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + ViewGroup.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecViewGroup = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -4175,10 +3883,9 @@ class ViewGroup extends View { PigeonInstanceManager? pigeon_instanceManager, ViewGroup Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4201,15 +3908,14 @@ class ViewGroup extends View { 'Argument for dev.flutter.pigeon.interactive_media_ads.ViewGroup.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ViewGroup.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ViewGroup.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4225,19 +3931,15 @@ class ViewGroup extends View { /// Adds a child view. Future addView(View view) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecViewGroup; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecViewGroup; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.addView'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.addView'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, view], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, view]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4256,19 +3958,15 @@ class ViewGroup extends View { /// must first know its size on screen before it can calculate how many child /// views it will render. Future removeView(View view) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecViewGroup; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecViewGroup; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.removeView'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.ViewGroup.removeView'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, view], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, view]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4299,15 +3997,9 @@ class VideoView extends View { factory VideoView({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - Future Function(VideoView pigeon_instance, MediaPlayer player)? - onPrepared, + Future Function(VideoView pigeon_instance, MediaPlayer player)? onPrepared, void Function(VideoView pigeon_instance, MediaPlayer player)? onCompletion, - required void Function( - VideoView pigeon_instance, - MediaPlayer player, - int what, - int extra, - ) + required void Function(VideoView pigeon_instance, MediaPlayer player, int what, int extra) onError, }) { if (PigeonOverrides.videoView_new != null) { @@ -4334,10 +4026,8 @@ class VideoView extends View { this.onCompletion, required this.onError, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoView; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoView.pigeon_defaultConstructor'; @@ -4346,9 +4036,9 @@ class VideoView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4400,8 +4090,7 @@ class VideoView extends View { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final Future Function(VideoView pigeon_instance, MediaPlayer player)? - onPrepared; + final Future Function(VideoView pigeon_instance, MediaPlayer player)? onPrepared; /// Callback to be invoked when playback of a media source has completed. /// @@ -4422,8 +4111,7 @@ class VideoView extends View { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function(VideoView pigeon_instance, MediaPlayer player)? - onCompletion; + final void Function(VideoView pigeon_instance, MediaPlayer player)? onCompletion; /// Callback to be invoked when there has been an error during an asynchronous /// operation. @@ -4445,33 +4133,19 @@ class VideoView extends View { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoView pigeon_instance, - MediaPlayer player, - int what, - int extra, - ) - onError; + final void Function(VideoView pigeon_instance, MediaPlayer player, int what, int extra) onError; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - Future Function(VideoView pigeon_instance, MediaPlayer player)? - onPrepared, + Future Function(VideoView pigeon_instance, MediaPlayer player)? onPrepared, void Function(VideoView pigeon_instance, MediaPlayer player)? onCompletion, - void Function( - VideoView pigeon_instance, - MediaPlayer player, - int what, - int extra, - )? - onError, + void Function(VideoView pigeon_instance, MediaPlayer player, int what, int extra)? onError, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4614,19 +4288,15 @@ class VideoView extends View { /// Sets the URI of the video. Future setVideoUri(String? uri) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoView; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.VideoView.setVideoUri'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoView.setVideoUri'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, uri], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, uri]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4645,8 +4315,7 @@ class VideoView extends View { /// /// In milliseconds. Future getCurrentPosition() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoView; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoView.getCurrentPosition'; @@ -4655,9 +4324,7 @@ class VideoView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4682,8 +4349,7 @@ class VideoView extends View { /// /// Only available on Android API 26+. Noop on lower versions. Future setAudioFocusRequest(AudioManagerAudioFocus focusGain) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoView; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoView.setAudioFocusRequest'; @@ -4692,9 +4358,7 @@ class VideoView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, focusGain], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, focusGain]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4730,10 +4394,7 @@ class View extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - View.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + View.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -4741,10 +4402,9 @@ class View extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, View Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4767,15 +4427,14 @@ class View extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.View.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - View.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + View.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4808,10 +4467,7 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - MediaPlayer.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + MediaPlayer.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecMediaPlayer = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -4822,10 +4478,9 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, MediaPlayer Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4848,15 +4503,14 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - MediaPlayer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + MediaPlayer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4872,8 +4526,7 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { /// Gets the duration of the file. Future getDuration() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecMediaPlayer; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMediaPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.getDuration'; @@ -4882,9 +4535,7 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4906,19 +4557,15 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { /// Seeks to specified time position. Future seekTo(int mSec) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecMediaPlayer; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMediaPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.seekTo'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.seekTo'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, mSec], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, mSec]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4935,19 +4582,15 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { /// Starts or resumes playback. Future start() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecMediaPlayer; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMediaPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.start'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.start'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4964,19 +4607,15 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { /// Pauses playback. Future pause() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecMediaPlayer; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMediaPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pause'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.pause'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4993,19 +4632,15 @@ class MediaPlayer extends PigeonInternalProxyApiBaseClass { /// Stops playback after playback has been started or paused. Future stop() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecMediaPlayer; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMediaPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.stop'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.MediaPlayer.stop'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5043,10 +4678,8 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecVideoAdPlayerCallback = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecVideoAdPlayerCallback = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5054,10 +4687,9 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, VideoAdPlayerCallback Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5080,15 +4712,14 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayerCallback.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - VideoAdPlayerCallback.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoAdPlayerCallback.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5117,9 +4748,11 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo, videoProgressUpdate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + videoProgressUpdate, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5146,9 +4779,10 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5175,9 +4809,7 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5204,9 +4836,10 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5233,9 +4866,10 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5262,9 +4896,10 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5291,9 +4926,10 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5320,9 +4956,10 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5349,9 +4986,10 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5378,9 +5016,11 @@ class VideoAdPlayerCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adMediaInfo, percentage], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adMediaInfo, + percentage, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5412,10 +5052,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { factory VideoAdPlayer({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - ) + required void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback) addCallback, required void Function( VideoAdPlayer pigeon_instance, @@ -5423,27 +5060,12 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { AdPodInfo adPodInfo, ) loadAd, - required Future Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) - pauseAd, - required void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) - playAd, + required Future Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) pauseAd, + required void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) playAd, required void Function(VideoAdPlayer pigeon_instance) release, - required void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - ) + required void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback) removeCallback, - required void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) - stopAd, + required void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) stopAd, }) { if (PigeonOverrides.videoAdPlayer_new != null) { return PigeonOverrides.videoAdPlayer_new!( @@ -5481,10 +5103,8 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { required this.removeCallback, required this.stopAd, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoAdPlayer; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoAdPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pigeon_defaultConstructor'; @@ -5493,9 +5113,9 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5551,11 +5171,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - ) - addCallback; + final void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback) addCallback; /// Loads a video ad hosted at AdMediaInfo. /// @@ -5576,11 +5192,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - AdPodInfo adPodInfo, - ) + final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, AdPodInfo adPodInfo) loadAd; /// Pauses playing the current ad. @@ -5602,11 +5214,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final Future Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - ) - pauseAd; + final Future Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) pauseAd; /// Starts or resumes playing the video ad referenced by the AdMediaInfo, /// provided loadAd has already been called for it. @@ -5628,8 +5236,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) - playAd; + final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) playAd; /// Cleans up and releases all resources used by the `VideoAdPlayer`. /// @@ -5671,11 +5278,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - ) - removeCallback; + final void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback) removeCallback; /// Stops playing the current ad. /// @@ -5696,44 +5299,24 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) - stopAd; + final void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo) stopAd; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - )? - addCallback, - void Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - AdPodInfo adPodInfo, - )? + void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback)? addCallback, + void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo, AdPodInfo adPodInfo)? loadAd, - Future Function( - VideoAdPlayer pigeon_instance, - AdMediaInfo adMediaInfo, - )? - pauseAd, - void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? - playAd, + Future Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? pauseAd, + void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? playAd, void Function(VideoAdPlayer pigeon_instance)? release, - void Function( - VideoAdPlayer pigeon_instance, - VideoAdPlayerCallback callback, - )? - removeCallback, - void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? - stopAd, + void Function(VideoAdPlayer pigeon_instance, VideoAdPlayerCallback callback)? removeCallback, + void Function(VideoAdPlayer pigeon_instance, AdMediaInfo adMediaInfo)? stopAd, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5750,14 +5333,12 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null.', ); final List args = (message as List?)!; - final VideoAdPlayer? arg_pigeon_instance = - (args[0] as VideoAdPlayer?); + final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null, expected non-null VideoAdPlayer.', ); - final VideoAdPlayerCallback? arg_callback = - (args[1] as VideoAdPlayerCallback?); + final VideoAdPlayerCallback? arg_callback = (args[1] as VideoAdPlayerCallback?); assert( arg_callback != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.addCallback was null, expected non-null VideoAdPlayerCallback.', @@ -5794,8 +5375,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null.', ); final List args = (message as List?)!; - final VideoAdPlayer? arg_pigeon_instance = - (args[0] as VideoAdPlayer?); + final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.loadAd was null, expected non-null VideoAdPlayer.', @@ -5843,8 +5423,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null.', ); final List args = (message as List?)!; - final VideoAdPlayer? arg_pigeon_instance = - (args[0] as VideoAdPlayer?); + final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.pauseAd was null, expected non-null VideoAdPlayer.', @@ -5886,8 +5465,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null.', ); final List args = (message as List?)!; - final VideoAdPlayer? arg_pigeon_instance = - (args[0] as VideoAdPlayer?); + final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null, expected non-null VideoAdPlayer.', @@ -5898,10 +5476,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.playAd was null, expected non-null AdMediaInfo.', ); try { - (playAd ?? arg_pigeon_instance!.playAd).call( - arg_pigeon_instance!, - arg_adMediaInfo!, - ); + (playAd ?? arg_pigeon_instance!.playAd).call(arg_pigeon_instance!, arg_adMediaInfo!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5929,16 +5504,13 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release was null.', ); final List args = (message as List?)!; - final VideoAdPlayer? arg_pigeon_instance = - (args[0] as VideoAdPlayer?); + final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.release was null, expected non-null VideoAdPlayer.', ); try { - (release ?? arg_pigeon_instance!.release).call( - arg_pigeon_instance!, - ); + (release ?? arg_pigeon_instance!.release).call(arg_pigeon_instance!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5966,14 +5538,12 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null.', ); final List args = (message as List?)!; - final VideoAdPlayer? arg_pigeon_instance = - (args[0] as VideoAdPlayer?); + final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null, expected non-null VideoAdPlayer.', ); - final VideoAdPlayerCallback? arg_callback = - (args[1] as VideoAdPlayerCallback?); + final VideoAdPlayerCallback? arg_callback = (args[1] as VideoAdPlayerCallback?); assert( arg_callback != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.removeCallback was null, expected non-null VideoAdPlayerCallback.', @@ -6010,8 +5580,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null.', ); final List args = (message as List?)!; - final VideoAdPlayer? arg_pigeon_instance = - (args[0] as VideoAdPlayer?); + final VideoAdPlayer? arg_pigeon_instance = (args[0] as VideoAdPlayer?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null, expected non-null VideoAdPlayer.', @@ -6022,10 +5591,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.stopAd was null, expected non-null AdMediaInfo.', ); try { - (stopAd ?? arg_pigeon_instance!.stopAd).call( - arg_pigeon_instance!, - arg_adMediaInfo!, - ); + (stopAd ?? arg_pigeon_instance!.stopAd).call(arg_pigeon_instance!, arg_adMediaInfo!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6041,8 +5607,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// The volume of the player as a percentage from 0 to 100. Future setVolume(int value) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoAdPlayer; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoAdPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.setVolume'; @@ -6051,9 +5616,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6071,8 +5634,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { /// The `VideoProgressUpdate` describing playback progress of the current /// video. Future setAdProgress(VideoProgressUpdate progress) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecVideoAdPlayer; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoAdPlayer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.VideoAdPlayer.setAdProgress'; @@ -6081,9 +5643,7 @@ class VideoAdPlayer extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, progress], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, progress]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6121,16 +5681,11 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { factory AdsLoadedListener({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function( - AdsLoadedListener pigeon_instance, - AdsManagerLoadedEvent event, - ) + required void Function(AdsLoadedListener pigeon_instance, AdsManagerLoadedEvent event) onAdsManagerLoaded, }) { if (PigeonOverrides.adsLoadedListener_new != null) { - return PigeonOverrides.adsLoadedListener_new!( - onAdsManagerLoaded: onAdsManagerLoaded, - ); + return PigeonOverrides.adsLoadedListener_new!(onAdsManagerLoaded: onAdsManagerLoaded); } return AdsLoadedListener.pigeon_new( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -6145,10 +5700,8 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onAdsManagerLoaded, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdsLoadedListener; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsLoadedListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.pigeon_defaultConstructor'; @@ -6157,9 +5710,9 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6187,10 +5740,8 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { required this.onAdsManagerLoaded, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecAdsLoadedListener = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAdsLoadedListener = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Called once the AdsManager or StreamManager has been loaded. /// @@ -6211,26 +5762,19 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - AdsLoadedListener pigeon_instance, - AdsManagerLoadedEvent event, - ) + final void Function(AdsLoadedListener pigeon_instance, AdsManagerLoadedEvent event) onAdsManagerLoaded; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - AdsLoadedListener pigeon_instance, - AdsManagerLoadedEvent event, - )? + void Function(AdsLoadedListener pigeon_instance, AdsManagerLoadedEvent event)? onAdsManagerLoaded, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6247,21 +5791,21 @@ class AdsLoadedListener extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null.', ); final List args = (message as List?)!; - final AdsLoadedListener? arg_pigeon_instance = - (args[0] as AdsLoadedListener?); + final AdsLoadedListener? arg_pigeon_instance = (args[0] as AdsLoadedListener?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null, expected non-null AdsLoadedListener.', ); - final AdsManagerLoadedEvent? arg_event = - (args[1] as AdsManagerLoadedEvent?); + final AdsManagerLoadedEvent? arg_event = (args[1] as AdsManagerLoadedEvent?); assert( arg_event != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsLoadedListener.onAdsManagerLoaded was null, expected non-null AdsManagerLoadedEvent.', ); try { - (onAdsManagerLoaded ?? arg_pigeon_instance!.onAdsManagerLoaded) - .call(arg_pigeon_instance!, arg_event!); + (onAdsManagerLoaded ?? arg_pigeon_instance!.onAdsManagerLoaded).call( + arg_pigeon_instance!, + arg_event!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6292,8 +5836,7 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { factory AdErrorListener({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function(AdErrorListener pigeon_instance, AdErrorEvent event) - onAdError, + required void Function(AdErrorListener pigeon_instance, AdErrorEvent event) onAdError, }) { if (PigeonOverrides.adErrorListener_new != null) { return PigeonOverrides.adErrorListener_new!(onAdError: onAdError); @@ -6311,10 +5854,8 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onAdError, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdErrorListener; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdErrorListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdErrorListener.pigeon_defaultConstructor'; @@ -6323,9 +5864,9 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6375,20 +5916,17 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function(AdErrorListener pigeon_instance, AdErrorEvent event) - onAdError; + final void Function(AdErrorListener pigeon_instance, AdErrorEvent event) onAdError; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function(AdErrorListener pigeon_instance, AdErrorEvent event)? - onAdError, + void Function(AdErrorListener pigeon_instance, AdErrorEvent event)? onAdError, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6405,8 +5943,7 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null.', ); final List args = (message as List?)!; - final AdErrorListener? arg_pigeon_instance = - (args[0] as AdErrorListener?); + final AdErrorListener? arg_pigeon_instance = (args[0] as AdErrorListener?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null, expected non-null AdErrorListener.', @@ -6417,10 +5954,7 @@ class AdErrorListener extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdErrorListener.onAdError was null, expected non-null AdErrorEvent.', ); try { - (onAdError ?? arg_pigeon_instance!.onAdError).call( - arg_pigeon_instance!, - arg_event!, - ); + (onAdError ?? arg_pigeon_instance!.onAdError).call(arg_pigeon_instance!, arg_event!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6451,8 +5985,7 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { factory AdEventListener({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function(AdEventListener pigeon_instance, AdEvent event) - onAdEvent, + required void Function(AdEventListener pigeon_instance, AdEvent event) onAdEvent, }) { if (PigeonOverrides.adEventListener_new != null) { return PigeonOverrides.adEventListener_new!(onAdEvent: onAdEvent); @@ -6470,10 +6003,8 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onAdEvent, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdEventListener; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdEventListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdEventListener.pigeon_defaultConstructor'; @@ -6482,9 +6013,9 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -6542,10 +6073,9 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, void Function(AdEventListener pigeon_instance, AdEvent event)? onAdEvent, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6562,8 +6092,7 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null.', ); final List args = (message as List?)!; - final AdEventListener? arg_pigeon_instance = - (args[0] as AdEventListener?); + final AdEventListener? arg_pigeon_instance = (args[0] as AdEventListener?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null, expected non-null AdEventListener.', @@ -6574,10 +6103,7 @@ class AdEventListener extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdEventListener.onAdEvent was null, expected non-null AdEvent.', ); try { - (onAdEvent ?? arg_pigeon_instance!.onAdEvent).call( - arg_pigeon_instance!, - arg_event!, - ); + (onAdEvent ?? arg_pigeon_instance!.onAdEvent).call(arg_pigeon_instance!, arg_event!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6615,10 +6141,8 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecAdsRenderingSettings = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAdsRenderingSettings = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -6626,10 +6150,9 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AdsRenderingSettings Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6652,15 +6175,14 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdsRenderingSettings.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdsRenderingSettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AdsRenderingSettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6686,9 +6208,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6721,9 +6241,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6756,9 +6274,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6793,9 +6309,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6827,9 +6341,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6859,9 +6371,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, bitrate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, bitrate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6891,9 +6401,10 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enableCustomTabs], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + enableCustomTabs, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6924,9 +6435,10 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enablePreloading], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + enablePreloading, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6947,9 +6459,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { /// This is a no-op on non-Android TV devices. /// /// Default is true. - Future setFocusSkipButtonWhenAvailable( - bool enableFocusSkipButton, - ) async { + Future setFocusSkipButtonWhenAvailable(bool enableFocusSkipButton) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdsRenderingSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -6960,9 +6470,10 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enableFocusSkipButton], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + enableFocusSkipButton, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -6994,9 +6505,10 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, loadVideoTimeout], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + loadVideoTimeout, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7024,9 +6536,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, mimeTypes], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, mimeTypes]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7054,9 +6564,7 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, time], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, time]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7083,9 +6591,10 @@ class AdsRenderingSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, uiElements], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + uiElements, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -7161,10 +6670,9 @@ class AdProgressInfo extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7217,28 +6725,27 @@ class AdProgressInfo extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdProgressInfo.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adBreakDuration!, - arg_adPeriodDuration!, - arg_adPosition!, - arg_currentTime!, - arg_duration!, - arg_totalAds!, - ) ?? - AdProgressInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adBreakDuration: arg_adBreakDuration!, - adPeriodDuration: arg_adPeriodDuration!, - adPosition: arg_adPosition!, - currentTime: arg_currentTime!, - duration: arg_duration!, - totalAds: arg_totalAds!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_adBreakDuration!, + arg_adPeriodDuration!, + arg_adPosition!, + arg_currentTime!, + arg_duration!, + arg_totalAds!, + ) ?? + AdProgressInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adBreakDuration: arg_adBreakDuration!, + adPeriodDuration: arg_adPeriodDuration!, + adPosition: arg_adPosition!, + currentTime: arg_currentTime!, + duration: arg_duration!, + totalAds: arg_totalAds!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7305,18 +6812,12 @@ class CompanionAd extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - CompanionAd Function( - String? apiFramework, - int height, - String? resourceValue, - int width, - )? + CompanionAd Function(String? apiFramework, int height, String? resourceValue, int width)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7351,24 +6852,23 @@ class CompanionAd extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAd.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_apiFramework, - arg_height!, - arg_resourceValue, - arg_width!, - ) ?? - CompanionAd.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - apiFramework: arg_apiFramework, - height: arg_height!, - resourceValue: arg_resourceValue, - width: arg_width!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_apiFramework, + arg_height!, + arg_resourceValue, + arg_width!, + ) ?? + CompanionAd.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + apiFramework: arg_apiFramework, + height: arg_height!, + resourceValue: arg_resourceValue, + width: arg_width!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7425,13 +6925,11 @@ class UniversalAdId extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - UniversalAdId Function(String adIdRegistry, String adIdValue)? - pigeon_newInstance, + UniversalAdId Function(String adIdRegistry, String adIdValue)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7464,17 +6962,16 @@ class UniversalAdId extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.UniversalAdId.pigeon_newInstance was null, expected non-null String.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adIdRegistry!, arg_adIdValue!) ?? - UniversalAdId.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adIdRegistry: arg_adIdRegistry!, - adIdValue: arg_adIdValue!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_adIdRegistry!, arg_adIdValue!) ?? + UniversalAdId.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adIdRegistry: arg_adIdRegistry!, + adIdValue: arg_adIdValue!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7662,10 +7159,9 @@ class Ad extends PigeonInternalProxyApiBaseClass { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -7702,20 +7198,18 @@ class Ad extends PigeonInternalProxyApiBaseClass { arg_adSystem != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', ); - final List? arg_adWrapperCreativeIds = - (args[4] as List?)?.cast(); + final List? arg_adWrapperCreativeIds = (args[4] as List?) + ?.cast(); assert( arg_adWrapperCreativeIds != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', ); - final List? arg_adWrapperIds = (args[5] as List?) - ?.cast(); + final List? arg_adWrapperIds = (args[5] as List?)?.cast(); assert( arg_adWrapperIds != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', ); - final List? arg_adWrapperSystems = (args[6] as List?) - ?.cast(); + final List? arg_adWrapperSystems = (args[6] as List?)?.cast(); assert( arg_adWrapperSystems != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', @@ -7725,8 +7219,8 @@ class Ad extends PigeonInternalProxyApiBaseClass { arg_advertiserName != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', ); - final List? arg_companionAds = - (args[8] as List?)?.cast(); + final List? arg_companionAds = (args[8] as List?) + ?.cast(); assert( arg_companionAds != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', @@ -7770,14 +7264,13 @@ class Ad extends PigeonInternalProxyApiBaseClass { arg_traffickingParameters != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null String.', ); - final List? arg_uiElements = (args[20] as List?) - ?.cast(); + final List? arg_uiElements = (args[20] as List?)?.cast(); assert( arg_uiElements != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', ); - final List? arg_universalAdIds = - (args[21] as List?)?.cast(); + final List? arg_universalAdIds = (args[21] as List?) + ?.cast(); assert( arg_universalAdIds != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null List.', @@ -7813,70 +7306,69 @@ class Ad extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.Ad.pigeon_newInstance was null, expected non-null bool.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adId!, - arg_adPodInfo!, - arg_adSystem!, - arg_adWrapperCreativeIds!, - arg_adWrapperIds!, - arg_adWrapperSystems!, - arg_advertiserName!, - arg_companionAds!, - arg_contentType, - arg_creativeAdId!, - arg_creativeId!, - arg_dealId!, - arg_description, - arg_duration!, - arg_height!, - arg_skipTimeOffset!, - arg_surveyUrl, - arg_title, - arg_traffickingParameters!, - arg_uiElements!, - arg_universalAdIds!, - arg_vastMediaBitrate!, - arg_vastMediaHeight!, - arg_vastMediaWidth!, - arg_width!, - arg_isLinear!, - arg_isSkippable!, - ) ?? - Ad.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adId: arg_adId!, - adPodInfo: arg_adPodInfo!, - adSystem: arg_adSystem!, - adWrapperCreativeIds: arg_adWrapperCreativeIds!, - adWrapperIds: arg_adWrapperIds!, - adWrapperSystems: arg_adWrapperSystems!, - advertiserName: arg_advertiserName!, - companionAds: arg_companionAds!, - contentType: arg_contentType, - creativeAdId: arg_creativeAdId!, - creativeId: arg_creativeId!, - dealId: arg_dealId!, - description: arg_description, - duration: arg_duration!, - height: arg_height!, - skipTimeOffset: arg_skipTimeOffset!, - surveyUrl: arg_surveyUrl, - title: arg_title, - traffickingParameters: arg_traffickingParameters!, - uiElements: arg_uiElements!, - universalAdIds: arg_universalAdIds!, - vastMediaBitrate: arg_vastMediaBitrate!, - vastMediaHeight: arg_vastMediaHeight!, - vastMediaWidth: arg_vastMediaWidth!, - width: arg_width!, - isLinear: arg_isLinear!, - isSkippable: arg_isSkippable!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_adId!, + arg_adPodInfo!, + arg_adSystem!, + arg_adWrapperCreativeIds!, + arg_adWrapperIds!, + arg_adWrapperSystems!, + arg_advertiserName!, + arg_companionAds!, + arg_contentType, + arg_creativeAdId!, + arg_creativeId!, + arg_dealId!, + arg_description, + arg_duration!, + arg_height!, + arg_skipTimeOffset!, + arg_surveyUrl, + arg_title, + arg_traffickingParameters!, + arg_uiElements!, + arg_universalAdIds!, + arg_vastMediaBitrate!, + arg_vastMediaHeight!, + arg_vastMediaWidth!, + arg_width!, + arg_isLinear!, + arg_isSkippable!, + ) ?? + Ad.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adId: arg_adId!, + adPodInfo: arg_adPodInfo!, + adSystem: arg_adSystem!, + adWrapperCreativeIds: arg_adWrapperCreativeIds!, + adWrapperIds: arg_adWrapperIds!, + adWrapperSystems: arg_adWrapperSystems!, + advertiserName: arg_advertiserName!, + companionAds: arg_companionAds!, + contentType: arg_contentType, + creativeAdId: arg_creativeAdId!, + creativeId: arg_creativeId!, + dealId: arg_dealId!, + description: arg_description, + duration: arg_duration!, + height: arg_height!, + skipTimeOffset: arg_skipTimeOffset!, + surveyUrl: arg_surveyUrl, + title: arg_title, + traffickingParameters: arg_traffickingParameters!, + uiElements: arg_uiElements!, + universalAdIds: arg_universalAdIds!, + vastMediaBitrate: arg_vastMediaBitrate!, + vastMediaHeight: arg_vastMediaHeight!, + vastMediaWidth: arg_vastMediaWidth!, + width: arg_width!, + isLinear: arg_isLinear!, + isSkippable: arg_isSkippable!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7933,8 +7425,7 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { factory CompanionAdSlotClickListener({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - required void Function(CompanionAdSlotClickListener pigeon_instance) - onCompanionAdClick, + required void Function(CompanionAdSlotClickListener pigeon_instance) onCompanionAdClick, }) { if (PigeonOverrides.companionAdSlotClickListener_new != null) { return PigeonOverrides.companionAdSlotClickListener_new!( @@ -7954,8 +7445,7 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, required this.onCompanionAdClick, }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCompanionAdSlotClickListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -7966,9 +7456,9 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -7996,8 +7486,7 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { required this.onCompanionAdClick, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecCompanionAdSlotClickListener = + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCompanionAdSlotClickListener = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Respond to a click on this companion ad slot. @@ -8019,20 +7508,17 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function(CompanionAdSlotClickListener pigeon_instance) - onCompanionAdClick; + final void Function(CompanionAdSlotClickListener pigeon_instance) onCompanionAdClick; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function(CompanionAdSlotClickListener pigeon_instance)? - onCompanionAdClick, + void Function(CompanionAdSlotClickListener pigeon_instance)? onCompanionAdClick, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8056,8 +7542,9 @@ class CompanionAdSlotClickListener extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlotClickListener.onCompanionAdClick was null, expected non-null CompanionAdSlotClickListener.', ); try { - (onCompanionAdClick ?? arg_pigeon_instance!.onCompanionAdClick) - .call(arg_pigeon_instance!); + (onCompanionAdClick ?? arg_pigeon_instance!.onCompanionAdClick).call( + arg_pigeon_instance!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8090,10 +7577,8 @@ class CompanionAdSlot extends AdSlot { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - CompanionAdSlot.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + CompanionAdSlot.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCompanionAdSlot = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -8104,10 +7589,9 @@ class CompanionAdSlot extends AdSlot { PigeonInstanceManager? pigeon_instanceManager, CompanionAdSlot Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8130,15 +7614,14 @@ class CompanionAdSlot extends AdSlot { 'Argument for dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - CompanionAdSlot.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CompanionAdSlot.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8153,11 +7636,8 @@ class CompanionAdSlot extends AdSlot { } /// Registers a listener for companion clicks. - Future addClickListener( - CompanionAdSlotClickListener clickListener, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCompanionAdSlot; + Future addClickListener(CompanionAdSlotClickListener clickListener) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.addClickListener'; @@ -8166,9 +7646,10 @@ class CompanionAdSlot extends AdSlot { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, clickListener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + clickListener, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8184,11 +7665,8 @@ class CompanionAdSlot extends AdSlot { } /// Removes a listener for companion clicks. - Future removeClickListener( - CompanionAdSlotClickListener clickListener, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecCompanionAdSlot; + Future removeClickListener(CompanionAdSlotClickListener clickListener) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.CompanionAdSlot.removeClickListener'; @@ -8197,9 +7675,10 @@ class CompanionAdSlot extends AdSlot { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, clickListener], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + clickListener, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8232,10 +7711,7 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - AdSlot.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + AdSlot.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAdSlot = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -8246,10 +7722,9 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, AdSlot Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -8272,15 +7747,14 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.AdSlot.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - AdSlot.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AdSlot.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -8296,19 +7770,15 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// Returns the ViewGroup into which the companion will be rendered. Future getContainer() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdSlot.getContainer'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdSlot.getContainer'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8325,19 +7795,15 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// Returns the height of the ad slot. Future getHeight() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdSlot.getHeight'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdSlot.getHeight'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8359,19 +7825,15 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// Returns the width of the ad slot. Future getWidth() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdSlot.getWidth'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdSlot.getWidth'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8393,19 +7855,15 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// Returns true if the ad slot is filled, false otherwise. Future isFilled() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdSlot.isFilled'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdSlot.isFilled'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8429,19 +7887,15 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// /// Required. Future setContainer(ViewGroup container) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdSlot.setContainer'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdSlot.setContainer'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, container], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, container]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8460,19 +7914,19 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// /// Only companions matching the slot size will be displayed in the slot. Future setSize(int width, int height) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdSlot.setSize'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdSlot.setSize'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, width, height], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + width, + height, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -8492,19 +7946,15 @@ class AdSlot extends PigeonInternalProxyApiBaseClass { /// This is a convenience method that sets both parameters of [setSize] to /// [CompanionAdSlot.FLUID_SIZE](https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/CompanionAdSlot#FLUID_SIZE()). Future setFluidSize() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.AdSlot.setFluidSize'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.AdSlot.setFluidSize'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); diff --git a/packages/interactive_media_ads/lib/src/companion_ad_slot.dart b/packages/interactive_media_ads/lib/src/companion_ad_slot.dart index 79842a76b311..f28f9aff3f87 100644 --- a/packages/interactive_media_ads/lib/src/companion_ad_slot.dart +++ b/packages/interactive_media_ads/lib/src/companion_ad_slot.dart @@ -33,15 +33,10 @@ class CompanionAdSlot { /// /// See [CompanionAdSlot.fromPlatformCreationParams] for setting parameters /// for a specific platform. - CompanionAdSlot({ - required CompanionAdSlotSize size, - void Function()? onClicked, - }) : this.fromPlatformCreationParams( - params: PlatformCompanionAdSlotCreationParams( - size: size, - onClicked: onClicked, - ), - ); + CompanionAdSlot({required CompanionAdSlotSize size, void Function()? onClicked}) + : this.fromPlatformCreationParams( + params: PlatformCompanionAdSlotCreationParams(size: size, onClicked: onClicked), + ); /// Constructs a [CompanionAdSlot] from creation params for a specific /// platform. diff --git a/packages/interactive_media_ads/lib/src/content_progress_provider.dart b/packages/interactive_media_ads/lib/src/content_progress_provider.dart index 059f0c30efae..2f87cdd5f2e8 100644 --- a/packages/interactive_media_ads/lib/src/content_progress_provider.dart +++ b/packages/interactive_media_ads/lib/src/content_progress_provider.dart @@ -35,9 +35,7 @@ class ContentProgressProvider { /// See [ContentProgressProvider.fromPlatformCreationParams] for setting /// parameters for a specific platform. ContentProgressProvider() - : this.fromPlatformCreationParams( - const PlatformContentProgressProviderCreationParams(), - ); + : this.fromPlatformCreationParams(const PlatformContentProgressProviderCreationParams()); /// Constructs an [ContentProgressProvider] from creation params for a /// specific platform. @@ -83,10 +81,7 @@ class ContentProgressProvider { /// /// When using a `Timer` to periodically send updates through this method, an /// interval of 200ms is recommended. - Future setProgress({ - required Duration progress, - required Duration duration, - }) { + Future setProgress({required Duration progress, required Duration duration}) { return platform.setProgress(progress: progress, duration: duration); } } diff --git a/packages/interactive_media_ads/lib/src/ima_settings.dart b/packages/interactive_media_ads/lib/src/ima_settings.dart index 1eea409af615..47bfa6a8dbc6 100644 --- a/packages/interactive_media_ads/lib/src/ima_settings.dart +++ b/packages/interactive_media_ads/lib/src/ima_settings.dart @@ -33,9 +33,7 @@ import 'platform_interface/platform_interface.dart'; class ImaSettings { /// Creates an [ImaSettings]. ImaSettings({String? language}) - : this.fromPlatformCreationParams( - PlatformImaSettingsCreationParams(language: language), - ); + : this.fromPlatformCreationParams(PlatformImaSettingsCreationParams(language: language)); /// Constructs an [ImaSettings] from creation params for a specific platform. /// @@ -64,9 +62,8 @@ class ImaSettings { /// ); /// ``` /// {@endtemplate} - ImaSettings.fromPlatformCreationParams( - PlatformImaSettingsCreationParams params, - ) : this.fromPlatform(PlatformImaSettings(params)); + ImaSettings.fromPlatformCreationParams(PlatformImaSettingsCreationParams params) + : this.fromPlatform(PlatformImaSettings(params)); /// Constructs an [ImaSettings] from a specific platform implementation. const ImaSettings.fromPlatform(this.platform); @@ -141,8 +138,7 @@ class ImaSettings { } @override - bool operator ==(Object other) => - other is ImaSettings && other.platform == platform; + bool operator ==(Object other) => other is ImaSettings && other.platform == platform; @override int get hashCode => platform.hashCode; diff --git a/packages/interactive_media_ads/lib/src/ios/enum_converter_utils.dart b/packages/interactive_media_ads/lib/src/ios/enum_converter_utils.dart index 8db0feda49c6..90f3f75e2c15 100644 --- a/packages/interactive_media_ads/lib/src/ios/enum_converter_utils.dart +++ b/packages/interactive_media_ads/lib/src/ios/enum_converter_utils.dart @@ -31,8 +31,7 @@ AdEventType toInterfaceEventType(ima.AdEventType type) { ima.AdEventType.adPeriodStarted => AdEventType.adPeriodStarted, ima.AdEventType.cuepointsChanged => AdEventType.cuepointsChanged, ima.AdEventType.firstQuartile => AdEventType.firstQuartile, - ima.AdEventType.iconFallbackImageClosed => - AdEventType.iconFallbackImageClosed, + ima.AdEventType.iconFallbackImageClosed => AdEventType.iconFallbackImageClosed, ima.AdEventType.iconTapped => AdEventType.iconTapped, ima.AdEventType.log => AdEventType.log, ima.AdEventType.midpoint => AdEventType.midpoint, @@ -51,15 +50,13 @@ AdEventType toInterfaceEventType(ima.AdEventType type) { /// Converts [ima.AdErrorCode] to [AdErrorCode]. AdErrorCode toInterfaceErrorCode(ima.AdErrorCode code) { return switch (code) { - ima.AdErrorCode.companionAdLoadingFailed => - AdErrorCode.companionAdLoadingFailed, + ima.AdErrorCode.companionAdLoadingFailed => AdErrorCode.companionAdLoadingFailed, ima.AdErrorCode.failedToRequestAds => AdErrorCode.failedToRequestAds, ima.AdErrorCode.invalidArguments => AdErrorCode.invalidArguments, ima.AdErrorCode.unknownError => AdErrorCode.unknownError, ima.AdErrorCode.vastAssetNotFound => AdErrorCode.vastAssetNotFound, ima.AdErrorCode.vastEmptyResponse => AdErrorCode.vastEmptyResponse, - ima.AdErrorCode.vastLinearAssetMismatch => - AdErrorCode.vastLinearAssetMismatch, + ima.AdErrorCode.vastLinearAssetMismatch => AdErrorCode.vastLinearAssetMismatch, ima.AdErrorCode.vastLoadTimeout => AdErrorCode.vastLoadTimeout, ima.AdErrorCode.vastMalformedResponse => AdErrorCode.vastMalformedResponse, ima.AdErrorCode.vastMediaLoadTimeout => AdErrorCode.vastMediaLoadTimeout, @@ -68,16 +65,12 @@ AdErrorCode toInterfaceErrorCode(ima.AdErrorCode code) { ima.AdErrorCode.videoPlayError => AdErrorCode.videoPlayError, ima.AdErrorCode.adslotNotVisible => AdErrorCode.adslotNotVisible, ima.AdErrorCode.apiError => AdErrorCode.apiError, - ima.AdErrorCode.contentPlayheadMissing => - AdErrorCode.contentPlayheadMissing, + ima.AdErrorCode.contentPlayheadMissing => AdErrorCode.contentPlayheadMissing, ima.AdErrorCode.failedLoadingAd => AdErrorCode.failedLoadingAd, ima.AdErrorCode.osRuntimeTooOld => AdErrorCode.osRuntimeTooOld, - ima.AdErrorCode.playlistMalformedResponse => - AdErrorCode.playlistMalformedResponse, - ima.AdErrorCode.requiredListenersNotAdded => - AdErrorCode.requiredListenersNotAdded, - ima.AdErrorCode.streamInitializationFailed => - AdErrorCode.streamInitializationFailed, + ima.AdErrorCode.playlistMalformedResponse => AdErrorCode.playlistMalformedResponse, + ima.AdErrorCode.requiredListenersNotAdded => AdErrorCode.requiredListenersNotAdded, + ima.AdErrorCode.streamInitializationFailed => AdErrorCode.streamInitializationFailed, ima.AdErrorCode.vastInvalidUrl => AdErrorCode.vastInvalidUrl, ima.AdErrorCode.videoElementUsed => AdErrorCode.videoElementUsed, ima.AdErrorCode.videoElementRequired => AdErrorCode.videoElementRequired, diff --git a/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart b/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart index 8f8c327c92f5..b736158ce4e0 100644 --- a/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart +++ b/packages/interactive_media_ads/lib/src/ios/interactive_media_ads.g.dart @@ -21,11 +21,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -57,8 +53,7 @@ class PigeonOverrides { /// Overrides [UIViewController.new]. static UIViewController Function({ - void Function(UIViewController pigeon_instance, bool animated)? - viewDidAppear, + void Function(UIViewController pigeon_instance, bool animated)? viewDidAppear, })? uIViewController_new; @@ -118,15 +113,9 @@ class PigeonOverrides { IMAAdError error, ) didReceiveAdError, - required void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - ) + required void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager) didRequestContentPause, - required void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - ) + required void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager) didRequestContentResume, })? iMAAdsManagerDelegate_new; @@ -143,8 +132,7 @@ class PigeonOverrides { iMAFriendlyObstruction_new; /// Overrides [IMACompanionAdSlot.new]. - static IMACompanionAdSlot Function({required UIView view})? - iMACompanionAdSlot_new; + static IMACompanionAdSlot Function({required UIView view})? iMACompanionAdSlot_new; /// Overrides [IMACompanionAdSlot.size]. static IMACompanionAdSlot Function({ @@ -156,16 +144,9 @@ class PigeonOverrides { /// Overrides [IMACompanionDelegate.new]. static IMACompanionDelegate Function({ - void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - bool filled, - )? + void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled)? companionAdSlotFilled, - void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - )? + void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot)? companionSlotWasClicked, })? iMACompanionDelegate_new; @@ -201,8 +182,7 @@ abstract class PigeonInternalProxyApiBaseClass { PigeonInternalProxyApiBaseClass({ this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + }) : pigeon_instanceManager = pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -272,8 +252,8 @@ class PigeonInstanceManager { // by calling instanceManager.getIdentifier() inside of `==` while this was a // HashMap). final Expando _identifiers = Expando(); - final Map> - _weakInstances = >{}; + final Map> _weakInstances = + >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -288,8 +268,7 @@ class PigeonInstanceManager { return PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); } WidgetsFlutterBinding.ensureInitialized(); - final _PigeonInternalInstanceManagerApi api = - _PigeonInternalInstanceManagerApi(); + final _PigeonInternalInstanceManagerApi api = _PigeonInternalInstanceManagerApi(); // Clears the native `PigeonInstanceManager` on the initial use of the Dart one. api.clear(); final PigeonInstanceManager instanceManager = PigeonInstanceManager( @@ -297,74 +276,30 @@ class PigeonInstanceManager { api.removeStrongReference(identifier); }, ); - _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager, - ); - IMAAdDisplayContainer.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + _PigeonInternalInstanceManagerApi.setUpMessageHandlers(instanceManager: instanceManager); + IMAAdDisplayContainer.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); UIView.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); - UIViewController.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAContentPlayhead.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdsLoader.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMASettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdsRequest.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdsLoaderDelegate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdsLoadedData.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdLoadingErrorData.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdError.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdsManager.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdsManagerDelegate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdEvent.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdsRenderingSettings.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - NSObject.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAFriendlyObstruction.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMACompanionAd.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMACompanionAdSlot.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMACompanionDelegate.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - IMAAdPodInfo.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + UIViewController.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAContentPlayhead.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdsLoader.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMASettings.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdsRequest.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdsLoaderDelegate.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdsLoadedData.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdLoadingErrorData.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdError.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdsManager.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdsManagerDelegate.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdEvent.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdsRenderingSettings.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + NSObject.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAFriendlyObstruction.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMACompanionAd.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMACompanionAdSlot.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMACompanionDelegate.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + IMAAdPodInfo.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); IMAAd.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); - IMAUniversalAdID.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + IMAUniversalAdID.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); return instanceManager; } @@ -381,9 +316,7 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = WeakReference( - instance, - ); + _weakInstances[identifier] = WeakReference(instance); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -444,21 +377,15 @@ class PigeonInstanceManager { /// /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. - T? getInstanceWithWeakReference( - int identifier, - ) { - final PigeonInternalProxyApiBaseClass? weakInstance = - _weakInstances[identifier]?.target; + T? getInstanceWithWeakReference(int identifier) { + final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; if (weakInstance == null) { - final PigeonInternalProxyApiBaseClass? strongInstance = - _strongInstances[identifier]; + final PigeonInternalProxyApiBaseClass? strongInstance = _strongInstances[identifier]; if (strongInstance != null) { - final PigeonInternalProxyApiBaseClass copy = strongInstance - .pigeon_copy(); + final PigeonInternalProxyApiBaseClass copy = strongInstance.pigeon_copy(); _identifiers[copy] = identifier; - _weakInstances[identifier] = - WeakReference(copy); + _weakInstances[identifier] = WeakReference(copy); _finalizer.attach(copy, identifier, detach: copy); return copy as T; } @@ -480,10 +407,7 @@ class PigeonInstanceManager { /// /// Throws assertion error if the instance or its identifier has already been /// added. - void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, - int identifier, - ) { + void addHostCreatedInstance(PigeonInternalProxyApiBaseClass instance, int identifier) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -494,8 +418,7 @@ class PigeonInstanceManager { /// Whether this manager contains the given [identifier]. bool containsIdentifier(int identifier) { - return _weakInstances.containsKey(identifier) || - _strongInstances.containsKey(identifier); + return _weakInstances.containsKey(identifier) || _strongInstances.containsKey(identifier); } int _nextUniqueIdentifier() { @@ -544,9 +467,7 @@ class _PigeonInternalInstanceManagerApi { 'Argument for dev.flutter.pigeon.interactive_media_ads.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', ); try { - (instanceManager ?? PigeonInstanceManager.instance).remove( - arg_identifier!, - ); + (instanceManager ?? PigeonInstanceManager.instance).remove(arg_identifier!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -568,9 +489,7 @@ class _PigeonInternalInstanceManagerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [identifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([identifier]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -629,9 +548,7 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager.getInstanceWithWeakReference( - readValue(buffer)! as int, - ); + return instanceManager.getInstanceWithWeakReference(readValue(buffer)! as int); default: return super.readValueOfType(type, buffer); } @@ -1030,8 +947,7 @@ class IMAAdDisplayContainer extends NSObject { this.companionSlots, UIViewController? adContainerViewController, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdDisplayContainer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1042,13 +958,12 @@ class IMAAdDisplayContainer extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - adContainer, - companionSlots, - adContainerViewController, - ]); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + adContainer, + companionSlots, + adContainerViewController, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1077,10 +992,8 @@ class IMAAdDisplayContainer extends NSObject { this.companionSlots, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdDisplayContainer = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAAdDisplayContainer = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// View containing the video display and ad related UI. /// @@ -1095,16 +1008,12 @@ class IMAAdDisplayContainer extends NSObject { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - IMAAdDisplayContainer Function( - UIView adContainer, - List? companionSlots, - )? + IMAAdDisplayContainer Function(UIView adContainer, List? companionSlots)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1131,23 +1040,19 @@ class IMAAdDisplayContainer extends NSObject { arg_adContainer != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdDisplayContainer.pigeon_newInstance was null, expected non-null UIView.', ); - final List? arg_companionSlots = - (args[2] as List?)?.cast(); + final List? arg_companionSlots = (args[2] as List?) + ?.cast(); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adContainer!, - arg_companionSlots, - ) ?? - IMAAdDisplayContainer.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adContainer: arg_adContainer!, - companionSlots: arg_companionSlots, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_adContainer!, arg_companionSlots) ?? + IMAAdDisplayContainer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adContainer: arg_adContainer!, + companionSlots: arg_companionSlots, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1162,9 +1067,7 @@ class IMAAdDisplayContainer extends NSObject { } /// View controller containing the ad container. - Future setAdContainerViewController( - UIViewController? controller, - ) async { + Future setAdContainerViewController(UIViewController? controller) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdDisplayContainer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1175,9 +1078,10 @@ class IMAAdDisplayContainer extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, controller], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + controller, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1204,9 +1108,7 @@ class IMAAdDisplayContainer extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1223,9 +1125,7 @@ class IMAAdDisplayContainer extends NSObject { /// Registers a view that overlays or obstructs this container as “friendly” /// for viewability measurement purposes. - Future registerFriendlyObstruction( - IMAFriendlyObstruction friendlyObstruction, - ) async { + Future registerFriendlyObstruction(IMAFriendlyObstruction friendlyObstruction) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdDisplayContainer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -1236,9 +1136,10 @@ class IMAAdDisplayContainer extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, friendlyObstruction], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + friendlyObstruction, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1265,9 +1166,7 @@ class IMAAdDisplayContainer extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1311,14 +1210,10 @@ class UIView extends NSObject { } @protected - UIView.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecUIView; + UIView.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecUIView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_defaultConstructor'; @@ -1327,9 +1222,9 @@ class UIView extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1351,10 +1246,8 @@ class UIView extends NSObject { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - UIView.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + UIView.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecUIView = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -1365,10 +1258,9 @@ class UIView extends NSObject { PigeonInstanceManager? pigeon_instanceManager, UIView Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1391,15 +1283,14 @@ class UIView extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.UIView.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - UIView.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + UIView.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1429,13 +1320,10 @@ class UIViewController extends NSObject { factory UIViewController({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function(UIViewController pigeon_instance, bool animated)? - viewDidAppear, + void Function(UIViewController pigeon_instance, bool animated)? viewDidAppear, }) { if (PigeonOverrides.uIViewController_new != null) { - return PigeonOverrides.uIViewController_new!( - viewDidAppear: viewDidAppear, - ); + return PigeonOverrides.uIViewController_new!(viewDidAppear: viewDidAppear); } return UIViewController.pigeon_new( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -1450,10 +1338,8 @@ class UIViewController extends NSObject { super.pigeon_instanceManager, this.viewDidAppear, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecUIViewController; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecUIViewController; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_defaultConstructor'; @@ -1462,9 +1348,9 @@ class UIViewController extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1514,8 +1400,7 @@ class UIViewController extends NSObject { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function(UIViewController pigeon_instance, bool animated)? - viewDidAppear; + final void Function(UIViewController pigeon_instance, bool animated)? viewDidAppear; /// Retrieves the view that the controller manages. /// @@ -1530,13 +1415,11 @@ class UIViewController extends NSObject { BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, UIViewController Function()? pigeon_newInstance, - void Function(UIViewController pigeon_instance, bool animated)? - viewDidAppear, + void Function(UIViewController pigeon_instance, bool animated)? viewDidAppear, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1559,15 +1442,14 @@ class UIViewController extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - UIViewController.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + UIViewController.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1595,8 +1477,7 @@ class UIViewController extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null.', ); final List args = (message as List?)!; - final UIViewController? arg_pigeon_instance = - (args[0] as UIViewController?); + final UIViewController? arg_pigeon_instance = (args[0] as UIViewController?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.UIViewController.viewDidAppear was null, expected non-null UIViewController.', @@ -1629,11 +1510,11 @@ class UIViewController extends NSObject { pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecUIViewController; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecUIViewController; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.UIViewController.view'; @@ -1642,9 +1523,10 @@ class UIViewController extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1690,14 +1572,10 @@ class IMAContentPlayhead extends NSObject { } @protected - IMAContentPlayhead.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAContentPlayhead; + IMAContentPlayhead.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAContentPlayhead; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_defaultConstructor'; @@ -1706,9 +1584,9 @@ class IMAContentPlayhead extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1730,15 +1608,11 @@ class IMAContentPlayhead extends NSObject { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - IMAContentPlayhead.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + IMAContentPlayhead.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAContentPlayhead = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAContentPlayhead = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -1746,10 +1620,9 @@ class IMAContentPlayhead extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMAContentPlayhead Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1772,15 +1645,14 @@ class IMAContentPlayhead extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAContentPlayhead.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + IMAContentPlayhead.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1796,8 +1668,7 @@ class IMAContentPlayhead extends NSObject { /// Reflects the current playback time in seconds for the content. Future setCurrentTime(double timeInterval) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAContentPlayhead; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAContentPlayhead; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAContentPlayhead.setCurrentTime'; @@ -1806,9 +1677,10 @@ class IMAContentPlayhead extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, timeInterval], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + timeInterval, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1857,10 +1729,8 @@ class IMAAdsLoader extends NSObject { super.pigeon_instanceManager, IMASettings? settings, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsLoader; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_defaultConstructor'; @@ -1869,9 +1739,10 @@ class IMAAdsLoader extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, settings], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + settings, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -1893,10 +1764,8 @@ class IMAAdsLoader extends NSObject { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - IMAAdsLoader.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + IMAAdsLoader.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAAdsLoader = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -1907,10 +1776,9 @@ class IMAAdsLoader extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMAAdsLoader Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -1933,15 +1801,14 @@ class IMAAdsLoader extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAAdsLoader.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + IMAAdsLoader.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -1957,8 +1824,7 @@ class IMAAdsLoader extends NSObject { /// Signal to the SDK that the content has completed. Future contentComplete() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsLoader; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.contentComplete'; @@ -1967,9 +1833,7 @@ class IMAAdsLoader extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -1986,8 +1850,7 @@ class IMAAdsLoader extends NSObject { /// Request ads from the ad server. Future requestAds(IMAAdsRequest request) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsLoader; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.requestAds'; @@ -1996,9 +1859,7 @@ class IMAAdsLoader extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, request], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, request]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2017,8 +1878,7 @@ class IMAAdsLoader extends NSObject { /// /// Note that this sets to a `weak` property in Swift. Future setDelegate(IMAAdsLoaderDelegate? delegate) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsLoader; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsLoader; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsLoader.setDelegate'; @@ -2027,9 +1887,7 @@ class IMAAdsLoader extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, delegate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, delegate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2071,14 +1929,10 @@ class IMASettings extends NSObject { } @protected - IMASettings.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + IMASettings.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_defaultConstructor'; @@ -2087,9 +1941,9 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2111,10 +1965,8 @@ class IMASettings extends NSObject { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - IMASettings.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + IMASettings.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMASettings = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -2125,10 +1977,9 @@ class IMASettings extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMASettings Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2151,15 +2002,14 @@ class IMASettings extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMASettings.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMASettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + IMASettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2175,19 +2025,15 @@ class IMASettings extends NSObject { /// Publisher Provided Identification (PPID) sent with ads request. Future setPPID(String? ppid) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setPPID'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setPPID'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, ppid], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, ppid]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2210,8 +2056,7 @@ class IMASettings extends NSObject { /// Setting this property after it has been sent to the IMAAdsLoader will be /// ignored and a warning will be logged. Future setLanguage(String language) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setLanguage'; @@ -2220,9 +2065,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, language], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, language]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2245,8 +2088,7 @@ class IMASettings extends NSObject { /// /// The default value is 4. Future setMaxRedirects(int max) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setMaxRedirects'; @@ -2255,9 +2097,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, max], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, max]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2274,8 +2114,7 @@ class IMASettings extends NSObject { /// Feature flags and their states. Future setFeatureFlags(Map flags) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setFeatureFlags'; @@ -2284,9 +2123,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, flags], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, flags]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2305,8 +2142,7 @@ class IMASettings extends NSObject { /// /// The default value is false. Future setEnableBackgroundPlayback(bool enabled) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setEnableBackgroundPlayback'; @@ -2315,9 +2151,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enabled], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, enabled]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2336,8 +2170,7 @@ class IMASettings extends NSObject { /// /// The default value is true. Future setAutoPlayAdBreaks(bool autoPlay) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setAutoPlayAdBreaks'; @@ -2346,9 +2179,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, autoPlay], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, autoPlay]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2370,8 +2201,7 @@ class IMASettings extends NSObject { /// /// The default value is false. Future setDisableNowPlayingInfo(bool disable) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setDisableNowPlayingInfo'; @@ -2380,9 +2210,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, disable], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, disable]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2399,8 +2227,7 @@ class IMASettings extends NSObject { /// The partner specified video player that is integrating with the SDK. Future setPlayerType(String? type) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setPlayerType'; @@ -2409,9 +2236,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, type], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, type]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2428,8 +2253,7 @@ class IMASettings extends NSObject { /// The partner specified player version that is integrating with the SDK. Future setPlayerVersion(String? version) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setPlayerVersion'; @@ -2438,9 +2262,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, version], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, version]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2461,8 +2283,7 @@ class IMASettings extends NSObject { /// /// It is used exclusively for frequency capping across the user session. Future setSessionID(String? sessionID) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setSessionID'; @@ -2471,9 +2292,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, sessionID], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, sessionID]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2494,8 +2313,7 @@ class IMASettings extends NSObject { /// /// The key is enabled by default. Future setSameAppKeyEnabled(bool enabled) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setSameAppKeyEnabled'; @@ -2504,9 +2322,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enabled], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, enabled]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2529,8 +2345,7 @@ class IMASettings extends NSObject { /// /// The default value is false. Future setEnableDebugMode(bool enable) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMASettings; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMASettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMASettings.setEnableDebugMode'; @@ -2539,9 +2354,7 @@ class IMASettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enable], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, enable]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2614,10 +2427,8 @@ class IMAAdsRequest extends NSObject { required IMAAdDisplayContainer adDisplayContainer, IMAContentPlayhead? contentPlayhead, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_defaultConstructor'; @@ -2626,14 +2437,12 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [ - pigeonVar_instanceIdentifier, - adTagUrl, - adDisplayContainer, - contentPlayhead, - ], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + adTagUrl, + adDisplayContainer, + contentPlayhead, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2695,10 +2504,8 @@ class IMAAdsRequest extends NSObject { required IMAAdDisplayContainer adDisplayContainer, IMAContentPlayhead? contentPlayhead, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.withAdsResponse'; @@ -2707,14 +2514,12 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [ - pigeonVar_instanceIdentifier, - adsResponse, - adDisplayContainer, - contentPlayhead, - ], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + adsResponse, + adDisplayContainer, + contentPlayhead, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -2736,10 +2541,8 @@ class IMAAdsRequest extends NSObject { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - IMAAdsRequest.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached(); + IMAAdsRequest.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached(); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAAdsRequest = _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); @@ -2750,10 +2553,9 @@ class IMAAdsRequest extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMAAdsRequest Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2776,15 +2578,14 @@ class IMAAdsRequest extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAAdsRequest.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + IMAAdsRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2802,8 +2603,7 @@ class IMAAdsRequest extends NSObject { /// /// Required for any adsRequest. Future getAdTagUrl() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.getAdTagUrl'; @@ -2812,9 +2612,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2832,8 +2630,7 @@ class IMAAdsRequest extends NSObject { /// Specifies a VAST, VMAP, or ad rules response to be used instead of making /// a request through an ad tag URL. Future getAdsResponse() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.getAdsResponse'; @@ -2842,9 +2639,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2861,8 +2656,7 @@ class IMAAdsRequest extends NSObject { /// The ad display container. Future getAdDisplayContainer() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.getAdDisplayContainer'; @@ -2871,9 +2665,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2898,8 +2690,7 @@ class IMAAdsRequest extends NSObject { /// /// Changing this setting will have no impact on ad playback. Future setAdWillAutoPlay(bool adWillAutoPlay) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setAdWillAutoPlay'; @@ -2908,9 +2699,10 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adWillAutoPlay], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adWillAutoPlay, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2930,8 +2722,7 @@ class IMAAdsRequest extends NSObject { /// /// Changing this setting will have no impact on ad playback. Future setAdWillPlayMuted(bool adWillPlayMuted) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setAdWillPlayMuted'; @@ -2940,9 +2731,10 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adWillPlayMuted], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adWillPlayMuted, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2963,8 +2755,7 @@ class IMAAdsRequest extends NSObject { /// Not calling this function leaves the setting as unknown. Note: Changing /// this setting will have no impact on ad playback. Future setContinuousPlayback(bool continuousPlayback) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContinuousPlayback'; @@ -2973,9 +2764,10 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, continuousPlayback], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + continuousPlayback, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -2994,8 +2786,7 @@ class IMAAdsRequest extends NSObject { /// /// Used in AdX requests. This parameter is optional. Future setContentDuration(double duration) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentDuration'; @@ -3004,9 +2795,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, duration], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, duration]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3025,8 +2814,7 @@ class IMAAdsRequest extends NSObject { /// /// Used in AdX requests. This parameter is optional. Future setContentKeywords(List? keywords) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentKeywords'; @@ -3035,9 +2823,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, keywords], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, keywords]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3056,8 +2842,7 @@ class IMAAdsRequest extends NSObject { /// /// Used in AdX requests. This parameter is optional. Future setContentTitle(String? title) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentTitle'; @@ -3066,9 +2851,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, title], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, title]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3089,8 +2872,7 @@ class IMAAdsRequest extends NSObject { /// [Apple documentation](https://developer.apple.com/documentation/xcode/allowing-apps-and-websites-to-link-to-your-content) /// for more information. Future setContentURL(String? contentURL) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setContentURL'; @@ -3099,9 +2881,10 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, contentURL], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + contentURL, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3121,8 +2904,7 @@ class IMAAdsRequest extends NSObject { /// /// This parameter is optional and will override the default timeout. Future setVastLoadTimeout(double timeout) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setVastLoadTimeout'; @@ -3131,9 +2913,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, timeout], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, timeout]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3154,8 +2934,7 @@ class IMAAdsRequest extends NSObject { /// This can be used to stagger requests during a live-stream event, in order /// to mitigate spikes in the number of requests. Future setLiveStreamPrefetchSeconds(double seconds) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsRequest; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRequest; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsRequest.setLiveStreamPrefetchSeconds'; @@ -3164,9 +2943,7 @@ class IMAAdsRequest extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, seconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, seconds]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3231,8 +3008,7 @@ class IMAAdsLoaderDelegate extends NSObject { required this.adLoaderLoadedWith, required this.adsLoaderFailedWithErrorData, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsLoaderDelegate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -3243,9 +3019,9 @@ class IMAAdsLoaderDelegate extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -3274,10 +3050,8 @@ class IMAAdsLoaderDelegate extends NSObject { required this.adsLoaderFailedWithErrorData, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdsLoaderDelegate = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAAdsLoaderDelegate = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Called when ads are successfully loaded from the ad servers by the loader. /// @@ -3348,10 +3122,9 @@ class IMAAdsLoaderDelegate extends NSObject { )? adsLoaderFailedWithErrorData, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3368,8 +3141,7 @@ class IMAAdsLoaderDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null.', ); final List args = (message as List?)!; - final IMAAdsLoaderDelegate? arg_pigeon_instance = - (args[0] as IMAAdsLoaderDelegate?); + final IMAAdsLoaderDelegate? arg_pigeon_instance = (args[0] as IMAAdsLoaderDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoaderDelegate.', @@ -3379,15 +3151,17 @@ class IMAAdsLoaderDelegate extends NSObject { arg_loader != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoader.', ); - final IMAAdsLoadedData? arg_adsLoadedData = - (args[2] as IMAAdsLoadedData?); + final IMAAdsLoadedData? arg_adsLoadedData = (args[2] as IMAAdsLoadedData?); assert( arg_adsLoadedData != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adLoaderLoadedWith was null, expected non-null IMAAdsLoadedData.', ); try { - (adLoaderLoadedWith ?? arg_pigeon_instance!.adLoaderLoadedWith) - .call(arg_pigeon_instance!, arg_loader!, arg_adsLoadedData!); + (adLoaderLoadedWith ?? arg_pigeon_instance!.adLoaderLoadedWith).call( + arg_pigeon_instance!, + arg_loader!, + arg_adsLoadedData!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3415,8 +3189,7 @@ class IMAAdsLoaderDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null.', ); final List args = (message as List?)!; - final IMAAdsLoaderDelegate? arg_pigeon_instance = - (args[0] as IMAAdsLoaderDelegate?); + final IMAAdsLoaderDelegate? arg_pigeon_instance = (args[0] as IMAAdsLoaderDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdsLoaderDelegate.', @@ -3426,15 +3199,13 @@ class IMAAdsLoaderDelegate extends NSObject { arg_loader != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdsLoader.', ); - final IMAAdLoadingErrorData? arg_adErrorData = - (args[2] as IMAAdLoadingErrorData?); + final IMAAdLoadingErrorData? arg_adErrorData = (args[2] as IMAAdLoadingErrorData?); assert( arg_adErrorData != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsLoaderDelegate.adsLoaderFailedWithErrorData was null, expected non-null IMAAdLoadingErrorData.', ); try { - (adsLoaderFailedWithErrorData ?? - arg_pigeon_instance!.adsLoaderFailedWithErrorData) + (adsLoaderFailedWithErrorData ?? arg_pigeon_instance!.adsLoaderFailedWithErrorData) .call(arg_pigeon_instance!, arg_loader!, arg_adErrorData!); return wrapResponse(empty: true); } on PlatformException catch (e) { @@ -3486,10 +3257,9 @@ class IMAAdsLoadedData extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMAAdsLoadedData Function(IMAAdsManager? adsManager)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3513,16 +3283,15 @@ class IMAAdsLoadedData extends NSObject { ); final IMAAdsManager? arg_adsManager = (args[1] as IMAAdsManager?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adsManager) ?? - IMAAdsLoadedData.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adsManager: arg_adsManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_adsManager) ?? + IMAAdsLoadedData.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adsManager: arg_adsManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3570,10 +3339,9 @@ class IMAAdLoadingErrorData extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMAAdLoadingErrorData Function(IMAAdError adError)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3601,16 +3369,15 @@ class IMAAdLoadingErrorData extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdLoadingErrorData.pigeon_newInstance was null, expected non-null IMAAdError.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adError!) ?? - IMAAdLoadingErrorData.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adError: arg_adError!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_adError!) ?? + IMAAdLoadingErrorData.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adError: arg_adError!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3664,13 +3431,11 @@ class IMAAdError extends NSObject { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - IMAAdError Function(AdErrorType type, AdErrorCode code, String? message)? - pigeon_newInstance, + IMAAdError Function(AdErrorType type, AdErrorCode code, String? message)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3704,18 +3469,17 @@ class IMAAdError extends NSObject { ); final String? arg_message = (args[3] as String?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_type!, arg_code!, arg_message) ?? - IMAAdError.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - code: arg_code!, - message: arg_message, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_type!, arg_code!, arg_message) ?? + IMAAdError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + code: arg_code!, + message: arg_message, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3771,10 +3535,9 @@ class IMAAdsManager extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMAAdsManager Function(List adCuePoints)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -3796,23 +3559,21 @@ class IMAAdsManager extends NSObject { arg_pigeon_instanceIdentifier != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance was null, expected non-null int.', ); - final List? arg_adCuePoints = (args[1] as List?) - ?.cast(); + final List? arg_adCuePoints = (args[1] as List?)?.cast(); assert( arg_adCuePoints != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pigeon_newInstance was null, expected non-null List.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adCuePoints!) ?? - IMAAdsManager.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adCuePoints: arg_adCuePoints!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_adCuePoints!) ?? + IMAAdsManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adCuePoints: arg_adCuePoints!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3828,8 +3589,7 @@ class IMAAdsManager extends NSObject { /// The `IMAAdsManagerDelegate` to notify with events during ad playback. Future setDelegate(IMAAdsManagerDelegate? delegate) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.setDelegate'; @@ -3838,9 +3598,7 @@ class IMAAdsManager extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, delegate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, delegate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3857,8 +3615,7 @@ class IMAAdsManager extends NSObject { /// Initializes and loads the ad. Future initialize(IMAAdsRenderingSettings? adsRenderingSettings) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.initialize'; @@ -3867,9 +3624,10 @@ class IMAAdsManager extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, adsRenderingSettings], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + adsRenderingSettings, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3886,19 +3644,15 @@ class IMAAdsManager extends NSObject { /// Starts advertisement playback. Future start() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.start'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.start'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3915,19 +3669,15 @@ class IMAAdsManager extends NSObject { /// Pauses advertisement. Future pause() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pause'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.pause'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3944,19 +3694,15 @@ class IMAAdsManager extends NSObject { /// Resumes the current ad. Future resume() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.resume'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.resume'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -3974,19 +3720,15 @@ class IMAAdsManager extends NSObject { /// Skips the advertisement if the ad is skippable and the skip offset has /// been reached. Future skip() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.skip'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.skip'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4003,8 +3745,7 @@ class IMAAdsManager extends NSObject { /// If an ad break is currently playing, discard it and resume content. Future discardAdBreak() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.discardAdBreak'; @@ -4013,9 +3754,7 @@ class IMAAdsManager extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4032,19 +3771,15 @@ class IMAAdsManager extends NSObject { /// Causes the ads manager to stop the ad and clean its internal state. Future destroy() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMAAdsManager; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const pigeonVar_channelName = - 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.destroy'; + const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMAAdsManager.destroy'; final pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4088,15 +3823,9 @@ class IMAAdsManagerDelegate extends NSObject { IMAAdError error, ) didReceiveAdError, - required void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - ) + required void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager) didRequestContentPause, - required void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - ) + required void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager) didRequestContentResume, }) { if (PigeonOverrides.iMAAdsManagerDelegate_new != null) { @@ -4126,8 +3855,7 @@ class IMAAdsManagerDelegate extends NSObject { required this.didRequestContentPause, required this.didRequestContentResume, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsManagerDelegate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4138,9 +3866,9 @@ class IMAAdsManagerDelegate extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4171,10 +3899,8 @@ class IMAAdsManagerDelegate extends NSObject { required this.didRequestContentResume, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdsManagerDelegate = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAAdsManagerDelegate = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Called when there is an IMAAdEvent. /// @@ -4247,10 +3973,7 @@ class IMAAdsManagerDelegate extends NSObject { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - ) + final void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager) didRequestContentPause; /// Called when an ad has finished or an error occurred during the playback. @@ -4272,10 +3995,7 @@ class IMAAdsManagerDelegate extends NSObject { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - ) + final void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager) didRequestContentResume; static void pigeon_setUpMessageHandlers({ @@ -4294,21 +4014,14 @@ class IMAAdsManagerDelegate extends NSObject { IMAAdError error, )? didReceiveAdError, - void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - )? + void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager)? didRequestContentPause, - void Function( - IMAAdsManagerDelegate pigeon_instance, - IMAAdsManager adsManager, - )? + void Function(IMAAdsManagerDelegate pigeon_instance, IMAAdsManager adsManager)? didRequestContentResume, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4325,8 +4038,7 @@ class IMAAdsManagerDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null.', ); final List args = (message as List?)!; - final IMAAdsManagerDelegate? arg_pigeon_instance = - (args[0] as IMAAdsManagerDelegate?); + final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdEvent was null, expected non-null IMAAdsManagerDelegate.', @@ -4374,8 +4086,7 @@ class IMAAdsManagerDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null.', ); final List args = (message as List?)!; - final IMAAdsManagerDelegate? arg_pigeon_instance = - (args[0] as IMAAdsManagerDelegate?); + final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didReceiveAdError was null, expected non-null IMAAdsManagerDelegate.', @@ -4423,8 +4134,7 @@ class IMAAdsManagerDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null.', ); final List args = (message as List?)!; - final IMAAdsManagerDelegate? arg_pigeon_instance = - (args[0] as IMAAdsManagerDelegate?); + final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null, expected non-null IMAAdsManagerDelegate.', @@ -4435,9 +4145,10 @@ class IMAAdsManagerDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentPause was null, expected non-null IMAAdsManager.', ); try { - (didRequestContentPause ?? - arg_pigeon_instance!.didRequestContentPause) - .call(arg_pigeon_instance!, arg_adsManager!); + (didRequestContentPause ?? arg_pigeon_instance!.didRequestContentPause).call( + arg_pigeon_instance!, + arg_adsManager!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4465,8 +4176,7 @@ class IMAAdsManagerDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null.', ); final List args = (message as List?)!; - final IMAAdsManagerDelegate? arg_pigeon_instance = - (args[0] as IMAAdsManagerDelegate?); + final IMAAdsManagerDelegate? arg_pigeon_instance = (args[0] as IMAAdsManagerDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null, expected non-null IMAAdsManagerDelegate.', @@ -4477,9 +4187,10 @@ class IMAAdsManagerDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsManagerDelegate.didRequestContentResume was null, expected non-null IMAAdsManager.', ); try { - (didRequestContentResume ?? - arg_pigeon_instance!.didRequestContentResume) - .call(arg_pigeon_instance!, arg_adsManager!); + (didRequestContentResume ?? arg_pigeon_instance!.didRequestContentResume).call( + arg_pigeon_instance!, + arg_adsManager!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4551,10 +4262,9 @@ class IMAAdEvent extends NSObject { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4586,28 +4296,22 @@ class IMAAdEvent extends NSObject { arg_typeString != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdEvent.pigeon_newInstance was null, expected non-null String.', ); - final Map? arg_adData = - (args[3] as Map?)?.cast(); + final Map? arg_adData = (args[3] as Map?) + ?.cast(); final IMAAd? arg_ad = (args[4] as IMAAd?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_type!, - arg_typeString!, - arg_adData, - arg_ad, - ) ?? - IMAAdEvent.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - type: arg_type!, - typeString: arg_typeString!, - adData: arg_adData, - ad: arg_ad, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_type!, arg_typeString!, arg_adData, arg_ad) ?? + IMAAdEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + typeString: arg_typeString!, + adData: arg_adData, + ad: arg_ad, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4652,12 +4356,9 @@ class IMAAdsRenderingSettings extends NSObject { } @protected - IMAAdsRenderingSettings.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + IMAAdsRenderingSettings.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) + : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRenderingSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4668,9 +4369,9 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -4697,10 +4398,8 @@ class IMAAdsRenderingSettings extends NSObject { super.pigeon_instanceManager, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAAdsRenderingSettings = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAAdsRenderingSettings = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -4708,10 +4407,9 @@ class IMAAdsRenderingSettings extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMAAdsRenderingSettings Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -4734,15 +4432,14 @@ class IMAAdsRenderingSettings extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdsRenderingSettings.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMAAdsRenderingSettings.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + IMAAdsRenderingSettings.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4768,9 +4465,7 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, types], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, types]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4799,9 +4494,7 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, bitrate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, bitrate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4830,9 +4523,7 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, seconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, seconds]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4860,9 +4551,7 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, seconds], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, seconds]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4889,9 +4578,7 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, types], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, types]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4920,9 +4607,7 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, enable], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, enable]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4939,9 +4624,7 @@ class IMAAdsRenderingSettings extends NSObject { /// Specifies the optional UIViewController that will be used to open links /// in-app. - Future setLinkOpenerPresentingController( - UIViewController controller, - ) async { + Future setLinkOpenerPresentingController(UIViewController controller) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAAdsRenderingSettings; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -4952,9 +4635,10 @@ class IMAAdsRenderingSettings extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, controller], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + controller, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -4989,10 +4673,7 @@ class NSObject extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - NSObject.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + NSObject.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5000,10 +4681,9 @@ class NSObject extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, NSObject Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5026,15 +4706,14 @@ class NSObject extends PigeonInternalProxyApiBaseClass { 'Argument for dev.flutter.pigeon.interactive_media_ads.NSObject.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - NSObject.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + NSObject.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5095,8 +4774,7 @@ class IMAFriendlyObstruction extends NSObject { required this.purpose, this.detailedReason, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMAFriendlyObstruction; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5107,9 +4785,12 @@ class IMAFriendlyObstruction extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, view, purpose, detailedReason], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + view, + purpose, + detailedReason, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5139,10 +4820,8 @@ class IMAFriendlyObstruction extends NSObject { this.detailedReason, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMAFriendlyObstruction = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMAFriendlyObstruction = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// The view causing the obstruction. final UIView view; @@ -5168,10 +4847,9 @@ class IMAFriendlyObstruction extends NSObject { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5198,30 +4876,24 @@ class IMAFriendlyObstruction extends NSObject { arg_view != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null UIView.', ); - final FriendlyObstructionPurpose? arg_purpose = - (args[2] as FriendlyObstructionPurpose?); + final FriendlyObstructionPurpose? arg_purpose = (args[2] as FriendlyObstructionPurpose?); assert( arg_purpose != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAFriendlyObstruction.pigeon_newInstance was null, expected non-null FriendlyObstructionPurpose.', ); final String? arg_detailedReason = (args[3] as String?); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_view!, - arg_purpose!, - arg_detailedReason, - ) ?? - IMAFriendlyObstruction.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - view: arg_view!, - purpose: arg_purpose!, - detailedReason: arg_detailedReason, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_view!, arg_purpose!, arg_detailedReason) ?? + IMAFriendlyObstruction.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + view: arg_view!, + purpose: arg_purpose!, + detailedReason: arg_detailedReason, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5285,18 +4957,12 @@ class IMACompanionAd extends NSObject { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - IMACompanionAd Function( - String? resourceValue, - String? apiFramework, - int width, - int height, - )? + IMACompanionAd Function(String? resourceValue, String? apiFramework, int width, int height)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5331,24 +4997,23 @@ class IMACompanionAd extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAd.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_resourceValue, - arg_apiFramework, - arg_width!, - arg_height!, - ) ?? - IMACompanionAd.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - resourceValue: arg_resourceValue, - apiFramework: arg_apiFramework, - width: arg_width!, - height: arg_height!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_resourceValue, + arg_apiFramework, + arg_width!, + arg_height!, + ) ?? + IMACompanionAd.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resourceValue: arg_resourceValue, + apiFramework: arg_apiFramework, + width: arg_width!, + height: arg_height!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5402,10 +5067,8 @@ class IMACompanionAdSlot extends NSObject { super.pigeon_instanceManager, required this.view, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMACompanionAdSlot; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_defaultConstructor'; @@ -5414,9 +5077,10 @@ class IMACompanionAdSlot extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, view], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + view, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5445,11 +5109,7 @@ class IMACompanionAdSlot extends NSObject { required int height, }) { if (PigeonOverrides.iMACompanionAdSlot_size != null) { - return PigeonOverrides.iMACompanionAdSlot_size!( - view: view, - width: width, - height: height, - ); + return PigeonOverrides.iMACompanionAdSlot_size!(view: view, width: width, height: height); } return IMACompanionAdSlot.pigeon_size( pigeon_binaryMessenger: pigeon_binaryMessenger, @@ -5472,10 +5132,8 @@ class IMACompanionAdSlot extends NSObject { required int width, required int height, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMACompanionAdSlot; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.size'; @@ -5484,9 +5142,12 @@ class IMACompanionAdSlot extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, view, width, height], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + view, + width, + height, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5514,10 +5175,8 @@ class IMACompanionAdSlot extends NSObject { required this.view, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMACompanionAdSlot = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMACompanionAdSlot = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// The view the companion will be rendered in. /// @@ -5530,10 +5189,9 @@ class IMACompanionAdSlot extends NSObject { PigeonInstanceManager? pigeon_instanceManager, IMACompanionAdSlot Function(UIView view)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5561,16 +5219,15 @@ class IMACompanionAdSlot extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.pigeon_newInstance was null, expected non-null UIView.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_view!) ?? - IMACompanionAdSlot.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - view: arg_view!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_view!) ?? + IMACompanionAdSlot.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + view: arg_view!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5589,8 +5246,7 @@ class IMACompanionAdSlot extends NSObject { /// This instance only creates a weak reference to the delegate, so the Dart /// instance should create an explicit reference to receive callbacks. Future setDelegate(IMACompanionDelegate? delegate) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMACompanionAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.setDelegate'; @@ -5599,9 +5255,7 @@ class IMACompanionAdSlot extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, delegate], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, delegate]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5618,8 +5272,7 @@ class IMACompanionAdSlot extends NSObject { /// Width of the slot, in pixels. Future width() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMACompanionAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.width'; @@ -5628,9 +5281,7 @@ class IMACompanionAdSlot extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5652,8 +5303,7 @@ class IMACompanionAdSlot extends NSObject { /// Height of the slot, in pixels. Future height() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecIMACompanionAdSlot; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionAdSlot; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.interactive_media_ads.IMACompanionAdSlot.height'; @@ -5662,9 +5312,7 @@ class IMACompanionAdSlot extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); @@ -5701,16 +5349,9 @@ class IMACompanionDelegate extends NSObject { factory IMACompanionDelegate({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - bool filled, - )? + void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled)? companionAdSlotFilled, - void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - )? + void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot)? companionSlotWasClicked, }) { if (PigeonOverrides.iMACompanionDelegate_new != null) { @@ -5734,8 +5375,7 @@ class IMACompanionDelegate extends NSObject { this.companionAdSlotFilled, this.companionSlotWasClicked, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecIMACompanionDelegate; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5746,9 +5386,9 @@ class IMACompanionDelegate extends NSObject { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { @@ -5777,10 +5417,8 @@ class IMACompanionDelegate extends NSObject { this.companionSlotWasClicked, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecIMACompanionDelegate = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecIMACompanionDelegate = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); /// Called when the slot is either filled or not filled. /// @@ -5801,11 +5439,7 @@ class IMACompanionDelegate extends NSObject { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - bool filled, - )? + final void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled)? companionAdSlotFilled; /// Called when the slot is clicked on by the user and will successfully @@ -5828,10 +5462,7 @@ class IMACompanionDelegate extends NSObject { /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - )? + final void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot)? companionSlotWasClicked; static void pigeon_setUpMessageHandlers({ @@ -5839,22 +5470,14 @@ class IMACompanionDelegate extends NSObject { BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, IMACompanionDelegate Function()? pigeon_newInstance, - void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - bool filled, - )? + void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot, bool filled)? companionAdSlotFilled, - void Function( - IMACompanionDelegate pigeon_instance, - IMACompanionAdSlot slot, - )? + void Function(IMACompanionDelegate pigeon_instance, IMACompanionAdSlot slot)? companionSlotWasClicked, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5877,15 +5500,14 @@ class IMACompanionDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.pigeon_newInstance was null, expected non-null int.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - IMACompanionDelegate.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + IMACompanionDelegate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5913,8 +5535,7 @@ class IMACompanionDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null.', ); final List args = (message as List?)!; - final IMACompanionDelegate? arg_pigeon_instance = - (args[0] as IMACompanionDelegate?); + final IMACompanionDelegate? arg_pigeon_instance = (args[0] as IMACompanionDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null IMACompanionDelegate.', @@ -5930,9 +5551,11 @@ class IMACompanionDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionAdSlotFilled was null, expected non-null bool.', ); try { - (companionAdSlotFilled ?? - arg_pigeon_instance!.companionAdSlotFilled) - ?.call(arg_pigeon_instance!, arg_slot!, arg_filled!); + (companionAdSlotFilled ?? arg_pigeon_instance!.companionAdSlotFilled)?.call( + arg_pigeon_instance!, + arg_slot!, + arg_filled!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5960,8 +5583,7 @@ class IMACompanionDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null.', ); final List args = (message as List?)!; - final IMACompanionDelegate? arg_pigeon_instance = - (args[0] as IMACompanionDelegate?); + final IMACompanionDelegate? arg_pigeon_instance = (args[0] as IMACompanionDelegate?); assert( arg_pigeon_instance != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null, expected non-null IMACompanionDelegate.', @@ -5972,9 +5594,10 @@ class IMACompanionDelegate extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMACompanionDelegate.companionSlotWasClicked was null, expected non-null IMACompanionAdSlot.', ); try { - (companionSlotWasClicked ?? - arg_pigeon_instance!.companionSlotWasClicked) - ?.call(arg_pigeon_instance!, arg_slot!); + (companionSlotWasClicked ?? arg_pigeon_instance!.companionSlotWasClicked)?.call( + arg_pigeon_instance!, + arg_slot!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6074,10 +5697,9 @@ class IMAAdPodInfo extends NSObject { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6130,28 +5752,27 @@ class IMAAdPodInfo extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAdPodInfo.pigeon_newInstance was null, expected non-null bool.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adPosition!, - arg_maxDuration!, - arg_podIndex!, - arg_timeOffset!, - arg_totalAds!, - arg_isBumper!, - ) ?? - IMAAdPodInfo.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adPosition: arg_adPosition!, - maxDuration: arg_maxDuration!, - podIndex: arg_podIndex!, - timeOffset: arg_timeOffset!, - totalAds: arg_totalAds!, - isBumper: arg_isBumper!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_adPosition!, + arg_maxDuration!, + arg_podIndex!, + arg_timeOffset!, + arg_totalAds!, + arg_isBumper!, + ) ?? + IMAAdPodInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adPosition: arg_adPosition!, + maxDuration: arg_maxDuration!, + podIndex: arg_podIndex!, + timeOffset: arg_timeOffset!, + totalAds: arg_totalAds!, + isBumper: arg_isBumper!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6361,10 +5982,9 @@ class IMAAd extends NSObject { )? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6406,8 +6026,8 @@ class IMAAd extends NSObject { arg_adSystem != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null String.', ); - final List? arg_companionAds = - (args[5] as List?)?.cast(); + final List? arg_companionAds = (args[5] as List?) + ?.cast(); assert( arg_companionAds != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null List.', @@ -6422,8 +6042,8 @@ class IMAAd extends NSObject { arg_duration != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null double.', ); - final List? arg_uiElements = - (args[8] as List?)?.cast(); + final List? arg_uiElements = (args[8] as List?) + ?.cast(); assert( arg_uiElements != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null List.', @@ -6488,8 +6108,8 @@ class IMAAd extends NSObject { arg_creativeAdID != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null String.', ); - final List? arg_universalAdIDs = - (args[21] as List?)?.cast(); + final List? arg_universalAdIDs = (args[21] as List?) + ?.cast(); assert( arg_universalAdIDs != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null List.', @@ -6505,89 +6125,85 @@ class IMAAd extends NSObject { arg_dealID != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null String.', ); - final List? arg_wrapperAdIDs = (args[25] as List?) - ?.cast(); + final List? arg_wrapperAdIDs = (args[25] as List?)?.cast(); assert( arg_wrapperAdIDs != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null List.', ); - final List? arg_wrapperCreativeIDs = - (args[26] as List?)?.cast(); + final List? arg_wrapperCreativeIDs = (args[26] as List?)?.cast(); assert( arg_wrapperCreativeIDs != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null List.', ); - final List? arg_wrapperSystems = (args[27] as List?) - ?.cast(); + final List? arg_wrapperSystems = (args[27] as List?)?.cast(); assert( arg_wrapperSystems != null, 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAAd.pigeon_newInstance was null, expected non-null List.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call( - arg_adId!, - arg_adTitle!, - arg_adDescription!, - arg_adSystem!, - arg_companionAds!, - arg_contentType!, - arg_duration!, - arg_uiElements!, - arg_width!, - arg_height!, - arg_vastMediaWidth!, - arg_vastMediaHeight!, - arg_vastMediaBitrate!, - arg_isLinear!, - arg_isSkippable!, - arg_skipTimeOffset!, - arg_adPodInfo!, - arg_traffickingParameters!, - arg_creativeID!, - arg_creativeAdID!, - arg_universalAdIDs!, - arg_advertiserName!, - arg_surveyURL, - arg_dealID!, - arg_wrapperAdIDs!, - arg_wrapperCreativeIDs!, - arg_wrapperSystems!, - ) ?? - IMAAd.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adId: arg_adId!, - adTitle: arg_adTitle!, - adDescription: arg_adDescription!, - adSystem: arg_adSystem!, - companionAds: arg_companionAds!, - contentType: arg_contentType!, - duration: arg_duration!, - uiElements: arg_uiElements!, - width: arg_width!, - height: arg_height!, - vastMediaWidth: arg_vastMediaWidth!, - vastMediaHeight: arg_vastMediaHeight!, - vastMediaBitrate: arg_vastMediaBitrate!, - isLinear: arg_isLinear!, - isSkippable: arg_isSkippable!, - skipTimeOffset: arg_skipTimeOffset!, - adPodInfo: arg_adPodInfo!, - traffickingParameters: arg_traffickingParameters!, - creativeID: arg_creativeID!, - creativeAdID: arg_creativeAdID!, - universalAdIDs: arg_universalAdIDs!, - advertiserName: arg_advertiserName!, - surveyURL: arg_surveyURL, - dealID: arg_dealID!, - wrapperAdIDs: arg_wrapperAdIDs!, - wrapperCreativeIDs: arg_wrapperCreativeIDs!, - wrapperSystems: arg_wrapperSystems!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call( + arg_adId!, + arg_adTitle!, + arg_adDescription!, + arg_adSystem!, + arg_companionAds!, + arg_contentType!, + arg_duration!, + arg_uiElements!, + arg_width!, + arg_height!, + arg_vastMediaWidth!, + arg_vastMediaHeight!, + arg_vastMediaBitrate!, + arg_isLinear!, + arg_isSkippable!, + arg_skipTimeOffset!, + arg_adPodInfo!, + arg_traffickingParameters!, + arg_creativeID!, + arg_creativeAdID!, + arg_universalAdIDs!, + arg_advertiserName!, + arg_surveyURL, + arg_dealID!, + arg_wrapperAdIDs!, + arg_wrapperCreativeIDs!, + arg_wrapperSystems!, + ) ?? + IMAAd.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adId: arg_adId!, + adTitle: arg_adTitle!, + adDescription: arg_adDescription!, + adSystem: arg_adSystem!, + companionAds: arg_companionAds!, + contentType: arg_contentType!, + duration: arg_duration!, + uiElements: arg_uiElements!, + width: arg_width!, + height: arg_height!, + vastMediaWidth: arg_vastMediaWidth!, + vastMediaHeight: arg_vastMediaHeight!, + vastMediaBitrate: arg_vastMediaBitrate!, + isLinear: arg_isLinear!, + isSkippable: arg_isSkippable!, + skipTimeOffset: arg_skipTimeOffset!, + adPodInfo: arg_adPodInfo!, + traffickingParameters: arg_traffickingParameters!, + creativeID: arg_creativeID!, + creativeAdID: arg_creativeAdID!, + universalAdIDs: arg_universalAdIDs!, + advertiserName: arg_advertiserName!, + surveyURL: arg_surveyURL, + dealID: arg_dealID!, + wrapperAdIDs: arg_wrapperAdIDs!, + wrapperCreativeIDs: arg_wrapperCreativeIDs!, + wrapperSystems: arg_wrapperSystems!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6667,13 +6283,11 @@ class IMAUniversalAdID extends NSObject { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - IMAUniversalAdID Function(String adIDValue, String adIDRegistry)? - pigeon_newInstance, + IMAUniversalAdID Function(String adIDValue, String adIDRegistry)? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -6706,17 +6320,16 @@ class IMAUniversalAdID extends NSObject { 'Argument for dev.flutter.pigeon.interactive_media_ads.IMAUniversalAdID.pigeon_newInstance was null, expected non-null String.', ); try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call(arg_adIDValue!, arg_adIDRegistry!) ?? - IMAUniversalAdID.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - adIDValue: arg_adIDValue!, - adIDRegistry: arg_adIDRegistry!, - ), - arg_pigeon_instanceIdentifier!, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call(arg_adIDValue!, arg_adIDRegistry!) ?? + IMAUniversalAdID.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + adIDValue: arg_adIDValue!, + adIDRegistry: arg_adIDRegistry!, + ), + arg_pigeon_instanceIdentifier!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart b/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart index a5cd9da11f30..d6c5337e523f 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ad_display_container.dart @@ -13,8 +13,7 @@ import 'interactive_media_ads.g.dart'; import 'ios_companion_ad_slot.dart'; /// Implementation of [PlatformAdDisplayContainerCreationParams] for iOS. -final class IOSAdDisplayContainerCreationParams - extends PlatformAdDisplayContainerCreationParams { +final class IOSAdDisplayContainerCreationParams extends PlatformAdDisplayContainerCreationParams { /// Constructs a [IOSAdDisplayContainerCreationParams]. const IOSAdDisplayContainerCreationParams({ super.key, @@ -56,9 +55,7 @@ base class IOSAdDisplayContainer extends PlatformAdDisplayContainer { late final IOSAdDisplayContainerCreationParams _iosParams = params is IOSAdDisplayContainerCreationParams ? params as IOSAdDisplayContainerCreationParams - : IOSAdDisplayContainerCreationParams.fromPlatformAdDisplayContainerCreationParams( - params, - ); + : IOSAdDisplayContainerCreationParams.fromPlatformAdDisplayContainerCreationParams(params); @override Widget build(BuildContext context) { @@ -78,9 +75,7 @@ base class IOSAdDisplayContainer extends PlatformAdDisplayContainer { params.onContainerAdded(this); }, layoutDirection: params.layoutDirection, - creationParams: PigeonInstanceManager.instance.getIdentifier( - _controller.view, - ), + creationParams: PigeonInstanceManager.instance.getIdentifier(_controller.view), creationParamsCodec: const StandardMessageCodec(), ); } @@ -94,8 +89,7 @@ base class IOSAdDisplayContainer extends PlatformAdDisplayContainer { return UIViewController( viewDidAppear: (_, bool animated) { final IOSAdDisplayContainer? container = interfaceContainer.target; - if (container != null && - !container._viewDidAppearCompleter.isCompleted) { + if (container != null && !container._viewDidAppearCompleter.isCompleted) { container._viewDidAppearCompleter.complete(); } }, diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart index 33cf8fa23b1a..b42199b77d87 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_loader.dart @@ -52,8 +52,7 @@ base class IOSAdsLoader extends PlatformAdsLoader { WeakReference(this), ); - late final IOSAdsLoaderCreationParams _iosParams = - params is IOSAdsLoaderCreationParams + late final IOSAdsLoaderCreationParams _iosParams = params is IOSAdsLoaderCreationParams ? params as IOSAdsLoaderCreationParams : IOSAdsLoaderCreationParams.fromPlatformAdsLoaderCreationParams(params); @@ -66,10 +65,8 @@ base class IOSAdsLoader extends PlatformAdsLoader { Future requestAds(PlatformAdsRequest request) { final IMAAdDisplayContainer adDisplayContainer = (_iosParams.container as IOSAdDisplayContainer).adDisplayContainer!; - final IMAContentPlayhead? contentProgressProvider = - request.contentProgressProvider != null - ? (request.contentProgressProvider! as IOSContentProgressProvider) - .contentPlayhead + final IMAContentPlayhead? contentProgressProvider = request.contentProgressProvider != null + ? (request.contentProgressProvider! as IOSContentProgressProvider).contentPlayhead : null; final IMAAdsRequest adsRequest = switch (request) { @@ -100,16 +97,12 @@ base class IOSAdsLoader extends PlatformAdsLoader { adsRequest.setContentKeywords(contentKeywords), if (request.contentTitle case final String contentTitle) adsRequest.setContentTitle(contentTitle), - if (request.liveStreamPrefetchMaxWaitTime - case final Duration liveStreamPrefetchMaxWaitTime) + if (request.liveStreamPrefetchMaxWaitTime case final Duration liveStreamPrefetchMaxWaitTime) adsRequest.setLiveStreamPrefetchSeconds( - liveStreamPrefetchMaxWaitTime.inMilliseconds / - Duration.millisecondsPerSecond, + liveStreamPrefetchMaxWaitTime.inMilliseconds / Duration.millisecondsPerSecond, ), if (request.vastLoadTimeout case final Duration vastLoadTimeout) - adsRequest.setVastLoadTimeout( - vastLoadTimeout.inMilliseconds.toDouble(), - ), + adsRequest.setVastLoadTimeout(vastLoadTimeout.inMilliseconds.toDouble()), _adsLoader.requestAds(adsRequest), ]); } @@ -123,9 +116,7 @@ base class IOSAdsLoader extends PlatformAdsLoader { return IMAAdsLoaderDelegate( adLoaderLoadedWith: (_, __, IMAAdsLoadedData adsLoadedData) { interfaceLoader.target?._iosParams.onAdsLoaded( - PlatformOnAdsLoadedData( - manager: IOSAdsManager(adsLoadedData.adsManager!), - ), + PlatformOnAdsLoadedData(manager: IOSAdsManager(adsLoadedData.adsManager!)), ); }, adsLoaderFailedWithErrorData: (_, __, IMAAdLoadingErrorData adErrorData) { @@ -148,7 +139,6 @@ base class IOSAdsLoader extends PlatformAdsLoader { _ => IOSImaSettings(_iosParams.settings.params), }; - return IMAAdsLoader(settings: settings.nativeSettings) - ..setDelegate(_delegate); + return IMAAdsLoader(settings: settings.nativeSettings)..setDelegate(_delegate); } } diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart index 45f00c0f24cc..3bd6a24699fb 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager.dart @@ -20,9 +20,7 @@ class IOSAdsManager extends PlatformAdsManager { super( adCuePoints: List.unmodifiable( manager.adCuePoints.map((double seconds) { - return Duration( - milliseconds: (seconds * Duration.millisecondsPerSecond).round(), - ); + return Duration(milliseconds: (seconds * Duration.millisecondsPerSecond).round()); }), ), ); @@ -55,8 +53,7 @@ class IOSAdsManager extends PlatformAdsManager { @override Future setAdsManagerDelegate(PlatformAdsManagerDelegate delegate) { - final IOSAdsManagerDelegate platformDelegate = - delegate is IOSAdsManagerDelegate + final IOSAdsManagerDelegate platformDelegate = delegate is IOSAdsManagerDelegate ? delegate : IOSAdsManagerDelegate(delegate.params); _delegate = platformDelegate; diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart index 76d05b166d44..4f9f3745c301 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_manager_delegate.dart @@ -9,13 +9,9 @@ import 'enum_converter_utils.dart'; import 'interactive_media_ads.g.dart' as ima; /// Implementation of [PlatformAdsManagerDelegateCreationParams] for iOS. -final class IOSAdsManagerDelegateCreationParams - extends PlatformAdsManagerDelegateCreationParams { +final class IOSAdsManagerDelegateCreationParams extends PlatformAdsManagerDelegateCreationParams { /// Constructs an [IOSAdsManagerDelegateCreationParams]. - const IOSAdsManagerDelegateCreationParams({ - super.onAdEvent, - super.onAdErrorEvent, - }) : super(); + const IOSAdsManagerDelegateCreationParams({super.onAdEvent, super.onAdErrorEvent}) : super(); /// Creates an [IOSAdsManagerDelegateCreationParams] from an instance of /// [PlatformAdsManagerDelegateCreationParams]. @@ -107,17 +103,11 @@ PlatformAd _asPlatformAd(ima.IMAAd ad) { description: ad.adDescription, duration: ad.duration == -1 ? null - : Duration( - milliseconds: (ad.duration * Duration.millisecondsPerSecond) - .round(), - ), + : Duration(milliseconds: (ad.duration * Duration.millisecondsPerSecond).round()), height: ad.height, skipTimeOffset: ad.skipTimeOffset == -1 ? null - : Duration( - milliseconds: (ad.skipTimeOffset * Duration.millisecondsPerSecond) - .round(), - ), + : Duration(milliseconds: (ad.skipTimeOffset * Duration.millisecondsPerSecond).round()), surveyUrl: ad.surveyURL, title: ad.adTitle, traffickingParameters: ad.traffickingParameters, @@ -146,15 +136,10 @@ PlatformAdPodInfo _asPlatformAdInfo(ima.IMAAdPodInfo adPodInfo) { adPosition: adPodInfo.adPosition, maxDuration: adPodInfo.maxDuration == -1 ? null - : Duration( - milliseconds: - (adPodInfo.maxDuration * Duration.millisecondsPerSecond) - .round(), - ), + : Duration(milliseconds: (adPodInfo.maxDuration * Duration.millisecondsPerSecond).round()), podIndex: adPodInfo.podIndex, timeOffset: Duration( - milliseconds: (adPodInfo.timeOffset * Duration.millisecondsPerSecond) - .round(), + milliseconds: (adPodInfo.timeOffset * Duration.millisecondsPerSecond).round(), ), totalAds: adPodInfo.totalAds, isBumper: adPodInfo.isBumper, @@ -170,15 +155,9 @@ PlatformCompanionAd _asPlatformCompanionAd(ima.IMACompanionAd ad) { ); } -PlatformUniversalAdId _asPlatformUniversalAdId( - ima.IMAUniversalAdID universalAdId, -) { +PlatformUniversalAdId _asPlatformUniversalAdId(ima.IMAUniversalAdID universalAdId) { return PlatformUniversalAdId( - adIdValue: universalAdId.adIDValue == 'unknown' - ? null - : universalAdId.adIDValue, - adIdRegistry: universalAdId.adIDRegistry == 'unknown' - ? null - : universalAdId.adIDRegistry, + adIdValue: universalAdId.adIDValue == 'unknown' ? null : universalAdId.adIDValue, + adIdRegistry: universalAdId.adIDRegistry == 'unknown' ? null : universalAdId.adIDRegistry, ); } diff --git a/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart b/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart index bafccbe68c77..dc9fe004484a 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_ads_rendering_settings.dart @@ -47,16 +47,14 @@ base class IOSAdsRenderingSettings extends PlatformAdsRenderingSettings { nativeSettings.setEnablePreloading(_iosParams.enablePreloading!); } nativeSettings.setLoadVideoTimeout( - _iosParams.loadVideoTimeout.inMicroseconds / - Duration.microsecondsPerSecond, + _iosParams.loadVideoTimeout.inMicroseconds / Duration.microsecondsPerSecond, ); if (_iosParams.mimeTypes != null) { nativeSettings.setMimeTypes(_iosParams.mimeTypes); } if (_iosParams.playAdsAfterTime != null) { nativeSettings.setPlayAdsAfterTime( - _iosParams.playAdsAfterTime!.inMicroseconds / - Duration.microsecondsPerSecond, + _iosParams.playAdsAfterTime!.inMicroseconds / Duration.microsecondsPerSecond, ); } if (_iosParams.uiElements != null) { diff --git a/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart b/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart index 6a97a7323363..49c6a42bdd65 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_companion_ad_slot.dart @@ -12,21 +12,16 @@ import '../platform_interface/platform_companion_ad_slot.dart'; import 'interactive_media_ads.g.dart'; /// Implementation of [PlatformCompanionAdSlotCreationParams] for iOS. -final class IOSCompanionAdSlotCreationParams - extends PlatformCompanionAdSlotCreationParams { +final class IOSCompanionAdSlotCreationParams extends PlatformCompanionAdSlotCreationParams { /// Constructs an [IOSCompanionAdSlotCreationParams]. - const IOSCompanionAdSlotCreationParams({required super.size, super.onClicked}) - : super(); + const IOSCompanionAdSlotCreationParams({required super.size, super.onClicked}) : super(); /// Creates an [IOSCompanionAdSlotCreationParams] from an instance of /// [PlatformCompanionAdSlotCreationParams]. factory IOSCompanionAdSlotCreationParams.fromPlatformCompanionAdSlotCreationParamsSize( PlatformCompanionAdSlotCreationParams params, ) { - return IOSCompanionAdSlotCreationParams( - size: params.size, - onClicked: params.onClicked, - ); + return IOSCompanionAdSlotCreationParams(size: params.size, onClicked: params.onClicked); } } @@ -77,9 +72,7 @@ base class IOSCompanionAdSlot extends PlatformCompanionAdSlot { // This value is created in a static method because the callback methods for // any wrapped classes must not reference the encapsulating object. This is to // prevent a circular reference that prevents garbage collection. - static IMACompanionDelegate _createCompanionDelegate( - WeakReference weakThis, - ) { + static IMACompanionDelegate _createCompanionDelegate(WeakReference weakThis) { return IMACompanionDelegate( companionSlotWasClicked: (_, __) { weakThis.target?.params.onClicked!.call(); diff --git a/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart b/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart index 61f8c0b81077..72e4a5e34d5b 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_content_progress_provider.dart @@ -21,10 +21,7 @@ base class IOSContentProgressProvider extends PlatformContentProgressProvider { late final ima.IMAContentPlayhead contentPlayhead = ima.IMAContentPlayhead(); @override - Future setProgress({ - required Duration progress, - required Duration duration, - }) async { + Future setProgress({required Duration progress, required Duration duration}) async { return contentPlayhead.setCurrentTime(progress.inSeconds.toDouble()); } } diff --git a/packages/interactive_media_ads/lib/src/ios/ios_interactive_media_ads.dart b/packages/interactive_media_ads/lib/src/ios/ios_interactive_media_ads.dart index d785a8b98031..7793cc2c829c 100644 --- a/packages/interactive_media_ads/lib/src/ios/ios_interactive_media_ads.dart +++ b/packages/interactive_media_ads/lib/src/ios/ios_interactive_media_ads.dart @@ -59,16 +59,12 @@ final class IOSInteractiveMediaAds extends InteractiveMediaAdsPlatform { } @override - IOSCompanionAdSlot createPlatformCompanionAdSlot( - PlatformCompanionAdSlotCreationParams params, - ) { + IOSCompanionAdSlot createPlatformCompanionAdSlot(PlatformCompanionAdSlotCreationParams params) { return IOSCompanionAdSlot(params); } @override - IOSImaSettings createPlatformImaSettings( - PlatformImaSettingsCreationParams params, - ) { + IOSImaSettings createPlatformImaSettings(PlatformImaSettingsCreationParams params) { return IOSImaSettings(params); } } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart b/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart index 3557dd23cecb..9fdec16207ed 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/companion_ad_slot_size.dart @@ -24,8 +24,7 @@ sealed class CompanionAdSlotSize { /// A slot for a companion ad with a fixed with and height. @immutable class CompanionAdSlotSizeFixed extends CompanionAdSlotSize { - const CompanionAdSlotSizeFixed._({required this.width, required this.height}) - : super._(); + const CompanionAdSlotSizeFixed._({required this.width, required this.height}) : super._(); /// The width of the ad slot in pixels. final int width; diff --git a/packages/interactive_media_ads/lib/src/platform_interface/interactive_media_ads_platform.dart b/packages/interactive_media_ads/lib/src/platform_interface/interactive_media_ads_platform.dart index d0da75ea2e33..e848286f2443 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/interactive_media_ads_platform.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/interactive_media_ads_platform.dart @@ -20,9 +20,7 @@ abstract base class InteractiveMediaAdsPlatform { static InteractiveMediaAdsPlatform? instance; /// Creates a new [PlatformAdsLoader]. - PlatformAdsLoader createPlatformAdsLoader( - PlatformAdsLoaderCreationParams params, - ); + PlatformAdsLoader createPlatformAdsLoader(PlatformAdsLoaderCreationParams params); /// Creates a new [PlatformAdsManagerDelegate]. PlatformAdsManagerDelegate createPlatformAdsManagerDelegate( @@ -50,7 +48,5 @@ abstract base class InteractiveMediaAdsPlatform { ); /// Creates a new [PlatformImaSettings]. - PlatformImaSettings createPlatformImaSettings( - PlatformImaSettingsCreationParams params, - ); + PlatformImaSettings createPlatformImaSettings(PlatformImaSettingsCreationParams params); } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart index d0232d00e3d5..15587652db2b 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_display_container.dart @@ -71,9 +71,7 @@ base class PlatformAdDisplayContainerCreationParams { /// display ads. abstract base class PlatformAdDisplayContainer { /// Creates a new [PlatformAdDisplayContainer] - factory PlatformAdDisplayContainer( - PlatformAdDisplayContainerCreationParams params, - ) { + factory PlatformAdDisplayContainer(PlatformAdDisplayContainerCreationParams params) { assert( InteractiveMediaAdsPlatform.instance != null, 'A platform implementation for `interactive_media_ads` has not been set. ' @@ -82,10 +80,8 @@ abstract base class PlatformAdDisplayContainer { 'unit testing, `InteractiveMediaAdsPlatform.instance` can be set with ' 'your own test implementation.', ); - final PlatformAdDisplayContainer implementation = - InteractiveMediaAdsPlatform.instance!.createPlatformAdDisplayContainer( - params, - ); + final PlatformAdDisplayContainer implementation = InteractiveMediaAdsPlatform.instance! + .createPlatformAdDisplayContainer(params); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_event.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_event.dart index c651c2138ece..8ad513e51c8e 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_event.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ad_event.dart @@ -113,11 +113,7 @@ enum AdEventType { @immutable base class PlatformAdEvent { /// Creates an [PlatformAdEvent]. - const PlatformAdEvent({ - required this.type, - this.ad, - this.adData = const {}, - }); + const PlatformAdEvent({required this.type, this.ad, this.adData = const {}}); /// The type of event that occurred. final AdEventType type; diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart index b4818c7cdb62..45c3977d240a 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_loader.dart @@ -81,8 +81,7 @@ abstract base class PlatformAdsLoader { 'unit testing, `InteractiveMediaAdsPlatform.instance` can be set with ' 'your own test implementation.', ); - final PlatformAdsLoader implementation = InteractiveMediaAdsPlatform - .instance! + final PlatformAdsLoader implementation = InteractiveMediaAdsPlatform.instance! .createPlatformAdsLoader(params); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart index f6ce589ab99a..cde2cce92e01 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_manager_delegate.dart @@ -42,10 +42,7 @@ import 'platform_ad_event.dart'; @immutable base class PlatformAdsManagerDelegateCreationParams { /// Used by the platform implementation to create a new [PlatformAdsManagerDelegate]. - const PlatformAdsManagerDelegateCreationParams({ - this.onAdEvent, - this.onAdErrorEvent, - }); + const PlatformAdsManagerDelegateCreationParams({this.onAdEvent, this.onAdErrorEvent}); /// Invoked when there is an [PlatformAdEvent]. final void Function(PlatformAdEvent event)? onAdEvent; @@ -58,9 +55,7 @@ base class PlatformAdsManagerDelegateCreationParams { /// Interface for a platform implementation of a `AdsManagerDelegate`. abstract base class PlatformAdsManagerDelegate { /// Creates a new [PlatformAdsManagerDelegate] - factory PlatformAdsManagerDelegate( - PlatformAdsManagerDelegateCreationParams params, - ) { + factory PlatformAdsManagerDelegate(PlatformAdsManagerDelegateCreationParams params) { assert( InteractiveMediaAdsPlatform.instance != null, 'A platform implementation for `interactive_media_ads` has not been set. ' @@ -69,10 +64,8 @@ abstract base class PlatformAdsManagerDelegate { 'unit testing, `InteractiveMediaAdsPlatform.instance` can be set with ' 'your own test implementation.', ); - final PlatformAdsManagerDelegate implementation = - InteractiveMediaAdsPlatform.instance!.createPlatformAdsManagerDelegate( - params, - ); + final PlatformAdsManagerDelegate implementation = InteractiveMediaAdsPlatform.instance! + .createPlatformAdsManagerDelegate(params); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_rendering_settings.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_rendering_settings.dart index 5dc599587f98..dfa9ecdc5121 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_rendering_settings.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ads_rendering_settings.dart @@ -109,9 +109,7 @@ base class PlatformAdsRenderingSettingsCreationParams { /// Defines parameters that control the rendering of ads. abstract base class PlatformAdsRenderingSettings { /// Creates a new [PlatformAdsRenderingSettings] - factory PlatformAdsRenderingSettings( - PlatformAdsRenderingSettingsCreationParams params, - ) { + factory PlatformAdsRenderingSettings(PlatformAdsRenderingSettingsCreationParams params) { assert( InteractiveMediaAdsPlatform.instance != null, 'A platform implementation for `interactive_media_ads` has not been set. ' @@ -120,9 +118,8 @@ abstract base class PlatformAdsRenderingSettings { 'unit testing, `InteractiveMediaAdsPlatform.instance` can be set with ' 'your own test implementation.', ); - final PlatformAdsRenderingSettings implementation = - InteractiveMediaAdsPlatform.instance! - .createPlatformAdsRenderingSettings(params); + final PlatformAdsRenderingSettings implementation = InteractiveMediaAdsPlatform.instance! + .createPlatformAdsRenderingSettings(params); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_companion_ad_slot.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_companion_ad_slot.dart index ec9e0664f64a..3a559cecdab9 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_companion_ad_slot.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_companion_ad_slot.dart @@ -47,10 +47,7 @@ import 'interactive_media_ads_platform.dart'; base class PlatformCompanionAdSlotCreationParams { /// Used by the platform implementation to create a new /// [PlatformCompanionAdSlot]. - const PlatformCompanionAdSlotCreationParams({ - required this.size, - this.onClicked, - }); + const PlatformCompanionAdSlotCreationParams({required this.size, this.onClicked}); /// The size of the slot. final CompanionAdSlotSize size; @@ -63,9 +60,7 @@ base class PlatformCompanionAdSlotCreationParams { /// Ad slot for companion ads. abstract base class PlatformCompanionAdSlot { /// Creates a new [PlatformCompanionAdSlot] - factory PlatformCompanionAdSlot( - PlatformCompanionAdSlotCreationParams params, - ) { + factory PlatformCompanionAdSlot(PlatformCompanionAdSlotCreationParams params) { assert( InteractiveMediaAdsPlatform.instance != null, 'A platform implementation for `interactive_media_ads` has not been set. ' @@ -74,8 +69,7 @@ abstract base class PlatformCompanionAdSlot { 'unit testing, `InteractiveMediaAdsPlatform.instance` can be set with ' 'your own test implementation.', ); - final PlatformCompanionAdSlot implementation = InteractiveMediaAdsPlatform - .instance! + final PlatformCompanionAdSlot implementation = InteractiveMediaAdsPlatform.instance! .createPlatformCompanionAdSlot(params); return implementation; } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_content_progress_provider.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_content_progress_provider.dart index 99e520d0656b..494bcb13dc88 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_content_progress_provider.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_content_progress_provider.dart @@ -50,9 +50,7 @@ base class PlatformContentProgressProviderCreationParams { /// Provides updates required to enable triggering ads at configured cue points. abstract class PlatformContentProgressProvider { /// Creates a new [PlatformContentProgressProvider]. - factory PlatformContentProgressProvider( - PlatformContentProgressProviderCreationParams params, - ) { + factory PlatformContentProgressProvider(PlatformContentProgressProviderCreationParams params) { assert( InteractiveMediaAdsPlatform.instance != null, 'A platform implementation for `interactive_media_ads` has not been set. ' @@ -61,9 +59,8 @@ abstract class PlatformContentProgressProvider { 'unit testing, `InteractiveMediaAdsPlatform.instance` can be set with ' 'your own test implementation.', ); - final PlatformContentProgressProvider implementation = - InteractiveMediaAdsPlatform.instance! - .createPlatformContentProgressProvider(params); + final PlatformContentProgressProvider implementation = InteractiveMediaAdsPlatform.instance! + .createPlatformContentProgressProvider(params); return implementation; } @@ -79,8 +76,5 @@ abstract class PlatformContentProgressProvider { final PlatformContentProgressProviderCreationParams params; /// Sends an update on the progress of the content video. - Future setProgress({ - required Duration progress, - required Duration duration, - }); + Future setProgress({required Duration progress, required Duration duration}); } diff --git a/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart b/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart index eb159d683ce1..f050158728fb 100644 --- a/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart +++ b/packages/interactive_media_ads/lib/src/platform_interface/platform_ima_settings.dart @@ -62,8 +62,7 @@ abstract base class PlatformImaSettings { /// Creates a new [PlatformImaSettings]. factory PlatformImaSettings(PlatformImaSettingsCreationParams params) { assert(InteractiveMediaAdsPlatform.instance != null); - final PlatformImaSettings implementation = InteractiveMediaAdsPlatform - .instance! + final PlatformImaSettings implementation = InteractiveMediaAdsPlatform.instance! .createPlatformImaSettings(params); return implementation; } diff --git a/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart b/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart index bc5b57bbab6c..248b28ccdd0d 100644 --- a/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart +++ b/packages/interactive_media_ads/pigeons/interactive_media_ads_android.dart @@ -12,9 +12,7 @@ import 'package:pigeon/pigeon.dart'; dartOut: 'lib/src/android/interactive_media_ads.g.dart', kotlinOut: 'android/src/main/kotlin/dev/flutter/packages/interactive_media_ads/InteractiveMediaAdsLibrary.g.kt', - kotlinOptions: KotlinOptions( - package: 'dev.flutter.packages.interactive_media_ads', - ), + kotlinOptions: KotlinOptions(package: 'dev.flutter.packages.interactive_media_ads'), ), ) /// The types of error that can be encountered. @@ -255,8 +253,7 @@ enum AudioManagerAudioFocus { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/BaseDisplayContainer.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.BaseDisplayContainer', + fullClassName: 'com.google.ads.interactivemedia.v3.api.BaseDisplayContainer', ), ) abstract class BaseDisplayContainer { @@ -301,8 +298,7 @@ abstract class AdsLoader { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/AdsManagerLoadedEvent.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent', + fullClassName: 'com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent', ), ) abstract class AdsManagerLoadedEvent { @@ -424,8 +420,7 @@ abstract class AdsRequest { /// See https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/android/api/reference/com/google/ads/interactivemedia/v3/api/player/ContentProgressProvider.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider', + fullClassName: 'com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider', ), ) abstract class ContentProgressProvider { @@ -545,10 +540,7 @@ abstract class ImaSdkFactory { late final ImaSdkFactory instance; @static - AdDisplayContainer createAdDisplayContainer( - ViewGroup container, - VideoAdPlayer player, - ); + AdDisplayContainer createAdDisplayContainer(ViewGroup container, VideoAdPlayer player); /// Creates a CompanionAdSlot for the SDK to fill with companion ads. CompanionAdSlot createCompanionAdSlot(); @@ -558,10 +550,7 @@ abstract class ImaSdkFactory { /// Creates an `AdsLoader` for requesting ads using the specified settings /// object. - AdsLoader createAdsLoader( - ImaSdkSettings settings, - AdDisplayContainer container, - ); + AdsLoader createAdsLoader(ImaSdkSettings settings, AdDisplayContainer container); /// Creates an AdsRequest object to contain the data used to request ads. AdsRequest createAdsRequest(); @@ -634,8 +623,7 @@ abstract class ImaSdkSettings { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/player/VideoProgressUpdate.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate', + fullClassName: 'com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate', ), ) abstract class VideoProgressUpdate { @@ -701,11 +689,7 @@ abstract class AdPodInfo { /// single item. /// /// See https://developer.android.com/reference/android/widget/FrameLayout. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'android.widget.FrameLayout', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.widget.FrameLayout')) abstract class FrameLayout extends ViewGroup { FrameLayout(); } @@ -713,9 +697,7 @@ abstract class FrameLayout extends ViewGroup { /// A special view that can contain other views (called children.) /// /// See https://developer.android.com/reference/android/view/ViewGroup. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.view.ViewGroup'), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.view.ViewGroup')) abstract class ViewGroup extends View { /// Adds a child view. void addView(View view); @@ -729,11 +711,7 @@ abstract class ViewGroup extends View { /// Displays a video file. /// /// See https://developer.android.com/reference/android/widget/VideoView. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'android.widget.VideoView', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.widget.VideoView')) abstract class VideoView extends View { VideoView(); @@ -766,20 +744,14 @@ abstract class VideoView extends View { /// This class represents the basic building block for user interface components. /// /// See https://developer.android.com/reference/android/view/View. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.view.View'), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.view.View')) abstract class View {} /// MediaPlayer class can be used to control playback of audio/video files and /// streams. /// /// See https://developer.android.com/reference/android/media/MediaPlayer. -@ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'android.media.MediaPlayer', - ), -) +@ProxyApi(kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.media.MediaPlayer')) abstract class MediaPlayer { /// Gets the duration of the file. int getDuration(); @@ -808,10 +780,7 @@ abstract class MediaPlayer { ) abstract class VideoAdPlayerCallback { /// Fire this callback periodically as ad playback occurs. - void onAdProgress( - AdMediaInfo adMediaInfo, - VideoProgressUpdate videoProgressUpdate, - ); + void onAdProgress(AdMediaInfo adMediaInfo, VideoProgressUpdate videoProgressUpdate); /// Fire this callback when video playback stalls waiting for data. void onBuffering(AdMediaInfo adMediaInfo); @@ -847,8 +816,7 @@ abstract class VideoAdPlayerCallback { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/player/VideoAdPlayer.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer', + fullClassName: 'com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer', ), ) abstract class VideoAdPlayer { @@ -890,8 +858,7 @@ abstract class VideoAdPlayer { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/AdsLoader.AdsLoadedListener.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.AdsLoader.AdsLoadedListener', + fullClassName: 'com.google.ads.interactivemedia.v3.api.AdsLoader.AdsLoadedListener', ), ) abstract class AdsLoadedListener { @@ -906,8 +873,7 @@ abstract class AdsLoadedListener { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/AdErrorEvent.AdErrorListener.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.AdErrorEvent.AdErrorListener', + fullClassName: 'com.google.ads.interactivemedia.v3.api.AdErrorEvent.AdErrorListener', ), ) abstract class AdErrorListener { @@ -922,8 +888,7 @@ abstract class AdErrorListener { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/AdEvent.AdEventListener.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener', + fullClassName: 'com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener', ), ) abstract class AdEventListener { @@ -938,8 +903,7 @@ abstract class AdEventListener { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/AdsRenderingSettings.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.AdsRenderingSettings', + fullClassName: 'com.google.ads.interactivemedia.v3.api.AdsRenderingSettings', ), ) abstract class AdsRenderingSettings { @@ -1088,9 +1052,7 @@ abstract class UniversalAdId { /// /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/Ad.html. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'com.google.ads.interactivemedia.v3.api.Ad', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'com.google.ads.interactivemedia.v3.api.Ad'), ) abstract class Ad { /// The ad ID as specified in the VAST response. @@ -1186,8 +1148,7 @@ abstract class Ad { /// See https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/CompanionAdSlot.ClickListener.html. @ProxyApi( kotlinOptions: KotlinProxyApiOptions( - fullClassName: - 'com.google.ads.interactivemedia.v3.api.CompanionAdSlot.ClickListener', + fullClassName: 'com.google.ads.interactivemedia.v3.api.CompanionAdSlot.ClickListener', ), ) abstract class CompanionAdSlotClickListener { diff --git a/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart b/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart index ce39fd5ced20..bef8090a027d 100644 --- a/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart +++ b/packages/interactive_media_ads/pigeons/interactive_media_ads_ios.dart @@ -304,9 +304,7 @@ enum UIElementType { /// view and companion ad slots used for ad playback. /// /// See https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/ios/reference/Classes/IMAAdDisplayContainer. -@ProxyApi( - swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds'), -) +@ProxyApi(swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds')) abstract class IMAAdDisplayContainer extends NSObject { /// Initializes IMAAdDisplayContainer for rendering the ad and displaying the /// sad UI. @@ -579,14 +577,10 @@ abstract class IMAAdsLoaderDelegate extends NSObject { IMAAdsLoaderDelegate(); /// Called when ads are successfully loaded from the ad servers by the loader. - late final void Function(IMAAdsLoader loader, IMAAdsLoadedData adsLoadedData) - adLoaderLoadedWith; + late final void Function(IMAAdsLoader loader, IMAAdsLoadedData adsLoadedData) adLoaderLoadedWith; /// Error reported by the ads loader when loading or requesting an ad fails. - late final void Function( - IMAAdsLoader loader, - IMAAdLoadingErrorData adErrorData, - ) + late final void Function(IMAAdsLoader loader, IMAAdLoadingErrorData adErrorData) adsLoaderFailedWithErrorData; } @@ -670,12 +664,10 @@ abstract class IMAAdsManagerDelegate extends NSObject { IMAAdsManagerDelegate(); /// Called when there is an IMAAdEvent. - late final void Function(IMAAdsManager adsManager, IMAAdEvent event) - didReceiveAdEvent; + late final void Function(IMAAdsManager adsManager, IMAAdEvent event) didReceiveAdEvent; /// Called when there was an error playing the ad. - late final void Function(IMAAdsManager adsManager, IMAAdError error) - didReceiveAdError; + late final void Function(IMAAdsManager adsManager, IMAAdError error) didReceiveAdError; /// Called when an ad is ready to play. late final void Function(IMAAdsManager adsManager) didRequestContentPause; @@ -835,8 +827,7 @@ abstract class IMACompanionDelegate extends NSObject { IMACompanionDelegate(); /// Called when the slot is either filled or not filled. - late void Function(IMACompanionAdSlot slot, bool filled)? - companionAdSlotFilled; + late void Function(IMACompanionAdSlot slot, bool filled)? companionAdSlotFilled; /// Called when the slot is clicked on by the user and will successfully /// navigate away. @@ -846,9 +837,7 @@ abstract class IMACompanionDelegate extends NSObject { /// Simple data object containing podding metadata. /// /// See https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Classes/IMAAdPodInfo.html. -@ProxyApi( - swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds'), -) +@ProxyApi(swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds')) abstract class IMAAdPodInfo extends NSObject { /// The position of this ad within an ad pod. /// @@ -895,9 +884,7 @@ abstract class IMAAdPodInfo extends NSObject { /// Data object representing a single ad. /// /// See https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Classes/IMAAd. -@ProxyApi( - swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds'), -) +@ProxyApi(swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds')) abstract class IMAAd extends NSObject { /// The ad ID as specified in the VAST response. late final String adId; @@ -1008,9 +995,7 @@ abstract class IMAAd extends NSObject { /// Simple data object containing universal ad ID information. /// /// See https://developers.google.com/interactive-media-ads/docs/sdks/ios/client-side/reference/Classes/IMAUniversalAdID.html. -@ProxyApi( - swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds'), -) +@ProxyApi(swiftOptions: SwiftProxyApiOptions(import: 'GoogleInteractiveMediaAds')) abstract class IMAUniversalAdID extends NSObject { /// The universal ad ID value. /// diff --git a/packages/interactive_media_ads/test/ad_display_container_test.dart b/packages/interactive_media_ads/test/ad_display_container_test.dart index da68157bcc96..7579d575c950 100644 --- a/packages/interactive_media_ads/test/ad_display_container_test.dart +++ b/packages/interactive_media_ads/test/ad_display_container_test.dart @@ -19,44 +19,33 @@ void main() { onBuild: (_) => Container(), ); - await tester.pumpWidget( - AdDisplayContainer.fromPlatform(platform: adDisplayContainer), - ); + await tester.pumpWidget(AdDisplayContainer.fromPlatform(platform: adDisplayContainer)); expect(find.byType(Container), findsOneWidget); }); - testWidgets( - 'constructor parameters are correctly passed to creation params', - (WidgetTester tester) async { - InteractiveMediaAdsPlatform.instance = TestInteractiveMediaAdsPlatform( - onCreatePlatformAdDisplayContainer: - (PlatformAdDisplayContainerCreationParams params) { - return TestPlatformAdDisplayContainer( - params, - onBuild: (_) => Container(), - ); - }, - onCreatePlatformAdsLoader: (PlatformAdsLoaderCreationParams params) { - throw UnimplementedError(); - }, - onCreatePlatformAdsManagerDelegate: - (PlatformAdsManagerDelegateCreationParams params) { - throw UnimplementedError(); - }, - onCreatePlatformContentProgressProvider: (_) { - throw UnimplementedError(); - }, - ); - - final adDisplayContainer = AdDisplayContainer( - key: GlobalKey(), - onContainerAdded: (_) {}, - ); - - // The key passed to the default constructor is used by the super class - // and not passed to the platform implementation. - expect(adDisplayContainer.platform.params.key, isNull); - }, - ); + testWidgets('constructor parameters are correctly passed to creation params', ( + WidgetTester tester, + ) async { + InteractiveMediaAdsPlatform.instance = TestInteractiveMediaAdsPlatform( + onCreatePlatformAdDisplayContainer: (PlatformAdDisplayContainerCreationParams params) { + return TestPlatformAdDisplayContainer(params, onBuild: (_) => Container()); + }, + onCreatePlatformAdsLoader: (PlatformAdsLoaderCreationParams params) { + throw UnimplementedError(); + }, + onCreatePlatformAdsManagerDelegate: (PlatformAdsManagerDelegateCreationParams params) { + throw UnimplementedError(); + }, + onCreatePlatformContentProgressProvider: (_) { + throw UnimplementedError(); + }, + ); + + final adDisplayContainer = AdDisplayContainer(key: GlobalKey(), onContainerAdded: (_) {}); + + // The key passed to the default constructor is used by the super class + // and not passed to the platform implementation. + expect(adDisplayContainer.platform.params.key, isNull); + }); } diff --git a/packages/interactive_media_ads/test/ads_loader_test.dart b/packages/interactive_media_ads/test/ads_loader_test.dart index 8fbc27b5c9c5..8a6b326b7f04 100644 --- a/packages/interactive_media_ads/test/ads_loader_test.dart +++ b/packages/interactive_media_ads/test/ads_loader_test.dart @@ -65,10 +65,7 @@ void main() { platformRequest.liveStreamPrefetchMaxWaitTime, ); expect(request.vastLoadTimeout, platformRequest.vastLoadTimeout); - expect( - request.contentProgressProvider, - platformRequest.contentProgressProvider, - ); + expect(request.contentProgressProvider, platformRequest.contentProgressProvider); }), onContentComplete: () async {}, ); @@ -83,8 +80,7 @@ void main() { contentDuration: platformRequest.contentDuration, contentKeywords: platformRequest.contentKeywords, contentTitle: platformRequest.contentTitle, - liveStreamPrefetchMaxWaitTime: - platformRequest.liveStreamPrefetchMaxWaitTime, + liveStreamPrefetchMaxWaitTime: platformRequest.liveStreamPrefetchMaxWaitTime, vastLoadTimeout: platformRequest.vastLoadTimeout, contentProgressProvider: ContentProgressProvider.fromPlatform( platformRequest.contentProgressProvider!, diff --git a/packages/interactive_media_ads/test/ads_manager_delegate_test.dart b/packages/interactive_media_ads/test/ads_manager_delegate_test.dart index 7561421eb669..4540128f4c34 100644 --- a/packages/interactive_media_ads/test/ads_manager_delegate_test.dart +++ b/packages/interactive_media_ads/test/ads_manager_delegate_test.dart @@ -11,19 +11,16 @@ import 'test_stubs.dart'; void main() { test('passes params to platform instance', () async { InteractiveMediaAdsPlatform.instance = TestInteractiveMediaAdsPlatform( - onCreatePlatformAdsManagerDelegate: - (PlatformAdsManagerDelegateCreationParams params) { - return TestPlatformAdsManagerDelegate(params); - }, + onCreatePlatformAdsManagerDelegate: (PlatformAdsManagerDelegateCreationParams params) { + return TestPlatformAdsManagerDelegate(params); + }, onCreatePlatformAdsLoader: (PlatformAdsLoaderCreationParams params) { throw UnimplementedError(); }, - onCreatePlatformAdDisplayContainer: - (PlatformAdDisplayContainerCreationParams params) { - throw UnimplementedError(); - }, - onCreatePlatformContentProgressProvider: (_) => - throw UnimplementedError(), + onCreatePlatformAdDisplayContainer: (PlatformAdDisplayContainerCreationParams params) { + throw UnimplementedError(); + }, + onCreatePlatformContentProgressProvider: (_) => throw UnimplementedError(), ); void onAdErrorEvent(AdErrorEvent event) {} diff --git a/packages/interactive_media_ads/test/ads_manager_test.dart b/packages/interactive_media_ads/test/ads_manager_test.dart index ab053b513caa..7db8ebcfdfd8 100644 --- a/packages/interactive_media_ads/test/ads_manager_test.dart +++ b/packages/interactive_media_ads/test/ads_manager_test.dart @@ -14,9 +14,7 @@ import 'test_stubs.dart'; void main() { test('init', () async { final adsRenderingSettings = AdsRenderingSettings.fromPlatform( - TestAdsRenderingSettings( - const PlatformAdsRenderingSettingsCreationParams(), - ), + TestAdsRenderingSettings(const PlatformAdsRenderingSettingsCreationParams()), ); final settingsCompleter = Completer(); @@ -40,24 +38,18 @@ void main() { }); test('setAdsManagerDelegate', () async { - final platformManager = TestAdsManager( - onSetAdsManagerDelegate: expectAsync1((_) async {}), - ); + final platformManager = TestAdsManager(onSetAdsManagerDelegate: expectAsync1((_) async {})); final AdsManager manager = createAdsManager(platformManager); await manager.setAdsManagerDelegate( AdsManagerDelegate.fromPlatform( - TestPlatformAdsManagerDelegate( - const PlatformAdsManagerDelegateCreationParams(), - ), + TestPlatformAdsManagerDelegate(const PlatformAdsManagerDelegateCreationParams()), ), ); }); test('discardAdBreak', () async { - final platformManager = TestAdsManager( - onDiscardAdBreak: expectAsync0(() async {}), - ); + final platformManager = TestAdsManager(onDiscardAdBreak: expectAsync0(() async {})); final AdsManager manager = createAdsManager(platformManager); await manager.discardAdBreak(); @@ -85,18 +77,14 @@ void main() { }); test('destroy', () async { - final platformManager = TestAdsManager( - onDestroy: expectAsync0(() async {}), - ); + final platformManager = TestAdsManager(onDestroy: expectAsync0(() async {})); final AdsManager manager = createAdsManager(platformManager); await manager.destroy(); }); test('adCuePoints', () async { - final platformManager = TestAdsManager( - adCuePoints: const [Duration(seconds: 5)], - ); + final platformManager = TestAdsManager(adCuePoints: const [Duration(seconds: 5)]); final AdsManager manager = createAdsManager(platformManager); expect(platformManager.adCuePoints, manager.adCuePoints); @@ -112,14 +100,12 @@ AdsManager createAdsManager(PlatformAdsManager platformManager) { onRequestAds: (PlatformAdsRequest request) async {}, ); }, - onCreatePlatformAdsManagerDelegate: - (PlatformAdsManagerDelegateCreationParams params) { - throw UnimplementedError(); - }, - onCreatePlatformAdDisplayContainer: - (PlatformAdDisplayContainerCreationParams params) { - throw UnimplementedError(); - }, + onCreatePlatformAdsManagerDelegate: (PlatformAdsManagerDelegateCreationParams params) { + throw UnimplementedError(); + }, + onCreatePlatformAdDisplayContainer: (PlatformAdDisplayContainerCreationParams params) { + throw UnimplementedError(); + }, onCreatePlatformContentProgressProvider: (_) => throw UnimplementedError(), ); @@ -138,9 +124,7 @@ AdsManager createAdsManager(PlatformAdsManager platformManager) { onAdsLoadError: (_) {}, ); - loader.platform.params.onAdsLoaded( - PlatformOnAdsLoadedData(manager: platformManager), - ); + loader.platform.params.onAdsLoaded(PlatformOnAdsLoadedData(manager: platformManager)); return manager; } diff --git a/packages/interactive_media_ads/test/android/ad_display_container_test.dart b/packages/interactive_media_ads/test/android/ad_display_container_test.dart index 5db74a5b8f28..ec55f7b55b47 100644 --- a/packages/interactive_media_ads/test/android/ad_display_container_test.dart +++ b/packages/interactive_media_ads/test/android/ad_display_container_test.dart @@ -9,8 +9,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:interactive_media_ads/src/android/android_ad_display_container.dart'; import 'package:interactive_media_ads/src/android/android_companion_ad_slot.dart'; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/android/platform_views_service_proxy.dart'; import 'package:interactive_media_ads/src/platform_interface/platform_interface.dart'; import 'package:mockito/annotations.dart'; @@ -49,9 +48,7 @@ void main() { ), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); expect(find.byType(PlatformViewLink), findsOneWidget); expect(find.byKey(const Key('testKey')), findsOneWidget); @@ -59,26 +56,23 @@ void main() { testWidgets('onContainerAdded is called', (WidgetTester tester) async { ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); - ima.PigeonOverrides.videoView_new = - ({ - required dynamic onError, - dynamic onPrepared, - dynamic onCompletion, - }) => MockVideoView(); - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; - ima.PigeonOverrides.videoAdPlayer_new = - ({ - required dynamic addCallback, - required dynamic loadAd, - required dynamic pauseAd, - required dynamic playAd, - required dynamic release, - required dynamic removeCallback, - required dynamic stopAd, - }) => MockVideoAdPlayer(); + ima.PigeonOverrides.videoView_new = ({ + required dynamic onError, + dynamic onPrepared, + dynamic onCompletion, + }) => MockVideoView(); + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; + ima.PigeonOverrides.videoAdPlayer_new = ({ + required dynamic addCallback, + required dynamic loadAd, + required dynamic pauseAd, + required dynamic playAd, + required dynamic release, + required dynamic removeCallback, + required dynamic stopAd, + }) => MockVideoAdPlayer(); final mockPlatformViewsProxy = MockPlatformViewsServiceProxy(); final mockAndroidViewController = MockSurfaceAndroidViewController(); @@ -105,16 +99,10 @@ void main() { ), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); final onPlatformCreatedCallback = - verify( - mockAndroidViewController.addOnPlatformViewCreatedListener( - captureAny, - ), - ).captured[0] + verify(mockAndroidViewController.addOnPlatformViewCreatedListener(captureAny)).captured[0] as void Function(int); onPlatformCreatedCallback(platformViewId); @@ -123,18 +111,11 @@ void main() { }); test('completing the ad notifies IMA SDK the ad has ended', () { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; - late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallbackCallback; + late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallbackCallback; - late final void Function(ima.VideoView, ima.MediaPlayer) - onCompletionCallback; + late final void Function(ima.VideoView, ima.MediaPlayer) onCompletionCallback; ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); ima.PigeonOverrides.videoView_new = @@ -146,20 +127,13 @@ void main() { onCompletionCallback = onCompletion!; return MockVideoView(); }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ - required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallback, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -171,9 +145,7 @@ void main() { return MockVideoAdPlayer(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); final ima.AdMediaInfo mockAdMediaInfo = MockAdMediaInfo(); loadAdCallback(MockVideoAdPlayer(), mockAdMediaInfo, MockAdPodInfo()); @@ -187,44 +159,29 @@ void main() { }); test('error loading the ad notifies IMA SDK of error', () { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; - late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallbackCallback; + late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallbackCallback; - late final void Function(ima.VideoView, ima.MediaPlayer, int, int) - onErrorCallback; + late final void Function(ima.VideoView, ima.MediaPlayer, int, int) onErrorCallback; ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); ima.PigeonOverrides.videoView_new = ({ - required void Function(ima.VideoView, ima.MediaPlayer, int, int) - onError, + required void Function(ima.VideoView, ima.MediaPlayer, int, int) onError, dynamic onPrepared, dynamic onCompletion, }) { onErrorCallback = onError; return MockVideoView(); }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ - required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallback, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -236,9 +193,7 @@ void main() { return MockVideoAdPlayer(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); final ima.AdMediaInfo mockAdMediaInfo = MockAdMediaInfo(); loadAdCallback(MockVideoAdPlayer(), mockAdMediaInfo, MockAdPodInfo()); @@ -252,21 +207,13 @@ void main() { }); test('play ad once when it is prepared', () async { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; - late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallbackCallback; + late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallbackCallback; - late final Future Function(ima.VideoView, ima.MediaPlayer) - onPreparedCallback; + late final Future Function(ima.VideoView, ima.MediaPlayer) onPreparedCallback; - late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) - playAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAdCallback; const adDuration = 100; const adProgress = 10; @@ -280,25 +227,16 @@ void main() { }) { onPreparedCallback = onPrepared!; final mockVideoView = MockVideoView(); - when( - mockVideoView.getCurrentPosition(), - ).thenAnswer((_) async => adProgress); + when(mockVideoView.getCurrentPosition()).thenAnswer((_) async => adProgress); return mockVideoView; }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ - required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallback, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAd, required dynamic release, @@ -317,9 +255,7 @@ void main() { return MockVideoProgressUpdate(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); final ima.AdMediaInfo mockAdMediaInfo = MockAdMediaInfo(); loadAdCallback(MockVideoAdPlayer(), mockAdMediaInfo, MockAdPodInfo()); @@ -342,18 +278,11 @@ void main() { }); test('pause ad', () async { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; - late final Future Function(ima.VideoView, ima.MediaPlayer) - onPreparedCallback; + late final Future Function(ima.VideoView, ima.MediaPlayer) onPreparedCallback; - late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) - pauseAdCallback; + late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) pauseAdCallback; ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); ima.PigeonOverrides.videoView_new = @@ -365,27 +294,18 @@ void main() { // VideoView.onPrepared returns void, but the implementation uses an // async callback method. onPreparedCallback = - onPrepared! - as Future Function(ima.VideoView, ima.MediaPlayer); + onPrepared! as Future Function(ima.VideoView, ima.MediaPlayer); final mockVideoView = MockVideoView(); - when( - mockVideoView.getCurrentPosition(), - ).thenAnswer((_) async => 10); + when(mockVideoView.getCurrentPosition()).thenAnswer((_) async => 10); return mockVideoView; }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ required dynamic addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -395,12 +315,7 @@ void main() { loadAdCallback = loadAd; // VideoAdPlayer.pauseAd returns void, but the implementation uses an // async callback method. - pauseAdCallback = - pauseAd - as Future Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ); + pauseAdCallback = pauseAd as Future Function(ima.VideoAdPlayer, ima.AdMediaInfo); return MockVideoAdPlayer(); }; ima.PigeonOverrides.videoProgressUpdate_new = @@ -408,9 +323,7 @@ void main() { return MockVideoProgressUpdate(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); final ima.AdMediaInfo mockAdMediaInfo = MockAdMediaInfo(); loadAdCallback(MockVideoAdPlayer(), mockAdMediaInfo, MockAdPodInfo()); @@ -428,18 +341,11 @@ void main() { test('pauseAd does not call pause on null media player', () async { late final void Function(ima.VideoAdPlayer) releaseCallback; - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; - late Future Function(ima.VideoView, ima.MediaPlayer) - onPreparedCallback; + late Future Function(ima.VideoView, ima.MediaPlayer) onPreparedCallback; - late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) - pauseAdCallback; + late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) pauseAdCallback; ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); ima.PigeonOverrides.videoView_new = @@ -451,27 +357,18 @@ void main() { // VideoView.onPrepared returns void, but the implementation uses an // async callback method. onPreparedCallback = - onPrepared! - as Future Function(ima.VideoView, ima.MediaPlayer); + onPrepared! as Future Function(ima.VideoView, ima.MediaPlayer); final mockVideoView = MockVideoView(); - when( - mockVideoView.getCurrentPosition(), - ).thenAnswer((_) async => 10); + when(mockVideoView.getCurrentPosition()).thenAnswer((_) async => 10); return mockVideoView; }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ required dynamic addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -481,12 +378,7 @@ void main() { loadAdCallback = loadAd; // VideoAdPlayer.pauseAd returns void, but the implementation uses an // async callback method. - pauseAdCallback = - pauseAd - as Future Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ); + pauseAdCallback = pauseAd as Future Function(ima.VideoAdPlayer, ima.AdMediaInfo); releaseCallback = release as void Function(ima.VideoAdPlayer); return MockVideoAdPlayer(); }; @@ -495,9 +387,7 @@ void main() { return MockVideoProgressUpdate(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); final ima.AdMediaInfo mockAdMediaInfo = MockAdMediaInfo(); loadAdCallback(MockVideoAdPlayer(), mockAdMediaInfo, MockAdPodInfo()); @@ -513,21 +403,13 @@ void main() { }); test('ad does not play automatically after calling pause', () async { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; - late final Future Function(ima.VideoView, ima.MediaPlayer) - onPreparedCallback; + late final Future Function(ima.VideoView, ima.MediaPlayer) onPreparedCallback; - late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) - pauseAdCallback; + late final Future Function(ima.VideoAdPlayer, ima.AdMediaInfo) pauseAdCallback; - late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) - playAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAdCallback; ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); ima.PigeonOverrides.videoView_new = @@ -539,27 +421,18 @@ void main() { // VideoView.onPrepared returns void, but the implementation uses an // async callback method. onPreparedCallback = - onPrepared! - as Future Function(ima.VideoView, ima.MediaPlayer); + onPrepared! as Future Function(ima.VideoView, ima.MediaPlayer); final mockVideoView = MockVideoView(); - when( - mockVideoView.getCurrentPosition(), - ).thenAnswer((_) async => 10); + when(mockVideoView.getCurrentPosition()).thenAnswer((_) async => 10); return mockVideoView; }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ required dynamic addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAd, required dynamic release, @@ -569,12 +442,7 @@ void main() { loadAdCallback = loadAd; // VideoAdPlayer.pauseAd returns void, but the implementation uses an // async callback method. - pauseAdCallback = - pauseAd - as Future Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ); + pauseAdCallback = pauseAd as Future Function(ima.VideoAdPlayer, ima.AdMediaInfo); playAdCallback = playAd; return MockVideoAdPlayer(); }; @@ -583,9 +451,7 @@ void main() { return MockVideoProgressUpdate(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); final ima.AdMediaInfo mockAdMediaInfo = MockAdMediaInfo(); when(mockAdMediaInfo.url).thenReturn('url'); @@ -611,15 +477,9 @@ void main() { }); test('play ad', () async { - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; - late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) - playAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAdCallback; final mockVideoView = MockVideoView(); ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); @@ -627,19 +487,13 @@ void main() { ({dynamic onError, dynamic onPrepared, dynamic onCompletion}) { return mockVideoView; }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ required dynamic addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required void Function(ima.VideoAdPlayer, ima.AdMediaInfo) playAd, required dynamic release, @@ -651,9 +505,7 @@ void main() { return MockVideoAdPlayer(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); const videoUrl = 'url'; final ima.AdMediaInfo mockAdMediaInfo = MockAdMediaInfo(); @@ -665,8 +517,7 @@ void main() { }); test('stop ad creates and sets a new VideoView', () async { - late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) - stopAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) stopAdCallback; final mockFrameLayout = MockFrameLayout(); late final mockVideoView = MockVideoView(); @@ -686,19 +537,13 @@ void main() { fail('newVideoView was called too many times'); } }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ required dynamic addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -710,9 +555,7 @@ void main() { return MockVideoAdPlayer(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); stopAdCallback(MockVideoAdPlayer(), MockAdMediaInfo()); @@ -741,19 +584,13 @@ void main() { fail('newVideoView was called too many times'); } }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ required dynamic addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required dynamic playAd, required void Function(ima.VideoAdPlayer) release, @@ -765,9 +602,7 @@ void main() { return MockVideoAdPlayer(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); releaseCallback(MockVideoAdPlayer()); @@ -775,36 +610,29 @@ void main() { verify(mockFrameLayout.addView(mockVideoView2)); }); - testWidgets('AdDisplayContainer adds CompanionAdSlots', ( - WidgetTester tester, - ) async { + testWidgets('AdDisplayContainer adds CompanionAdSlots', (WidgetTester tester) async { final mockAdDisplayContainer = MockAdDisplayContainer(); final mockCompanionAdSlot = MockCompanionAdSlot(); ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); - ima.PigeonOverrides.videoView_new = - ({ - required dynamic onError, - dynamic onPrepared, - dynamic onCompletion, - }) => MockVideoView(); - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return mockAdDisplayContainer; - }; - ima.PigeonOverrides.videoAdPlayer_new = - ({ - required dynamic addCallback, - required dynamic loadAd, - required dynamic pauseAd, - required dynamic playAd, - required dynamic release, - required dynamic removeCallback, - required dynamic stopAd, - }) => MockVideoAdPlayer(); + ima.PigeonOverrides.videoView_new = ({ + required dynamic onError, + dynamic onPrepared, + dynamic onCompletion, + }) => MockVideoView(); + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return mockAdDisplayContainer; + }; + ima.PigeonOverrides.videoAdPlayer_new = ({ + required dynamic addCallback, + required dynamic loadAd, + required dynamic pauseAd, + required dynamic playAd, + required dynamic release, + required dynamic removeCallback, + required dynamic stopAd, + }) => MockVideoAdPlayer(); final mockFactory = MockImaSdkFactory(); - when( - mockFactory.createCompanionAdSlot(), - ).thenAnswer((_) async => mockCompanionAdSlot); + when(mockFactory.createCompanionAdSlot()).thenAnswer((_) async => mockCompanionAdSlot); ima.PigeonOverrides.imaSdkFactory_instance = mockFactory; final mockPlatformViewsProxy = MockPlatformViewsServiceProxy(); @@ -841,16 +669,10 @@ void main() { ), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); final onPlatformCreatedCallback = - verify( - mockAndroidViewController.addOnPlatformViewCreatedListener( - captureAny, - ), - ).captured[0] + verify(mockAndroidViewController.addOnPlatformViewCreatedListener(captureAny)).captured[0] as void Function(int); onPlatformCreatedCallback(platformViewId); @@ -859,26 +681,15 @@ void main() { await onContainerAddedCompleter.future; - verify( - mockAdDisplayContainer.setCompanionSlots([ - mockCompanionAdSlot, - ]), - ); + verify(mockAdDisplayContainer.setCompanionSlots([mockCompanionAdSlot])); }); test('AdDisplayContainer handles preloaded ads', () async { late void Function(ima.VideoView, ima.MediaPlayer) onCompletionCallback; - late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallbackCallback; - late final void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAdCallback; - late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) - stopAdCallback; + late final void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallbackCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAdCallback; + late final void Function(ima.VideoAdPlayer, ima.AdMediaInfo) stopAdCallback; final mockVideoView = MockVideoView(); ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); @@ -891,20 +702,13 @@ void main() { onCompletionCallback = onCompletion!; return mockVideoView; }; - ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = - (_, __) async { - return MockAdDisplayContainer(); - }; + ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { + return MockAdDisplayContainer(); + }; ima.PigeonOverrides.videoAdPlayer_new = ({ - required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallback, - required void Function( - ima.VideoAdPlayer, - ima.AdMediaInfo, - ima.AdPodInfo, - ) - loadAd, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallback, + required void Function(ima.VideoAdPlayer, ima.AdMediaInfo, ima.AdPodInfo) loadAd, required dynamic pauseAd, required dynamic playAd, required dynamic release, @@ -917,9 +721,7 @@ void main() { return MockVideoAdPlayer(); }; - AndroidAdDisplayContainer( - AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {}), - ); + AndroidAdDisplayContainer(AndroidAdDisplayContainerCreationParams(onContainerAdded: (_) {})); final mockPlayerCallback = MockVideoAdPlayerCallback(); addCallbackCallback(MockVideoAdPlayer(), mockPlayerCallback); diff --git a/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart b/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart index e5bd7c044126..fac4c74dc455 100644 --- a/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ad_display_container_test.mocks.dart @@ -7,10 +7,8 @@ import 'dart:async' as _i5; import 'dart:ui' as _i3; import 'package:flutter/services.dart' as _i4; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as _i2; -import 'package:interactive_media_ads/src/android/platform_views_service_proxy.dart' - as _i7; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as _i2; +import 'package:interactive_media_ads/src/android/platform_views_service_proxy.dart' as _i7; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i6; @@ -29,57 +27,47 @@ import 'package:mockito/src/dummies.dart' as _i6; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdDisplayContainer_1 extends _i1.SmartFake - implements _i2.AdDisplayContainer { +class _FakeAdDisplayContainer_1 extends _i1.SmartFake implements _i2.AdDisplayContainer { _FakeAdDisplayContainer_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdMediaInfo_2 extends _i1.SmartFake implements _i2.AdMediaInfo { - _FakeAdMediaInfo_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdMediaInfo_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdPodInfo_3 extends _i1.SmartFake implements _i2.AdPodInfo { - _FakeAdPodInfo_3(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdPodInfo_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCompanionAdSlot_4 extends _i1.SmartFake - implements _i2.CompanionAdSlot { +class _FakeCompanionAdSlot_4 extends _i1.SmartFake implements _i2.CompanionAdSlot { _FakeCompanionAdSlot_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeFrameLayout_5 extends _i1.SmartFake implements _i2.FrameLayout { - _FakeFrameLayout_5(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeFrameLayout_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImaSdkSettings_6 extends _i1.SmartFake - implements _i2.ImaSdkSettings { +class _FakeImaSdkSettings_6 extends _i1.SmartFake implements _i2.ImaSdkSettings { _FakeImaSdkSettings_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsLoader_7 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_7(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsLoader_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsRequest_8 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_8(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsRequest_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdsRenderingSettings_9 extends _i1.SmartFake - implements _i2.AdsRenderingSettings { +class _FakeAdsRenderingSettings_9 extends _i1.SmartFake implements _i2.AdsRenderingSettings { _FakeAdsRenderingSettings_9(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -90,8 +78,7 @@ class _FakeImaSdkFactory_10 extends _i1.SmartFake implements _i2.ImaSdkFactory { } class _FakeMediaPlayer_11 extends _i1.SmartFake implements _i2.MediaPlayer { - _FakeMediaPlayer_11(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeMediaPlayer_11(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeVideoAdPlayer_12 extends _i1.SmartFake implements _i2.VideoAdPlayer { @@ -99,94 +86,68 @@ class _FakeVideoAdPlayer_12 extends _i1.SmartFake implements _i2.VideoAdPlayer { : super(parent, parentInvocation); } -class _FakeVideoAdPlayerCallback_13 extends _i1.SmartFake - implements _i2.VideoAdPlayerCallback { +class _FakeVideoAdPlayerCallback_13 extends _i1.SmartFake implements _i2.VideoAdPlayerCallback { _FakeVideoAdPlayerCallback_13(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeVideoProgressUpdate_14 extends _i1.SmartFake - implements _i2.VideoProgressUpdate { +class _FakeVideoProgressUpdate_14 extends _i1.SmartFake implements _i2.VideoProgressUpdate { _FakeVideoProgressUpdate_14(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeVideoView_15 extends _i1.SmartFake implements _i2.VideoView { - _FakeVideoView_15(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeVideoView_15(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeOffset_16 extends _i1.SmartFake implements _i3.Offset { - _FakeOffset_16(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeOffset_16(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeSize_17 extends _i1.SmartFake implements _i3.Size { - _FakeSize_17(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeSize_17(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeExpensiveAndroidViewController_18 extends _i1.SmartFake implements _i4.ExpensiveAndroidViewController { - _FakeExpensiveAndroidViewController_18( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeExpensiveAndroidViewController_18(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSurfaceAndroidViewController_19 extends _i1.SmartFake implements _i4.SurfaceAndroidViewController { - _FakeSurfaceAndroidViewController_19( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeSurfaceAndroidViewController_19(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AdDisplayContainer]. /// /// See the documentation for Mockito's code generation for more information. -class MockAdDisplayContainer extends _i1.Mock - implements _i2.AdDisplayContainer { +class MockAdDisplayContainer extends _i1.Mock implements _i2.AdDisplayContainer { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdDisplayContainer pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdDisplayContainer_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdDisplayContainer_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdDisplayContainer); - - @override - _i5.Future setCompanionSlots( - List<_i2.CompanionAdSlot>? companionSlots, - ) => + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdDisplayContainer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdDisplayContainer_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdDisplayContainer_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdDisplayContainer); + + @override + _i5.Future setCompanionSlots(List<_i2.CompanionAdSlot>? companionSlots) => (super.noSuchMethod( - Invocation.method(#setCompanionSlots, [companionSlots]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#setCompanionSlots, [companionSlots]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [AdMediaInfo]. @@ -194,46 +155,28 @@ class MockAdDisplayContainer extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockAdMediaInfo extends _i1.Mock implements _i2.AdMediaInfo { @override - String get url => - (super.noSuchMethod( - Invocation.getter(#url), - returnValue: _i6.dummyValue(this, Invocation.getter(#url)), - returnValueForMissingStub: _i6.dummyValue( - this, - Invocation.getter(#url), - ), - ) - as String); + String get url => (super.noSuchMethod( + Invocation.getter(#url), + returnValue: _i6.dummyValue(this, Invocation.getter(#url)), + returnValueForMissingStub: _i6.dummyValue(this, Invocation.getter(#url)), + ) as String); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdMediaInfo pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdMediaInfo_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdMediaInfo_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdMediaInfo); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdMediaInfo pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdMediaInfo_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdMediaInfo_2(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdMediaInfo); } /// A class which mocks [AdPodInfo]. @@ -241,88 +184,63 @@ class MockAdMediaInfo extends _i1.Mock implements _i2.AdMediaInfo { /// See the documentation for Mockito's code generation for more information. class MockAdPodInfo extends _i1.Mock implements _i2.AdPodInfo { @override - int get adPosition => - (super.noSuchMethod( - Invocation.getter(#adPosition), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get adPosition => (super.noSuchMethod( + Invocation.getter(#adPosition), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - double get maxDuration => - (super.noSuchMethod( - Invocation.getter(#maxDuration), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) - as double); + double get maxDuration => (super.noSuchMethod( + Invocation.getter(#maxDuration), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); @override - int get podIndex => - (super.noSuchMethod( - Invocation.getter(#podIndex), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get podIndex => (super.noSuchMethod( + Invocation.getter(#podIndex), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - double get timeOffset => - (super.noSuchMethod( - Invocation.getter(#timeOffset), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) - as double); + double get timeOffset => (super.noSuchMethod( + Invocation.getter(#timeOffset), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); @override - int get totalAds => - (super.noSuchMethod( - Invocation.getter(#totalAds), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get totalAds => (super.noSuchMethod( + Invocation.getter(#totalAds), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - bool get isBumper => - (super.noSuchMethod( - Invocation.getter(#isBumper), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isBumper => (super.noSuchMethod( + Invocation.getter(#isBumper), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdPodInfo pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdPodInfo_3( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdPodInfo_3( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdPodInfo); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdPodInfo pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdPodInfo_3(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdPodInfo_3(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdPodInfo); } /// A class which mocks [CompanionAdSlot]. @@ -330,119 +248,86 @@ class MockAdPodInfo extends _i1.Mock implements _i2.AdPodInfo { /// See the documentation for Mockito's code generation for more information. class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future addClickListener( - _i2.CompanionAdSlotClickListener? clickListener, - ) => - (super.noSuchMethod( - Invocation.method(#addClickListener, [clickListener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future removeClickListener( - _i2.CompanionAdSlotClickListener? clickListener, - ) => + _i5.Future addClickListener(_i2.CompanionAdSlotClickListener? clickListener) => (super.noSuchMethod( - Invocation.method(#removeClickListener, [clickListener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#addClickListener, [clickListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.CompanionAdSlot pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCompanionAdSlot_4( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCompanionAdSlot_4( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.CompanionAdSlot); - - @override - _i5.Future<_i2.ViewGroup?> getContainer() => + _i5.Future removeClickListener(_i2.CompanionAdSlotClickListener? clickListener) => (super.noSuchMethod( - Invocation.method(#getContainer, []), - returnValue: _i5.Future<_i2.ViewGroup?>.value(), - returnValueForMissingStub: _i5.Future<_i2.ViewGroup?>.value(), - ) - as _i5.Future<_i2.ViewGroup?>); + Invocation.method(#removeClickListener, [clickListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future getHeight() => - (super.noSuchMethod( - Invocation.method(#getHeight, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i2.CompanionAdSlot pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCompanionAdSlot_4(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCompanionAdSlot_4(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.CompanionAdSlot); @override - _i5.Future getWidth() => - (super.noSuchMethod( - Invocation.method(#getWidth, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i5.Future<_i2.ViewGroup?> getContainer() => (super.noSuchMethod( + Invocation.method(#getContainer, []), + returnValue: _i5.Future<_i2.ViewGroup?>.value(), + returnValueForMissingStub: _i5.Future<_i2.ViewGroup?>.value(), + ) as _i5.Future<_i2.ViewGroup?>); @override - _i5.Future isFilled() => - (super.noSuchMethod( - Invocation.method(#isFilled, []), - returnValue: _i5.Future.value(false), - returnValueForMissingStub: _i5.Future.value(false), - ) - as _i5.Future); + _i5.Future getHeight() => (super.noSuchMethod( + Invocation.method(#getHeight, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); @override - _i5.Future setContainer(_i2.ViewGroup? container) => - (super.noSuchMethod( - Invocation.method(#setContainer, [container]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future getWidth() => (super.noSuchMethod( + Invocation.method(#getWidth, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); @override - _i5.Future setSize(int? width, int? height) => - (super.noSuchMethod( - Invocation.method(#setSize, [width, height]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future isFilled() => (super.noSuchMethod( + Invocation.method(#isFilled, []), + returnValue: _i5.Future.value(false), + returnValueForMissingStub: _i5.Future.value(false), + ) as _i5.Future); @override - _i5.Future setFluidSize() => - (super.noSuchMethod( - Invocation.method(#setFluidSize, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setContainer(_i2.ViewGroup? container) => (super.noSuchMethod( + Invocation.method(#setContainer, [container]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future setSize(int? width, int? height) => (super.noSuchMethod( + Invocation.method(#setSize, [width, height]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future setFluidSize() => (super.noSuchMethod( + Invocation.method(#setFluidSize, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [FrameLayout]. @@ -450,52 +335,35 @@ class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { /// See the documentation for Mockito's code generation for more information. class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.FrameLayout pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeFrameLayout_5( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeFrameLayout_5( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.FrameLayout); - - @override - _i5.Future addView(_i2.View? view) => - (super.noSuchMethod( - Invocation.method(#addView, [view]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future removeView(_i2.View? view) => - (super.noSuchMethod( - Invocation.method(#removeView, [view]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.FrameLayout pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFrameLayout_5(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeFrameLayout_5(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.FrameLayout); + + @override + _i5.Future addView(_i2.View? view) => (super.noSuchMethod( + Invocation.method(#addView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future removeView(_i2.View? view) => (super.noSuchMethod( + Invocation.method(#removeView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [ImaSdkFactory]. @@ -503,127 +371,79 @@ class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => - (super.noSuchMethod( - Invocation.method(#createCompanionAdSlot, []), - returnValue: _i5.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_4( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_4( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - ) - as _i5.Future<_i2.CompanionAdSlot>); - - @override - _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => - (super.noSuchMethod( - Invocation.method(#createImaSdkSettings, []), - returnValue: _i5.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_6( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_6( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - ) - as _i5.Future<_i2.ImaSdkSettings>); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_4(this, Invocation.method(#createCompanionAdSlot, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_4(this, Invocation.method(#createCompanionAdSlot, [])), + ), + ) as _i5.Future<_i2.CompanionAdSlot>); + + @override + _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_6(this, Invocation.method(#createImaSdkSettings, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_6(this, Invocation.method(#createImaSdkSettings, [])), + ), + ) as _i5.Future<_i2.ImaSdkSettings>); @override _i5.Future<_i2.AdsLoader> createAdsLoader( _i2.ImaSdkSettings? settings, _i2.AdDisplayContainer? container, - ) => - (super.noSuchMethod( - Invocation.method(#createAdsLoader, [settings, container]), - returnValue: _i5.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_7( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_7( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - ) - as _i5.Future<_i2.AdsLoader>); - - @override - _i5.Future<_i2.AdsRequest> createAdsRequest() => - (super.noSuchMethod( - Invocation.method(#createAdsRequest, []), - returnValue: _i5.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_8(this, Invocation.method(#createAdsRequest, [])), - ), - returnValueForMissingStub: _i5.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_8(this, Invocation.method(#createAdsRequest, [])), - ), - ) - as _i5.Future<_i2.AdsRequest>); - - @override - _i5.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => - (super.noSuchMethod( - Invocation.method(#createAdsRenderingSettings, []), - returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_9( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - returnValueForMissingStub: - _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_9( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - ) - as _i5.Future<_i2.AdsRenderingSettings>); - - @override - _i2.ImaSdkFactory pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImaSdkFactory_10( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImaSdkFactory_10( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImaSdkFactory); + ) => (super.noSuchMethod( + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_7(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_7(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + ) as _i5.Future<_i2.AdsLoader>); + + @override + _i5.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_8(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_8(this, Invocation.method(#createAdsRequest, [])), + ), + ) as _i5.Future<_i2.AdsRequest>); + + @override + _i5.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_9(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_9(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + ) as _i5.Future<_i2.AdsRenderingSettings>); + + @override + _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_10(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImaSdkFactory_10(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImaSdkFactory); } /// A class which mocks [MediaPlayer]. @@ -631,79 +451,56 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockMediaPlayer extends _i1.Mock implements _i2.MediaPlayer { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future getDuration() => - (super.noSuchMethod( - Invocation.method(#getDuration, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future seekTo(int? mSec) => - (super.noSuchMethod( - Invocation.method(#seekTo, [mSec]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future getDuration() => (super.noSuchMethod( + Invocation.method(#getDuration, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); @override - _i5.Future start() => - (super.noSuchMethod( - Invocation.method(#start, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future seekTo(int? mSec) => (super.noSuchMethod( + Invocation.method(#seekTo, [mSec]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future pause() => - (super.noSuchMethod( - Invocation.method(#pause, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future start() => (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future stop() => - (super.noSuchMethod( - Invocation.method(#stop, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.MediaPlayer pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeMediaPlayer_11( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeMediaPlayer_11( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.MediaPlayer); + _i5.Future stop() => (super.noSuchMethod( + Invocation.method(#stop, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.MediaPlayer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeMediaPlayer_11(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeMediaPlayer_11(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.MediaPlayer); } /// A class which mocks [VideoAdPlayer]. @@ -713,335 +510,225 @@ class MockVideoAdPlayer extends _i1.Mock implements _i2.VideoAdPlayer { @override void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) get addCallback => (super.noSuchMethod( - Invocation.getter(#addCallback), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + Invocation.getter(#addCallback), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.VideoAdPlayerCallback callback) {}, + returnValueForMissingStub: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); @override void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo) get loadAd => (super.noSuchMethod( - Invocation.getter(#loadAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo)); - - @override - _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get pauseAd => - (super.noSuchMethod( - Invocation.getter(#pauseAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) => _i5.Future.value(), - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) => _i5.Future.value(), - ) - as _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); - - @override - void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get playAd => - (super.noSuchMethod( - Invocation.getter(#playAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); - - @override - void Function(_i2.VideoAdPlayer) get release => - (super.noSuchMethod( - Invocation.getter(#release), - returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, - returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, - ) - as void Function(_i2.VideoAdPlayer)); + Invocation.getter(#loadAd), + returnValue: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + returnValueForMissingStub: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo)); @override - void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) - get removeCallback => - (super.noSuchMethod( - Invocation.getter(#removeCallback), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); - - @override - void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get stopAd => - (super.noSuchMethod( - Invocation.getter(#stopAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setVolume(int? value) => - (super.noSuchMethod( - Invocation.method(#setVolume, [value]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get pauseAd => (super.noSuchMethod( + Invocation.getter(#pauseAd), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) => + _i5.Future.value(), + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) => + _i5.Future.value(), + ) as _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); @override - _i5.Future setAdProgress(_i2.VideoProgressUpdate? progress) => - (super.noSuchMethod( - Invocation.method(#setAdProgress, [progress]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get playAd => (super.noSuchMethod( + Invocation.getter(#playAd), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + void Function(_i2.VideoAdPlayer) get release => (super.noSuchMethod( + Invocation.getter(#release), + returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, + ) as void Function(_i2.VideoAdPlayer)); @override - _i2.VideoAdPlayer pigeon_copy() => + void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) get removeCallback => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoAdPlayer_12( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoAdPlayer_12( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoAdPlayer); + Invocation.getter(#removeCallback), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.VideoAdPlayerCallback callback) {}, + returnValueForMissingStub: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get stopAd => (super.noSuchMethod( + Invocation.getter(#stopAd), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future setVolume(int? value) => (super.noSuchMethod( + Invocation.method(#setVolume, [value]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future setAdProgress(_i2.VideoProgressUpdate? progress) => (super.noSuchMethod( + Invocation.method(#setAdProgress, [progress]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.VideoAdPlayer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayer_12(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoAdPlayer_12(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.VideoAdPlayer); } /// A class which mocks [VideoAdPlayerCallback]. /// /// See the documentation for Mockito's code generation for more information. -class MockVideoAdPlayerCallback extends _i1.Mock - implements _i2.VideoAdPlayerCallback { +class MockVideoAdPlayerCallback extends _i1.Mock implements _i2.VideoAdPlayerCallback { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override _i5.Future onAdProgress( _i2.AdMediaInfo? adMediaInfo, _i2.VideoProgressUpdate? videoProgressUpdate, - ) => - (super.noSuchMethod( - Invocation.method(#onAdProgress, [ - adMediaInfo, - videoProgressUpdate, - ]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + ) => (super.noSuchMethod( + Invocation.method(#onAdProgress, [adMediaInfo, videoProgressUpdate]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onBuffering(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onBuffering, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onBuffering(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onBuffering, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onContentComplete() => - (super.noSuchMethod( - Invocation.method(#onContentComplete, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onContentComplete() => (super.noSuchMethod( + Invocation.method(#onContentComplete, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onEnded, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onEnded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onError, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onError, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onLoaded(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onLoaded, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onLoaded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onLoaded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onPause, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onPause, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onPlay, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onPlay, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onResume(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onResume, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onResume(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onResume, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onVolumeChanged( - _i2.AdMediaInfo? adMediaInfo, - int? percentage, - ) => + _i5.Future onVolumeChanged(_i2.AdMediaInfo? adMediaInfo, int? percentage) => (super.noSuchMethod( - Invocation.method(#onVolumeChanged, [adMediaInfo, percentage]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#onVolumeChanged, [adMediaInfo, percentage]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.VideoAdPlayerCallback pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoAdPlayerCallback_13( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoAdPlayerCallback_13( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoAdPlayerCallback); + _i2.VideoAdPlayerCallback pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayerCallback_13(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoAdPlayerCallback_13( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.VideoAdPlayerCallback); } /// A class which mocks [VideoProgressUpdate]. /// /// See the documentation for Mockito's code generation for more information. -class MockVideoProgressUpdate extends _i1.Mock - implements _i2.VideoProgressUpdate { +class MockVideoProgressUpdate extends _i1.Mock implements _i2.VideoProgressUpdate { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.VideoProgressUpdate pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoProgressUpdate_14( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoProgressUpdate_14( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoProgressUpdate); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.VideoProgressUpdate pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoProgressUpdate_14(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoProgressUpdate_14( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.VideoProgressUpdate); } /// A class which mocks [VideoView]. @@ -1049,84 +736,55 @@ class MockVideoProgressUpdate extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockVideoView extends _i1.Mock implements _i2.VideoView { @override - void Function(_i2.VideoView, _i2.MediaPlayer, int, int) get onError => - (super.noSuchMethod( - Invocation.getter(#onError), - returnValue: - ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - ) - as void Function(_i2.VideoView, _i2.MediaPlayer, int, int)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setVideoUri(String? uri) => - (super.noSuchMethod( - Invocation.method(#setVideoUri, [uri]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + void Function(_i2.VideoView, _i2.MediaPlayer, int, int) get onError => (super.noSuchMethod( + Invocation.getter(#onError), + returnValue: (_i2.VideoView pigeon_instance, _i2.MediaPlayer player, int what, int extra) {}, + returnValueForMissingStub: ( + _i2.VideoView pigeon_instance, + _i2.MediaPlayer player, + int what, + int extra, + ) {}, + ) as void Function(_i2.VideoView, _i2.MediaPlayer, int, int)); @override - _i5.Future getCurrentPosition() => - (super.noSuchMethod( - Invocation.method(#getCurrentPosition, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future setAudioFocusRequest( - _i2.AudioManagerAudioFocus? focusGain, - ) => - (super.noSuchMethod( - Invocation.method(#setAudioFocusRequest, [focusGain]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setVideoUri(String? uri) => (super.noSuchMethod( + Invocation.method(#setVideoUri, [uri]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.VideoView pigeon_copy() => + _i5.Future getCurrentPosition() => (super.noSuchMethod( + Invocation.method(#getCurrentPosition, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); + + @override + _i5.Future setAudioFocusRequest(_i2.AudioManagerAudioFocus? focusGain) => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoView_15( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoView_15( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoView); + Invocation.method(#setAudioFocusRequest, [focusGain]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.VideoView pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoView_15(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoView_15(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.VideoView); } /// A class which mocks [SurfaceAndroidViewController]. @@ -1135,60 +793,46 @@ class MockVideoView extends _i1.Mock implements _i2.VideoView { class MockSurfaceAndroidViewController extends _i1.Mock implements _i4.SurfaceAndroidViewController { @override - bool get requiresViewComposition => - (super.noSuchMethod( - Invocation.getter(#requiresViewComposition), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get requiresViewComposition => (super.noSuchMethod( + Invocation.getter(#requiresViewComposition), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override int get viewId => - (super.noSuchMethod( - Invocation.getter(#viewId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#viewId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - bool get awaitingCreation => - (super.noSuchMethod( - Invocation.getter(#awaitingCreation), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get awaitingCreation => (super.noSuchMethod( + Invocation.getter(#awaitingCreation), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i4.PointTransformer get pointTransformer => - (super.noSuchMethod( - Invocation.getter(#pointTransformer), - returnValue: (_i3.Offset position) => - _FakeOffset_16(this, Invocation.getter(#pointTransformer)), - returnValueForMissingStub: (_i3.Offset position) => - _FakeOffset_16(this, Invocation.getter(#pointTransformer)), - ) - as _i4.PointTransformer); + _i4.PointTransformer get pointTransformer => (super.noSuchMethod( + Invocation.getter(#pointTransformer), + returnValue: (_i3.Offset position) => + _FakeOffset_16(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: (_i3.Offset position) => + _FakeOffset_16(this, Invocation.getter(#pointTransformer)), + ) as _i4.PointTransformer); @override - bool get isCreated => - (super.noSuchMethod( - Invocation.getter(#isCreated), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isCreated => (super.noSuchMethod( + Invocation.getter(#isCreated), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - List<_i4.PlatformViewCreatedCallback> get createdCallbacks => - (super.noSuchMethod( - Invocation.getter(#createdCallbacks), - returnValue: <_i4.PlatformViewCreatedCallback>[], - returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], - ) - as List<_i4.PlatformViewCreatedCallback>); + List<_i4.PlatformViewCreatedCallback> get createdCallbacks => (super.noSuchMethod( + Invocation.getter(#createdCallbacks), + returnValue: <_i4.PlatformViewCreatedCallback>[], + returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], + ) as List<_i4.PlatformViewCreatedCallback>); @override set pointTransformer(_i4.PointTransformer? transformer) => super.noSuchMethod( @@ -1197,104 +841,85 @@ class MockSurfaceAndroidViewController extends _i1.Mock ); @override - _i5.Future setOffset(_i3.Offset? off) => - (super.noSuchMethod( - Invocation.method(#setOffset, [off]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setOffset(_i3.Offset? off) => (super.noSuchMethod( + Invocation.method(#setOffset, [off]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future create({_i3.Size? size, _i3.Offset? position}) => - (super.noSuchMethod( - Invocation.method(#create, [], {#size: size, #position: position}), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future create({_i3.Size? size, _i3.Offset? position}) => (super.noSuchMethod( + Invocation.method(#create, [], {#size: size, #position: position}), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i3.Size> setSize(_i3.Size? size) => - (super.noSuchMethod( - Invocation.method(#setSize, [size]), - returnValue: _i5.Future<_i3.Size>.value( - _FakeSize_17(this, Invocation.method(#setSize, [size])), - ), - returnValueForMissingStub: _i5.Future<_i3.Size>.value( - _FakeSize_17(this, Invocation.method(#setSize, [size])), - ), - ) - as _i5.Future<_i3.Size>); - - @override - _i5.Future sendMotionEvent(_i4.AndroidMotionEvent? event) => - (super.noSuchMethod( - Invocation.method(#sendMotionEvent, [event]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future<_i3.Size> setSize(_i3.Size? size) => (super.noSuchMethod( + Invocation.method(#setSize, [size]), + returnValue: _i5.Future<_i3.Size>.value( + _FakeSize_17(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i5.Future<_i3.Size>.value( + _FakeSize_17(this, Invocation.method(#setSize, [size])), + ), + ) as _i5.Future<_i3.Size>); @override - void addOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener, - ) => super.noSuchMethod( - Invocation.method(#addOnPlatformViewCreatedListener, [listener]), - returnValueForMissingStub: null, - ); + _i5.Future sendMotionEvent(_i4.AndroidMotionEvent? event) => (super.noSuchMethod( + Invocation.method(#sendMotionEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - void removeOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener, - ) => super.noSuchMethod( - Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), - returnValueForMissingStub: null, - ); + void addOnPlatformViewCreatedListener(_i4.PlatformViewCreatedCallback? listener) => + super.noSuchMethod( + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override - _i5.Future setLayoutDirection(_i3.TextDirection? layoutDirection) => - (super.noSuchMethod( - Invocation.method(#setLayoutDirection, [layoutDirection]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + void removeOnPlatformViewCreatedListener(_i4.PlatformViewCreatedCallback? listener) => + super.noSuchMethod( + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override - _i5.Future dispatchPointerEvent(_i4.PointerEvent? event) => - (super.noSuchMethod( - Invocation.method(#dispatchPointerEvent, [event]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setLayoutDirection(_i3.TextDirection? layoutDirection) => (super.noSuchMethod( + Invocation.method(#setLayoutDirection, [layoutDirection]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future clearFocus() => - (super.noSuchMethod( - Invocation.method(#clearFocus, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future dispatchPointerEvent(_i4.PointerEvent? event) => (super.noSuchMethod( + Invocation.method(#dispatchPointerEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future dispose() => - (super.noSuchMethod( - Invocation.method(#dispose, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future clearFocus() => (super.noSuchMethod( + Invocation.method(#clearFocus, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future dispose() => (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [PlatformViewsServiceProxy]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable -class MockPlatformViewsServiceProxy extends _i1.Mock - implements _i7.PlatformViewsServiceProxy { +class MockPlatformViewsServiceProxy extends _i1.Mock implements _i7.PlatformViewsServiceProxy { @override _i4.ExpensiveAndroidViewController initExpensiveAndroidView({ required int? id, @@ -1303,40 +928,38 @@ class MockPlatformViewsServiceProxy extends _i1.Mock dynamic creationParams, _i4.MessageCodec? creationParamsCodec, _i3.VoidCallback? onFocus, - }) => - (super.noSuchMethod( - Invocation.method(#initExpensiveAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - returnValue: _FakeExpensiveAndroidViewController_18( - this, - Invocation.method(#initExpensiveAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - returnValueForMissingStub: _FakeExpensiveAndroidViewController_18( - this, - Invocation.method(#initExpensiveAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - ) - as _i4.ExpensiveAndroidViewController); + }) => (super.noSuchMethod( + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + returnValue: _FakeExpensiveAndroidViewController_18( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeExpensiveAndroidViewController_18( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) as _i4.ExpensiveAndroidViewController); @override _i4.SurfaceAndroidViewController initSurfaceAndroidView({ @@ -1346,38 +969,36 @@ class MockPlatformViewsServiceProxy extends _i1.Mock dynamic creationParams, _i4.MessageCodec? creationParamsCodec, _i3.VoidCallback? onFocus, - }) => - (super.noSuchMethod( - Invocation.method(#initSurfaceAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - returnValue: _FakeSurfaceAndroidViewController_19( - this, - Invocation.method(#initSurfaceAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - returnValueForMissingStub: _FakeSurfaceAndroidViewController_19( - this, - Invocation.method(#initSurfaceAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - ) - as _i4.SurfaceAndroidViewController); + }) => (super.noSuchMethod( + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + returnValue: _FakeSurfaceAndroidViewController_19( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeSurfaceAndroidViewController_19( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) as _i4.SurfaceAndroidViewController); } diff --git a/packages/interactive_media_ads/test/android/ad_test.dart b/packages/interactive_media_ads/test/android/ad_test.dart index ebcecf6b8848..705d3c5957e2 100644 --- a/packages/interactive_media_ads/test/android/ad_test.dart +++ b/packages/interactive_media_ads/test/android/ad_test.dart @@ -5,8 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:interactive_media_ads/src/android/android_ads_manager.dart'; import 'package:interactive_media_ads/src/android/android_ads_manager_delegate.dart'; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/platform_interface/platform_interface.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -28,22 +27,16 @@ void main() { test('UniversalAdId sets unknown values to null', () async { final mockAdsManager = MockAdsManager(); - late final void Function(ima.AdEventListener, ima.AdEvent) - onAdEventCallback; + late final void Function(ima.AdEventListener, ima.AdEvent) onAdEventCallback; ima.PigeonOverrides.adEventListener_new = - ({ - required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent, - }) { + ({required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent}) { onAdEventCallback = onAdEvent; return MockAdEventListener(); }; ima.PigeonOverrides.adErrorListener_new = - ({ - required void Function(ima.AdErrorListener, ima.AdErrorEvent) - onAdError, - }) { + ({required void Function(ima.AdErrorListener, ima.AdErrorEvent) onAdError}) { return MockAdErrorListener(); }; @@ -65,10 +58,7 @@ void main() { when(mockAdEvent.ad).thenReturn( createTestAd( universalAdIds: [ - ima.UniversalAdId.pigeon_detached( - adIdRegistry: 'unknown', - adIdValue: 'unknown', - ), + ima.UniversalAdId.pigeon_detached(adIdRegistry: 'unknown', adIdValue: 'unknown'), ], ), ); @@ -79,22 +69,16 @@ void main() { test('CompanionAd sets 0 values for height/width to null', () async { final mockAdsManager = MockAdsManager(); - late final void Function(ima.AdEventListener, ima.AdEvent) - onAdEventCallback; + late final void Function(ima.AdEventListener, ima.AdEvent) onAdEventCallback; ima.PigeonOverrides.adEventListener_new = - ({ - required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent, - }) { + ({required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent}) { onAdEventCallback = onAdEvent; return MockAdEventListener(); }; ima.PigeonOverrides.adErrorListener_new = - ({ - required void Function(ima.AdErrorListener, ima.AdErrorEvent) - onAdError, - }) { + ({required void Function(ima.AdErrorListener, ima.AdErrorEvent) onAdError}) { return MockAdErrorListener(); }; @@ -115,9 +99,7 @@ void main() { when(mockAdEvent.type).thenReturn(ima.AdEventType.allAdsCompleted); when(mockAdEvent.ad).thenReturn( createTestAd( - companionAds: [ - ima.CompanionAd.pigeon_detached(height: 0, width: 0), - ], + companionAds: [ima.CompanionAd.pigeon_detached(height: 0, width: 0)], ), ); @@ -127,22 +109,16 @@ void main() { test('Ad sets durations of -1 to null', () async { final mockAdsManager = MockAdsManager(); - late final void Function(ima.AdEventListener, ima.AdEvent) - onAdEventCallback; + late final void Function(ima.AdEventListener, ima.AdEvent) onAdEventCallback; ima.PigeonOverrides.adEventListener_new = - ({ - required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent, - }) { + ({required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent}) { onAdEventCallback = onAdEvent; return MockAdEventListener(); }; ima.PigeonOverrides.adErrorListener_new = - ({ - required void Function(ima.AdErrorListener, ima.AdErrorEvent) - onAdError, - }) { + ({required void Function(ima.AdErrorListener, ima.AdErrorEvent) onAdError}) { return MockAdErrorListener(); }; diff --git a/packages/interactive_media_ads/test/android/ad_test.mocks.dart b/packages/interactive_media_ads/test/android/ad_test.mocks.dart index 4d1e6f1a0fae..b0b983837613 100644 --- a/packages/interactive_media_ads/test/android/ad_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ad_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -24,30 +23,25 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsManager_1 extends _i1.SmartFake implements _i2.AdsManager { - _FakeAdsManager_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsManager_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdEvent_2 extends _i1.SmartFake implements _i2.AdEvent { - _FakeAdEvent_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdEvent_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdEventListener_3 extends _i1.SmartFake - implements _i2.AdEventListener { +class _FakeAdEventListener_3 extends _i1.SmartFake implements _i2.AdEventListener { _FakeAdEventListener_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdErrorListener_4 extends _i1.SmartFake - implements _i2.AdErrorListener { +class _FakeAdErrorListener_4 extends _i1.SmartFake implements _i2.AdErrorListener { _FakeAdErrorListener_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -57,171 +51,127 @@ class _FakeAdErrorListener_4 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockAdsManager extends _i1.Mock implements _i2.AdsManager { @override - List get adCuePoints => - (super.noSuchMethod( - Invocation.getter(#adCuePoints), - returnValue: [], - returnValueForMissingStub: [], - ) - as List); + List get adCuePoints => (super.noSuchMethod( + Invocation.getter(#adCuePoints), + returnValue: [], + returnValueForMissingStub: [], + ) as List); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future discardAdBreak() => - (super.noSuchMethod( - Invocation.method(#discardAdBreak, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future discardAdBreak() => (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future pause() => - (super.noSuchMethod( - Invocation.method(#pause, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future start() => - (super.noSuchMethod( - Invocation.method(#start, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future start() => (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future resume() => - (super.noSuchMethod( - Invocation.method(#resume, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future resume() => (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future skip() => - (super.noSuchMethod( - Invocation.method(#skip, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future skip() => (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.AdsManager pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsManager_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsManager_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsManager); + _i2.AdsManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsManager_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsManager_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdsManager); @override - _i3.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => - (super.noSuchMethod( - Invocation.method(#addAdErrorListener, [errorListener]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( + Invocation.method(#addAdErrorListener, [errorListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future addAdEventListener(_i2.AdEventListener? adEventListener) => - (super.noSuchMethod( - Invocation.method(#addAdEventListener, [adEventListener]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future addAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( + Invocation.method(#addAdEventListener, [adEventListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future destroy() => - (super.noSuchMethod( - Invocation.method(#destroy, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future destroy() => (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future init(_i2.AdsRenderingSettings? settings) => - (super.noSuchMethod( - Invocation.method(#init, [settings]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future init(_i2.AdsRenderingSettings? settings) => (super.noSuchMethod( + Invocation.method(#init, [settings]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future focus() => - (super.noSuchMethod( - Invocation.method(#focus, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future focus() => (super.noSuchMethod( + Invocation.method(#focus, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future<_i2.AdProgressInfo?> getAdProgressInfo() => - (super.noSuchMethod( - Invocation.method(#getAdProgressInfo, []), - returnValue: _i3.Future<_i2.AdProgressInfo?>.value(), - returnValueForMissingStub: _i3.Future<_i2.AdProgressInfo?>.value(), - ) - as _i3.Future<_i2.AdProgressInfo?>); + _i3.Future<_i2.AdProgressInfo?> getAdProgressInfo() => (super.noSuchMethod( + Invocation.method(#getAdProgressInfo, []), + returnValue: _i3.Future<_i2.AdProgressInfo?>.value(), + returnValueForMissingStub: _i3.Future<_i2.AdProgressInfo?>.value(), + ) as _i3.Future<_i2.AdProgressInfo?>); @override - _i3.Future<_i2.Ad?> getCurrentAd() => - (super.noSuchMethod( - Invocation.method(#getCurrentAd, []), - returnValue: _i3.Future<_i2.Ad?>.value(), - returnValueForMissingStub: _i3.Future<_i2.Ad?>.value(), - ) - as _i3.Future<_i2.Ad?>); + _i3.Future<_i2.Ad?> getCurrentAd() => (super.noSuchMethod( + Invocation.method(#getCurrentAd, []), + returnValue: _i3.Future<_i2.Ad?>.value(), + returnValueForMissingStub: _i3.Future<_i2.Ad?>.value(), + ) as _i3.Future<_i2.Ad?>); @override - _i3.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => - (super.noSuchMethod( - Invocation.method(#removeAdErrorListener, [errorListener]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( + Invocation.method(#removeAdErrorListener, [errorListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future removeAdEventListener( - _i2.AdEventListener? adEventListener, - ) => + _i3.Future removeAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( - Invocation.method(#removeAdEventListener, [adEventListener]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#removeAdEventListener, [adEventListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); } /// A class which mocks [AdEvent]. @@ -229,43 +179,28 @@ class MockAdsManager extends _i1.Mock implements _i2.AdsManager { /// See the documentation for Mockito's code generation for more information. class MockAdEvent extends _i1.Mock implements _i2.AdEvent { @override - _i2.AdEventType get type => - (super.noSuchMethod( - Invocation.getter(#type), - returnValue: _i2.AdEventType.adBreakEnded, - returnValueForMissingStub: _i2.AdEventType.adBreakEnded, - ) - as _i2.AdEventType); + _i2.AdEventType get type => (super.noSuchMethod( + Invocation.getter(#type), + returnValue: _i2.AdEventType.adBreakEnded, + returnValueForMissingStub: _i2.AdEventType.adBreakEnded, + ) as _i2.AdEventType); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.AdEvent pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdEvent_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdEvent_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdEvent); + _i2.AdEvent pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdEvent_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdEvent_2(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdEvent); } /// A class which mocks [AdEventListener]. @@ -273,45 +208,28 @@ class MockAdEvent extends _i1.Mock implements _i2.AdEvent { /// See the documentation for Mockito's code generation for more information. class MockAdEventListener extends _i1.Mock implements _i2.AdEventListener { @override - void Function(_i2.AdEventListener, _i2.AdEvent) get onAdEvent => - (super.noSuchMethod( - Invocation.getter(#onAdEvent), - returnValue: - (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, - returnValueForMissingStub: - (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, - ) - as void Function(_i2.AdEventListener, _i2.AdEvent)); + void Function(_i2.AdEventListener, _i2.AdEvent) get onAdEvent => (super.noSuchMethod( + Invocation.getter(#onAdEvent), + returnValue: (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, + returnValueForMissingStub: (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, + ) as void Function(_i2.AdEventListener, _i2.AdEvent)); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.AdEventListener pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdEventListener_3( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdEventListener_3( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdEventListener); + _i2.AdEventListener pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdEventListener_3(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdEventListener_3(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdEventListener); } /// A class which mocks [AdErrorListener]. @@ -319,49 +237,26 @@ class MockAdEventListener extends _i1.Mock implements _i2.AdEventListener { /// See the documentation for Mockito's code generation for more information. class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { @override - void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => - (super.noSuchMethod( - Invocation.getter(#onAdError), - returnValue: - ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - returnValueForMissingStub: - ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - ) - as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); + void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => (super.noSuchMethod( + Invocation.getter(#onAdError), + returnValue: (_i2.AdErrorListener pigeon_instance, _i2.AdErrorEvent event) {}, + returnValueForMissingStub: (_i2.AdErrorListener pigeon_instance, _i2.AdErrorEvent event) {}, + ) as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.AdErrorListener pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdErrorListener_4( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdErrorListener_4( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdErrorListener); + _i2.AdErrorListener pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorListener_4(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdErrorListener_4(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdErrorListener); } diff --git a/packages/interactive_media_ads/test/android/ads_loader_test.dart b/packages/interactive_media_ads/test/android/ads_loader_test.dart index 8c60343409a6..562918dde5dc 100644 --- a/packages/interactive_media_ads/test/android/ads_loader_test.dart +++ b/packages/interactive_media_ads/test/android/ads_loader_test.dart @@ -11,8 +11,7 @@ import 'package:interactive_media_ads/src/android/android_ad_display_container.d import 'package:interactive_media_ads/src/android/android_ads_loader.dart'; import 'package:interactive_media_ads/src/android/android_content_progress_provider.dart'; import 'package:interactive_media_ads/src/android/android_ima_settings.dart'; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/android/platform_views_service_proxy.dart'; import 'package:interactive_media_ads/src/platform_interface/platform_interface.dart'; import 'package:mockito/annotations.dart'; @@ -50,18 +49,14 @@ void main() { }); testWidgets('instantiate AndroidAdsLoader', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer(tester); final mockImaSdkSettings = MockImaSdkSettings(); final MockImaSdkFactory mockSdkFactory = _mockImaSdkFactoryInstance( imaSdkSettings: mockImaSdkSettings, ); - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); AndroidAdsLoader( AndroidAdsLoaderCreationParams( @@ -73,12 +68,7 @@ void main() { ); expect(await settings.nativeSettingsFuture, mockImaSdkSettings); - verify( - mockSdkFactory.createAdsLoader( - mockImaSdkSettings, - container.adDisplayContainer, - ), - ); + verify(mockSdkFactory.createAdsLoader(mockImaSdkSettings, container.adDisplayContainer)); }); testWidgets('contentComplete', (WidgetTester tester) async { @@ -93,9 +83,7 @@ void main() { final loader = AndroidAdsLoader( AndroidAdsLoaderCreationParams( container: container, - settings: AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ), + settings: AndroidImaSettings(const PlatformImaSettingsCreationParams()), onAdsLoaded: (PlatformOnAdsLoadedData data) {}, onAdsLoadError: (AdsLoadErrorData data) {}, ), @@ -106,16 +94,11 @@ void main() { }); testWidgets('requestAds', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer(tester); final mockAdsLoader = MockAdsLoader(); final mockAdsRequest = MockAdsRequest(); - _mockImaSdkFactoryInstance( - adsRequest: mockAdsRequest, - adsLoader: mockAdsLoader, - ); + _mockImaSdkFactoryInstance(adsRequest: mockAdsRequest, adsLoader: mockAdsLoader); ima.PigeonOverrides.contentProgressProvider_new = () => ima.ContentProgressProvider.pigeon_detached(); @@ -123,9 +106,7 @@ void main() { final adsLoader = AndroidAdsLoader( AndroidAdsLoaderCreationParams( container: container, - settings: AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ), + settings: AndroidImaSettings(const PlatformImaSettingsCreationParams()), onAdsLoaded: (PlatformOnAdsLoadedData data) {}, onAdsLoadError: (AdsLoadErrorData data) {}, ), @@ -160,24 +141,17 @@ void main() { mockAdsRequest.setContentTitle('contentTitle'), mockAdsRequest.setLiveStreamPrefetchSeconds(3.0), mockAdsRequest.setVastLoadTimeout(5000.0), - mockAdsRequest.setContentProgressProvider( - progressProvider.progressProvider, - ), + mockAdsRequest.setContentProgressProvider(progressProvider.progressProvider), mockAdsLoader.requestAds(mockAdsRequest), ]); }); testWidgets('requestAds with adsResponse', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer(tester); final mockAdsLoader = MockAdsLoader(); final mockAdsRequest = MockAdsRequest(); - _mockImaSdkFactoryInstance( - adsRequest: mockAdsRequest, - adsLoader: mockAdsLoader, - ); + _mockImaSdkFactoryInstance(adsRequest: mockAdsRequest, adsLoader: mockAdsLoader); ima.PigeonOverrides.contentProgressProvider_new = () => ima.ContentProgressProvider.pigeon_detached(); @@ -185,9 +159,7 @@ void main() { final adsLoader = AndroidAdsLoader( AndroidAdsLoaderCreationParams( container: container, - settings: AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ), + settings: AndroidImaSettings(const PlatformImaSettingsCreationParams()), onAdsLoaded: (PlatformOnAdsLoadedData data) {}, onAdsLoadError: (AdsLoadErrorData data) {}, ), @@ -222,17 +194,13 @@ void main() { mockAdsRequest.setContentTitle('contentTitle'), mockAdsRequest.setLiveStreamPrefetchSeconds(3.0), mockAdsRequest.setVastLoadTimeout(5000.0), - mockAdsRequest.setContentProgressProvider( - progressProvider.progressProvider, - ), + mockAdsRequest.setContentProgressProvider(progressProvider.progressProvider), mockAdsLoader.requestAds(mockAdsRequest), ]); }); testWidgets('onAdsLoaded', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer(tester); final mockAdsLoader = MockAdsLoader(); final addEventListenerCompleter = Completer(); @@ -246,10 +214,7 @@ void main() { ima.PigeonOverrides.adsLoadedListener_new = ({ - required void Function( - ima.AdsLoadedListener, - ima.AdsManagerLoadedEvent, - ) + required void Function(ima.AdsLoadedListener, ima.AdsManagerLoadedEvent) onAdsManagerLoaded, }) { onAdsManagerLoadedCallback = onAdsManagerLoaded; @@ -262,9 +227,7 @@ void main() { AndroidAdsLoader( AndroidAdsLoaderCreationParams( container: container, - settings: AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ), + settings: AndroidImaSettings(const PlatformImaSettingsCreationParams()), onAdsLoaded: expectAsync1((_) {}), onAdsLoadError: (_) {}, ), @@ -278,12 +241,8 @@ void main() { onAdsManagerLoadedCallback(MockAdsLoadedListener(), mockLoadedEvent); }); - testWidgets('onAdsLoaded does not crash with null manager', ( - WidgetTester tester, - ) async { - final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + testWidgets('onAdsLoaded does not crash with null manager', (WidgetTester tester) async { + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer(tester); final mockAdsLoader = MockAdsLoader(); final addEventListenerCompleter = Completer(); @@ -297,10 +256,7 @@ void main() { ima.PigeonOverrides.adsLoadedListener_new = ({ - required void Function( - ima.AdsLoadedListener, - ima.AdsManagerLoadedEvent, - ) + required void Function(ima.AdsLoadedListener, ima.AdsManagerLoadedEvent) onAdsManagerLoaded, }) { onAdsManagerLoadedCallback = onAdsManagerLoaded; @@ -313,9 +269,7 @@ void main() { AndroidAdsLoader( AndroidAdsLoaderCreationParams( container: container, - settings: AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ), + settings: AndroidImaSettings(const PlatformImaSettingsCreationParams()), onAdsLoaded: (_) { fail('onAdsLoaded should not be called when AdsManager is null'); }, @@ -333,9 +287,7 @@ void main() { }); testWidgets('onAdError', (WidgetTester tester) async { - final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final AndroidAdDisplayContainer container = await _pumpAdDisplayContainer(tester); final mockAdsLoader = MockAdsLoader(); final addErrorListenerCompleter = Completer(); @@ -344,18 +296,13 @@ void main() { }); _mockImaSdkFactoryInstance(adsLoader: mockAdsLoader); - late final void Function(ima.AdErrorListener, ima.AdErrorEvent) - onAdErrorCallback; + late final void Function(ima.AdErrorListener, ima.AdErrorEvent) onAdErrorCallback; - ima.PigeonOverrides.adsLoadedListener_new = - ({required dynamic onAdsManagerLoaded}) { - return MockAdsLoadedListener(); - }; + ima.PigeonOverrides.adsLoadedListener_new = ({required dynamic onAdsManagerLoaded}) { + return MockAdsLoadedListener(); + }; ima.PigeonOverrides.adErrorListener_new = - ({ - required void Function(ima.AdErrorListener, ima.AdErrorEvent) - onAdError, - }) { + ({required void Function(ima.AdErrorListener, ima.AdErrorEvent) onAdError}) { onAdErrorCallback = onAdError; return MockAdErrorListener(); }; @@ -363,9 +310,7 @@ void main() { AndroidAdsLoader( AndroidAdsLoaderCreationParams( container: container, - settings: AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ), + settings: AndroidImaSettings(const PlatformImaSettingsCreationParams()), onAdsLoaded: (_) {}, onAdsLoadError: expectAsync1((_) {}), ), @@ -374,9 +319,7 @@ void main() { final mockErrorEvent = MockAdErrorEvent(); final mockError = MockAdError(); when(mockError.errorType).thenReturn(ima.AdErrorType.load); - when( - mockError.errorCode, - ).thenReturn(ima.AdErrorCode.adsRequestNetworkError); + when(mockError.errorCode).thenReturn(ima.AdErrorCode.adsRequestNetworkError); when(mockError.message).thenReturn('error message'); when(mockErrorEvent.error).thenReturn(mockError); @@ -411,16 +354,17 @@ Future _pumpAdDisplayContainer( MockVideoAdPlayerCallback? mockAdPlayerCallback, }) async { ima.PigeonOverrides.frameLayout_new = () => MockFrameLayout(); - ima.PigeonOverrides.videoView_new = - ({required dynamic onError, dynamic onPrepared, dynamic onCompletion}) => - MockVideoView(); + ima.PigeonOverrides.videoView_new = ({ + required dynamic onError, + dynamic onPrepared, + dynamic onCompletion, + }) => MockVideoView(); ima.PigeonOverrides.imaSdkFactory_createAdDisplayContainer = (_, __) async { return MockAdDisplayContainer(); }; ima.PigeonOverrides.videoAdPlayer_new = ({ - required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) - addCallback, + required void Function(ima.VideoAdPlayer, ima.VideoAdPlayerCallback) addCallback, required dynamic loadAd, required dynamic pauseAd, required dynamic playAd, @@ -457,24 +401,16 @@ Future _pumpAdDisplayContainer( final container = AndroidAdDisplayContainer( AndroidAdDisplayContainerCreationParams( onContainerAdded: (PlatformAdDisplayContainer container) { - adDisplayContainerCompleter.complete( - container as AndroidAdDisplayContainer, - ); + adDisplayContainerCompleter.complete(container as AndroidAdDisplayContainer); }, platformViewsProxy: mockPlatformViewsProxy, ), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); final onPlatformCreatedCallback = - verify( - mockAndroidViewController.addOnPlatformViewCreatedListener( - captureAny, - ), - ).captured[0] + verify(mockAndroidViewController.addOnPlatformViewCreatedListener(captureAny)).captured[0] as void Function(int); onPlatformCreatedCallback(platformViewId); diff --git a/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart b/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart index 6115bd3b27b0..1feb60536c91 100644 --- a/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ads_loader_test.mocks.dart @@ -7,10 +7,8 @@ import 'dart:async' as _i5; import 'dart:ui' as _i3; import 'package:flutter/services.dart' as _i4; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as _i2; -import 'package:interactive_media_ads/src/android/platform_views_service_proxy.dart' - as _i7; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as _i2; +import 'package:interactive_media_ads/src/android/platform_views_service_proxy.dart' as _i7; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i6; @@ -29,80 +27,66 @@ import 'package:mockito/src/dummies.dart' as _i6; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdDisplayContainer_1 extends _i1.SmartFake - implements _i2.AdDisplayContainer { +class _FakeAdDisplayContainer_1 extends _i1.SmartFake implements _i2.AdDisplayContainer { _FakeAdDisplayContainer_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdError_2 extends _i1.SmartFake implements _i2.AdError { - _FakeAdError_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdError_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdErrorEvent_3 extends _i1.SmartFake implements _i2.AdErrorEvent { - _FakeAdErrorEvent_3(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdErrorEvent_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdErrorListener_4 extends _i1.SmartFake - implements _i2.AdErrorListener { +class _FakeAdErrorListener_4 extends _i1.SmartFake implements _i2.AdErrorListener { _FakeAdErrorListener_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdsLoadedListener_5 extends _i1.SmartFake - implements _i2.AdsLoadedListener { +class _FakeAdsLoadedListener_5 extends _i1.SmartFake implements _i2.AdsLoadedListener { _FakeAdsLoadedListener_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsManager_6 extends _i1.SmartFake implements _i2.AdsManager { - _FakeAdsManager_6(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsManager_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdsManagerLoadedEvent_7 extends _i1.SmartFake - implements _i2.AdsManagerLoadedEvent { +class _FakeAdsManagerLoadedEvent_7 extends _i1.SmartFake implements _i2.AdsManagerLoadedEvent { _FakeAdsManagerLoadedEvent_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsLoader_8 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_8(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsLoader_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsRequest_9 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_9(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsRequest_9(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeFrameLayout_10 extends _i1.SmartFake implements _i2.FrameLayout { - _FakeFrameLayout_10(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeFrameLayout_10(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCompanionAdSlot_11 extends _i1.SmartFake - implements _i2.CompanionAdSlot { +class _FakeCompanionAdSlot_11 extends _i1.SmartFake implements _i2.CompanionAdSlot { _FakeCompanionAdSlot_11(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImaSdkSettings_12 extends _i1.SmartFake - implements _i2.ImaSdkSettings { +class _FakeImaSdkSettings_12 extends _i1.SmartFake implements _i2.ImaSdkSettings { _FakeImaSdkSettings_12(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdsRenderingSettings_13 extends _i1.SmartFake - implements _i2.AdsRenderingSettings { +class _FakeAdsRenderingSettings_13 extends _i1.SmartFake implements _i2.AdsRenderingSettings { _FakeAdsRenderingSettings_13(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -117,88 +101,63 @@ class _FakeVideoAdPlayer_15 extends _i1.SmartFake implements _i2.VideoAdPlayer { : super(parent, parentInvocation); } -class _FakeVideoAdPlayerCallback_16 extends _i1.SmartFake - implements _i2.VideoAdPlayerCallback { +class _FakeVideoAdPlayerCallback_16 extends _i1.SmartFake implements _i2.VideoAdPlayerCallback { _FakeVideoAdPlayerCallback_16(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeVideoView_17 extends _i1.SmartFake implements _i2.VideoView { - _FakeVideoView_17(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeVideoView_17(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeOffset_18 extends _i1.SmartFake implements _i3.Offset { - _FakeOffset_18(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeOffset_18(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeSize_19 extends _i1.SmartFake implements _i3.Size { - _FakeSize_19(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeSize_19(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeExpensiveAndroidViewController_20 extends _i1.SmartFake implements _i4.ExpensiveAndroidViewController { - _FakeExpensiveAndroidViewController_20( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeExpensiveAndroidViewController_20(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSurfaceAndroidViewController_21 extends _i1.SmartFake implements _i4.SurfaceAndroidViewController { - _FakeSurfaceAndroidViewController_21( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeSurfaceAndroidViewController_21(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AdDisplayContainer]. /// /// See the documentation for Mockito's code generation for more information. -class MockAdDisplayContainer extends _i1.Mock - implements _i2.AdDisplayContainer { +class MockAdDisplayContainer extends _i1.Mock implements _i2.AdDisplayContainer { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdDisplayContainer pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdDisplayContainer_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdDisplayContainer_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdDisplayContainer); - - @override - _i5.Future setCompanionSlots( - List<_i2.CompanionAdSlot>? companionSlots, - ) => + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdDisplayContainer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdDisplayContainer_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdDisplayContainer_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdDisplayContainer); + + @override + _i5.Future setCompanionSlots(List<_i2.CompanionAdSlot>? companionSlots) => (super.noSuchMethod( - Invocation.method(#setCompanionSlots, [companionSlots]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#setCompanionSlots, [companionSlots]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [AdError]. @@ -206,76 +165,49 @@ class MockAdDisplayContainer extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockAdError extends _i1.Mock implements _i2.AdError { @override - _i2.AdErrorCode get errorCode => - (super.noSuchMethod( - Invocation.getter(#errorCode), - returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, - returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, - ) - as _i2.AdErrorCode); + _i2.AdErrorCode get errorCode => (super.noSuchMethod( + Invocation.getter(#errorCode), + returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, + returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, + ) as _i2.AdErrorCode); @override - int get errorCodeNumber => - (super.noSuchMethod( - Invocation.getter(#errorCodeNumber), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get errorCodeNumber => (super.noSuchMethod( + Invocation.getter(#errorCodeNumber), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - _i2.AdErrorType get errorType => - (super.noSuchMethod( - Invocation.getter(#errorType), - returnValue: _i2.AdErrorType.load, - returnValueForMissingStub: _i2.AdErrorType.load, - ) - as _i2.AdErrorType); + _i2.AdErrorType get errorType => (super.noSuchMethod( + Invocation.getter(#errorType), + returnValue: _i2.AdErrorType.load, + returnValueForMissingStub: _i2.AdErrorType.load, + ) as _i2.AdErrorType); @override - String get message => - (super.noSuchMethod( - Invocation.getter(#message), - returnValue: _i6.dummyValue( - this, - Invocation.getter(#message), - ), - returnValueForMissingStub: _i6.dummyValue( - this, - Invocation.getter(#message), - ), - ) - as String); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdError pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdError_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdError_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdError); + String get message => (super.noSuchMethod( + Invocation.getter(#message), + returnValue: _i6.dummyValue(this, Invocation.getter(#message)), + returnValueForMissingStub: _i6.dummyValue(this, Invocation.getter(#message)), + ) as String); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdError pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdError_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdError_2(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdError); } /// A class which mocks [AdErrorEvent]. @@ -283,46 +215,28 @@ class MockAdError extends _i1.Mock implements _i2.AdError { /// See the documentation for Mockito's code generation for more information. class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { @override - _i2.AdError get error => - (super.noSuchMethod( - Invocation.getter(#error), - returnValue: _FakeAdError_2(this, Invocation.getter(#error)), - returnValueForMissingStub: _FakeAdError_2( - this, - Invocation.getter(#error), - ), - ) - as _i2.AdError); + _i2.AdError get error => (super.noSuchMethod( + Invocation.getter(#error), + returnValue: _FakeAdError_2(this, Invocation.getter(#error)), + returnValueForMissingStub: _FakeAdError_2(this, Invocation.getter(#error)), + ) as _i2.AdError); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorEvent pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdErrorEvent_3( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdErrorEvent_3( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdErrorEvent); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorEvent pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorEvent_3(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdErrorEvent_3(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdErrorEvent); } /// A class which mocks [AdErrorListener]. @@ -330,51 +244,28 @@ class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { /// See the documentation for Mockito's code generation for more information. class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { @override - void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => - (super.noSuchMethod( - Invocation.getter(#onAdError), - returnValue: - ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - returnValueForMissingStub: - ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - ) - as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorListener pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdErrorListener_4( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdErrorListener_4( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdErrorListener); + void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => (super.noSuchMethod( + Invocation.getter(#onAdError), + returnValue: (_i2.AdErrorListener pigeon_instance, _i2.AdErrorEvent event) {}, + returnValueForMissingStub: (_i2.AdErrorListener pigeon_instance, _i2.AdErrorEvent event) {}, + ) as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorListener pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorListener_4(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdErrorListener_4(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdErrorListener); } /// A class which mocks [AdsLoadedListener]. @@ -382,52 +273,32 @@ class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { /// See the documentation for Mockito's code generation for more information. class MockAdsLoadedListener extends _i1.Mock implements _i2.AdsLoadedListener { @override - void Function(_i2.AdsLoadedListener, _i2.AdsManagerLoadedEvent) - get onAdsManagerLoaded => - (super.noSuchMethod( - Invocation.getter(#onAdsManagerLoaded), - returnValue: - ( - _i2.AdsLoadedListener pigeon_instance, - _i2.AdsManagerLoadedEvent event, - ) {}, - returnValueForMissingStub: - ( - _i2.AdsLoadedListener pigeon_instance, - _i2.AdsManagerLoadedEvent event, - ) {}, - ) - as void Function(_i2.AdsLoadedListener, _i2.AdsManagerLoadedEvent)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdsLoadedListener pigeon_copy() => + void Function(_i2.AdsLoadedListener, _i2.AdsManagerLoadedEvent) get onAdsManagerLoaded => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsLoadedListener_5( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsLoadedListener_5( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsLoadedListener); + Invocation.getter(#onAdsManagerLoaded), + returnValue: (_i2.AdsLoadedListener pigeon_instance, _i2.AdsManagerLoadedEvent event) {}, + returnValueForMissingStub: ( + _i2.AdsLoadedListener pigeon_instance, + _i2.AdsManagerLoadedEvent event, + ) {}, + ) as void Function(_i2.AdsLoadedListener, _i2.AdsManagerLoadedEvent)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdsLoadedListener pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsLoadedListener_5(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsLoadedListener_5(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdsLoadedListener); } /// A class which mocks [AdsManager]. @@ -435,207 +306,152 @@ class MockAdsLoadedListener extends _i1.Mock implements _i2.AdsLoadedListener { /// See the documentation for Mockito's code generation for more information. class MockAdsManager extends _i1.Mock implements _i2.AdsManager { @override - List get adCuePoints => - (super.noSuchMethod( - Invocation.getter(#adCuePoints), - returnValue: [], - returnValueForMissingStub: [], - ) - as List); + List get adCuePoints => (super.noSuchMethod( + Invocation.getter(#adCuePoints), + returnValue: [], + returnValueForMissingStub: [], + ) as List); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future discardAdBreak() => - (super.noSuchMethod( - Invocation.method(#discardAdBreak, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future pause() => - (super.noSuchMethod( - Invocation.method(#pause, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future discardAdBreak() => (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future start() => - (super.noSuchMethod( - Invocation.method(#start, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future resume() => - (super.noSuchMethod( - Invocation.method(#resume, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future start() => (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future skip() => - (super.noSuchMethod( - Invocation.method(#skip, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future resume() => (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.AdsManager pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsManager_6( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsManager_6( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsManager); - - @override - _i5.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => - (super.noSuchMethod( - Invocation.method(#addAdErrorListener, [errorListener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future skip() => (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future addAdEventListener(_i2.AdEventListener? adEventListener) => - (super.noSuchMethod( - Invocation.method(#addAdEventListener, [adEventListener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.AdsManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsManager_6(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsManager_6(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdsManager); @override - _i5.Future destroy() => - (super.noSuchMethod( - Invocation.method(#destroy, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( + Invocation.method(#addAdErrorListener, [errorListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future init(_i2.AdsRenderingSettings? settings) => - (super.noSuchMethod( - Invocation.method(#init, [settings]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future addAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( + Invocation.method(#addAdEventListener, [adEventListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future focus() => - (super.noSuchMethod( - Invocation.method(#focus, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future destroy() => (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i2.AdProgressInfo?> getAdProgressInfo() => - (super.noSuchMethod( - Invocation.method(#getAdProgressInfo, []), - returnValue: _i5.Future<_i2.AdProgressInfo?>.value(), - returnValueForMissingStub: _i5.Future<_i2.AdProgressInfo?>.value(), - ) - as _i5.Future<_i2.AdProgressInfo?>); + _i5.Future init(_i2.AdsRenderingSettings? settings) => (super.noSuchMethod( + Invocation.method(#init, [settings]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i2.Ad?> getCurrentAd() => - (super.noSuchMethod( - Invocation.method(#getCurrentAd, []), - returnValue: _i5.Future<_i2.Ad?>.value(), - returnValueForMissingStub: _i5.Future<_i2.Ad?>.value(), - ) - as _i5.Future<_i2.Ad?>); + _i5.Future focus() => (super.noSuchMethod( + Invocation.method(#focus, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => - (super.noSuchMethod( - Invocation.method(#removeAdErrorListener, [errorListener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future<_i2.AdProgressInfo?> getAdProgressInfo() => (super.noSuchMethod( + Invocation.method(#getAdProgressInfo, []), + returnValue: _i5.Future<_i2.AdProgressInfo?>.value(), + returnValueForMissingStub: _i5.Future<_i2.AdProgressInfo?>.value(), + ) as _i5.Future<_i2.AdProgressInfo?>); + + @override + _i5.Future<_i2.Ad?> getCurrentAd() => (super.noSuchMethod( + Invocation.method(#getCurrentAd, []), + returnValue: _i5.Future<_i2.Ad?>.value(), + returnValueForMissingStub: _i5.Future<_i2.Ad?>.value(), + ) as _i5.Future<_i2.Ad?>); + + @override + _i5.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( + Invocation.method(#removeAdErrorListener, [errorListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future removeAdEventListener( - _i2.AdEventListener? adEventListener, - ) => + _i5.Future removeAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( - Invocation.method(#removeAdEventListener, [adEventListener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#removeAdEventListener, [adEventListener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [AdsManagerLoadedEvent]. /// /// See the documentation for Mockito's code generation for more information. -class MockAdsManagerLoadedEvent extends _i1.Mock - implements _i2.AdsManagerLoadedEvent { - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdsManagerLoadedEvent pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsManagerLoadedEvent_7( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsManagerLoadedEvent_7( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsManagerLoadedEvent); +class MockAdsManagerLoadedEvent extends _i1.Mock implements _i2.AdsManagerLoadedEvent { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdsManagerLoadedEvent pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsManagerLoadedEvent_7(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsManagerLoadedEvent_7( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.AdsManagerLoadedEvent); } /// A class which mocks [AdsLoader]. @@ -643,61 +459,42 @@ class MockAdsManagerLoadedEvent extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockAdsLoader extends _i1.Mock implements _i2.AdsLoader { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future addAdErrorListener(_i2.AdErrorListener? listener) => - (super.noSuchMethod( - Invocation.method(#addAdErrorListener, [listener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future addAdsLoadedListener(_i2.AdsLoadedListener? listener) => - (super.noSuchMethod( - Invocation.method(#addAdsLoadedListener, [listener]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future addAdErrorListener(_i2.AdErrorListener? listener) => (super.noSuchMethod( + Invocation.method(#addAdErrorListener, [listener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future requestAds(_i2.AdsRequest? request) => - (super.noSuchMethod( - Invocation.method(#requestAds, [request]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future addAdsLoadedListener(_i2.AdsLoadedListener? listener) => (super.noSuchMethod( + Invocation.method(#addAdsLoadedListener, [listener]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.AdsLoader pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsLoader_8( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsLoader_8( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsLoader); + _i5.Future requestAds(_i2.AdsRequest? request) => (super.noSuchMethod( + Invocation.method(#requestAds, [request]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.AdsLoader pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsLoader_8(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsLoader_8(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdsLoader); } /// A class which mocks [AdsRequest]. @@ -705,135 +502,99 @@ class MockAdsLoader extends _i1.Mock implements _i2.AdsLoader { /// See the documentation for Mockito's code generation for more information. class MockAdsRequest extends _i1.Mock implements _i2.AdsRequest { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setAdTagUrl(String? adTagUrl) => - (super.noSuchMethod( - Invocation.method(#setAdTagUrl, [adTagUrl]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future setContentProgressProvider( - _i2.ContentProgressProvider? provider, - ) => - (super.noSuchMethod( - Invocation.method(#setContentProgressProvider, [provider]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setAdTagUrl(String? adTagUrl) => (super.noSuchMethod( + Invocation.method(#setAdTagUrl, [adTagUrl]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setAdWillAutoPlay(bool? willAutoPlay) => + _i5.Future setContentProgressProvider(_i2.ContentProgressProvider? provider) => (super.noSuchMethod( - Invocation.method(#setAdWillAutoPlay, [willAutoPlay]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#setContentProgressProvider, [provider]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setAdWillPlayMuted(bool? willPlayMuted) => - (super.noSuchMethod( - Invocation.method(#setAdWillPlayMuted, [willPlayMuted]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setAdWillAutoPlay(bool? willAutoPlay) => (super.noSuchMethod( + Invocation.method(#setAdWillAutoPlay, [willAutoPlay]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setAdsResponse(String? cannedAdResponse) => - (super.noSuchMethod( - Invocation.method(#setAdsResponse, [cannedAdResponse]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setAdWillPlayMuted(bool? willPlayMuted) => (super.noSuchMethod( + Invocation.method(#setAdWillPlayMuted, [willPlayMuted]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setContentDuration(double? duration) => - (super.noSuchMethod( - Invocation.method(#setContentDuration, [duration]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setAdsResponse(String? cannedAdResponse) => (super.noSuchMethod( + Invocation.method(#setAdsResponse, [cannedAdResponse]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setContentKeywords(List? keywords) => - (super.noSuchMethod( - Invocation.method(#setContentKeywords, [keywords]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setContentDuration(double? duration) => (super.noSuchMethod( + Invocation.method(#setContentDuration, [duration]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setContentTitle(String? title) => - (super.noSuchMethod( - Invocation.method(#setContentTitle, [title]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setContentKeywords(List? keywords) => (super.noSuchMethod( + Invocation.method(#setContentKeywords, [keywords]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setContinuousPlayback(bool? continuousPlayback) => - (super.noSuchMethod( - Invocation.method(#setContinuousPlayback, [continuousPlayback]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setContentTitle(String? title) => (super.noSuchMethod( + Invocation.method(#setContentTitle, [title]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setLiveStreamPrefetchSeconds(double? prefetchTime) => - (super.noSuchMethod( - Invocation.method(#setLiveStreamPrefetchSeconds, [prefetchTime]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setContinuousPlayback(bool? continuousPlayback) => (super.noSuchMethod( + Invocation.method(#setContinuousPlayback, [continuousPlayback]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setVastLoadTimeout(double? timeout) => - (super.noSuchMethod( - Invocation.method(#setVastLoadTimeout, [timeout]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setLiveStreamPrefetchSeconds(double? prefetchTime) => (super.noSuchMethod( + Invocation.method(#setLiveStreamPrefetchSeconds, [prefetchTime]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.AdsRequest pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsRequest_9( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsRequest_9( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsRequest); + _i5.Future setVastLoadTimeout(double? timeout) => (super.noSuchMethod( + Invocation.method(#setVastLoadTimeout, [timeout]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.AdsRequest pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsRequest_9(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsRequest_9(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdsRequest); } /// A class which mocks [FrameLayout]. @@ -841,52 +602,35 @@ class MockAdsRequest extends _i1.Mock implements _i2.AdsRequest { /// See the documentation for Mockito's code generation for more information. class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.FrameLayout pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeFrameLayout_10( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeFrameLayout_10( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.FrameLayout); - - @override - _i5.Future addView(_i2.View? view) => - (super.noSuchMethod( - Invocation.method(#addView, [view]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future removeView(_i2.View? view) => - (super.noSuchMethod( - Invocation.method(#removeView, [view]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.FrameLayout pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFrameLayout_10(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeFrameLayout_10(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.FrameLayout); + + @override + _i5.Future addView(_i2.View? view) => (super.noSuchMethod( + Invocation.method(#addView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future removeView(_i2.View? view) => (super.noSuchMethod( + Invocation.method(#removeView, [view]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [ImaSdkFactory]. @@ -894,127 +638,79 @@ class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => - (super.noSuchMethod( - Invocation.method(#createCompanionAdSlot, []), - returnValue: _i5.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_11( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_11( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - ) - as _i5.Future<_i2.CompanionAdSlot>); - - @override - _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => - (super.noSuchMethod( - Invocation.method(#createImaSdkSettings, []), - returnValue: _i5.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_12( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_12( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - ) - as _i5.Future<_i2.ImaSdkSettings>); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_11(this, Invocation.method(#createCompanionAdSlot, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_11(this, Invocation.method(#createCompanionAdSlot, [])), + ), + ) as _i5.Future<_i2.CompanionAdSlot>); + + @override + _i5.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_12(this, Invocation.method(#createImaSdkSettings, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_12(this, Invocation.method(#createImaSdkSettings, [])), + ), + ) as _i5.Future<_i2.ImaSdkSettings>); @override _i5.Future<_i2.AdsLoader> createAdsLoader( _i2.ImaSdkSettings? settings, _i2.AdDisplayContainer? container, - ) => - (super.noSuchMethod( - Invocation.method(#createAdsLoader, [settings, container]), - returnValue: _i5.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_8( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - returnValueForMissingStub: _i5.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_8( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - ) - as _i5.Future<_i2.AdsLoader>); - - @override - _i5.Future<_i2.AdsRequest> createAdsRequest() => - (super.noSuchMethod( - Invocation.method(#createAdsRequest, []), - returnValue: _i5.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), - ), - returnValueForMissingStub: _i5.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), - ), - ) - as _i5.Future<_i2.AdsRequest>); - - @override - _i5.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => - (super.noSuchMethod( - Invocation.method(#createAdsRenderingSettings, []), - returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_13( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - returnValueForMissingStub: - _i5.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_13( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - ) - as _i5.Future<_i2.AdsRenderingSettings>); - - @override - _i2.ImaSdkFactory pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImaSdkFactory_14( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImaSdkFactory_14( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImaSdkFactory); + ) => (super.noSuchMethod( + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_8(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_8(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + ) as _i5.Future<_i2.AdsLoader>); + + @override + _i5.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_9(this, Invocation.method(#createAdsRequest, [])), + ), + ) as _i5.Future<_i2.AdsRequest>); + + @override + _i5.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_13(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_13(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + ) as _i5.Future<_i2.AdsRenderingSettings>); + + @override + _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_14(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImaSdkFactory_14(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImaSdkFactory); } /// A class which mocks [ImaSdkSettings]. @@ -1022,115 +718,84 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockImaSdkSettings extends _i1.Mock implements _i2.ImaSdkSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setAutoPlayAdBreaks(bool? autoPlayAdBreaks) => - (super.noSuchMethod( - Invocation.method(#setAutoPlayAdBreaks, [autoPlayAdBreaks]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future setDebugMode(bool? debugMode) => - (super.noSuchMethod( - Invocation.method(#setDebugMode, [debugMode]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setAutoPlayAdBreaks(bool? autoPlayAdBreaks) => (super.noSuchMethod( + Invocation.method(#setAutoPlayAdBreaks, [autoPlayAdBreaks]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setFeatureFlags(Map? featureFlags) => - (super.noSuchMethod( - Invocation.method(#setFeatureFlags, [featureFlags]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setDebugMode(bool? debugMode) => (super.noSuchMethod( + Invocation.method(#setDebugMode, [debugMode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setLanguage(String? language) => - (super.noSuchMethod( - Invocation.method(#setLanguage, [language]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setFeatureFlags(Map? featureFlags) => (super.noSuchMethod( + Invocation.method(#setFeatureFlags, [featureFlags]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setMaxRedirects(int? maxRedirects) => - (super.noSuchMethod( - Invocation.method(#setMaxRedirects, [maxRedirects]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setLanguage(String? language) => (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setPlayerType(String? playerType) => - (super.noSuchMethod( - Invocation.method(#setPlayerType, [playerType]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setMaxRedirects(int? maxRedirects) => (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [maxRedirects]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setPlayerVersion(String? playerVersion) => - (super.noSuchMethod( - Invocation.method(#setPlayerVersion, [playerVersion]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setPlayerType(String? playerType) => (super.noSuchMethod( + Invocation.method(#setPlayerType, [playerType]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setPpid(String? ppid) => - (super.noSuchMethod( - Invocation.method(#setPpid, [ppid]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setPlayerVersion(String? playerVersion) => (super.noSuchMethod( + Invocation.method(#setPlayerVersion, [playerVersion]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future setSessionId(String? sessionId) => - (super.noSuchMethod( - Invocation.method(#setSessionId, [sessionId]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setPpid(String? ppid) => (super.noSuchMethod( + Invocation.method(#setPpid, [ppid]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.ImaSdkSettings pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImaSdkSettings_12( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImaSdkSettings_12( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImaSdkSettings); + _i5.Future setSessionId(String? sessionId) => (super.noSuchMethod( + Invocation.method(#setSessionId, [sessionId]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.ImaSdkSettings pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkSettings_12(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImaSdkSettings_12(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImaSdkSettings); } /// A class which mocks [VideoAdPlayer]. @@ -1140,299 +805,200 @@ class MockVideoAdPlayer extends _i1.Mock implements _i2.VideoAdPlayer { @override void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) get addCallback => (super.noSuchMethod( - Invocation.getter(#addCallback), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + Invocation.getter(#addCallback), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.VideoAdPlayerCallback callback) {}, + returnValueForMissingStub: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); @override void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo) get loadAd => (super.noSuchMethod( - Invocation.getter(#loadAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - _i2.AdPodInfo adPodInfo, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo)); - - @override - _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get pauseAd => - (super.noSuchMethod( - Invocation.getter(#pauseAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) => _i5.Future.value(), - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) => _i5.Future.value(), - ) - as _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); - - @override - void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get playAd => - (super.noSuchMethod( - Invocation.getter(#playAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); - - @override - void Function(_i2.VideoAdPlayer) get release => - (super.noSuchMethod( - Invocation.getter(#release), - returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, - returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, - ) - as void Function(_i2.VideoAdPlayer)); - - @override - void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) - get removeCallback => - (super.noSuchMethod( - Invocation.getter(#removeCallback), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.VideoAdPlayerCallback callback, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); - - @override - void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get stopAd => - (super.noSuchMethod( - Invocation.getter(#stopAd), - returnValue: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoAdPlayer pigeon_instance, - _i2.AdMediaInfo adMediaInfo, - ) {}, - ) - as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setVolume(int? value) => - (super.noSuchMethod( - Invocation.method(#setVolume, [value]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); - - @override - _i5.Future setAdProgress(_i2.VideoProgressUpdate? progress) => - (super.noSuchMethod( - Invocation.method(#setAdProgress, [progress]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); - - @override - _i2.VideoAdPlayer pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoAdPlayer_15( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoAdPlayer_15( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoAdPlayer); + Invocation.getter(#loadAd), + returnValue: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + returnValueForMissingStub: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.AdMediaInfo adMediaInfo, + _i2.AdPodInfo adPodInfo, + ) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo, _i2.AdPodInfo)); + + @override + _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get pauseAd => (super.noSuchMethod( + Invocation.getter(#pauseAd), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) => + _i5.Future.value(), + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) => + _i5.Future.value(), + ) as _i5.Future Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get playAd => (super.noSuchMethod( + Invocation.getter(#playAd), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + void Function(_i2.VideoAdPlayer) get release => (super.noSuchMethod( + Invocation.getter(#release), + returnValue: (_i2.VideoAdPlayer pigeon_instance) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance) {}, + ) as void Function(_i2.VideoAdPlayer)); + + @override + void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback) get removeCallback => + (super.noSuchMethod( + Invocation.getter(#removeCallback), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.VideoAdPlayerCallback callback) {}, + returnValueForMissingStub: ( + _i2.VideoAdPlayer pigeon_instance, + _i2.VideoAdPlayerCallback callback, + ) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.VideoAdPlayerCallback)); + + @override + void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo) get stopAd => (super.noSuchMethod( + Invocation.getter(#stopAd), + returnValue: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + returnValueForMissingStub: (_i2.VideoAdPlayer pigeon_instance, _i2.AdMediaInfo adMediaInfo) {}, + ) as void Function(_i2.VideoAdPlayer, _i2.AdMediaInfo)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future setVolume(int? value) => (super.noSuchMethod( + Invocation.method(#setVolume, [value]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future setAdProgress(_i2.VideoProgressUpdate? progress) => (super.noSuchMethod( + Invocation.method(#setAdProgress, [progress]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.VideoAdPlayer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayer_15(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoAdPlayer_15(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.VideoAdPlayer); } /// A class which mocks [VideoAdPlayerCallback]. /// /// See the documentation for Mockito's code generation for more information. -class MockVideoAdPlayerCallback extends _i1.Mock - implements _i2.VideoAdPlayerCallback { +class MockVideoAdPlayerCallback extends _i1.Mock implements _i2.VideoAdPlayerCallback { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override _i5.Future onAdProgress( _i2.AdMediaInfo? adMediaInfo, _i2.VideoProgressUpdate? videoProgressUpdate, - ) => - (super.noSuchMethod( - Invocation.method(#onAdProgress, [ - adMediaInfo, - videoProgressUpdate, - ]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + ) => (super.noSuchMethod( + Invocation.method(#onAdProgress, [adMediaInfo, videoProgressUpdate]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onBuffering(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onBuffering, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onBuffering(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onBuffering, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onContentComplete() => - (super.noSuchMethod( - Invocation.method(#onContentComplete, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onContentComplete() => (super.noSuchMethod( + Invocation.method(#onContentComplete, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onEnded, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onEnded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onEnded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onError, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onError(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onError, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onLoaded(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onLoaded, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onLoaded(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onLoaded, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onPause, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onPause(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onPause, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onPlay, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onPlay(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onPlay, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onResume(_i2.AdMediaInfo? adMediaInfo) => - (super.noSuchMethod( - Invocation.method(#onResume, [adMediaInfo]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future onResume(_i2.AdMediaInfo? adMediaInfo) => (super.noSuchMethod( + Invocation.method(#onResume, [adMediaInfo]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future onVolumeChanged( - _i2.AdMediaInfo? adMediaInfo, - int? percentage, - ) => + _i5.Future onVolumeChanged(_i2.AdMediaInfo? adMediaInfo, int? percentage) => (super.noSuchMethod( - Invocation.method(#onVolumeChanged, [adMediaInfo, percentage]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + Invocation.method(#onVolumeChanged, [adMediaInfo, percentage]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i2.VideoAdPlayerCallback pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoAdPlayerCallback_16( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoAdPlayerCallback_16( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoAdPlayerCallback); + _i2.VideoAdPlayerCallback pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoAdPlayerCallback_16(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoAdPlayerCallback_16( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.VideoAdPlayerCallback); } /// A class which mocks [VideoView]. @@ -1440,84 +1006,55 @@ class MockVideoAdPlayerCallback extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockVideoView extends _i1.Mock implements _i2.VideoView { @override - void Function(_i2.VideoView, _i2.MediaPlayer, int, int) get onError => - (super.noSuchMethod( - Invocation.getter(#onError), - returnValue: - ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - returnValueForMissingStub: - ( - _i2.VideoView pigeon_instance, - _i2.MediaPlayer player, - int what, - int extra, - ) {}, - ) - as void Function(_i2.VideoView, _i2.MediaPlayer, int, int)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i5.Future setVideoUri(String? uri) => - (super.noSuchMethod( - Invocation.method(#setVideoUri, [uri]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + void Function(_i2.VideoView, _i2.MediaPlayer, int, int) get onError => (super.noSuchMethod( + Invocation.getter(#onError), + returnValue: (_i2.VideoView pigeon_instance, _i2.MediaPlayer player, int what, int extra) {}, + returnValueForMissingStub: ( + _i2.VideoView pigeon_instance, + _i2.MediaPlayer player, + int what, + int extra, + ) {}, + ) as void Function(_i2.VideoView, _i2.MediaPlayer, int, int)); @override - _i5.Future getCurrentPosition() => - (super.noSuchMethod( - Invocation.method(#getCurrentPosition, []), - returnValue: _i5.Future.value(0), - returnValueForMissingStub: _i5.Future.value(0), - ) - as _i5.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i5.Future setAudioFocusRequest( - _i2.AudioManagerAudioFocus? focusGain, - ) => - (super.noSuchMethod( - Invocation.method(#setAudioFocusRequest, [focusGain]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setVideoUri(String? uri) => (super.noSuchMethod( + Invocation.method(#setVideoUri, [uri]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future getCurrentPosition() => (super.noSuchMethod( + Invocation.method(#getCurrentPosition, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); @override - _i2.VideoView pigeon_copy() => + _i5.Future setAudioFocusRequest(_i2.AudioManagerAudioFocus? focusGain) => (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoView_17( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeVideoView_17( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.VideoView); + Invocation.method(#setAudioFocusRequest, [focusGain]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.VideoView pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoView_17(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeVideoView_17(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.VideoView); } /// A class which mocks [SurfaceAndroidViewController]. @@ -1526,60 +1063,46 @@ class MockVideoView extends _i1.Mock implements _i2.VideoView { class MockSurfaceAndroidViewController extends _i1.Mock implements _i4.SurfaceAndroidViewController { @override - bool get requiresViewComposition => - (super.noSuchMethod( - Invocation.getter(#requiresViewComposition), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get requiresViewComposition => (super.noSuchMethod( + Invocation.getter(#requiresViewComposition), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override int get viewId => - (super.noSuchMethod( - Invocation.getter(#viewId), - returnValue: 0, - returnValueForMissingStub: 0, - ) + (super.noSuchMethod(Invocation.getter(#viewId), returnValue: 0, returnValueForMissingStub: 0) as int); @override - bool get awaitingCreation => - (super.noSuchMethod( - Invocation.getter(#awaitingCreation), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get awaitingCreation => (super.noSuchMethod( + Invocation.getter(#awaitingCreation), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i4.PointTransformer get pointTransformer => - (super.noSuchMethod( - Invocation.getter(#pointTransformer), - returnValue: (_i3.Offset position) => - _FakeOffset_18(this, Invocation.getter(#pointTransformer)), - returnValueForMissingStub: (_i3.Offset position) => - _FakeOffset_18(this, Invocation.getter(#pointTransformer)), - ) - as _i4.PointTransformer); + _i4.PointTransformer get pointTransformer => (super.noSuchMethod( + Invocation.getter(#pointTransformer), + returnValue: (_i3.Offset position) => + _FakeOffset_18(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: (_i3.Offset position) => + _FakeOffset_18(this, Invocation.getter(#pointTransformer)), + ) as _i4.PointTransformer); @override - bool get isCreated => - (super.noSuchMethod( - Invocation.getter(#isCreated), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isCreated => (super.noSuchMethod( + Invocation.getter(#isCreated), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - List<_i4.PlatformViewCreatedCallback> get createdCallbacks => - (super.noSuchMethod( - Invocation.getter(#createdCallbacks), - returnValue: <_i4.PlatformViewCreatedCallback>[], - returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], - ) - as List<_i4.PlatformViewCreatedCallback>); + List<_i4.PlatformViewCreatedCallback> get createdCallbacks => (super.noSuchMethod( + Invocation.getter(#createdCallbacks), + returnValue: <_i4.PlatformViewCreatedCallback>[], + returnValueForMissingStub: <_i4.PlatformViewCreatedCallback>[], + ) as List<_i4.PlatformViewCreatedCallback>); @override set pointTransformer(_i4.PointTransformer? transformer) => super.noSuchMethod( @@ -1588,104 +1111,85 @@ class MockSurfaceAndroidViewController extends _i1.Mock ); @override - _i5.Future setOffset(_i3.Offset? off) => - (super.noSuchMethod( - Invocation.method(#setOffset, [off]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setOffset(_i3.Offset? off) => (super.noSuchMethod( + Invocation.method(#setOffset, [off]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future create({_i3.Size? size, _i3.Offset? position}) => - (super.noSuchMethod( - Invocation.method(#create, [], {#size: size, #position: position}), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future create({_i3.Size? size, _i3.Offset? position}) => (super.noSuchMethod( + Invocation.method(#create, [], {#size: size, #position: position}), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future<_i3.Size> setSize(_i3.Size? size) => - (super.noSuchMethod( - Invocation.method(#setSize, [size]), - returnValue: _i5.Future<_i3.Size>.value( - _FakeSize_19(this, Invocation.method(#setSize, [size])), - ), - returnValueForMissingStub: _i5.Future<_i3.Size>.value( - _FakeSize_19(this, Invocation.method(#setSize, [size])), - ), - ) - as _i5.Future<_i3.Size>); - - @override - _i5.Future sendMotionEvent(_i4.AndroidMotionEvent? event) => - (super.noSuchMethod( - Invocation.method(#sendMotionEvent, [event]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future<_i3.Size> setSize(_i3.Size? size) => (super.noSuchMethod( + Invocation.method(#setSize, [size]), + returnValue: _i5.Future<_i3.Size>.value( + _FakeSize_19(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i5.Future<_i3.Size>.value( + _FakeSize_19(this, Invocation.method(#setSize, [size])), + ), + ) as _i5.Future<_i3.Size>); @override - void addOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener, - ) => super.noSuchMethod( - Invocation.method(#addOnPlatformViewCreatedListener, [listener]), - returnValueForMissingStub: null, - ); + _i5.Future sendMotionEvent(_i4.AndroidMotionEvent? event) => (super.noSuchMethod( + Invocation.method(#sendMotionEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - void removeOnPlatformViewCreatedListener( - _i4.PlatformViewCreatedCallback? listener, - ) => super.noSuchMethod( - Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), - returnValueForMissingStub: null, - ); + void addOnPlatformViewCreatedListener(_i4.PlatformViewCreatedCallback? listener) => + super.noSuchMethod( + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override - _i5.Future setLayoutDirection(_i3.TextDirection? layoutDirection) => - (super.noSuchMethod( - Invocation.method(#setLayoutDirection, [layoutDirection]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + void removeOnPlatformViewCreatedListener(_i4.PlatformViewCreatedCallback? listener) => + super.noSuchMethod( + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), + returnValueForMissingStub: null, + ); @override - _i5.Future dispatchPointerEvent(_i4.PointerEvent? event) => - (super.noSuchMethod( - Invocation.method(#dispatchPointerEvent, [event]), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future setLayoutDirection(_i3.TextDirection? layoutDirection) => (super.noSuchMethod( + Invocation.method(#setLayoutDirection, [layoutDirection]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future clearFocus() => - (super.noSuchMethod( - Invocation.method(#clearFocus, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future dispatchPointerEvent(_i4.PointerEvent? event) => (super.noSuchMethod( + Invocation.method(#dispatchPointerEvent, [event]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i5.Future dispose() => - (super.noSuchMethod( - Invocation.method(#dispose, []), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) - as _i5.Future); + _i5.Future clearFocus() => (super.noSuchMethod( + Invocation.method(#clearFocus, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future dispose() => (super.noSuchMethod( + Invocation.method(#dispose, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [PlatformViewsServiceProxy]. /// /// See the documentation for Mockito's code generation for more information. // ignore: must_be_immutable -class MockPlatformViewsServiceProxy extends _i1.Mock - implements _i7.PlatformViewsServiceProxy { +class MockPlatformViewsServiceProxy extends _i1.Mock implements _i7.PlatformViewsServiceProxy { @override _i4.ExpensiveAndroidViewController initExpensiveAndroidView({ required int? id, @@ -1694,40 +1198,38 @@ class MockPlatformViewsServiceProxy extends _i1.Mock dynamic creationParams, _i4.MessageCodec? creationParamsCodec, _i3.VoidCallback? onFocus, - }) => - (super.noSuchMethod( - Invocation.method(#initExpensiveAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - returnValue: _FakeExpensiveAndroidViewController_20( - this, - Invocation.method(#initExpensiveAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - returnValueForMissingStub: _FakeExpensiveAndroidViewController_20( - this, - Invocation.method(#initExpensiveAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - ) - as _i4.ExpensiveAndroidViewController); + }) => (super.noSuchMethod( + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + returnValue: _FakeExpensiveAndroidViewController_20( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeExpensiveAndroidViewController_20( + this, + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) as _i4.ExpensiveAndroidViewController); @override _i4.SurfaceAndroidViewController initSurfaceAndroidView({ @@ -1737,38 +1239,36 @@ class MockPlatformViewsServiceProxy extends _i1.Mock dynamic creationParams, _i4.MessageCodec? creationParamsCodec, _i3.VoidCallback? onFocus, - }) => - (super.noSuchMethod( - Invocation.method(#initSurfaceAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - returnValue: _FakeSurfaceAndroidViewController_21( - this, - Invocation.method(#initSurfaceAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - returnValueForMissingStub: _FakeSurfaceAndroidViewController_21( - this, - Invocation.method(#initSurfaceAndroidView, [], { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }), - ), - ) - as _i4.SurfaceAndroidViewController); + }) => (super.noSuchMethod( + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + returnValue: _FakeSurfaceAndroidViewController_21( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + returnValueForMissingStub: _FakeSurfaceAndroidViewController_21( + this, + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + ), + ) as _i4.SurfaceAndroidViewController); } diff --git a/packages/interactive_media_ads/test/android/ads_manager_test.dart b/packages/interactive_media_ads/test/android/ads_manager_test.dart index 6c16ec274e7a..36f2d11574f4 100644 --- a/packages/interactive_media_ads/test/android/ads_manager_test.dart +++ b/packages/interactive_media_ads/test/android/ads_manager_test.dart @@ -6,8 +6,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:interactive_media_ads/src/android/android_ads_manager.dart'; import 'package:interactive_media_ads/src/android/android_ads_manager_delegate.dart'; import 'package:interactive_media_ads/src/android/android_ads_rendering_settings.dart'; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/platform_interface/platform_interface.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -43,9 +42,9 @@ void main() { final mockImaSdkFactory = MockImaSdkFactory(); final mockAdsRenderingSettings = MockAdsRenderingSettings(); - when(mockImaSdkFactory.createAdsRenderingSettings()).thenAnswer( - (_) => Future.value(mockAdsRenderingSettings), - ); + when( + mockImaSdkFactory.createAdsRenderingSettings(), + ).thenAnswer((_) => Future.value(mockAdsRenderingSettings)); final adsManager = AndroidAdsManager(mockAdsManager); @@ -69,9 +68,7 @@ void main() { mockAdsRenderingSettings.setLoadVideoTimeout(2000), mockAdsRenderingSettings.setMimeTypes(['value']), mockAdsRenderingSettings.setPlayAdsAfterTime(5.0), - mockAdsRenderingSettings.setUiElements([ - ima.UiElement.countdown, - ]), + mockAdsRenderingSettings.setUiElements([ima.UiElement.countdown]), mockAdsRenderingSettings.setEnableCustomTabs(true), mockAdsManager.init(mockAdsRenderingSettings), ]); @@ -120,13 +117,10 @@ void main() { test('onAdEvent', () async { final mockAdsManager = MockAdsManager(); - late final void Function(ima.AdEventListener, ima.AdEvent) - onAdEventCallback; + late final void Function(ima.AdEventListener, ima.AdEvent) onAdEventCallback; ima.PigeonOverrides.adEventListener_new = - ({ - required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent, - }) { + ({required void Function(ima.AdEventListener, ima.AdEvent) onAdEvent}) { onAdEventCallback = onAdEvent; return MockAdEventListener(); }; @@ -155,17 +149,13 @@ void main() { test('onAdErrorEvent', () async { final mockAdsManager = MockAdsManager(); - late final void Function(ima.AdErrorListener, ima.AdErrorEvent) - onAdErrorCallback; + late final void Function(ima.AdErrorListener, ima.AdErrorEvent) onAdErrorCallback; ima.PigeonOverrides.adEventListener_new = ({required dynamic onAdEvent}) { return MockAdEventListener(); }; ima.PigeonOverrides.adErrorListener_new = - ({ - required void Function(ima.AdErrorListener, ima.AdErrorEvent) - onAdError, - }) { + ({required void Function(ima.AdErrorListener, ima.AdErrorEvent) onAdError}) { onAdErrorCallback = onAdError; return MockAdErrorListener(); }; @@ -173,18 +163,14 @@ void main() { final adsManager = AndroidAdsManager(mockAdsManager); await adsManager.setAdsManagerDelegate( AndroidAdsManagerDelegate( - PlatformAdsManagerDelegateCreationParams( - onAdErrorEvent: expectAsync1((_) {}), - ), + PlatformAdsManagerDelegateCreationParams(onAdErrorEvent: expectAsync1((_) {})), ), ); final mockErrorEvent = MockAdErrorEvent(); final mockError = MockAdError(); when(mockError.errorType).thenReturn(ima.AdErrorType.load); - when( - mockError.errorCode, - ).thenReturn(ima.AdErrorCode.adsRequestNetworkError); + when(mockError.errorCode).thenReturn(ima.AdErrorCode.adsRequestNetworkError); when(mockError.message).thenReturn('error message'); when(mockErrorEvent.error).thenReturn(mockError); onAdErrorCallback(MockAdErrorListener(), mockErrorEvent); diff --git a/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart b/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart index 6b482343914a..8cf05a1986be 100644 --- a/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ads_manager_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i4; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i3; @@ -25,70 +24,58 @@ import 'package:mockito/src/dummies.dart' as _i3; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdError_1 extends _i1.SmartFake implements _i2.AdError { - _FakeAdError_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdError_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdErrorEvent_2 extends _i1.SmartFake implements _i2.AdErrorEvent { - _FakeAdErrorEvent_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdErrorEvent_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdErrorListener_3 extends _i1.SmartFake - implements _i2.AdErrorListener { +class _FakeAdErrorListener_3 extends _i1.SmartFake implements _i2.AdErrorListener { _FakeAdErrorListener_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdEvent_4 extends _i1.SmartFake implements _i2.AdEvent { - _FakeAdEvent_4(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdEvent_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdEventListener_5 extends _i1.SmartFake - implements _i2.AdEventListener { +class _FakeAdEventListener_5 extends _i1.SmartFake implements _i2.AdEventListener { _FakeAdEventListener_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsManager_6 extends _i1.SmartFake implements _i2.AdsManager { - _FakeAdsManager_6(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsManager_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdsRenderingSettings_7 extends _i1.SmartFake - implements _i2.AdsRenderingSettings { +class _FakeAdsRenderingSettings_7 extends _i1.SmartFake implements _i2.AdsRenderingSettings { _FakeAdsRenderingSettings_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCompanionAdSlot_8 extends _i1.SmartFake - implements _i2.CompanionAdSlot { +class _FakeCompanionAdSlot_8 extends _i1.SmartFake implements _i2.CompanionAdSlot { _FakeCompanionAdSlot_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImaSdkSettings_9 extends _i1.SmartFake - implements _i2.ImaSdkSettings { +class _FakeImaSdkSettings_9 extends _i1.SmartFake implements _i2.ImaSdkSettings { _FakeImaSdkSettings_9(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsLoader_10 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_10(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsLoader_10(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsRequest_11 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_11(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsRequest_11(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeImaSdkFactory_12 extends _i1.SmartFake implements _i2.ImaSdkFactory { @@ -101,76 +88,49 @@ class _FakeImaSdkFactory_12 extends _i1.SmartFake implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockAdError extends _i1.Mock implements _i2.AdError { @override - _i2.AdErrorCode get errorCode => - (super.noSuchMethod( - Invocation.getter(#errorCode), - returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, - returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, - ) - as _i2.AdErrorCode); + _i2.AdErrorCode get errorCode => (super.noSuchMethod( + Invocation.getter(#errorCode), + returnValue: _i2.AdErrorCode.adsPlayerWasNotProvided, + returnValueForMissingStub: _i2.AdErrorCode.adsPlayerWasNotProvided, + ) as _i2.AdErrorCode); @override - int get errorCodeNumber => - (super.noSuchMethod( - Invocation.getter(#errorCodeNumber), - returnValue: 0, - returnValueForMissingStub: 0, - ) - as int); + int get errorCodeNumber => (super.noSuchMethod( + Invocation.getter(#errorCodeNumber), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); @override - _i2.AdErrorType get errorType => - (super.noSuchMethod( - Invocation.getter(#errorType), - returnValue: _i2.AdErrorType.load, - returnValueForMissingStub: _i2.AdErrorType.load, - ) - as _i2.AdErrorType); + _i2.AdErrorType get errorType => (super.noSuchMethod( + Invocation.getter(#errorType), + returnValue: _i2.AdErrorType.load, + returnValueForMissingStub: _i2.AdErrorType.load, + ) as _i2.AdErrorType); @override - String get message => - (super.noSuchMethod( - Invocation.getter(#message), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#message), - ), - returnValueForMissingStub: _i3.dummyValue( - this, - Invocation.getter(#message), - ), - ) - as String); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdError pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdError_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdError_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdError); + String get message => (super.noSuchMethod( + Invocation.getter(#message), + returnValue: _i3.dummyValue(this, Invocation.getter(#message)), + returnValueForMissingStub: _i3.dummyValue(this, Invocation.getter(#message)), + ) as String); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdError pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdError_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdError_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdError); } /// A class which mocks [AdErrorEvent]. @@ -178,46 +138,28 @@ class MockAdError extends _i1.Mock implements _i2.AdError { /// See the documentation for Mockito's code generation for more information. class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { @override - _i2.AdError get error => - (super.noSuchMethod( - Invocation.getter(#error), - returnValue: _FakeAdError_1(this, Invocation.getter(#error)), - returnValueForMissingStub: _FakeAdError_1( - this, - Invocation.getter(#error), - ), - ) - as _i2.AdError); + _i2.AdError get error => (super.noSuchMethod( + Invocation.getter(#error), + returnValue: _FakeAdError_1(this, Invocation.getter(#error)), + returnValueForMissingStub: _FakeAdError_1(this, Invocation.getter(#error)), + ) as _i2.AdError); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorEvent pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdErrorEvent_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdErrorEvent_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdErrorEvent); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorEvent pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorEvent_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdErrorEvent_2(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdErrorEvent); } /// A class which mocks [AdErrorListener]. @@ -225,51 +167,28 @@ class MockAdErrorEvent extends _i1.Mock implements _i2.AdErrorEvent { /// See the documentation for Mockito's code generation for more information. class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { @override - void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => - (super.noSuchMethod( - Invocation.getter(#onAdError), - returnValue: - ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - returnValueForMissingStub: - ( - _i2.AdErrorListener pigeon_instance, - _i2.AdErrorEvent event, - ) {}, - ) - as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdErrorListener pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdErrorListener_3( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdErrorListener_3( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdErrorListener); + void Function(_i2.AdErrorListener, _i2.AdErrorEvent) get onAdError => (super.noSuchMethod( + Invocation.getter(#onAdError), + returnValue: (_i2.AdErrorListener pigeon_instance, _i2.AdErrorEvent event) {}, + returnValueForMissingStub: (_i2.AdErrorListener pigeon_instance, _i2.AdErrorEvent event) {}, + ) as void Function(_i2.AdErrorListener, _i2.AdErrorEvent)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdErrorListener pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdErrorListener_3(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdErrorListener_3(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdErrorListener); } /// A class which mocks [AdEvent]. @@ -277,43 +196,28 @@ class MockAdErrorListener extends _i1.Mock implements _i2.AdErrorListener { /// See the documentation for Mockito's code generation for more information. class MockAdEvent extends _i1.Mock implements _i2.AdEvent { @override - _i2.AdEventType get type => - (super.noSuchMethod( - Invocation.getter(#type), - returnValue: _i2.AdEventType.adBreakEnded, - returnValueForMissingStub: _i2.AdEventType.adBreakEnded, - ) - as _i2.AdEventType); + _i2.AdEventType get type => (super.noSuchMethod( + Invocation.getter(#type), + returnValue: _i2.AdEventType.adBreakEnded, + returnValueForMissingStub: _i2.AdEventType.adBreakEnded, + ) as _i2.AdEventType); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdEvent pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdEvent_4( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdEvent_4( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdEvent); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdEvent pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdEvent_4(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdEvent_4(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdEvent); } /// A class which mocks [AdEventListener]. @@ -321,45 +225,28 @@ class MockAdEvent extends _i1.Mock implements _i2.AdEvent { /// See the documentation for Mockito's code generation for more information. class MockAdEventListener extends _i1.Mock implements _i2.AdEventListener { @override - void Function(_i2.AdEventListener, _i2.AdEvent) get onAdEvent => - (super.noSuchMethod( - Invocation.getter(#onAdEvent), - returnValue: - (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, - returnValueForMissingStub: - (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, - ) - as void Function(_i2.AdEventListener, _i2.AdEvent)); + void Function(_i2.AdEventListener, _i2.AdEvent) get onAdEvent => (super.noSuchMethod( + Invocation.getter(#onAdEvent), + returnValue: (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, + returnValueForMissingStub: (_i2.AdEventListener pigeon_instance, _i2.AdEvent event) {}, + ) as void Function(_i2.AdEventListener, _i2.AdEvent)); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.AdEventListener pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdEventListener_5( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdEventListener_5( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdEventListener); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.AdEventListener pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdEventListener_5(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdEventListener_5(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdEventListener); } /// A class which mocks [AdsManager]. @@ -367,328 +254,244 @@ class MockAdEventListener extends _i1.Mock implements _i2.AdEventListener { /// See the documentation for Mockito's code generation for more information. class MockAdsManager extends _i1.Mock implements _i2.AdsManager { @override - List get adCuePoints => - (super.noSuchMethod( - Invocation.getter(#adCuePoints), - returnValue: [], - returnValueForMissingStub: [], - ) - as List); + List get adCuePoints => (super.noSuchMethod( + Invocation.getter(#adCuePoints), + returnValue: [], + returnValueForMissingStub: [], + ) as List); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i4.Future discardAdBreak() => - (super.noSuchMethod( - Invocation.method(#discardAdBreak, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i4.Future pause() => - (super.noSuchMethod( - Invocation.method(#pause, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future discardAdBreak() => (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future start() => - (super.noSuchMethod( - Invocation.method(#start, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future resume() => - (super.noSuchMethod( - Invocation.method(#resume, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future start() => (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future skip() => - (super.noSuchMethod( - Invocation.method(#skip, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future resume() => (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i2.AdsManager pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsManager_6( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsManager_6( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsManager); - - @override - _i4.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => - (super.noSuchMethod( - Invocation.method(#addAdErrorListener, [errorListener]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future skip() => (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future addAdEventListener(_i2.AdEventListener? adEventListener) => - (super.noSuchMethod( - Invocation.method(#addAdEventListener, [adEventListener]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i2.AdsManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsManager_6(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsManager_6(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.AdsManager); @override - _i4.Future destroy() => - (super.noSuchMethod( - Invocation.method(#destroy, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future addAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( + Invocation.method(#addAdErrorListener, [errorListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future init(_i2.AdsRenderingSettings? settings) => - (super.noSuchMethod( - Invocation.method(#init, [settings]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future addAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( + Invocation.method(#addAdEventListener, [adEventListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future focus() => - (super.noSuchMethod( - Invocation.method(#focus, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future destroy() => (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.AdProgressInfo?> getAdProgressInfo() => - (super.noSuchMethod( - Invocation.method(#getAdProgressInfo, []), - returnValue: _i4.Future<_i2.AdProgressInfo?>.value(), - returnValueForMissingStub: _i4.Future<_i2.AdProgressInfo?>.value(), - ) - as _i4.Future<_i2.AdProgressInfo?>); + _i4.Future init(_i2.AdsRenderingSettings? settings) => (super.noSuchMethod( + Invocation.method(#init, [settings]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future<_i2.Ad?> getCurrentAd() => - (super.noSuchMethod( - Invocation.method(#getCurrentAd, []), - returnValue: _i4.Future<_i2.Ad?>.value(), - returnValueForMissingStub: _i4.Future<_i2.Ad?>.value(), - ) - as _i4.Future<_i2.Ad?>); + _i4.Future focus() => (super.noSuchMethod( + Invocation.method(#focus, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => - (super.noSuchMethod( - Invocation.method(#removeAdErrorListener, [errorListener]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future<_i2.AdProgressInfo?> getAdProgressInfo() => (super.noSuchMethod( + Invocation.method(#getAdProgressInfo, []), + returnValue: _i4.Future<_i2.AdProgressInfo?>.value(), + returnValueForMissingStub: _i4.Future<_i2.AdProgressInfo?>.value(), + ) as _i4.Future<_i2.AdProgressInfo?>); + + @override + _i4.Future<_i2.Ad?> getCurrentAd() => (super.noSuchMethod( + Invocation.method(#getCurrentAd, []), + returnValue: _i4.Future<_i2.Ad?>.value(), + returnValueForMissingStub: _i4.Future<_i2.Ad?>.value(), + ) as _i4.Future<_i2.Ad?>); @override - _i4.Future removeAdEventListener( - _i2.AdEventListener? adEventListener, - ) => + _i4.Future removeAdErrorListener(_i2.AdErrorListener? errorListener) => (super.noSuchMethod( + Invocation.method(#removeAdErrorListener, [errorListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); + + @override + _i4.Future removeAdEventListener(_i2.AdEventListener? adEventListener) => (super.noSuchMethod( - Invocation.method(#removeAdEventListener, [adEventListener]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#removeAdEventListener, [adEventListener]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } /// A class which mocks [AdsRenderingSettings]. /// /// See the documentation for Mockito's code generation for more information. -class MockAdsRenderingSettings extends _i1.Mock - implements _i2.AdsRenderingSettings { +class MockAdsRenderingSettings extends _i1.Mock implements _i2.AdsRenderingSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i4.Future getBitrateKbps() => - (super.noSuchMethod( - Invocation.method(#getBitrateKbps, []), - returnValue: _i4.Future.value(0), - returnValueForMissingStub: _i4.Future.value(0), - ) - as _i4.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i4.Future getEnableCustomTabs() => - (super.noSuchMethod( - Invocation.method(#getEnableCustomTabs, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future getBitrateKbps() => (super.noSuchMethod( + Invocation.method(#getBitrateKbps, []), + returnValue: _i4.Future.value(0), + returnValueForMissingStub: _i4.Future.value(0), + ) as _i4.Future); @override - _i4.Future getEnablePreloading() => - (super.noSuchMethod( - Invocation.method(#getEnablePreloading, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future getEnableCustomTabs() => (super.noSuchMethod( + Invocation.method(#getEnableCustomTabs, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future getFocusSkipButtonWhenAvailable() => - (super.noSuchMethod( - Invocation.method(#getFocusSkipButtonWhenAvailable, []), - returnValue: _i4.Future.value(false), - returnValueForMissingStub: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future getEnablePreloading() => (super.noSuchMethod( + Invocation.method(#getEnablePreloading, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future?> getMimeTypes() => - (super.noSuchMethod( - Invocation.method(#getMimeTypes, []), - returnValue: _i4.Future?>.value(), - returnValueForMissingStub: _i4.Future?>.value(), - ) - as _i4.Future?>); + _i4.Future getFocusSkipButtonWhenAvailable() => (super.noSuchMethod( + Invocation.method(#getFocusSkipButtonWhenAvailable, []), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future setBitrateKbps(int? bitrate) => - (super.noSuchMethod( - Invocation.method(#setBitrateKbps, [bitrate]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future?> getMimeTypes() => (super.noSuchMethod( + Invocation.method(#getMimeTypes, []), + returnValue: _i4.Future?>.value(), + returnValueForMissingStub: _i4.Future?>.value(), + ) as _i4.Future?>); @override - _i4.Future setEnableCustomTabs(bool? enableCustomTabs) => - (super.noSuchMethod( - Invocation.method(#setEnableCustomTabs, [enableCustomTabs]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setBitrateKbps(int? bitrate) => (super.noSuchMethod( + Invocation.method(#setBitrateKbps, [bitrate]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setEnablePreloading(bool? enablePreloading) => - (super.noSuchMethod( - Invocation.method(#setEnablePreloading, [enablePreloading]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setEnableCustomTabs(bool? enableCustomTabs) => (super.noSuchMethod( + Invocation.method(#setEnableCustomTabs, [enableCustomTabs]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setFocusSkipButtonWhenAvailable( - bool? enableFocusSkipButton, - ) => - (super.noSuchMethod( - Invocation.method(#setFocusSkipButtonWhenAvailable, [ - enableFocusSkipButton, - ]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setEnablePreloading(bool? enablePreloading) => (super.noSuchMethod( + Invocation.method(#setEnablePreloading, [enablePreloading]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setLoadVideoTimeout(int? loadVideoTimeout) => + _i4.Future setFocusSkipButtonWhenAvailable(bool? enableFocusSkipButton) => (super.noSuchMethod( - Invocation.method(#setLoadVideoTimeout, [loadVideoTimeout]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + Invocation.method(#setFocusSkipButtonWhenAvailable, [enableFocusSkipButton]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setMimeTypes(List? mimeTypes) => - (super.noSuchMethod( - Invocation.method(#setMimeTypes, [mimeTypes]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setLoadVideoTimeout(int? loadVideoTimeout) => (super.noSuchMethod( + Invocation.method(#setLoadVideoTimeout, [loadVideoTimeout]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setPlayAdsAfterTime(double? time) => - (super.noSuchMethod( - Invocation.method(#setPlayAdsAfterTime, [time]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setMimeTypes(List? mimeTypes) => (super.noSuchMethod( + Invocation.method(#setMimeTypes, [mimeTypes]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future setUiElements(List<_i2.UiElement>? uiElements) => - (super.noSuchMethod( - Invocation.method(#setUiElements, [uiElements]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future setPlayAdsAfterTime(double? time) => (super.noSuchMethod( + Invocation.method(#setPlayAdsAfterTime, [time]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i2.AdsRenderingSettings pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeAdsRenderingSettings_7( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeAdsRenderingSettings_7( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.AdsRenderingSettings); + _i4.Future setUiElements(List<_i2.UiElement>? uiElements) => (super.noSuchMethod( + Invocation.method(#setUiElements, [uiElements]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); + + @override + _i2.AdsRenderingSettings pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAdsRenderingSettings_7(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeAdsRenderingSettings_7( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.AdsRenderingSettings); } /// A class which mocks [ImaSdkFactory]. @@ -696,131 +499,77 @@ class MockAdsRenderingSettings extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i4.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => - (super.noSuchMethod( - Invocation.method(#createCompanionAdSlot, []), - returnValue: _i4.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_8( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_8( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - ) - as _i4.Future<_i2.CompanionAdSlot>); - - @override - _i4.Future<_i2.ImaSdkSettings> createImaSdkSettings() => - (super.noSuchMethod( - Invocation.method(#createImaSdkSettings, []), - returnValue: _i4.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_9( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_9( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - ) - as _i4.Future<_i2.ImaSdkSettings>); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i4.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i4.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_8(this, Invocation.method(#createCompanionAdSlot, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_8(this, Invocation.method(#createCompanionAdSlot, [])), + ), + ) as _i4.Future<_i2.CompanionAdSlot>); + + @override + _i4.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i4.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_9(this, Invocation.method(#createImaSdkSettings, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_9(this, Invocation.method(#createImaSdkSettings, [])), + ), + ) as _i4.Future<_i2.ImaSdkSettings>); @override _i4.Future<_i2.AdsLoader> createAdsLoader( _i2.ImaSdkSettings? settings, _i2.AdDisplayContainer? container, - ) => - (super.noSuchMethod( - Invocation.method(#createAdsLoader, [settings, container]), - returnValue: _i4.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_10( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_10( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - ) - as _i4.Future<_i2.AdsLoader>); - - @override - _i4.Future<_i2.AdsRequest> createAdsRequest() => - (super.noSuchMethod( - Invocation.method(#createAdsRequest, []), - returnValue: _i4.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_11( - this, - Invocation.method(#createAdsRequest, []), - ), - ), - returnValueForMissingStub: _i4.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_11( - this, - Invocation.method(#createAdsRequest, []), - ), - ), - ) - as _i4.Future<_i2.AdsRequest>); - - @override - _i4.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => - (super.noSuchMethod( - Invocation.method(#createAdsRenderingSettings, []), - returnValue: _i4.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_7( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - returnValueForMissingStub: - _i4.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_7( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - ) - as _i4.Future<_i2.AdsRenderingSettings>); - - @override - _i2.ImaSdkFactory pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImaSdkFactory_12( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImaSdkFactory_12( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImaSdkFactory); + ) => (super.noSuchMethod( + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i4.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_10(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + returnValueForMissingStub: _i4.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_10(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + ) as _i4.Future<_i2.AdsLoader>); + + @override + _i4.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i4.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_11(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_11(this, Invocation.method(#createAdsRequest, [])), + ), + ) as _i4.Future<_i2.AdsRequest>); + + @override + _i4.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i4.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_7(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + returnValueForMissingStub: _i4.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_7(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + ) as _i4.Future<_i2.AdsRenderingSettings>); + + @override + _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_12(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImaSdkFactory_12(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImaSdkFactory); } diff --git a/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart b/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart index aea989425bcd..755d901456b3 100644 --- a/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart +++ b/packages/interactive_media_ads/test/android/companion_ad_slot_test.dart @@ -4,8 +4,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:interactive_media_ads/src/android/android_companion_ad_slot.dart'; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/platform_interface/companion_ad_slot_size.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -31,9 +30,7 @@ void main() { return frameLayout; }; final mockFactory = MockImaSdkFactory(); - when( - mockFactory.createCompanionAdSlot(), - ).thenAnswer((_) async => mockCompanionAdSlot); + when(mockFactory.createCompanionAdSlot()).thenAnswer((_) async => mockCompanionAdSlot); ima.PigeonOverrides.imaSdkFactory_instance = mockFactory; final params = AndroidCompanionAdSlotCreationParams( size: CompanionAdSlotSize.fixed(width: 300, height: 400), @@ -48,18 +45,12 @@ void main() { test('AndroidCompanionAdSlot receives onClick', () async { final mockCompanionAdSlot = MockCompanionAdSlot(); - ima.PigeonOverrides.frameLayout_new = () => - ima.FrameLayout.pigeon_detached(); + ima.PigeonOverrides.frameLayout_new = () => ima.FrameLayout.pigeon_detached(); final mockFactory = MockImaSdkFactory(); - when( - mockFactory.createCompanionAdSlot(), - ).thenAnswer((_) async => mockCompanionAdSlot); + when(mockFactory.createCompanionAdSlot()).thenAnswer((_) async => mockCompanionAdSlot); ima.PigeonOverrides.imaSdkFactory_instance = mockFactory; ima.PigeonOverrides.companionAdSlotClickListener_new = - ({ - required void Function(ima.CompanionAdSlotClickListener) - onCompanionAdClick, - }) { + ({required void Function(ima.CompanionAdSlotClickListener) onCompanionAdClick}) { return ima.CompanionAdSlotClickListener.pigeon_detached( onCompanionAdClick: onCompanionAdClick, ); @@ -73,9 +64,7 @@ void main() { await adSlot.getNativeCompanionAdSlot(); final clickListener = - verify( - mockCompanionAdSlot.addClickListener(captureAny), - ).captured.single + verify(mockCompanionAdSlot.addClickListener(captureAny)).captured.single as ima.CompanionAdSlotClickListener; clickListener.onCompanionAdClick(clickListener); diff --git a/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart b/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart index 838d2b818a65..c8458979c1cb 100644 --- a/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/companion_ad_slot_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -24,41 +23,34 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCompanionAdSlot_1 extends _i1.SmartFake - implements _i2.CompanionAdSlot { +class _FakeCompanionAdSlot_1 extends _i1.SmartFake implements _i2.CompanionAdSlot { _FakeCompanionAdSlot_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeFrameLayout_2 extends _i1.SmartFake implements _i2.FrameLayout { - _FakeFrameLayout_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeFrameLayout_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImaSdkSettings_3 extends _i1.SmartFake - implements _i2.ImaSdkSettings { +class _FakeImaSdkSettings_3 extends _i1.SmartFake implements _i2.ImaSdkSettings { _FakeImaSdkSettings_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsLoader_4 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_4(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsLoader_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsRequest_5 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_5(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsRequest_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdsRenderingSettings_6 extends _i1.SmartFake - implements _i2.AdsRenderingSettings { +class _FakeAdsRenderingSettings_6 extends _i1.SmartFake implements _i2.AdsRenderingSettings { _FakeAdsRenderingSettings_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -73,119 +65,86 @@ class _FakeImaSdkFactory_7 extends _i1.SmartFake implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future addClickListener( - _i2.CompanionAdSlotClickListener? clickListener, - ) => + _i3.Future addClickListener(_i2.CompanionAdSlotClickListener? clickListener) => (super.noSuchMethod( - Invocation.method(#addClickListener, [clickListener]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#addClickListener, [clickListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future removeClickListener( - _i2.CompanionAdSlotClickListener? clickListener, - ) => + _i3.Future removeClickListener(_i2.CompanionAdSlotClickListener? clickListener) => (super.noSuchMethod( - Invocation.method(#removeClickListener, [clickListener]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#removeClickListener, [clickListener]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.CompanionAdSlot pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeCompanionAdSlot_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeCompanionAdSlot_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.CompanionAdSlot); + _i2.CompanionAdSlot pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCompanionAdSlot_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeCompanionAdSlot_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.CompanionAdSlot); @override - _i3.Future<_i2.ViewGroup?> getContainer() => - (super.noSuchMethod( - Invocation.method(#getContainer, []), - returnValue: _i3.Future<_i2.ViewGroup?>.value(), - returnValueForMissingStub: _i3.Future<_i2.ViewGroup?>.value(), - ) - as _i3.Future<_i2.ViewGroup?>); + _i3.Future<_i2.ViewGroup?> getContainer() => (super.noSuchMethod( + Invocation.method(#getContainer, []), + returnValue: _i3.Future<_i2.ViewGroup?>.value(), + returnValueForMissingStub: _i3.Future<_i2.ViewGroup?>.value(), + ) as _i3.Future<_i2.ViewGroup?>); @override - _i3.Future getHeight() => - (super.noSuchMethod( - Invocation.method(#getHeight, []), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) - as _i3.Future); + _i3.Future getHeight() => (super.noSuchMethod( + Invocation.method(#getHeight, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) as _i3.Future); @override - _i3.Future getWidth() => - (super.noSuchMethod( - Invocation.method(#getWidth, []), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) - as _i3.Future); + _i3.Future getWidth() => (super.noSuchMethod( + Invocation.method(#getWidth, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) as _i3.Future); @override - _i3.Future isFilled() => - (super.noSuchMethod( - Invocation.method(#isFilled, []), - returnValue: _i3.Future.value(false), - returnValueForMissingStub: _i3.Future.value(false), - ) - as _i3.Future); + _i3.Future isFilled() => (super.noSuchMethod( + Invocation.method(#isFilled, []), + returnValue: _i3.Future.value(false), + returnValueForMissingStub: _i3.Future.value(false), + ) as _i3.Future); @override - _i3.Future setContainer(_i2.ViewGroup? container) => - (super.noSuchMethod( - Invocation.method(#setContainer, [container]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setContainer(_i2.ViewGroup? container) => (super.noSuchMethod( + Invocation.method(#setContainer, [container]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setSize(int? width, int? height) => - (super.noSuchMethod( - Invocation.method(#setSize, [width, height]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setSize(int? width, int? height) => (super.noSuchMethod( + Invocation.method(#setSize, [width, height]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setFluidSize() => - (super.noSuchMethod( - Invocation.method(#setFluidSize, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setFluidSize() => (super.noSuchMethod( + Invocation.method(#setFluidSize, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); } /// A class which mocks [FrameLayout]. @@ -193,52 +152,35 @@ class MockCompanionAdSlot extends _i1.Mock implements _i2.CompanionAdSlot { /// See the documentation for Mockito's code generation for more information. class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.FrameLayout pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeFrameLayout_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeFrameLayout_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.FrameLayout); + _i2.FrameLayout pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFrameLayout_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeFrameLayout_2(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.FrameLayout); @override - _i3.Future addView(_i2.View? view) => - (super.noSuchMethod( - Invocation.method(#addView, [view]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future addView(_i2.View? view) => (super.noSuchMethod( + Invocation.method(#addView, [view]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future removeView(_i2.View? view) => - (super.noSuchMethod( - Invocation.method(#removeView, [view]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future removeView(_i2.View? view) => (super.noSuchMethod( + Invocation.method(#removeView, [view]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); } /// A class which mocks [ImaSdkFactory]. @@ -246,125 +188,77 @@ class MockFrameLayout extends _i1.Mock implements _i2.FrameLayout { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => - (super.noSuchMethod( - Invocation.method(#createCompanionAdSlot, []), - returnValue: _i3.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_1( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_1( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - ) - as _i3.Future<_i2.CompanionAdSlot>); + _i3.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_1(this, Invocation.method(#createCompanionAdSlot, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_1(this, Invocation.method(#createCompanionAdSlot, [])), + ), + ) as _i3.Future<_i2.CompanionAdSlot>); @override - _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => - (super.noSuchMethod( - Invocation.method(#createImaSdkSettings, []), - returnValue: _i3.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_3( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_3( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - ) - as _i3.Future<_i2.ImaSdkSettings>); + _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_3(this, Invocation.method(#createImaSdkSettings, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_3(this, Invocation.method(#createImaSdkSettings, [])), + ), + ) as _i3.Future<_i2.ImaSdkSettings>); @override _i3.Future<_i2.AdsLoader> createAdsLoader( _i2.ImaSdkSettings? settings, _i2.AdDisplayContainer? container, - ) => - (super.noSuchMethod( - Invocation.method(#createAdsLoader, [settings, container]), - returnValue: _i3.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_4( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_4( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - ) - as _i3.Future<_i2.AdsLoader>); + ) => (super.noSuchMethod( + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_4(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_4(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + ) as _i3.Future<_i2.AdsLoader>); @override - _i3.Future<_i2.AdsRequest> createAdsRequest() => - (super.noSuchMethod( - Invocation.method(#createAdsRequest, []), - returnValue: _i3.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_5(this, Invocation.method(#createAdsRequest, [])), - ), - returnValueForMissingStub: _i3.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_5(this, Invocation.method(#createAdsRequest, [])), - ), - ) - as _i3.Future<_i2.AdsRequest>); + _i3.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_5(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_5(this, Invocation.method(#createAdsRequest, [])), + ), + ) as _i3.Future<_i2.AdsRequest>); @override - _i3.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => - (super.noSuchMethod( - Invocation.method(#createAdsRenderingSettings, []), - returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_6( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - returnValueForMissingStub: - _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_6( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - ) - as _i3.Future<_i2.AdsRenderingSettings>); + _i3.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_6(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_6(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + ) as _i3.Future<_i2.AdsRenderingSettings>); @override - _i2.ImaSdkFactory pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImaSdkFactory_7( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImaSdkFactory_7( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImaSdkFactory); + _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_7(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImaSdkFactory_7(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImaSdkFactory); } diff --git a/packages/interactive_media_ads/test/android/content_progress_provider_test.dart b/packages/interactive_media_ads/test/android/content_progress_provider_test.dart index b086bdf8af19..f9fa0db15a42 100644 --- a/packages/interactive_media_ads/test/android/content_progress_provider_test.dart +++ b/packages/interactive_media_ads/test/android/content_progress_provider_test.dart @@ -4,8 +4,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:interactive_media_ads/src/android/android_content_progress_provider.dart'; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/platform_interface/platform_interface.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -22,8 +21,7 @@ void main() { test('setProgress', () async { final mockContentProgressProvider = MockContentProgressProvider(); - ima.PigeonOverrides.contentProgressProvider_new = () => - mockContentProgressProvider; + ima.PigeonOverrides.contentProgressProvider_new = () => mockContentProgressProvider; ima.PigeonOverrides.videoProgressUpdate_new = ({required int currentTimeMs, required int durationMs}) { expect(currentTimeMs, 1000); diff --git a/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart b/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart index e73d08385e6e..1a6e02bd265d 100644 --- a/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/content_progress_provider_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -24,14 +23,12 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeContentProgressProvider_1 extends _i1.SmartFake - implements _i2.ContentProgressProvider { +class _FakeContentProgressProvider_1 extends _i1.SmartFake implements _i2.ContentProgressProvider { _FakeContentProgressProvider_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -39,44 +36,31 @@ class _FakeContentProgressProvider_1 extends _i1.SmartFake /// A class which mocks [ContentProgressProvider]. /// /// See the documentation for Mockito's code generation for more information. -class MockContentProgressProvider extends _i1.Mock - implements _i2.ContentProgressProvider { +class MockContentProgressProvider extends _i1.Mock implements _i2.ContentProgressProvider { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setContentProgress(_i2.VideoProgressUpdate? update) => - (super.noSuchMethod( - Invocation.method(#setContentProgress, [update]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setContentProgress(_i2.VideoProgressUpdate? update) => (super.noSuchMethod( + Invocation.method(#setContentProgress, [update]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.ContentProgressProvider pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeContentProgressProvider_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeContentProgressProvider_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ContentProgressProvider); + _i2.ContentProgressProvider pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeContentProgressProvider_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeContentProgressProvider_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ContentProgressProvider); } diff --git a/packages/interactive_media_ads/test/android/ima_settings_test.dart b/packages/interactive_media_ads/test/android/ima_settings_test.dart index 91a1fa6fe482..198cd706df5c 100644 --- a/packages/interactive_media_ads/test/android/ima_settings_test.dart +++ b/packages/interactive_media_ads/test/android/ima_settings_test.dart @@ -4,8 +4,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:interactive_media_ads/src/android/android_ima_settings.dart'; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/platform_interface/platform_ima_settings.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -38,9 +37,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const autoPlayAdBreaks = true; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setAutoPlayAdBreaks(autoPlayAdBreaks); verify(mockImaSdkSettings.setAutoPlayAdBreaks(autoPlayAdBreaks)); @@ -50,9 +47,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const debugMode = false; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setDebugMode(debugMode); verify(mockImaSdkSettings.setDebugMode(debugMode)); @@ -62,9 +57,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const featureFlags = {'a': 'flag'}; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setFeatureFlags(featureFlags); verify(mockImaSdkSettings.setFeatureFlags(featureFlags)); @@ -74,9 +67,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const maxRedirects = 12; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setMaxRedirects(maxRedirects); verify(mockImaSdkSettings.setMaxRedirects(maxRedirects)); @@ -86,9 +77,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const playerType = 'playerType'; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setPlayerType(playerType); verify(mockImaSdkSettings.setPlayerType(playerType)); @@ -98,9 +87,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const playerVersion = 'playerVersion'; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setPlayerVersion(playerVersion); verify(mockImaSdkSettings.setPlayerVersion(playerVersion)); @@ -110,9 +97,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const ppid = 'ppid'; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setPpid(ppid); verify(mockImaSdkSettings.setPpid(ppid)); @@ -122,9 +107,7 @@ void main() { final MockImaSdkSettings mockImaSdkSettings = _mockImaSdkSettings(); const sessionID = 'sessionID'; - final settings = AndroidImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = AndroidImaSettings(const PlatformImaSettingsCreationParams()); await settings.setSessionID(sessionID); verify(mockImaSdkSettings.setSessionId(sessionID)); @@ -135,9 +118,7 @@ void main() { MockImaSdkSettings _mockImaSdkSettings() { final mockImaSdkFactory = MockImaSdkFactory(); final mockImaSdkSettings = MockImaSdkSettings(); - when( - mockImaSdkFactory.createImaSdkSettings(), - ).thenAnswer((_) async => mockImaSdkSettings); + when(mockImaSdkFactory.createImaSdkSettings()).thenAnswer((_) async => mockImaSdkSettings); ima.PigeonOverrides.imaSdkFactory_instance = mockImaSdkFactory; return mockImaSdkSettings; diff --git a/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart b/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart index 355e43b06550..46cee9130e80 100644 --- a/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart +++ b/packages/interactive_media_ads/test/android/ima_settings_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/android/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -24,36 +23,30 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCompanionAdSlot_1 extends _i1.SmartFake - implements _i2.CompanionAdSlot { +class _FakeCompanionAdSlot_1 extends _i1.SmartFake implements _i2.CompanionAdSlot { _FakeCompanionAdSlot_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImaSdkSettings_2 extends _i1.SmartFake - implements _i2.ImaSdkSettings { +class _FakeImaSdkSettings_2 extends _i1.SmartFake implements _i2.ImaSdkSettings { _FakeImaSdkSettings_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsLoader_3 extends _i1.SmartFake implements _i2.AdsLoader { - _FakeAdsLoader_3(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsLoader_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeAdsRequest_4 extends _i1.SmartFake implements _i2.AdsRequest { - _FakeAdsRequest_4(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAdsRequest_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAdsRenderingSettings_5 extends _i1.SmartFake - implements _i2.AdsRenderingSettings { +class _FakeAdsRenderingSettings_5 extends _i1.SmartFake implements _i2.AdsRenderingSettings { _FakeAdsRenderingSettings_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -68,127 +61,79 @@ class _FakeImaSdkFactory_6 extends _i1.SmartFake implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i3.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => - (super.noSuchMethod( - Invocation.method(#createCompanionAdSlot, []), - returnValue: _i3.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_1( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.CompanionAdSlot>.value( - _FakeCompanionAdSlot_1( - this, - Invocation.method(#createCompanionAdSlot, []), - ), - ), - ) - as _i3.Future<_i2.CompanionAdSlot>); - - @override - _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => - (super.noSuchMethod( - Invocation.method(#createImaSdkSettings, []), - returnValue: _i3.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_2( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.ImaSdkSettings>.value( - _FakeImaSdkSettings_2( - this, - Invocation.method(#createImaSdkSettings, []), - ), - ), - ) - as _i3.Future<_i2.ImaSdkSettings>); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i3.Future<_i2.CompanionAdSlot> createCompanionAdSlot() => (super.noSuchMethod( + Invocation.method(#createCompanionAdSlot, []), + returnValue: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_1(this, Invocation.method(#createCompanionAdSlot, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.CompanionAdSlot>.value( + _FakeCompanionAdSlot_1(this, Invocation.method(#createCompanionAdSlot, [])), + ), + ) as _i3.Future<_i2.CompanionAdSlot>); + + @override + _i3.Future<_i2.ImaSdkSettings> createImaSdkSettings() => (super.noSuchMethod( + Invocation.method(#createImaSdkSettings, []), + returnValue: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_2(this, Invocation.method(#createImaSdkSettings, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.ImaSdkSettings>.value( + _FakeImaSdkSettings_2(this, Invocation.method(#createImaSdkSettings, [])), + ), + ) as _i3.Future<_i2.ImaSdkSettings>); @override _i3.Future<_i2.AdsLoader> createAdsLoader( _i2.ImaSdkSettings? settings, _i2.AdDisplayContainer? container, - ) => - (super.noSuchMethod( - Invocation.method(#createAdsLoader, [settings, container]), - returnValue: _i3.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_3( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - returnValueForMissingStub: _i3.Future<_i2.AdsLoader>.value( - _FakeAdsLoader_3( - this, - Invocation.method(#createAdsLoader, [settings, container]), - ), - ), - ) - as _i3.Future<_i2.AdsLoader>); - - @override - _i3.Future<_i2.AdsRequest> createAdsRequest() => - (super.noSuchMethod( - Invocation.method(#createAdsRequest, []), - returnValue: _i3.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_4(this, Invocation.method(#createAdsRequest, [])), - ), - returnValueForMissingStub: _i3.Future<_i2.AdsRequest>.value( - _FakeAdsRequest_4(this, Invocation.method(#createAdsRequest, [])), - ), - ) - as _i3.Future<_i2.AdsRequest>); - - @override - _i3.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => - (super.noSuchMethod( - Invocation.method(#createAdsRenderingSettings, []), - returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_5( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - returnValueForMissingStub: - _i3.Future<_i2.AdsRenderingSettings>.value( - _FakeAdsRenderingSettings_5( - this, - Invocation.method(#createAdsRenderingSettings, []), - ), - ), - ) - as _i3.Future<_i2.AdsRenderingSettings>); - - @override - _i2.ImaSdkFactory pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImaSdkFactory_6( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImaSdkFactory_6( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImaSdkFactory); + ) => (super.noSuchMethod( + Invocation.method(#createAdsLoader, [settings, container]), + returnValue: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_3(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsLoader>.value( + _FakeAdsLoader_3(this, Invocation.method(#createAdsLoader, [settings, container])), + ), + ) as _i3.Future<_i2.AdsLoader>); + + @override + _i3.Future<_i2.AdsRequest> createAdsRequest() => (super.noSuchMethod( + Invocation.method(#createAdsRequest, []), + returnValue: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_4(this, Invocation.method(#createAdsRequest, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsRequest>.value( + _FakeAdsRequest_4(this, Invocation.method(#createAdsRequest, [])), + ), + ) as _i3.Future<_i2.AdsRequest>); + + @override + _i3.Future<_i2.AdsRenderingSettings> createAdsRenderingSettings() => (super.noSuchMethod( + Invocation.method(#createAdsRenderingSettings, []), + returnValue: _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_5(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.AdsRenderingSettings>.value( + _FakeAdsRenderingSettings_5(this, Invocation.method(#createAdsRenderingSettings, [])), + ), + ) as _i3.Future<_i2.AdsRenderingSettings>); + + @override + _i2.ImaSdkFactory pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkFactory_6(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImaSdkFactory_6(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImaSdkFactory); } /// A class which mocks [ImaSdkSettings]. @@ -196,113 +141,82 @@ class MockImaSdkFactory extends _i1.Mock implements _i2.ImaSdkFactory { /// See the documentation for Mockito's code generation for more information. class MockImaSdkSettings extends _i1.Mock implements _i2.ImaSdkSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setAutoPlayAdBreaks(bool? autoPlayAdBreaks) => - (super.noSuchMethod( - Invocation.method(#setAutoPlayAdBreaks, [autoPlayAdBreaks]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setAutoPlayAdBreaks(bool? autoPlayAdBreaks) => (super.noSuchMethod( + Invocation.method(#setAutoPlayAdBreaks, [autoPlayAdBreaks]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setDebugMode(bool? debugMode) => - (super.noSuchMethod( - Invocation.method(#setDebugMode, [debugMode]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setDebugMode(bool? debugMode) => (super.noSuchMethod( + Invocation.method(#setDebugMode, [debugMode]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setFeatureFlags(Map? featureFlags) => - (super.noSuchMethod( - Invocation.method(#setFeatureFlags, [featureFlags]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setFeatureFlags(Map? featureFlags) => (super.noSuchMethod( + Invocation.method(#setFeatureFlags, [featureFlags]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setLanguage(String? language) => - (super.noSuchMethod( - Invocation.method(#setLanguage, [language]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setLanguage(String? language) => (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setMaxRedirects(int? maxRedirects) => - (super.noSuchMethod( - Invocation.method(#setMaxRedirects, [maxRedirects]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setMaxRedirects(int? maxRedirects) => (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [maxRedirects]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPlayerType(String? playerType) => - (super.noSuchMethod( - Invocation.method(#setPlayerType, [playerType]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPlayerType(String? playerType) => (super.noSuchMethod( + Invocation.method(#setPlayerType, [playerType]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPlayerVersion(String? playerVersion) => - (super.noSuchMethod( - Invocation.method(#setPlayerVersion, [playerVersion]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPlayerVersion(String? playerVersion) => (super.noSuchMethod( + Invocation.method(#setPlayerVersion, [playerVersion]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPpid(String? ppid) => - (super.noSuchMethod( - Invocation.method(#setPpid, [ppid]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPpid(String? ppid) => (super.noSuchMethod( + Invocation.method(#setPpid, [ppid]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setSessionId(String? sessionId) => - (super.noSuchMethod( - Invocation.method(#setSessionId, [sessionId]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setSessionId(String? sessionId) => (super.noSuchMethod( + Invocation.method(#setSessionId, [sessionId]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.ImaSdkSettings pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeImaSdkSettings_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeImaSdkSettings_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.ImaSdkSettings); + _i2.ImaSdkSettings pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImaSdkSettings_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeImaSdkSettings_2(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.ImaSdkSettings); } diff --git a/packages/interactive_media_ads/test/content_progress_provider_test.dart b/packages/interactive_media_ads/test/content_progress_provider_test.dart index e128b3c786f1..e33e144c169e 100644 --- a/packages/interactive_media_ads/test/content_progress_provider_test.dart +++ b/packages/interactive_media_ads/test/content_progress_provider_test.dart @@ -15,11 +15,10 @@ void main() { final platformProvider = TestContentProgressProvider( const PlatformContentProgressProviderCreationParams(), - onSetProgress: - ({required Duration progress, required Duration duration}) async { - callbackProgress = progress; - callbackDuration = duration; - }, + onSetProgress: ({required Duration progress, required Duration duration}) async { + callbackProgress = progress; + callbackDuration = duration; + }, ); final provider = ContentProgressProvider.fromPlatform(platformProvider); diff --git a/packages/interactive_media_ads/test/ios/ad_display_container_test.dart b/packages/interactive_media_ads/test/ios/ad_display_container_test.dart index 4afd1936dbef..cb3c21cd2225 100644 --- a/packages/interactive_media_ads/test/ios/ad_display_container_test.dart +++ b/packages/interactive_media_ads/test/ios/ad_display_container_test.dart @@ -31,15 +31,10 @@ void main() { group('IOSAdDisplayContainer', () { testWidgets('build with key', (WidgetTester tester) async { final container = IOSAdDisplayContainer( - IOSAdDisplayContainerCreationParams( - key: const Key('testKey'), - onContainerAdded: (_) {}, - ), + IOSAdDisplayContainerCreationParams(key: const Key('testKey'), onContainerAdded: (_) {}), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); expect(find.byType(UiKitView), findsOneWidget); expect(find.byKey(const Key('testKey')), findsOneWidget); @@ -58,12 +53,11 @@ void main() { when(mockController.view).thenReturn(view); return mockController; }; - PigeonOverrides.iMAAdDisplayContainer_new = - ({ - required UIView adContainer, - UIViewController? adContainerViewController, - List? companionSlots, - }) => MockIMAAdDisplayContainer(); + PigeonOverrides.iMAAdDisplayContainer_new = ({ + required UIView adContainer, + UIViewController? adContainerViewController, + List? companionSlots, + }) => MockIMAAdDisplayContainer(); final onContainerAddedCompleter = Completer(); @@ -73,9 +67,7 @@ void main() { ), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); final view = find.byType(UiKitView).evaluate().single.widget as UiKitView; view.onPlatformViewCreated!.call(0); @@ -89,9 +81,7 @@ void main() { expect(onContainerAddedCompleter.isCompleted, isTrue); }); - testWidgets('AdDisplayContainer ads CompanionAdSlots', ( - WidgetTester tester, - ) async { + testWidgets('AdDisplayContainer ads CompanionAdSlots', (WidgetTester tester) async { final mockCompanionAdSlot = MockIMACompanionAdSlot(); late final void Function(UIViewController, bool) viewDidAppearCallback; final addedAdSlotsCompleter = Completer?>(); @@ -140,9 +130,7 @@ void main() { ), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); final view = find.byType(UiKitView).evaluate().single.widget as UiKitView; view.onPlatformViewCreated!.call(0); @@ -152,9 +140,7 @@ void main() { await onContainerAddedCompleter.future; - expect(await addedAdSlotsCompleter.future, [ - mockCompanionAdSlot, - ]); + expect(await addedAdSlotsCompleter.future, [mockCompanionAdSlot]); }); }); } diff --git a/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart b/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart index f6932c234e4d..bbcbd89dbf21 100644 --- a/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ad_display_container_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -25,30 +24,25 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: invalid_use_of_internal_member class _FakeUIView_0 extends _i1.SmartFake implements _i2.UIView { - _FakeUIView_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeUIView_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePigeonInstanceManager_1 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_1 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIMAAdDisplayContainer_2 extends _i1.SmartFake - implements _i2.IMAAdDisplayContainer { +class _FakeIMAAdDisplayContainer_2 extends _i1.SmartFake implements _i2.IMAAdDisplayContainer { _FakeIMAAdDisplayContainer_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIMACompanionAdSlot_3 extends _i1.SmartFake - implements _i2.IMACompanionAdSlot { +class _FakeIMACompanionAdSlot_3 extends _i1.SmartFake implements _i2.IMACompanionAdSlot { _FakeIMACompanionAdSlot_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeUIViewController_4 extends _i1.SmartFake - implements _i2.UIViewController { +class _FakeUIViewController_4 extends _i1.SmartFake implements _i2.UIViewController { _FakeUIViewController_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -56,167 +50,113 @@ class _FakeUIViewController_4 extends _i1.SmartFake /// A class which mocks [IMAAdDisplayContainer]. /// /// See the documentation for Mockito's code generation for more information. -class MockIMAAdDisplayContainer extends _i1.Mock - implements _i2.IMAAdDisplayContainer { +class MockIMAAdDisplayContainer extends _i1.Mock implements _i2.IMAAdDisplayContainer { @override - _i2.UIView get adContainer => - (super.noSuchMethod( - Invocation.getter(#adContainer), - returnValue: _FakeUIView_0(this, Invocation.getter(#adContainer)), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#adContainer), - ), - ) - as _i2.UIView); + _i2.UIView get adContainer => (super.noSuchMethod( + Invocation.getter(#adContainer), + returnValue: _FakeUIView_0(this, Invocation.getter(#adContainer)), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.getter(#adContainer)), + ) as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setAdContainerViewController( - _i2.UIViewController? controller, - ) => + _i3.Future setAdContainerViewController(_i2.UIViewController? controller) => (super.noSuchMethod( - Invocation.method(#setAdContainerViewController, [controller]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#setAdContainerViewController, [controller]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future<_i2.UIViewController?> getAdContainerViewController() => - (super.noSuchMethod( - Invocation.method(#getAdContainerViewController, []), - returnValue: _i3.Future<_i2.UIViewController?>.value(), - returnValueForMissingStub: - _i3.Future<_i2.UIViewController?>.value(), - ) - as _i3.Future<_i2.UIViewController?>); + _i3.Future<_i2.UIViewController?> getAdContainerViewController() => (super.noSuchMethod( + Invocation.method(#getAdContainerViewController, []), + returnValue: _i3.Future<_i2.UIViewController?>.value(), + returnValueForMissingStub: _i3.Future<_i2.UIViewController?>.value(), + ) as _i3.Future<_i2.UIViewController?>); @override - _i3.Future registerFriendlyObstruction( - _i2.IMAFriendlyObstruction? friendlyObstruction, - ) => + _i3.Future registerFriendlyObstruction(_i2.IMAFriendlyObstruction? friendlyObstruction) => (super.noSuchMethod( - Invocation.method(#registerFriendlyObstruction, [ - friendlyObstruction, - ]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#registerFriendlyObstruction, [friendlyObstruction]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future unregisterAllFriendlyObstructions() => - (super.noSuchMethod( - Invocation.method(#unregisterAllFriendlyObstructions, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future unregisterAllFriendlyObstructions() => (super.noSuchMethod( + Invocation.method(#unregisterAllFriendlyObstructions, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAAdDisplayContainer pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdDisplayContainer); + _i2.IMAAdDisplayContainer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdDisplayContainer_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.IMAAdDisplayContainer); } /// A class which mocks [IMACompanionAdSlot]. /// /// See the documentation for Mockito's code generation for more information. -class MockIMACompanionAdSlot extends _i1.Mock - implements _i2.IMACompanionAdSlot { +class MockIMACompanionAdSlot extends _i1.Mock implements _i2.IMACompanionAdSlot { @override - _i2.UIView get view => - (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0(this, Invocation.getter(#view)), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) - as _i2.UIView); + _i2.UIView get view => (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.getter(#view)), + ) as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setDelegate(_i2.IMACompanionDelegate? delegate) => - (super.noSuchMethod( - Invocation.method(#setDelegate, [delegate]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setDelegate(_i2.IMACompanionDelegate? delegate) => (super.noSuchMethod( + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future width() => - (super.noSuchMethod( - Invocation.method(#width, []), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) - as _i3.Future); + _i3.Future width() => (super.noSuchMethod( + Invocation.method(#width, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) as _i3.Future); @override - _i3.Future height() => - (super.noSuchMethod( - Invocation.method(#height, []), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) - as _i3.Future); + _i3.Future height() => (super.noSuchMethod( + Invocation.method(#height, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) as _i3.Future); @override - _i2.IMACompanionAdSlot pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMACompanionAdSlot_3( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMACompanionAdSlot_3( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMACompanionAdSlot); + _i2.IMACompanionAdSlot pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMACompanionAdSlot_3(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMACompanionAdSlot_3(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMACompanionAdSlot); } /// A class which mocks [UIView]. @@ -224,34 +164,21 @@ class MockIMACompanionAdSlot extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockUIView extends _i1.Mock implements _i2.UIView { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.UIView pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeUIView_0( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.UIView); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.UIView pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIView_0(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.UIView); } /// A class which mocks [UIViewController]. @@ -259,59 +186,33 @@ class MockUIView extends _i1.Mock implements _i2.UIView { /// See the documentation for Mockito's code generation for more information. class MockUIViewController extends _i1.Mock implements _i2.UIViewController { @override - _i2.UIView get view => - (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0(this, Invocation.getter(#view)), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) - as _i2.UIView); + _i2.UIView get view => (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.getter(#view)), + ) as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i2.UIView pigeonVar_view() => - (super.noSuchMethod( - Invocation.method(#pigeonVar_view, []), - returnValue: _FakeUIView_0( - this, - Invocation.method(#pigeonVar_view, []), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method(#pigeonVar_view, []), - ), - ) - as _i2.UIView); + _i2.UIView pigeonVar_view() => (super.noSuchMethod( + Invocation.method(#pigeonVar_view, []), + returnValue: _FakeUIView_0(this, Invocation.method(#pigeonVar_view, [])), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.method(#pigeonVar_view, [])), + ) as _i2.UIView); @override - _i2.UIViewController pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeUIViewController_4( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeUIViewController_4( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.UIViewController); + _i2.UIViewController pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIViewController_4(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeUIViewController_4(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.UIViewController); } diff --git a/packages/interactive_media_ads/test/ios/ad_test.dart b/packages/interactive_media_ads/test/ios/ad_test.dart index 35606233097f..3a39a6cf3a8a 100644 --- a/packages/interactive_media_ads/test/ios/ad_test.dart +++ b/packages/interactive_media_ads/test/ios/ad_test.dart @@ -21,22 +21,12 @@ void main() { late final IMAAdsManagerDelegate delegate; PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - IMAAdsManagerDelegate, - IMAAdsManager, - IMAAdEvent, - ) + required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdEvent) didReceiveAdEvent, - required void Function( - IMAAdsManagerDelegate, - IMAAdsManager, - IMAAdError, - ) + required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdError) didReceiveAdError, - required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentPause, - required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentResume, + required void Function(IMAAdsManagerDelegate, IMAAdsManager) didRequestContentPause, + required void Function(IMAAdsManagerDelegate, IMAAdsManager) didRequestContentResume, }) { didReceiveAdEventCallback = didReceiveAdEvent; delegate = IMAAdsManagerDelegate.pigeon_detached( @@ -69,10 +59,7 @@ void main() { typeString: 'typeString', ad: createTestAd( universalAdIds: [ - IMAUniversalAdID.pigeon_detached( - adIDRegistry: 'unknown', - adIDValue: 'unknown', - ), + IMAUniversalAdID.pigeon_detached(adIDRegistry: 'unknown', adIDValue: 'unknown'), ], ), ), @@ -86,22 +73,12 @@ void main() { late final IMAAdsManagerDelegate delegate; PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - IMAAdsManagerDelegate, - IMAAdsManager, - IMAAdEvent, - ) + required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdEvent) didReceiveAdEvent, - required void Function( - IMAAdsManagerDelegate, - IMAAdsManager, - IMAAdError, - ) + required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdError) didReceiveAdError, - required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentPause, - required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentResume, + required void Function(IMAAdsManagerDelegate, IMAAdsManager) didRequestContentPause, + required void Function(IMAAdsManagerDelegate, IMAAdsManager) didRequestContentResume, }) { didReceiveAdEventCallback = didReceiveAdEvent; delegate = IMAAdsManagerDelegate.pigeon_detached( @@ -133,9 +110,7 @@ void main() { type: AdEventType.allAdsCompleted, typeString: 'typeString', ad: createTestAd( - companionAds: [ - IMACompanionAd.pigeon_detached(height: 0, width: 0), - ], + companionAds: [IMACompanionAd.pigeon_detached(height: 0, width: 0)], ), ), ); @@ -148,22 +123,12 @@ void main() { late final IMAAdsManagerDelegate delegate; PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - IMAAdsManagerDelegate, - IMAAdsManager, - IMAAdEvent, - ) + required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdEvent) didReceiveAdEvent, - required void Function( - IMAAdsManagerDelegate, - IMAAdsManager, - IMAAdError, - ) + required void Function(IMAAdsManagerDelegate, IMAAdsManager, IMAAdError) didReceiveAdError, - required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentPause, - required void Function(IMAAdsManagerDelegate, IMAAdsManager) - didRequestContentResume, + required void Function(IMAAdsManagerDelegate, IMAAdsManager) didRequestContentPause, + required void Function(IMAAdsManagerDelegate, IMAAdsManager) didRequestContentResume, }) { didReceiveAdEventCallback = didReceiveAdEvent; delegate = IMAAdsManagerDelegate.pigeon_detached( diff --git a/packages/interactive_media_ads/test/ios/ads_loader_test.dart b/packages/interactive_media_ads/test/ios/ads_loader_test.dart index 92c1b09c0e39..9305a836595b 100644 --- a/packages/interactive_media_ads/test/ios/ads_loader_test.dart +++ b/packages/interactive_media_ads/test/ios/ads_loader_test.dart @@ -4,8 +4,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/ios/ios_ad_display_container.dart'; import 'package:interactive_media_ads/src/ios/ios_ads_loader.dart'; import 'package:interactive_media_ads/src/ios/ios_content_progress_provider.dart'; @@ -37,9 +36,7 @@ void main() { }); testWidgets('instantiate IOSAdsLoader', (WidgetTester tester) async { - final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer(tester); IOSAdsLoader( IOSAdsLoaderCreationParams( @@ -52,15 +49,12 @@ void main() { }); testWidgets('contentComplete', (WidgetTester tester) async { - final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer(tester); ima.PigeonOverrides.iMASettings_new = () => MockIMASettings(); final mockLoader = MockIMAAdsLoader(); - ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => - mockLoader; + ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => mockLoader; final loader = IOSAdsLoader( IOSAdsLoaderCreationParams( @@ -76,9 +70,7 @@ void main() { }); testWidgets('requestAds', (WidgetTester tester) async { - final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer(tester); ima.PigeonOverrides.iMASettings_new = () => MockIMASettings(); @@ -87,10 +79,8 @@ void main() { final mockLoader = MockIMAAdsLoader(); final contentPlayheadInstance = ima.IMAContentPlayhead(); final mockRequest = MockIMAAdsRequest(); - ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => - mockLoader; - ima.PigeonOverrides.iMAContentPlayhead_new = () => - contentPlayheadInstance; + ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => mockLoader; + ima.PigeonOverrides.iMAContentPlayhead_new = () => contentPlayheadInstance; ima.PigeonOverrides.iMAAdsRequest_new = ({ @@ -145,28 +135,17 @@ void main() { }); testWidgets('onAdsLoaded', (WidgetTester tester) async { - final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer(tester); ima.PigeonOverrides.iMASettings_new = () => MockIMASettings(); - late final void Function( - ima.IMAAdsLoaderDelegate, - ima.IMAAdsLoader, - ima.IMAAdsLoadedData, - ) + late final void Function(ima.IMAAdsLoaderDelegate, ima.IMAAdsLoader, ima.IMAAdsLoadedData) adLoaderLoadedWithCallback; - ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => - MockIMAAdsLoader(); + ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => MockIMAAdsLoader(); ima.PigeonOverrides.iMAAdsLoaderDelegate_new = ({ - required void Function( - ima.IMAAdsLoaderDelegate, - ima.IMAAdsLoader, - ima.IMAAdsLoadedData, - ) + required void Function(ima.IMAAdsLoaderDelegate, ima.IMAAdsLoader, ima.IMAAdsLoadedData) adLoaderLoadedWith, required dynamic adsLoaderFailedWithErrorData, }) { @@ -193,9 +172,7 @@ void main() { }); testWidgets('onAdsLoadError', (WidgetTester tester) async { - final IOSAdDisplayContainer container = await _pumpAdDisplayContainer( - tester, - ); + final IOSAdDisplayContainer container = await _pumpAdDisplayContainer(tester); ima.PigeonOverrides.iMASettings_new = () => MockIMASettings(); @@ -206,8 +183,7 @@ void main() { ) adsLoaderFailedWithErrorDataCallback; - ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => - MockIMAAdsLoader(); + ima.PigeonOverrides.iMAAdsLoader_new = ({ima.IMASettings? settings}) => MockIMAAdsLoader(); ima.PigeonOverrides.iMAAdsLoaderDelegate_new = ({ required dynamic adLoaderLoadedWith, @@ -250,9 +226,7 @@ void main() { }); } -Future _pumpAdDisplayContainer( - WidgetTester tester, -) async { +Future _pumpAdDisplayContainer(WidgetTester tester) async { ima.PigeonOverrides.uIViewController_new = ({void Function(ima.UIViewController, bool)? viewDidAppear}) { final view = ima.UIView.pigeon_detached(); @@ -263,20 +237,17 @@ Future _pumpAdDisplayContainer( when(mockController.view).thenReturn(view); return mockController; }; - ima.PigeonOverrides.iMAAdDisplayContainer_new = - ({ - required ima.UIView adContainer, - ima.UIViewController? adContainerViewController, - List? companionSlots, - }) => MockIMAAdDisplayContainer(); + ima.PigeonOverrides.iMAAdDisplayContainer_new = ({ + required ima.UIView adContainer, + ima.UIViewController? adContainerViewController, + List? companionSlots, + }) => MockIMAAdDisplayContainer(); final container = IOSAdDisplayContainer( IOSAdDisplayContainerCreationParams(onContainerAdded: expectAsync1((_) {})), ); - await tester.pumpWidget( - Builder(builder: (BuildContext context) => container.build(context)), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => container.build(context))); final view = find.byType(UiKitView).evaluate().single.widget as UiKitView; view.onPlatformViewCreated!.call(0); diff --git a/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart b/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart index 1bbc281316aa..f07a40065811 100644 --- a/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ads_loader_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -25,29 +24,24 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: invalid_use_of_internal_member class _FakeUIView_0 extends _i1.SmartFake implements _i2.UIView { - _FakeUIView_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeUIView_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePigeonInstanceManager_1 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_1 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIMAAdDisplayContainer_2 extends _i1.SmartFake - implements _i2.IMAAdDisplayContainer { +class _FakeIMAAdDisplayContainer_2 extends _i1.SmartFake implements _i2.IMAAdDisplayContainer { _FakeIMAAdDisplayContainer_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeIMAAdsLoader_3 extends _i1.SmartFake implements _i2.IMAAdsLoader { - _FakeIMAAdsLoader_3(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeIMAAdsLoader_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIMAAdsLoaderDelegate_4 extends _i1.SmartFake - implements _i2.IMAAdsLoaderDelegate { +class _FakeIMAAdsLoaderDelegate_4 extends _i1.SmartFake implements _i2.IMAAdsLoaderDelegate { _FakeIMAAdsLoaderDelegate_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -63,12 +57,10 @@ class _FakeIMAAdsRequest_6 extends _i1.SmartFake implements _i2.IMAAdsRequest { } class _FakeIMASettings_7 extends _i1.SmartFake implements _i2.IMASettings { - _FakeIMASettings_7(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeIMASettings_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeUIViewController_8 extends _i1.SmartFake - implements _i2.UIViewController { +class _FakeUIViewController_8 extends _i1.SmartFake implements _i2.UIViewController { _FakeUIViewController_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -76,92 +68,63 @@ class _FakeUIViewController_8 extends _i1.SmartFake /// A class which mocks [IMAAdDisplayContainer]. /// /// See the documentation for Mockito's code generation for more information. -class MockIMAAdDisplayContainer extends _i1.Mock - implements _i2.IMAAdDisplayContainer { +class MockIMAAdDisplayContainer extends _i1.Mock implements _i2.IMAAdDisplayContainer { @override - _i2.UIView get adContainer => - (super.noSuchMethod( - Invocation.getter(#adContainer), - returnValue: _FakeUIView_0(this, Invocation.getter(#adContainer)), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#adContainer), - ), - ) - as _i2.UIView); + _i2.UIView get adContainer => (super.noSuchMethod( + Invocation.getter(#adContainer), + returnValue: _FakeUIView_0(this, Invocation.getter(#adContainer)), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.getter(#adContainer)), + ) as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i3.Future setAdContainerViewController( - _i2.UIViewController? controller, - ) => - (super.noSuchMethod( - Invocation.method(#setAdContainerViewController, [controller]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future<_i2.UIViewController?> getAdContainerViewController() => + _i3.Future setAdContainerViewController(_i2.UIViewController? controller) => (super.noSuchMethod( - Invocation.method(#getAdContainerViewController, []), - returnValue: _i3.Future<_i2.UIViewController?>.value(), - returnValueForMissingStub: - _i3.Future<_i2.UIViewController?>.value(), - ) - as _i3.Future<_i2.UIViewController?>); + Invocation.method(#setAdContainerViewController, [controller]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future registerFriendlyObstruction( - _i2.IMAFriendlyObstruction? friendlyObstruction, - ) => - (super.noSuchMethod( - Invocation.method(#registerFriendlyObstruction, [ - friendlyObstruction, - ]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future<_i2.UIViewController?> getAdContainerViewController() => (super.noSuchMethod( + Invocation.method(#getAdContainerViewController, []), + returnValue: _i3.Future<_i2.UIViewController?>.value(), + returnValueForMissingStub: _i3.Future<_i2.UIViewController?>.value(), + ) as _i3.Future<_i2.UIViewController?>); @override - _i3.Future unregisterAllFriendlyObstructions() => + _i3.Future registerFriendlyObstruction(_i2.IMAFriendlyObstruction? friendlyObstruction) => (super.noSuchMethod( - Invocation.method(#unregisterAllFriendlyObstructions, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#registerFriendlyObstruction, [friendlyObstruction]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAAdDisplayContainer pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdDisplayContainer); + _i3.Future unregisterAllFriendlyObstructions() => (super.noSuchMethod( + Invocation.method(#unregisterAllFriendlyObstructions, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); + + @override + _i2.IMAAdDisplayContainer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdDisplayContainer_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdDisplayContainer_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.IMAAdDisplayContainer); } /// A class which mocks [IMAAdsLoader]. @@ -169,153 +132,99 @@ class MockIMAAdDisplayContainer extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockIMAAdsLoader extends _i1.Mock implements _i2.IMAAdsLoader { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i3.Future contentComplete() => - (super.noSuchMethod( - Invocation.method(#contentComplete, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future requestAds(_i2.IMAAdsRequest? request) => - (super.noSuchMethod( - Invocation.method(#requestAds, [request]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future contentComplete() => (super.noSuchMethod( + Invocation.method(#contentComplete, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setDelegate(_i2.IMAAdsLoaderDelegate? delegate) => - (super.noSuchMethod( - Invocation.method(#setDelegate, [delegate]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future requestAds(_i2.IMAAdsRequest? request) => (super.noSuchMethod( + Invocation.method(#requestAds, [request]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAAdsLoader pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdsLoader_3( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdsLoader_3( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdsLoader); + _i3.Future setDelegate(_i2.IMAAdsLoaderDelegate? delegate) => (super.noSuchMethod( + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); + + @override + _i2.IMAAdsLoader pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsLoader_3(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdsLoader_3(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMAAdsLoader); } /// A class which mocks [IMAAdsLoaderDelegate]. /// /// See the documentation for Mockito's code generation for more information. -class MockIMAAdsLoaderDelegate extends _i1.Mock - implements _i2.IMAAdsLoaderDelegate { - @override - void Function( - _i2.IMAAdsLoaderDelegate, - _i2.IMAAdsLoader, - _i2.IMAAdsLoadedData, - ) - get adLoaderLoadedWith => - (super.noSuchMethod( - Invocation.getter(#adLoaderLoadedWith), - returnValue: - ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdsLoadedData adsLoadedData, - ) {}, - returnValueForMissingStub: - ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdsLoadedData adsLoadedData, - ) {}, - ) - as void Function( - _i2.IMAAdsLoaderDelegate, - _i2.IMAAdsLoader, - _i2.IMAAdsLoadedData, - )); - - @override - void Function( - _i2.IMAAdsLoaderDelegate, - _i2.IMAAdsLoader, - _i2.IMAAdLoadingErrorData, - ) - get adsLoaderFailedWithErrorData => - (super.noSuchMethod( - Invocation.getter(#adsLoaderFailedWithErrorData), - returnValue: - ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdLoadingErrorData adErrorData, - ) {}, - returnValueForMissingStub: - ( - _i2.IMAAdsLoaderDelegate pigeon_instance, - _i2.IMAAdsLoader loader, - _i2.IMAAdLoadingErrorData adErrorData, - ) {}, - ) - as void Function( - _i2.IMAAdsLoaderDelegate, - _i2.IMAAdsLoader, - _i2.IMAAdLoadingErrorData, - )); - - @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.IMAAdsLoaderDelegate pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdsLoaderDelegate_4( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdsLoaderDelegate_4( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdsLoaderDelegate); +class MockIMAAdsLoaderDelegate extends _i1.Mock implements _i2.IMAAdsLoaderDelegate { + @override + void Function(_i2.IMAAdsLoaderDelegate, _i2.IMAAdsLoader, _i2.IMAAdsLoadedData) + get adLoaderLoadedWith => (super.noSuchMethod( + Invocation.getter(#adLoaderLoadedWith), + returnValue: ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdsLoadedData adsLoadedData, + ) {}, + returnValueForMissingStub: ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdsLoadedData adsLoadedData, + ) {}, + ) as void Function(_i2.IMAAdsLoaderDelegate, _i2.IMAAdsLoader, _i2.IMAAdsLoadedData)); + + @override + void Function(_i2.IMAAdsLoaderDelegate, _i2.IMAAdsLoader, _i2.IMAAdLoadingErrorData) + get adsLoaderFailedWithErrorData => (super.noSuchMethod( + Invocation.getter(#adsLoaderFailedWithErrorData), + returnValue: ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdLoadingErrorData adErrorData, + ) {}, + returnValueForMissingStub: ( + _i2.IMAAdsLoaderDelegate pigeon_instance, + _i2.IMAAdsLoader loader, + _i2.IMAAdLoadingErrorData adErrorData, + ) {}, + ) as void Function(_i2.IMAAdsLoaderDelegate, _i2.IMAAdsLoader, _i2.IMAAdLoadingErrorData)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.IMAAdsLoaderDelegate pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsLoaderDelegate_4(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdsLoaderDelegate_4( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.IMAAdsLoaderDelegate); } /// A class which mocks [IMAAdsManager]. @@ -323,117 +232,85 @@ class MockIMAAdsLoaderDelegate extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockIMAAdsManager extends _i1.Mock implements _i2.IMAAdsManager { @override - List get adCuePoints => - (super.noSuchMethod( - Invocation.getter(#adCuePoints), - returnValue: [], - returnValueForMissingStub: [], - ) - as List); + List get adCuePoints => (super.noSuchMethod( + Invocation.getter(#adCuePoints), + returnValue: [], + returnValueForMissingStub: [], + ) as List); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i3.Future setDelegate(_i2.IMAAdsManagerDelegate? delegate) => - (super.noSuchMethod( - Invocation.method(#setDelegate, [delegate]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future initialize( - _i2.IMAAdsRenderingSettings? adsRenderingSettings, - ) => - (super.noSuchMethod( - Invocation.method(#initialize, [adsRenderingSettings]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setDelegate(_i2.IMAAdsManagerDelegate? delegate) => (super.noSuchMethod( + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future start() => + _i3.Future initialize(_i2.IMAAdsRenderingSettings? adsRenderingSettings) => (super.noSuchMethod( - Invocation.method(#start, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#initialize, [adsRenderingSettings]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future pause() => - (super.noSuchMethod( - Invocation.method(#pause, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future start() => (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future resume() => - (super.noSuchMethod( - Invocation.method(#resume, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future skip() => - (super.noSuchMethod( - Invocation.method(#skip, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future resume() => (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future discardAdBreak() => - (super.noSuchMethod( - Invocation.method(#discardAdBreak, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future skip() => (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future destroy() => - (super.noSuchMethod( - Invocation.method(#destroy, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future discardAdBreak() => (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAAdsManager pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdsManager_5( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdsManager_5( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdsManager); + _i3.Future destroy() => (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); + + @override + _i2.IMAAdsManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsManager_5(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdsManager_5(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMAAdsManager); } /// A class which mocks [IMAAdsRequest]. @@ -441,153 +318,109 @@ class MockIMAAdsManager extends _i1.Mock implements _i2.IMAAdsManager { /// See the documentation for Mockito's code generation for more information. class MockIMAAdsRequest extends _i1.Mock implements _i2.IMAAdsRequest { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i3.Future getAdTagUrl() => - (super.noSuchMethod( - Invocation.method(#getAdTagUrl, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future getAdsResponse() => - (super.noSuchMethod( - Invocation.method(#getAdsResponse, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future getAdTagUrl() => (super.noSuchMethod( + Invocation.method(#getAdTagUrl, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future<_i2.IMAAdDisplayContainer> getAdDisplayContainer() => - (super.noSuchMethod( - Invocation.method(#getAdDisplayContainer, []), - returnValue: _i3.Future<_i2.IMAAdDisplayContainer>.value( - _FakeIMAAdDisplayContainer_2( - this, - Invocation.method(#getAdDisplayContainer, []), - ), - ), - returnValueForMissingStub: - _i3.Future<_i2.IMAAdDisplayContainer>.value( - _FakeIMAAdDisplayContainer_2( - this, - Invocation.method(#getAdDisplayContainer, []), - ), - ), - ) - as _i3.Future<_i2.IMAAdDisplayContainer>); - - @override - _i3.Future setAdWillAutoPlay(bool? adWillAutoPlay) => - (super.noSuchMethod( - Invocation.method(#setAdWillAutoPlay, [adWillAutoPlay]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future getAdsResponse() => (super.noSuchMethod( + Invocation.method(#getAdsResponse, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setAdWillPlayMuted(bool? adWillPlayMuted) => - (super.noSuchMethod( - Invocation.method(#setAdWillPlayMuted, [adWillPlayMuted]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future<_i2.IMAAdDisplayContainer> getAdDisplayContainer() => (super.noSuchMethod( + Invocation.method(#getAdDisplayContainer, []), + returnValue: _i3.Future<_i2.IMAAdDisplayContainer>.value( + _FakeIMAAdDisplayContainer_2(this, Invocation.method(#getAdDisplayContainer, [])), + ), + returnValueForMissingStub: _i3.Future<_i2.IMAAdDisplayContainer>.value( + _FakeIMAAdDisplayContainer_2(this, Invocation.method(#getAdDisplayContainer, [])), + ), + ) as _i3.Future<_i2.IMAAdDisplayContainer>); @override - _i3.Future setContinuousPlayback(bool? continuousPlayback) => - (super.noSuchMethod( - Invocation.method(#setContinuousPlayback, [continuousPlayback]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setAdWillAutoPlay(bool? adWillAutoPlay) => (super.noSuchMethod( + Invocation.method(#setAdWillAutoPlay, [adWillAutoPlay]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setContentDuration(double? duration) => - (super.noSuchMethod( - Invocation.method(#setContentDuration, [duration]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setAdWillPlayMuted(bool? adWillPlayMuted) => (super.noSuchMethod( + Invocation.method(#setAdWillPlayMuted, [adWillPlayMuted]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setContentKeywords(List? keywords) => - (super.noSuchMethod( - Invocation.method(#setContentKeywords, [keywords]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setContinuousPlayback(bool? continuousPlayback) => (super.noSuchMethod( + Invocation.method(#setContinuousPlayback, [continuousPlayback]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setContentTitle(String? title) => - (super.noSuchMethod( - Invocation.method(#setContentTitle, [title]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setContentDuration(double? duration) => (super.noSuchMethod( + Invocation.method(#setContentDuration, [duration]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setContentURL(String? contentURL) => - (super.noSuchMethod( - Invocation.method(#setContentURL, [contentURL]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setContentKeywords(List? keywords) => (super.noSuchMethod( + Invocation.method(#setContentKeywords, [keywords]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setVastLoadTimeout(double? timeout) => - (super.noSuchMethod( - Invocation.method(#setVastLoadTimeout, [timeout]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setContentTitle(String? title) => (super.noSuchMethod( + Invocation.method(#setContentTitle, [title]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setLiveStreamPrefetchSeconds(double? seconds) => - (super.noSuchMethod( - Invocation.method(#setLiveStreamPrefetchSeconds, [seconds]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setContentURL(String? contentURL) => (super.noSuchMethod( + Invocation.method(#setContentURL, [contentURL]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAAdsRequest pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdsRequest_6( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdsRequest_6( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdsRequest); + _i3.Future setVastLoadTimeout(double? timeout) => (super.noSuchMethod( + Invocation.method(#setVastLoadTimeout, [timeout]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); + + @override + _i3.Future setLiveStreamPrefetchSeconds(double? seconds) => (super.noSuchMethod( + Invocation.method(#setLiveStreamPrefetchSeconds, [seconds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); + + @override + _i2.IMAAdsRequest pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsRequest_6(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdsRequest_6(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMAAdsRequest); } /// A class which mocks [IMASettings]. @@ -595,142 +428,105 @@ class MockIMAAdsRequest extends _i1.Mock implements _i2.IMAAdsRequest { /// See the documentation for Mockito's code generation for more information. class MockIMASettings extends _i1.Mock implements _i2.IMASettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i3.Future setPPID(String? ppid) => - (super.noSuchMethod( - Invocation.method(#setPPID, [ppid]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setLanguage(String? language) => - (super.noSuchMethod( - Invocation.method(#setLanguage, [language]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPPID(String? ppid) => (super.noSuchMethod( + Invocation.method(#setPPID, [ppid]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setMaxRedirects(int? max) => - (super.noSuchMethod( - Invocation.method(#setMaxRedirects, [max]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setLanguage(String? language) => (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setFeatureFlags(Map? flags) => - (super.noSuchMethod( - Invocation.method(#setFeatureFlags, [flags]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setMaxRedirects(int? max) => (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [max]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setEnableBackgroundPlayback(bool? enabled) => - (super.noSuchMethod( - Invocation.method(#setEnableBackgroundPlayback, [enabled]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setFeatureFlags(Map? flags) => (super.noSuchMethod( + Invocation.method(#setFeatureFlags, [flags]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => - (super.noSuchMethod( - Invocation.method(#setAutoPlayAdBreaks, [autoPlay]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setEnableBackgroundPlayback(bool? enabled) => (super.noSuchMethod( + Invocation.method(#setEnableBackgroundPlayback, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setDisableNowPlayingInfo(bool? disable) => - (super.noSuchMethod( - Invocation.method(#setDisableNowPlayingInfo, [disable]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => (super.noSuchMethod( + Invocation.method(#setAutoPlayAdBreaks, [autoPlay]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPlayerType(String? type) => - (super.noSuchMethod( - Invocation.method(#setPlayerType, [type]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setDisableNowPlayingInfo(bool? disable) => (super.noSuchMethod( + Invocation.method(#setDisableNowPlayingInfo, [disable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPlayerVersion(String? version) => - (super.noSuchMethod( - Invocation.method(#setPlayerVersion, [version]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPlayerType(String? type) => (super.noSuchMethod( + Invocation.method(#setPlayerType, [type]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setSessionID(String? sessionID) => - (super.noSuchMethod( - Invocation.method(#setSessionID, [sessionID]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPlayerVersion(String? version) => (super.noSuchMethod( + Invocation.method(#setPlayerVersion, [version]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setSameAppKeyEnabled(bool? enabled) => - (super.noSuchMethod( - Invocation.method(#setSameAppKeyEnabled, [enabled]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setSessionID(String? sessionID) => (super.noSuchMethod( + Invocation.method(#setSessionID, [sessionID]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setEnableDebugMode(bool? enable) => - (super.noSuchMethod( - Invocation.method(#setEnableDebugMode, [enable]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setSameAppKeyEnabled(bool? enabled) => (super.noSuchMethod( + Invocation.method(#setSameAppKeyEnabled, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMASettings pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMASettings_7( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMASettings_7( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMASettings); + _i3.Future setEnableDebugMode(bool? enable) => (super.noSuchMethod( + Invocation.method(#setEnableDebugMode, [enable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); + + @override + _i2.IMASettings pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMASettings_7(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMASettings_7(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMASettings); } /// A class which mocks [UIView]. @@ -738,34 +534,21 @@ class MockIMASettings extends _i1.Mock implements _i2.IMASettings { /// See the documentation for Mockito's code generation for more information. class MockUIView extends _i1.Mock implements _i2.UIView { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.UIView pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeUIView_0( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.UIView); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.UIView pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIView_0(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.UIView); } /// A class which mocks [UIViewController]. @@ -773,59 +556,33 @@ class MockUIView extends _i1.Mock implements _i2.UIView { /// See the documentation for Mockito's code generation for more information. class MockUIViewController extends _i1.Mock implements _i2.UIViewController { @override - _i2.UIView get view => - (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0(this, Invocation.getter(#view)), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) - as _i2.UIView); + _i2.UIView get view => (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.getter(#view)), + ) as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); - - @override - _i2.UIView pigeonVar_view() => - (super.noSuchMethod( - Invocation.method(#pigeonVar_view, []), - returnValue: _FakeUIView_0( - this, - Invocation.method(#pigeonVar_view, []), - ), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.method(#pigeonVar_view, []), - ), - ) - as _i2.UIView); - - @override - _i2.UIViewController pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeUIViewController_8( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeUIViewController_8( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.UIViewController); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.UIView pigeonVar_view() => (super.noSuchMethod( + Invocation.method(#pigeonVar_view, []), + returnValue: _FakeUIView_0(this, Invocation.method(#pigeonVar_view, [])), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.method(#pigeonVar_view, [])), + ) as _i2.UIView); + + @override + _i2.UIViewController pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeUIViewController_8(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeUIViewController_8(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.UIViewController); } diff --git a/packages/interactive_media_ads/test/ios/ads_manager_delegate_test.dart b/packages/interactive_media_ads/test/ios/ads_manager_delegate_test.dart index ec89c1753833..7bc285fb5292 100644 --- a/packages/interactive_media_ads/test/ios/ads_manager_delegate_test.dart +++ b/packages/interactive_media_ads/test/ios/ads_manager_delegate_test.dart @@ -3,8 +3,7 @@ // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/ios/ios_ads_manager_delegate.dart'; import 'package:interactive_media_ads/src/platform_interface/platform_interface.dart'; @@ -15,27 +14,15 @@ void main() { group('IOSAdsManagerDelegate', () { test('didReceiveAdEvent calls onAdEvent', () { - late final void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdEvent, - ) + late final void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent) didReceiveAdEventCallback; late final ima.IMAAdsManagerDelegate delegate; ima.PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdEvent, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent) didReceiveAdEvent, - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdError, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError) didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) didRequestContentPause, @@ -83,17 +70,9 @@ void main() { late final ima.IMAAdsManagerDelegate delegate; ima.PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdEvent, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent) didReceiveAdEvent, - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdError, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError) didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) didRequestContentPause, @@ -135,17 +114,9 @@ void main() { late final ima.IMAAdsManagerDelegate delegate; ima.PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdEvent, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent) didReceiveAdEvent, - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdError, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError) didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) didRequestContentPause, @@ -181,27 +152,15 @@ void main() { }); test('didReceiveAdError calls onAdErrorEvent', () { - late final void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdError, - ) + late final void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError) didReceiveAdErrorCallback; late final ima.IMAAdsManagerDelegate delegate; ima.PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdEvent, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent) didReceiveAdEvent, - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdError, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError) didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) didRequestContentPause, diff --git a/packages/interactive_media_ads/test/ios/ads_manager_test.dart b/packages/interactive_media_ads/test/ios/ads_manager_test.dart index e0ee2402eb3a..8ca9b9f4f724 100644 --- a/packages/interactive_media_ads/test/ios/ads_manager_test.dart +++ b/packages/interactive_media_ads/test/ios/ads_manager_test.dart @@ -3,8 +3,7 @@ // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as ima; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as ima; import 'package:interactive_media_ads/src/ios/ios_ads_manager.dart'; import 'package:interactive_media_ads/src/ios/ios_ads_manager_delegate.dart'; import 'package:interactive_media_ads/src/ios/ios_ads_rendering_settings.dart'; @@ -39,8 +38,7 @@ void main() { final adsManager = IOSAdsManager(mockAdsManager); - ima.PigeonOverrides.iMAAdsRenderingSettings_new = () => - mockAdsRenderingSettings; + ima.PigeonOverrides.iMAAdsRenderingSettings_new = () => mockAdsRenderingSettings; final settings = IOSAdsRenderingSettings( const IOSAdsRenderingSettingsCreationParams( @@ -60,9 +58,7 @@ void main() { mockAdsRenderingSettings.setLoadVideoTimeout(9.0), mockAdsRenderingSettings.setMimeTypes(['value']), mockAdsRenderingSettings.setPlayAdsAfterTime(5.0), - mockAdsRenderingSettings.setUIElements([ - ima.UIElementType.countdown, - ]), + mockAdsRenderingSettings.setUIElements([ima.UIElementType.countdown]), mockAdsManager.initialize(mockAdsRenderingSettings), ]); }); @@ -114,17 +110,9 @@ void main() { late final ima.IMAAdsManagerDelegate delegate; ima.PigeonOverrides.iMAAdsManagerDelegate_new = ({ - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdEvent, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdEvent) didReceiveAdEvent, - required void Function( - ima.IMAAdsManagerDelegate, - ima.IMAAdsManager, - ima.IMAAdError, - ) + required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager, ima.IMAAdError) didReceiveAdError, required void Function(ima.IMAAdsManagerDelegate, ima.IMAAdsManager) didRequestContentPause, diff --git a/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart b/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart index f85015f7e74c..22c3c9d26b01 100644 --- a/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ads_manager_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -24,8 +23,7 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -35,8 +33,7 @@ class _FakeIMAAdsManager_1 extends _i1.SmartFake implements _i2.IMAAdsManager { : super(parent, parentInvocation); } -class _FakeIMAAdsRenderingSettings_2 extends _i1.SmartFake - implements _i2.IMAAdsRenderingSettings { +class _FakeIMAAdsRenderingSettings_2 extends _i1.SmartFake implements _i2.IMAAdsRenderingSettings { _FakeIMAAdsRenderingSettings_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -46,216 +43,158 @@ class _FakeIMAAdsRenderingSettings_2 extends _i1.SmartFake /// See the documentation for Mockito's code generation for more information. class MockIMAAdsManager extends _i1.Mock implements _i2.IMAAdsManager { @override - List get adCuePoints => - (super.noSuchMethod( - Invocation.getter(#adCuePoints), - returnValue: [], - returnValueForMissingStub: [], - ) - as List); + List get adCuePoints => (super.noSuchMethod( + Invocation.getter(#adCuePoints), + returnValue: [], + returnValueForMissingStub: [], + ) as List); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setDelegate(_i2.IMAAdsManagerDelegate? delegate) => - (super.noSuchMethod( - Invocation.method(#setDelegate, [delegate]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setDelegate(_i2.IMAAdsManagerDelegate? delegate) => (super.noSuchMethod( + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future initialize( - _i2.IMAAdsRenderingSettings? adsRenderingSettings, - ) => + _i3.Future initialize(_i2.IMAAdsRenderingSettings? adsRenderingSettings) => (super.noSuchMethod( - Invocation.method(#initialize, [adsRenderingSettings]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#initialize, [adsRenderingSettings]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future start() => - (super.noSuchMethod( - Invocation.method(#start, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future start() => (super.noSuchMethod( + Invocation.method(#start, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future pause() => - (super.noSuchMethod( - Invocation.method(#pause, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future resume() => - (super.noSuchMethod( - Invocation.method(#resume, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future resume() => (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future skip() => - (super.noSuchMethod( - Invocation.method(#skip, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future skip() => (super.noSuchMethod( + Invocation.method(#skip, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future discardAdBreak() => - (super.noSuchMethod( - Invocation.method(#discardAdBreak, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future discardAdBreak() => (super.noSuchMethod( + Invocation.method(#discardAdBreak, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future destroy() => - (super.noSuchMethod( - Invocation.method(#destroy, []), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future destroy() => (super.noSuchMethod( + Invocation.method(#destroy, []), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAAdsManager pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdsManager_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdsManager_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdsManager); + _i2.IMAAdsManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsManager_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdsManager_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMAAdsManager); } /// A class which mocks [IMAAdsRenderingSettings]. /// /// See the documentation for Mockito's code generation for more information. -class MockIMAAdsRenderingSettings extends _i1.Mock - implements _i2.IMAAdsRenderingSettings { +class MockIMAAdsRenderingSettings extends _i1.Mock implements _i2.IMAAdsRenderingSettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setMimeTypes(List? types) => - (super.noSuchMethod( - Invocation.method(#setMimeTypes, [types]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setMimeTypes(List? types) => (super.noSuchMethod( + Invocation.method(#setMimeTypes, [types]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setBitrate(int? bitrate) => - (super.noSuchMethod( - Invocation.method(#setBitrate, [bitrate]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setBitrate(int? bitrate) => (super.noSuchMethod( + Invocation.method(#setBitrate, [bitrate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setLoadVideoTimeout(double? seconds) => - (super.noSuchMethod( - Invocation.method(#setLoadVideoTimeout, [seconds]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setLoadVideoTimeout(double? seconds) => (super.noSuchMethod( + Invocation.method(#setLoadVideoTimeout, [seconds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPlayAdsAfterTime(double? seconds) => - (super.noSuchMethod( - Invocation.method(#setPlayAdsAfterTime, [seconds]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPlayAdsAfterTime(double? seconds) => (super.noSuchMethod( + Invocation.method(#setPlayAdsAfterTime, [seconds]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setUIElements(List<_i2.UIElementType>? types) => - (super.noSuchMethod( - Invocation.method(#setUIElements, [types]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setUIElements(List<_i2.UIElementType>? types) => (super.noSuchMethod( + Invocation.method(#setUIElements, [types]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setEnablePreloading(bool? enable) => - (super.noSuchMethod( - Invocation.method(#setEnablePreloading, [enable]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setEnablePreloading(bool? enable) => (super.noSuchMethod( + Invocation.method(#setEnablePreloading, [enable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setLinkOpenerPresentingController( - _i2.UIViewController? controller, - ) => + _i3.Future setLinkOpenerPresentingController(_i2.UIViewController? controller) => (super.noSuchMethod( - Invocation.method(#setLinkOpenerPresentingController, [controller]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + Invocation.method(#setLinkOpenerPresentingController, [controller]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAAdsRenderingSettings pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAAdsRenderingSettings_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAAdsRenderingSettings_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAAdsRenderingSettings); + _i2.IMAAdsRenderingSettings pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAAdsRenderingSettings_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAAdsRenderingSettings_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.IMAAdsRenderingSettings); } diff --git a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart index ec907f117a04..0ac86fa30ff2 100644 --- a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart +++ b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.dart @@ -49,10 +49,8 @@ void main() { }; PigeonOverrides.iMACompanionDelegate_new = ({ - void Function(IMACompanionDelegate, IMACompanionAdSlot, bool)? - companionAdSlotFilled, - void Function(IMACompanionDelegate, IMACompanionAdSlot)? - companionSlotWasClicked, + void Function(IMACompanionDelegate, IMACompanionAdSlot, bool)? companionAdSlotFilled, + void Function(IMACompanionDelegate, IMACompanionAdSlot)? companionSlotWasClicked, }) { return IMACompanionDelegate.pigeon_detached( companionAdSlotFilled: companionAdSlotFilled, diff --git a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart index e26acc0349d3..0dc6061baa9f 100644 --- a/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/companion_ad_slot_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -25,18 +24,15 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: invalid_use_of_internal_member class _FakeUIView_0 extends _i1.SmartFake implements _i2.UIView { - _FakeUIView_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeUIView_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePigeonInstanceManager_1 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_1 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIMACompanionAdSlot_2 extends _i1.SmartFake - implements _i2.IMACompanionAdSlot { +class _FakeIMACompanionAdSlot_2 extends _i1.SmartFake implements _i2.IMACompanionAdSlot { _FakeIMACompanionAdSlot_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -44,74 +40,49 @@ class _FakeIMACompanionAdSlot_2 extends _i1.SmartFake /// A class which mocks [IMACompanionAdSlot]. /// /// See the documentation for Mockito's code generation for more information. -class MockIMACompanionAdSlot extends _i1.Mock - implements _i2.IMACompanionAdSlot { +class MockIMACompanionAdSlot extends _i1.Mock implements _i2.IMACompanionAdSlot { @override - _i2.UIView get view => - (super.noSuchMethod( - Invocation.getter(#view), - returnValue: _FakeUIView_0(this, Invocation.getter(#view)), - returnValueForMissingStub: _FakeUIView_0( - this, - Invocation.getter(#view), - ), - ) - as _i2.UIView); + _i2.UIView get view => (super.noSuchMethod( + Invocation.getter(#view), + returnValue: _FakeUIView_0(this, Invocation.getter(#view)), + returnValueForMissingStub: _FakeUIView_0(this, Invocation.getter(#view)), + ) as _i2.UIView); @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_1( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_1(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_1( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setDelegate(_i2.IMACompanionDelegate? delegate) => - (super.noSuchMethod( - Invocation.method(#setDelegate, [delegate]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setDelegate(_i2.IMACompanionDelegate? delegate) => (super.noSuchMethod( + Invocation.method(#setDelegate, [delegate]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future width() => - (super.noSuchMethod( - Invocation.method(#width, []), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) - as _i3.Future); + _i3.Future width() => (super.noSuchMethod( + Invocation.method(#width, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) as _i3.Future); @override - _i3.Future height() => - (super.noSuchMethod( - Invocation.method(#height, []), - returnValue: _i3.Future.value(0), - returnValueForMissingStub: _i3.Future.value(0), - ) - as _i3.Future); + _i3.Future height() => (super.noSuchMethod( + Invocation.method(#height, []), + returnValue: _i3.Future.value(0), + returnValueForMissingStub: _i3.Future.value(0), + ) as _i3.Future); @override - _i2.IMACompanionAdSlot pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMACompanionAdSlot_2( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMACompanionAdSlot_2( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMACompanionAdSlot); + _i2.IMACompanionAdSlot pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMACompanionAdSlot_2(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMACompanionAdSlot_2(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMACompanionAdSlot); } diff --git a/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart b/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart index 2ac35b1d2cb5..6e9ccfa6c530 100644 --- a/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/content_progress_provider_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -24,14 +23,12 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeIMAContentPlayhead_1 extends _i1.SmartFake - implements _i2.IMAContentPlayhead { +class _FakeIMAContentPlayhead_1 extends _i1.SmartFake implements _i2.IMAContentPlayhead { _FakeIMAContentPlayhead_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -39,44 +36,28 @@ class _FakeIMAContentPlayhead_1 extends _i1.SmartFake /// A class which mocks [IMAContentPlayhead]. /// /// See the documentation for Mockito's code generation for more information. -class MockIMAContentPlayhead extends _i1.Mock - implements _i2.IMAContentPlayhead { +class MockIMAContentPlayhead extends _i1.Mock implements _i2.IMAContentPlayhead { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setCurrentTime(double? timeInterval) => - (super.noSuchMethod( - Invocation.method(#setCurrentTime, [timeInterval]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setCurrentTime(double? timeInterval) => (super.noSuchMethod( + Invocation.method(#setCurrentTime, [timeInterval]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMAContentPlayhead pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMAContentPlayhead_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMAContentPlayhead_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMAContentPlayhead); + _i2.IMAContentPlayhead pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMAContentPlayhead_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMAContentPlayhead_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMAContentPlayhead); } diff --git a/packages/interactive_media_ads/test/ios/ima_settings_test.dart b/packages/interactive_media_ads/test/ios/ima_settings_test.dart index 5f7a2ca2170c..6f73b6172f56 100644 --- a/packages/interactive_media_ads/test/ios/ima_settings_test.dart +++ b/packages/interactive_media_ads/test/ios/ima_settings_test.dart @@ -22,9 +22,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const language = 'en'; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(language: language), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams(language: language)); // Trigger lazy initialization. // ignore: unnecessary_statements @@ -37,9 +35,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const autoPlayAdBreaks = true; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setAutoPlayAdBreaks(autoPlayAdBreaks); verify(mockIMASettings.setAutoPlayAdBreaks(autoPlayAdBreaks)); @@ -49,9 +45,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const debugMode = false; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setDebugMode(debugMode); verify(mockIMASettings.setEnableDebugMode(debugMode)); @@ -61,9 +55,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const featureFlags = {'a': 'flag'}; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setFeatureFlags(featureFlags); verify(mockIMASettings.setFeatureFlags(featureFlags)); @@ -73,9 +65,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const maxRedirects = 12; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setMaxRedirects(maxRedirects); verify(mockIMASettings.setMaxRedirects(maxRedirects)); @@ -85,9 +75,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const playerType = 'playerType'; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setPlayerType(playerType); verify(mockIMASettings.setPlayerType(playerType)); @@ -97,9 +85,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const playerVersion = 'playerVersion'; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setPlayerVersion(playerVersion); verify(mockIMASettings.setPlayerVersion(playerVersion)); @@ -109,9 +95,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const ppid = 'ppid'; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setPpid(ppid); verify(mockIMASettings.setPPID(ppid)); @@ -121,9 +105,7 @@ void main() { final MockIMASettings mockIMASettings = _mockIMASettings(); const sessionID = 'sessionID'; - final settings = IOSImaSettings( - const PlatformImaSettingsCreationParams(), - ); + final settings = IOSImaSettings(const PlatformImaSettingsCreationParams()); await settings.setSessionID(sessionID); verify(mockIMASettings.setSessionID(sessionID)); diff --git a/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart b/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart index 6eea733d94b9..5fbd670793bd 100644 --- a/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart +++ b/packages/interactive_media_ads/test/ios/ima_settings_test.mocks.dart @@ -5,8 +5,7 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; -import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' - as _i2; +import 'package:interactive_media_ads/src/ios/interactive_media_ads.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint @@ -24,15 +23,13 @@ import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakePigeonInstanceManager_0 extends _i1.SmartFake - implements _i2.PigeonInstanceManager { +class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeIMASettings_1 extends _i1.SmartFake implements _i2.IMASettings { - _FakeIMASettings_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeIMASettings_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [IMASettings]. @@ -40,140 +37,103 @@ class _FakeIMASettings_1 extends _i1.SmartFake implements _i2.IMASettings { /// See the documentation for Mockito's code generation for more information. class MockIMASettings extends _i1.Mock implements _i2.IMASettings { @override - _i2.PigeonInstanceManager get pigeon_instanceManager => - (super.noSuchMethod( - Invocation.getter(#pigeon_instanceManager), - returnValue: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - returnValueForMissingStub: _FakePigeonInstanceManager_0( - this, - Invocation.getter(#pigeon_instanceManager), - ), - ) - as _i2.PigeonInstanceManager); + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0(this, Invocation.getter(#pigeon_instanceManager)), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i3.Future setPPID(String? ppid) => - (super.noSuchMethod( - Invocation.method(#setPPID, [ppid]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPPID(String? ppid) => (super.noSuchMethod( + Invocation.method(#setPPID, [ppid]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setLanguage(String? language) => - (super.noSuchMethod( - Invocation.method(#setLanguage, [language]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setLanguage(String? language) => (super.noSuchMethod( + Invocation.method(#setLanguage, [language]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setMaxRedirects(int? max) => - (super.noSuchMethod( - Invocation.method(#setMaxRedirects, [max]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setMaxRedirects(int? max) => (super.noSuchMethod( + Invocation.method(#setMaxRedirects, [max]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setFeatureFlags(Map? flags) => - (super.noSuchMethod( - Invocation.method(#setFeatureFlags, [flags]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setFeatureFlags(Map? flags) => (super.noSuchMethod( + Invocation.method(#setFeatureFlags, [flags]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setEnableBackgroundPlayback(bool? enabled) => - (super.noSuchMethod( - Invocation.method(#setEnableBackgroundPlayback, [enabled]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setEnableBackgroundPlayback(bool? enabled) => (super.noSuchMethod( + Invocation.method(#setEnableBackgroundPlayback, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => - (super.noSuchMethod( - Invocation.method(#setAutoPlayAdBreaks, [autoPlay]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setAutoPlayAdBreaks(bool? autoPlay) => (super.noSuchMethod( + Invocation.method(#setAutoPlayAdBreaks, [autoPlay]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setDisableNowPlayingInfo(bool? disable) => - (super.noSuchMethod( - Invocation.method(#setDisableNowPlayingInfo, [disable]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setDisableNowPlayingInfo(bool? disable) => (super.noSuchMethod( + Invocation.method(#setDisableNowPlayingInfo, [disable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPlayerType(String? type) => - (super.noSuchMethod( - Invocation.method(#setPlayerType, [type]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPlayerType(String? type) => (super.noSuchMethod( + Invocation.method(#setPlayerType, [type]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setPlayerVersion(String? version) => - (super.noSuchMethod( - Invocation.method(#setPlayerVersion, [version]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setPlayerVersion(String? version) => (super.noSuchMethod( + Invocation.method(#setPlayerVersion, [version]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setSessionID(String? sessionID) => - (super.noSuchMethod( - Invocation.method(#setSessionID, [sessionID]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setSessionID(String? sessionID) => (super.noSuchMethod( + Invocation.method(#setSessionID, [sessionID]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setSameAppKeyEnabled(bool? enabled) => - (super.noSuchMethod( - Invocation.method(#setSameAppKeyEnabled, [enabled]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setSameAppKeyEnabled(bool? enabled) => (super.noSuchMethod( + Invocation.method(#setSameAppKeyEnabled, [enabled]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i3.Future setEnableDebugMode(bool? enable) => - (super.noSuchMethod( - Invocation.method(#setEnableDebugMode, [enable]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) - as _i3.Future); + _i3.Future setEnableDebugMode(bool? enable) => (super.noSuchMethod( + Invocation.method(#setEnableDebugMode, [enable]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) as _i3.Future); @override - _i2.IMASettings pigeon_copy() => - (super.noSuchMethod( - Invocation.method(#pigeon_copy, []), - returnValue: _FakeIMASettings_1( - this, - Invocation.method(#pigeon_copy, []), - ), - returnValueForMissingStub: _FakeIMASettings_1( - this, - Invocation.method(#pigeon_copy, []), - ), - ) - as _i2.IMASettings); + _i2.IMASettings pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeIMASettings_1(this, Invocation.method(#pigeon_copy, [])), + returnValueForMissingStub: _FakeIMASettings_1(this, Invocation.method(#pigeon_copy, [])), + ) as _i2.IMASettings); } diff --git a/packages/interactive_media_ads/test/test_stubs.dart b/packages/interactive_media_ads/test/test_stubs.dart index 60e319f6fed0..84f6a745b66f 100644 --- a/packages/interactive_media_ads/test/test_stubs.dart +++ b/packages/interactive_media_ads/test/test_stubs.dart @@ -5,8 +5,7 @@ import 'package:flutter/material.dart'; import 'package:interactive_media_ads/src/platform_interface/platform_interface.dart'; -final class TestInteractiveMediaAdsPlatform - extends InteractiveMediaAdsPlatform { +final class TestInteractiveMediaAdsPlatform extends InteractiveMediaAdsPlatform { TestInteractiveMediaAdsPlatform({ required this.onCreatePlatformAdsLoader, required this.onCreatePlatformAdsManagerDelegate, @@ -16,41 +15,28 @@ final class TestInteractiveMediaAdsPlatform this.onCreatePlatformCompanionAdSlot, }); - PlatformAdsLoader Function(PlatformAdsLoaderCreationParams params) - onCreatePlatformAdsLoader; + PlatformAdsLoader Function(PlatformAdsLoaderCreationParams params) onCreatePlatformAdsLoader; - PlatformAdsManagerDelegate Function( - PlatformAdsManagerDelegateCreationParams params, - ) + PlatformAdsManagerDelegate Function(PlatformAdsManagerDelegateCreationParams params) onCreatePlatformAdsManagerDelegate; - PlatformAdDisplayContainer Function( - PlatformAdDisplayContainerCreationParams params, - ) + PlatformAdDisplayContainer Function(PlatformAdDisplayContainerCreationParams params) onCreatePlatformAdDisplayContainer; - PlatformContentProgressProvider Function( - PlatformContentProgressProviderCreationParams params, - ) + PlatformContentProgressProvider Function(PlatformContentProgressProviderCreationParams params) onCreatePlatformContentProgressProvider; - PlatformAdsRenderingSettings Function( - PlatformAdsRenderingSettingsCreationParams params, - )? + PlatformAdsRenderingSettings Function(PlatformAdsRenderingSettingsCreationParams params)? onCreatePlatformAdsRenderingSettings; - PlatformCompanionAdSlot Function( - PlatformCompanionAdSlotCreationParams params, - )? + PlatformCompanionAdSlot Function(PlatformCompanionAdSlotCreationParams params)? onCreatePlatformCompanionAdSlot; PlatformImaSettings Function(PlatformImaSettingsCreationParams params)? onCreatePlatformImaSettings; @override - PlatformAdsLoader createPlatformAdsLoader( - PlatformAdsLoaderCreationParams params, - ) { + PlatformAdsLoader createPlatformAdsLoader(PlatformAdsLoaderCreationParams params) { return onCreatePlatformAdsLoader(params); } @@ -79,8 +65,7 @@ final class TestInteractiveMediaAdsPlatform PlatformAdsRenderingSettings createPlatformAdsRenderingSettings( PlatformAdsRenderingSettingsCreationParams params, ) { - return onCreatePlatformAdsRenderingSettings?.call(params) ?? - TestAdsRenderingSettings(params); + return onCreatePlatformAdsRenderingSettings?.call(params) ?? TestAdsRenderingSettings(params); } @override @@ -92,16 +77,13 @@ final class TestInteractiveMediaAdsPlatform } @override - PlatformImaSettings createPlatformImaSettings( - PlatformImaSettingsCreationParams params, - ) { + PlatformImaSettings createPlatformImaSettings(PlatformImaSettingsCreationParams params) { return onCreatePlatformImaSettings?.call(params) ?? TestImaSettings(params); } } final class TestPlatformAdDisplayContainer extends PlatformAdDisplayContainer { - TestPlatformAdDisplayContainer(super.params, {required this.onBuild}) - : super.implementation(); + TestPlatformAdDisplayContainer(super.params, {required this.onBuild}) : super.implementation(); Widget Function(BuildContext context) onBuild; @@ -112,11 +94,8 @@ final class TestPlatformAdDisplayContainer extends PlatformAdDisplayContainer { } final class TestPlatformAdsLoader extends PlatformAdsLoader { - TestPlatformAdsLoader( - super.params, { - required this.onContentComplete, - required this.onRequestAds, - }) : super.implementation(); + TestPlatformAdsLoader(super.params, {required this.onContentComplete, required this.onRequestAds}) + : super.implementation(); Future Function() onContentComplete; @@ -152,8 +131,7 @@ class TestAdsManager extends PlatformAdsManager { Future Function({PlatformAdsRenderingSettings? settings})? onInit; - Future Function(PlatformAdsManagerDelegate delegate)? - onSetAdsManagerDelegate; + Future Function(PlatformAdsManagerDelegate delegate)? onSetAdsManagerDelegate; Future Function(AdsManagerStartParams params)? onStart; @@ -173,9 +151,7 @@ class TestAdsManager extends PlatformAdsManager { } @override - Future setAdsManagerDelegate( - PlatformAdsManagerDelegate delegate, - ) async { + Future setAdsManagerDelegate(PlatformAdsManagerDelegate delegate) async { return onSetAdsManagerDelegate?.call(delegate); } @@ -211,20 +187,12 @@ class TestAdsManager extends PlatformAdsManager { } class TestContentProgressProvider extends PlatformContentProgressProvider { - TestContentProgressProvider(super.params, {this.onSetProgress}) - : super.implementation(); + TestContentProgressProvider(super.params, {this.onSetProgress}) : super.implementation(); - Future Function({ - required Duration progress, - required Duration duration, - })? - onSetProgress; + Future Function({required Duration progress, required Duration duration})? onSetProgress; @override - Future setProgress({ - required Duration progress, - required Duration duration, - }) async { + Future setProgress({required Duration progress, required Duration duration}) async { return onSetProgress?.call(progress: progress, duration: duration); } } @@ -234,8 +202,7 @@ final class TestAdsRenderingSettings extends PlatformAdsRenderingSettings { } final class TestCompanionAdSlot extends PlatformCompanionAdSlot { - TestCompanionAdSlot(super.params, {required this.onBuildWidget}) - : super.implementation(); + TestCompanionAdSlot(super.params, {required this.onBuildWidget}) : super.implementation(); Widget Function(BuildWidgetCreationParams params) onBuildWidget; diff --git a/packages/interactive_media_ads/test/version_test.dart b/packages/interactive_media_ads/test/version_test.dart index 176bd79af5bb..ca115f659f30 100644 --- a/packages/interactive_media_ads/test/version_test.dart +++ b/packages/interactive_media_ads/test/version_test.dart @@ -12,14 +12,9 @@ void main() { final adsRequestProxyApiPath = '${Directory.current.path}/android/src/main/kotlin/dev/flutter/packages/interactive_media_ads/AdsRequestProxyApi.kt'; - final String apiFileAsString = File( - adsRequestProxyApiPath, - ).readAsStringSync(); - - expect( - apiFileAsString, - contains('const val pluginVersion = "$pubspecVersion"'), - ); + final String apiFileAsString = File(adsRequestProxyApiPath).readAsStringSync(); + + expect(apiFileAsString, contains('const val pluginVersion = "$pubspecVersion"')); }); test('AdsRequestProxyAPIDelegate.pluginVersion matches pubspec version', () { @@ -27,14 +22,9 @@ void main() { final adsRequestProxyApiDelegatePath = '${Directory.current.path}/ios/interactive_media_ads/Sources/interactive_media_ads/AdsRequestProxyAPIDelegate.swift'; - final String apiFileAsString = File( - adsRequestProxyApiDelegatePath, - ).readAsStringSync(); - - expect( - apiFileAsString, - contains('static let pluginVersion = "$pubspecVersion"'), - ); + final String apiFileAsString = File(adsRequestProxyApiDelegatePath).readAsStringSync(); + + expect(apiFileAsString, contains('static let pluginVersion = "$pubspecVersion"')); }); } diff --git a/packages/local_auth/local_auth/example/lib/main.dart b/packages/local_auth/local_auth/example/lib/main.dart index 4dfc1b86b791..b09c3dcbeb4d 100644 --- a/packages/local_auth/local_auth/example/lib/main.dart +++ b/packages/local_auth/local_auth/example/lib/main.dart @@ -34,9 +34,7 @@ class _MyAppState extends State { super.initState(); auth.isDeviceSupported().then( (bool isSupported) => setState( - () => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported, + () => _supportState = isSupported ? _SupportState.supported : _SupportState.unsupported, ), ); } @@ -112,9 +110,7 @@ class _MyAppState extends State { return; } - setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', - ); + setState(() => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); } Future _authenticateWithBiometrics() async { @@ -125,8 +121,7 @@ class _MyAppState extends State { _authorized = 'Authenticating'; }); authenticated = await auth.authenticate( - localizedReason: - 'Scan your fingerprint (or face or whatever) to authenticate', + localizedReason: 'Scan your fingerprint (or face or whatever) to authenticate', persistAcrossBackgrounding: true, biometricOnly: true, ); @@ -187,10 +182,7 @@ class _MyAppState extends State { const Text('This device is not supported'), const Divider(height: 100), Text('Can check biometrics: $_canCheckBiometrics\n'), - ElevatedButton( - onPressed: _checkBiometrics, - child: const Text('Check biometrics'), - ), + ElevatedButton(onPressed: _checkBiometrics, child: const Text('Check biometrics')), const Divider(height: 100), Text('Available biometrics: $_availableBiometrics\n'), ElevatedButton( @@ -204,10 +196,7 @@ class _MyAppState extends State { onPressed: _cancelAuthentication, child: const Row( mainAxisSize: MainAxisSize.min, - children: [ - Text('Cancel Authentication'), - Icon(Icons.cancel), - ], + children: [Text('Cancel Authentication'), Icon(Icons.cancel)], ), ) else @@ -228,11 +217,7 @@ class _MyAppState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Text( - _isAuthenticating - ? 'Cancel' - : 'Authenticate: biometrics only', - ), + Text(_isAuthenticating ? 'Cancel' : 'Authenticate: biometrics only'), const Icon(Icons.fingerprint), ], ), diff --git a/packages/local_auth/local_auth/example/lib/readme_excerpts.dart b/packages/local_auth/local_auth/example/lib/readme_excerpts.dart index 928e4ee97554..28f242505caf 100644 --- a/packages/local_auth/local_auth/example/lib/readme_excerpts.dart +++ b/packages/local_auth/local_auth/example/lib/readme_excerpts.dart @@ -17,6 +17,7 @@ import 'package:local_auth/local_auth.dart'; // #docregion CustomMessages import 'package:local_auth_android/local_auth_android.dart'; import 'package:local_auth_darwin/local_auth_darwin.dart'; + // #enddocregion CustomMessages void main() { @@ -50,8 +51,7 @@ class _MyAppState extends State { Future checkSupport() async { // #docregion CanCheck final bool canAuthenticateWithBiometrics = await auth.canCheckBiometrics; - final bool canAuthenticate = - canAuthenticateWithBiometrics || await auth.isDeviceSupported(); + final bool canAuthenticate = canAuthenticateWithBiometrics || await auth.isDeviceSupported(); // #enddocregion CanCheck print('Can authenticate: $canAuthenticate'); @@ -60,8 +60,7 @@ class _MyAppState extends State { Future getEnrolledBiometrics() async { // #docregion Enrolled - final List availableBiometrics = await auth - .getAvailableBiometrics(); + final List availableBiometrics = await auth.getAvailableBiometrics(); if (availableBiometrics.isNotEmpty) { // Some biometrics are enrolled. diff --git a/packages/local_auth/local_auth/lib/src/local_auth.dart b/packages/local_auth/local_auth/lib/src/local_auth.dart index b2eddb823827..ba641e7d2141 100644 --- a/packages/local_auth/local_auth/lib/src/local_auth.dart +++ b/packages/local_auth/local_auth/lib/src/local_auth.dart @@ -82,13 +82,11 @@ class LocalAuthentication { } /// Returns true if device is capable of checking biometrics. - Future get canCheckBiometrics => - LocalAuthPlatform.instance.deviceSupportsBiometrics(); + Future get canCheckBiometrics => LocalAuthPlatform.instance.deviceSupportsBiometrics(); /// Returns true if device is capable of checking biometrics or is able to /// fail over to device credentials. - Future isDeviceSupported() async => - LocalAuthPlatform.instance.isDeviceSupported(); + Future isDeviceSupported() async => LocalAuthPlatform.instance.isDeviceSupported(); /// Returns a list of enrolled biometrics. Future> getAvailableBiometrics() => diff --git a/packages/local_auth/local_auth/test/local_auth_test.dart b/packages/local_auth/local_auth/test/local_auth_test.dart index 2f84804292f3..fc2e9059d2e0 100644 --- a/packages/local_auth/local_auth/test/local_auth_test.dart +++ b/packages/local_auth/local_auth/test/local_auth_test.dart @@ -46,39 +46,29 @@ void main() { }); test('isDeviceSupported calls platform implementation', () { - when( - mockLocalAuthPlatform.isDeviceSupported(), - ).thenAnswer((_) async => true); + when(mockLocalAuthPlatform.isDeviceSupported()).thenAnswer((_) async => true); localAuthentication.isDeviceSupported(); verify(mockLocalAuthPlatform.isDeviceSupported()).called(1); }); test('getEnrolledBiometrics calls platform implementation', () { - when( - mockLocalAuthPlatform.getEnrolledBiometrics(), - ).thenAnswer((_) async => []); + when(mockLocalAuthPlatform.getEnrolledBiometrics()).thenAnswer((_) async => []); localAuthentication.getAvailableBiometrics(); verify(mockLocalAuthPlatform.getEnrolledBiometrics()).called(1); }); test('stopAuthentication calls platform implementation', () { - when( - mockLocalAuthPlatform.stopAuthentication(), - ).thenAnswer((_) async => true); + when(mockLocalAuthPlatform.stopAuthentication()).thenAnswer((_) async => true); localAuthentication.stopAuthentication(); verify(mockLocalAuthPlatform.stopAuthentication()).called(1); }); test('canCheckBiometrics returns correct result', () async { - when( - mockLocalAuthPlatform.deviceSupportsBiometrics(), - ).thenAnswer((_) async => false); + when(mockLocalAuthPlatform.deviceSupportsBiometrics()).thenAnswer((_) async => false); bool? result; result = await localAuthentication.canCheckBiometrics; expect(result, false); - when( - mockLocalAuthPlatform.deviceSupportsBiometrics(), - ).thenAnswer((_) async => true); + when(mockLocalAuthPlatform.deviceSupportsBiometrics()).thenAnswer((_) async => true); result = await localAuthentication.canCheckBiometrics; expect(result, true); verify(mockLocalAuthPlatform.deviceSupportsBiometrics()).called(2); @@ -97,46 +87,36 @@ class MockLocalAuthPlatform extends Mock required String? localizedReason, required Iterable? authMessages, AuthenticationOptions? options = const AuthenticationOptions(), - }) => - super.noSuchMethod( - Invocation.method(#authenticate, [], { - #localizedReason: localizedReason, - #authMessages: authMessages, - #options: options, - }), - returnValue: Future.value(false), - ) - as Future; + }) => super.noSuchMethod( + Invocation.method(#authenticate, [], { + #localizedReason: localizedReason, + #authMessages: authMessages, + #options: options, + }), + returnValue: Future.value(false), + ) as Future; @override - Future> getEnrolledBiometrics() => - super.noSuchMethod( - Invocation.method(#getEnrolledBiometrics, []), - returnValue: Future>.value([]), - ) - as Future>; + Future> getEnrolledBiometrics() => super.noSuchMethod( + Invocation.method(#getEnrolledBiometrics, []), + returnValue: Future>.value([]), + ) as Future>; @override - Future isDeviceSupported() => - super.noSuchMethod( - Invocation.method(#isDeviceSupported, []), - returnValue: Future.value(false), - ) - as Future; + Future isDeviceSupported() => super.noSuchMethod( + Invocation.method(#isDeviceSupported, []), + returnValue: Future.value(false), + ) as Future; @override - Future stopAuthentication() => - super.noSuchMethod( - Invocation.method(#stopAuthentication, []), - returnValue: Future.value(false), - ) - as Future; + Future stopAuthentication() => super.noSuchMethod( + Invocation.method(#stopAuthentication, []), + returnValue: Future.value(false), + ) as Future; @override - Future deviceSupportsBiometrics() => - super.noSuchMethod( - Invocation.method(#deviceSupportsBiometrics, []), - returnValue: Future.value(false), - ) - as Future; + Future deviceSupportsBiometrics() => super.noSuchMethod( + Invocation.method(#deviceSupportsBiometrics, []), + returnValue: Future.value(false), + ) as Future; } diff --git a/packages/local_auth/local_auth_android/example/lib/main.dart b/packages/local_auth/local_auth_android/example/lib/main.dart index ed2cfea72162..9a5f35cb462b 100644 --- a/packages/local_auth/local_auth_android/example/lib/main.dart +++ b/packages/local_auth/local_auth_android/example/lib/main.dart @@ -34,9 +34,7 @@ class _MyAppState extends State { super.initState(); LocalAuthPlatform.instance.isDeviceSupported().then( (bool isSupported) => setState( - () => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported, + () => _supportState = isSupported ? _SupportState.supported : _SupportState.unsupported, ), ); } @@ -44,8 +42,7 @@ class _MyAppState extends State { Future _checkBiometrics() async { late bool deviceSupportsBiometrics; try { - deviceSupportsBiometrics = await LocalAuthPlatform.instance - .deviceSupportsBiometrics(); + deviceSupportsBiometrics = await LocalAuthPlatform.instance.deviceSupportsBiometrics(); } on PlatformException catch (e) { deviceSupportsBiometrics = false; print(e); @@ -62,8 +59,7 @@ class _MyAppState extends State { Future _getEnrolledBiometrics() async { late List availableBiometrics; try { - availableBiometrics = await LocalAuthPlatform.instance - .getEnrolledBiometrics(); + availableBiometrics = await LocalAuthPlatform.instance.getEnrolledBiometrics(); } on PlatformException catch (e) { availableBiometrics = []; print(e); @@ -114,9 +110,7 @@ class _MyAppState extends State { return; } - setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', - ); + setState(() => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); } Future _authenticateWithBiometrics() async { @@ -127,13 +121,9 @@ class _MyAppState extends State { _authorized = 'Authenticating'; }); authenticated = await LocalAuthPlatform.instance.authenticate( - localizedReason: - 'Scan your fingerprint (or face or whatever) to authenticate', + localizedReason: 'Scan your fingerprint (or face or whatever) to authenticate', authMessages: [const AndroidAuthMessages()], - options: const AuthenticationOptions( - stickyAuth: true, - biometricOnly: true, - ), + options: const AuthenticationOptions(stickyAuth: true, biometricOnly: true), ); setState(() { _isAuthenticating = false; @@ -190,13 +180,8 @@ class _MyAppState extends State { else const Text('This device is not supported'), const Divider(height: 100), - Text( - 'Device supports biometrics: $_deviceSupportsBiometrics\n', - ), - ElevatedButton( - onPressed: _checkBiometrics, - child: const Text('Check biometrics'), - ), + Text('Device supports biometrics: $_deviceSupportsBiometrics\n'), + ElevatedButton(onPressed: _checkBiometrics, child: const Text('Check biometrics')), const Divider(height: 100), Text('Enrolled biometrics: $_enrolledBiometrics\n'), ElevatedButton( @@ -210,10 +195,7 @@ class _MyAppState extends State { onPressed: _cancelAuthentication, child: const Row( mainAxisSize: MainAxisSize.min, - children: [ - Text('Cancel Authentication'), - Icon(Icons.cancel), - ], + children: [Text('Cancel Authentication'), Icon(Icons.cancel)], ), ) else @@ -234,11 +216,7 @@ class _MyAppState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Text( - _isAuthenticating - ? 'Cancel' - : 'Authenticate: biometrics only', - ), + Text(_isAuthenticating ? 'Cancel' : 'Authenticate: biometrics only'), const Icon(Icons.fingerprint), ], ), diff --git a/packages/local_auth/local_auth_android/lib/local_auth_android.dart b/packages/local_auth/local_auth_android/lib/local_auth_android.dart index 017eb07a897d..0cce6ca5c2b1 100644 --- a/packages/local_auth/local_auth_android/lib/local_auth_android.dart +++ b/packages/local_auth/local_auth_android/lib/local_auth_android.dart @@ -16,8 +16,7 @@ export 'package:local_auth_platform_interface/types/biometric_type.dart'; /// The implementation of [LocalAuthPlatform] for Android. class LocalAuthAndroid extends LocalAuthPlatform { /// Creates a new plugin implementation instance. - LocalAuthAndroid({@visibleForTesting LocalAuthApi? api}) - : _api = api ?? LocalAuthApi(); + LocalAuthAndroid({@visibleForTesting LocalAuthApi? api}) : _api = api ?? LocalAuthApi(); /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { @@ -48,19 +47,13 @@ class LocalAuthAndroid extends LocalAuthPlatform { case AuthResultCode.userCanceled: // Variants of user cancelation format are not currently distinguished, // but could be if there's a use case for it in the future. - throw const LocalAuthException( - code: LocalAuthExceptionCode.userCanceled, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.userCanceled); case AuthResultCode.systemCanceled: - throw const LocalAuthException( - code: LocalAuthExceptionCode.systemCanceled, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.systemCanceled); case AuthResultCode.timeout: throw const LocalAuthException(code: LocalAuthExceptionCode.timeout); case AuthResultCode.alreadyInProgress: - throw const LocalAuthException( - code: LocalAuthExceptionCode.authInProgress, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.authInProgress); case AuthResultCode.noActivity: throw const LocalAuthException( code: LocalAuthExceptionCode.uiUnavailable, @@ -72,29 +65,19 @@ class LocalAuthAndroid extends LocalAuthPlatform { description: 'The current Activity must be a FragmentActivity.', ); case AuthResultCode.noCredentials: - throw const LocalAuthException( - code: LocalAuthExceptionCode.noCredentialsSet, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.noCredentialsSet); case AuthResultCode.noHardware: - throw const LocalAuthException( - code: LocalAuthExceptionCode.noBiometricHardware, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.noBiometricHardware); case AuthResultCode.hardwareUnavailable: throw const LocalAuthException( code: LocalAuthExceptionCode.biometricHardwareTemporarilyUnavailable, ); case AuthResultCode.notEnrolled: - throw const LocalAuthException( - code: LocalAuthExceptionCode.noBiometricsEnrolled, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.noBiometricsEnrolled); case AuthResultCode.lockedOutTemporarily: - throw const LocalAuthException( - code: LocalAuthExceptionCode.temporaryLockout, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.temporaryLockout); case AuthResultCode.lockedOutPermanently: - throw const LocalAuthException( - code: LocalAuthExceptionCode.biometricLockout, - ); + throw const LocalAuthException(code: LocalAuthExceptionCode.biometricLockout); case AuthResultCode.noSpace: throw LocalAuthException( code: LocalAuthExceptionCode.deviceError, diff --git a/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart b/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart index b499f4963f94..19afa0186629 100644 --- a/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart +++ b/packages/local_auth/local_auth_android/lib/src/auth_messages_android.dart @@ -12,11 +12,7 @@ import 'package:local_auth_platform_interface/types/auth_messages.dart'; @immutable class AndroidAuthMessages extends AuthMessages { /// Constructs a new instance. - const AndroidAuthMessages({ - this.signInHint, - this.cancelButton, - this.signInTitle, - }); + const AndroidAuthMessages({this.signInHint, this.cancelButton, this.signInTitle}); /// Hint message advising the user how to authenticate. /// Maximum 60 characters. @@ -52,8 +48,7 @@ class AndroidAuthMessages extends AuthMessages { signInTitle == other.signInTitle; @override - int get hashCode => - Object.hash(super.hashCode, signInHint, cancelButton, signInTitle); + int get hashCode => Object.hash(super.hashCode, signInHint, cancelButton, signInTitle); } // Default strings for AndroidAuthMessages. Currently supports English. diff --git a/packages/local_auth/local_auth_android/lib/src/messages.g.dart b/packages/local_auth/local_auth_android/lib/src/messages.g.dart index a0f627154aee..dcb19cade273 100644 --- a/packages/local_auth/local_auth_android/lib/src/messages.g.dart +++ b/packages/local_auth/local_auth_android/lib/src/messages.g.dart @@ -40,9 +40,7 @@ Object? _extractReplyValueOrThrow( bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -190,10 +188,7 @@ class AuthResult { static AuthResult decode(Object result) { result as List; - return AuthResult( - code: result[0]! as AuthResultCode, - errorMessage: result[1] as String?, - ); + return AuthResult(code: result[0]! as AuthResultCode, errorMessage: result[1] as String?); } @override @@ -312,13 +307,11 @@ class LocalAuthApi { /// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - LocalAuthApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + LocalAuthApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -415,10 +408,7 @@ class LocalAuthApi { /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. - Future authenticate( - AuthOptions options, - AuthStrings strings, - ) async { + Future authenticate(AuthOptions options, AuthStrings strings) async { final pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_android.LocalAuthApi.authenticate$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -426,9 +416,10 @@ class LocalAuthApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [options, strings], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + options, + strings, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( diff --git a/packages/local_auth/local_auth_android/pigeons/messages.dart b/packages/local_auth/local_auth_android/pigeons/messages.dart index 11c29b377e0e..e4d30d77c615 100644 --- a/packages/local_auth/local_auth_android/pigeons/messages.dart +++ b/packages/local_auth/local_auth_android/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/localauth/Messages.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/localauth/Messages.kt', kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.localauth'), copyrightHeader: 'pigeons/copyright.txt', ), diff --git a/packages/local_auth/local_auth_android/test/local_auth_test.dart b/packages/local_auth/local_auth_android/test/local_auth_test.dart index ffc36392ade5..a05adc02b886 100644 --- a/packages/local_auth/local_auth_android/test/local_auth_test.dart +++ b/packages/local_auth/local_auth_android/test/local_auth_test.dart @@ -65,10 +65,7 @@ void main() { group('getEnrolledBiometrics', () { test('translates values', () async { when(api.getEnrolledBiometrics()).thenAnswer( - (_) async => [ - AuthClassification.weak, - AuthClassification.strong, - ], + (_) async => [AuthClassification.weak, AuthClassification.strong], ); final List result = await plugin.getEnrolledBiometrics(); @@ -77,9 +74,7 @@ void main() { }); test('handles empty', () async { - when( - api.getEnrolledBiometrics(), - ).thenAnswer((_) async => []); + when(api.getEnrolledBiometrics()).thenAnswer((_) async => []); final List result = await plugin.getEnrolledBiometrics(); @@ -110,14 +105,9 @@ void main() { ).thenAnswer((_) async => AuthResult(code: AuthResultCode.success)); const reason = 'test reason'; - await plugin.authenticate( - localizedReason: reason, - authMessages: [], - ); + await plugin.authenticate(localizedReason: reason, authMessages: []); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from @@ -127,31 +117,26 @@ void main() { expect(strings.signInTitle, androidSignInTitle); }); - test( - 'passes default values when only other platform values are provided', - () async { - when( - api.authenticate(any, any), - ).thenAnswer((_) async => AuthResult(code: AuthResultCode.success)); + test('passes default values when only other platform values are provided', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.success)); - const reason = 'test reason'; - await plugin.authenticate( - localizedReason: reason, - authMessages: [AnotherPlatformAuthMessages()], - ); + const reason = 'test reason'; + await plugin.authenticate( + localizedReason: reason, + authMessages: [AnotherPlatformAuthMessages()], + ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); - final strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - // These should all be the default values from - // auth_messages_android.dart - expect(strings.signInHint, androidSignInHint); - expect(strings.cancelButton, androidCancelButton); - expect(strings.signInTitle, androidSignInTitle); - }, - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); + final strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + // These should all be the default values from + // auth_messages_android.dart + expect(strings.signInHint, androidSignInHint); + expect(strings.cancelButton, androidCancelButton); + expect(strings.signInTitle, androidSignInTitle); + }); test('passes all non-default values correctly', () async { when( @@ -177,9 +162,7 @@ void main() { ], ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); expect(strings.signInHint, hint); @@ -205,9 +188,7 @@ void main() { ], ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the provided values. @@ -225,14 +206,9 @@ void main() { api.authenticate(any, any), ).thenAnswer((_) async => AuthResult(code: AuthResultCode.success)); - await plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ); + await plugin.authenticate(localizedReason: 'reason', authMessages: []); - final VerificationResult result = verify( - api.authenticate(captureAny, any), - ); + final VerificationResult result = verify(api.authenticate(captureAny, any)); final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, false); expect(options.sensitiveTransaction, true); @@ -254,9 +230,7 @@ void main() { ), ); - final VerificationResult result = verify( - api.authenticate(captureAny, any), - ); + final VerificationResult result = verify(api.authenticate(captureAny, any)); final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, true); expect(options.sensitiveTransaction, false); @@ -278,74 +252,59 @@ void main() { expect(result, true); }); - test( - 'converts negativeButton to userCanceled LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.negativeButton), - ); + test('converts negativeButton to userCanceled LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.negativeButton)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.userCanceled, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.userCanceled, ), - ); - }, - ); + ), + ); + }); - test( - 'converts userCanceled to userCanceled LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.userCanceled), - ); + test('converts userCanceled to userCanceled LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.userCanceled)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.userCanceled, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.userCanceled, ), - ); - }, - ); + ), + ); + }); - test( - 'converts systemCanceled to systemCanceled LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.systemCanceled), - ); + test('converts systemCanceled to systemCanceled LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.systemCanceled)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.systemCanceled, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.systemCanceled, ), - ); - }, - ); + ), + ); + }); test('converts timeout to timeout LocalAuthException', () async { when( @@ -353,10 +312,8 @@ void main() { ).thenAnswer((_) async => AuthResult(code: AuthResultCode.timeout)); expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), throwsA( isA().having( (LocalAuthException e) => e.code, @@ -367,28 +324,23 @@ void main() { ); }); - test( - 'converts alreadyInProgress to authInProgress LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.alreadyInProgress), - ); + test('converts alreadyInProgress to authInProgress LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.alreadyInProgress)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.authInProgress, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.authInProgress, ), - ); - }, - ); + ), + ); + }); test('converts noActivity to uiUnavailable LocalAuthException', () async { when( @@ -396,10 +348,8 @@ void main() { ).thenAnswer((_) async => AuthResult(code: AuthResultCode.noActivity)); expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), throwsA( isA().having( (LocalAuthException e) => e.code, @@ -410,87 +360,70 @@ void main() { ); }); - test( - 'converts notFragmentActivity to uiUnavailable LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.notFragmentActivity), - ); + test('converts notFragmentActivity to uiUnavailable LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.notFragmentActivity)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.uiUnavailable, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.uiUnavailable, ), - ); - }, - ); + ), + ); + }); - test( - 'converts noCredentials to noCredentialsSet LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.noCredentials), - ); + test('converts noCredentials to noCredentialsSet LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.noCredentials)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.noCredentialsSet, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.noCredentialsSet, ), - ); - }, - ); + ), + ); + }); - test( - 'converts noHardware to noBiometricHardware LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.noHardware), - ); + test('converts noHardware to noBiometricHardware LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.noHardware)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.noBiometricHardware, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.noBiometricHardware, ), - ); - }, - ); + ), + ); + }); test( 'converts hardwareUnavailable to biometricHardwareTemporarilyUnavailable LocalAuthException', () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.hardwareUnavailable), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.hardwareUnavailable)); expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), throwsA( isA().having( (LocalAuthException e) => e.code, @@ -502,74 +435,59 @@ void main() { }, ); - test( - 'converts notEnrolled to noBiometricsEnrolled LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.notEnrolled), - ); + test('converts notEnrolled to noBiometricsEnrolled LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.notEnrolled)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.noBiometricsEnrolled, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.noBiometricsEnrolled, ), - ); - }, - ); + ), + ); + }); - test( - 'converts lockedOutTemporarily to temporaryLockout LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.lockedOutTemporarily), - ); + test('converts lockedOutTemporarily to temporaryLockout LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.lockedOutTemporarily)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.temporaryLockout, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.temporaryLockout, ), - ); - }, - ); + ), + ); + }); - test( - 'converts lockedOutPermanently to biometricLockout LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult(code: AuthResultCode.lockedOutPermanently), - ); + test('converts lockedOutPermanently to biometricLockout LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.lockedOutPermanently)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA().having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.biometricLockout, - ), + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA().having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.biometricLockout, ), - ); - }, - ); + ), + ); + }); test('converts noSpace to deviceError LocalAuthException', () async { when( @@ -577,10 +495,8 @@ void main() { ).thenAnswer((_) async => AuthResult(code: AuthResultCode.noSpace)); expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), throwsA( isA() .having( @@ -597,52 +513,41 @@ void main() { ); }); - test( - 'converts securityUpdateRequired to deviceError LocalAuthException', - () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => - AuthResult(code: AuthResultCode.securityUpdateRequired), - ); + test('converts securityUpdateRequired to deviceError LocalAuthException', () async { + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResult(code: AuthResultCode.securityUpdateRequired)); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.deviceError, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - startsWith('Security update required:'), - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.deviceError, + ) + .having( + (LocalAuthException e) => e.description, + 'description', + startsWith('Security update required:'), + ), + ), + ); + }); test( 'converts unknownError to unknownError LocalAuthException, passing error message', () async { const errorMessage = 'Some error message'; when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResult( - code: AuthResultCode.unknownError, - errorMessage: errorMessage, - ), + (_) async => AuthResult(code: AuthResultCode.unknownError, errorMessage: errorMessage), ); expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), throwsA( isA() .having( @@ -650,11 +555,7 @@ void main() { 'code', LocalAuthExceptionCode.unknownError, ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ), + .having((LocalAuthException e) => e.description, 'description', errorMessage), ), ); }, diff --git a/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart b/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart index 64d3e9032310..2417e1a913b1 100644 --- a/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart +++ b/packages/local_auth/local_auth_android/test/local_auth_test.mocks.dart @@ -24,8 +24,7 @@ import 'package:mockito/src/dummies.dart' as _i3; // ignore_for_file: subtype_of_sealed_class class _FakeAuthResult_0 extends _i1.SmartFake implements _i2.AuthResult { - _FakeAuthResult_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeAuthResult_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [LocalAuthApi]. @@ -37,61 +36,41 @@ class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { } @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + ) as String); @override - _i4.Future isDeviceSupported() => - (super.noSuchMethod( - Invocation.method(#isDeviceSupported, []), - returnValue: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isDeviceSupported() => (super.noSuchMethod( + Invocation.method(#isDeviceSupported, []), + returnValue: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future deviceCanSupportBiometrics() => - (super.noSuchMethod( - Invocation.method(#deviceCanSupportBiometrics, []), - returnValue: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future deviceCanSupportBiometrics() => (super.noSuchMethod( + Invocation.method(#deviceCanSupportBiometrics, []), + returnValue: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future stopAuthentication() => - (super.noSuchMethod( - Invocation.method(#stopAuthentication, []), - returnValue: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future stopAuthentication() => (super.noSuchMethod( + Invocation.method(#stopAuthentication, []), + returnValue: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future?> getEnrolledBiometrics() => - (super.noSuchMethod( - Invocation.method(#getEnrolledBiometrics, []), - returnValue: _i4.Future?>.value(), - ) - as _i4.Future?>); + _i4.Future?> getEnrolledBiometrics() => (super.noSuchMethod( + Invocation.method(#getEnrolledBiometrics, []), + returnValue: _i4.Future?>.value(), + ) as _i4.Future?>); @override - _i4.Future<_i2.AuthResult> authenticate( - _i2.AuthOptions? options, - _i2.AuthStrings? strings, - ) => + _i4.Future<_i2.AuthResult> authenticate(_i2.AuthOptions? options, _i2.AuthStrings? strings) => (super.noSuchMethod( - Invocation.method(#authenticate, [options, strings]), - returnValue: _i4.Future<_i2.AuthResult>.value( - _FakeAuthResult_0( - this, - Invocation.method(#authenticate, [options, strings]), - ), - ), - ) - as _i4.Future<_i2.AuthResult>); + Invocation.method(#authenticate, [options, strings]), + returnValue: _i4.Future<_i2.AuthResult>.value( + _FakeAuthResult_0(this, Invocation.method(#authenticate, [options, strings])), + ), + ) as _i4.Future<_i2.AuthResult>); } diff --git a/packages/local_auth/local_auth_darwin/example/lib/main.dart b/packages/local_auth/local_auth_darwin/example/lib/main.dart index c14e5862d97f..6a25956e6a13 100644 --- a/packages/local_auth/local_auth_darwin/example/lib/main.dart +++ b/packages/local_auth/local_auth_darwin/example/lib/main.dart @@ -34,9 +34,7 @@ class _MyAppState extends State { super.initState(); LocalAuthPlatform.instance.isDeviceSupported().then( (bool isSupported) => setState( - () => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported, + () => _supportState = isSupported ? _SupportState.supported : _SupportState.unsupported, ), ); } @@ -44,8 +42,7 @@ class _MyAppState extends State { Future _checkBiometrics() async { late bool deviceSupportsBiometrics; try { - deviceSupportsBiometrics = await LocalAuthPlatform.instance - .deviceSupportsBiometrics(); + deviceSupportsBiometrics = await LocalAuthPlatform.instance.deviceSupportsBiometrics(); } on PlatformException catch (e) { deviceSupportsBiometrics = false; print(e); @@ -62,8 +59,7 @@ class _MyAppState extends State { Future _getEnrolledBiometrics() async { late List enrolledBiometrics; try { - enrolledBiometrics = await LocalAuthPlatform.instance - .getEnrolledBiometrics(); + enrolledBiometrics = await LocalAuthPlatform.instance.getEnrolledBiometrics(); } on PlatformException catch (e) { enrolledBiometrics = []; print(e); @@ -114,9 +110,7 @@ class _MyAppState extends State { return; } - setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', - ); + setState(() => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); } Future _authenticateWithBiometrics() async { @@ -127,13 +121,9 @@ class _MyAppState extends State { _authorized = 'Authenticating'; }); authenticated = await LocalAuthPlatform.instance.authenticate( - localizedReason: - 'Scan your fingerprint (or face or whatever) to authenticate', + localizedReason: 'Scan your fingerprint (or face or whatever) to authenticate', authMessages: [const IOSAuthMessages()], - options: const AuthenticationOptions( - stickyAuth: true, - biometricOnly: true, - ), + options: const AuthenticationOptions(stickyAuth: true, biometricOnly: true), ); setState(() { _isAuthenticating = false; @@ -191,10 +181,7 @@ class _MyAppState extends State { const Text('This device is not supported'), const Divider(height: 100), Text('Device supports biometrics: $_canCheckBiometrics\n'), - ElevatedButton( - onPressed: _checkBiometrics, - child: const Text('Check biometrics'), - ), + ElevatedButton(onPressed: _checkBiometrics, child: const Text('Check biometrics')), const Divider(height: 100), Text('Enrolled biometrics: $_enrolledBiometrics\n'), ElevatedButton( @@ -208,10 +195,7 @@ class _MyAppState extends State { onPressed: _cancelAuthentication, child: const Row( mainAxisSize: MainAxisSize.min, - children: [ - Text('Cancel Authentication'), - Icon(Icons.cancel), - ], + children: [Text('Cancel Authentication'), Icon(Icons.cancel)], ), ) else @@ -232,11 +216,7 @@ class _MyAppState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Text( - _isAuthenticating - ? 'Cancel' - : 'Authenticate: biometrics only', - ), + Text(_isAuthenticating ? 'Cancel' : 'Authenticate: biometrics only'), const Icon(Icons.fingerprint), ], ), diff --git a/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart b/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart index 461c0c57c748..726f2e1ded95 100644 --- a/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart +++ b/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart @@ -41,10 +41,7 @@ class LocalAuthDarwin extends LocalAuthPlatform { }) async { assert(localizedReason.isNotEmpty); final AuthResultDetails resultDetails = await _api.authenticate( - AuthOptions( - biometricOnly: options.biometricOnly, - sticky: options.stickyAuth, - ), + AuthOptions(biometricOnly: options.biometricOnly, sticky: options.stickyAuth), _useMacOSAuthMessages ? _pigeonStringsFromMacOSAuthMessages(localizedReason, authMessages) : _pigeonStringsFromiOSAuthMessages(localizedReason, authMessages), diff --git a/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart b/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart index 1901be9ea66d..b3c7f88d67a5 100644 --- a/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart +++ b/packages/local_auth/local_auth_darwin/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -69,11 +67,7 @@ enum AuthBiometric { face, fingerprint } /// /// See auth_messages_ios.dart for details. class AuthStrings { - AuthStrings({ - required this.reason, - required this.cancelButton, - this.localizedFallbackTitle, - }); + AuthStrings({required this.reason, required this.cancelButton, this.localizedFallbackTitle}); String reason; @@ -132,10 +126,7 @@ class AuthOptions { static AuthOptions decode(Object result) { result as List; - return AuthOptions( - biometricOnly: result[0]! as bool, - sticky: result[1]! as bool, - ); + return AuthOptions(biometricOnly: result[0]! as bool, sticky: result[1]! as bool); } @override @@ -156,11 +147,7 @@ class AuthOptions { } class AuthResultDetails { - AuthResultDetails({ - required this.result, - this.errorMessage, - this.errorDetails, - }); + AuthResultDetails({required this.result, this.errorMessage, this.errorDetails}); /// The result of authenticating. AuthResult result; @@ -257,13 +244,11 @@ class LocalAuthApi { /// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - LocalAuthApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + LocalAuthApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -274,15 +259,13 @@ class LocalAuthApi { Future isDeviceSupported() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.isDeviceSupported$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -306,15 +289,13 @@ class LocalAuthApi { Future deviceCanSupportBiometrics() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.deviceCanSupportBiometrics$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -338,15 +319,13 @@ class LocalAuthApi { Future> getEnrolledBiometrics() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.getEnrolledBiometrics$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -367,23 +346,19 @@ class LocalAuthApi { /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. - Future authenticate( - AuthOptions options, - AuthStrings strings, - ) async { + Future authenticate(AuthOptions options, AuthStrings strings) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_darwin.LocalAuthApi.authenticate$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [options, strings], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + options, + strings, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart index 49865d76e21b..a1e058536808 100644 --- a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart +++ b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart @@ -28,8 +28,7 @@ class IOSAuthMessages extends AuthMessages { Map get args { return { 'okButton': cancelButton ?? iOSCancelButton, - if (localizedFallbackTitle != null) - 'localizedFallbackTitle': localizedFallbackTitle!, + if (localizedFallbackTitle != null) 'localizedFallbackTitle': localizedFallbackTitle!, }; } @@ -42,8 +41,7 @@ class IOSAuthMessages extends AuthMessages { localizedFallbackTitle == other.localizedFallbackTitle; @override - int get hashCode => - Object.hash(super.hashCode, cancelButton, localizedFallbackTitle); + int get hashCode => Object.hash(super.hashCode, cancelButton, localizedFallbackTitle); } // Default Strings for IOSAuthMessages plugin. Currently supports English. diff --git a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart index 292bf3ba986b..0642c3add476 100644 --- a/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart +++ b/packages/local_auth/local_auth_darwin/lib/types/auth_messages_macos.dart @@ -28,8 +28,7 @@ class MacOSAuthMessages extends AuthMessages { Map get args { return { 'okButton': cancelButton ?? macOSCancelButton, - if (localizedFallbackTitle != null) - 'localizedFallbackTitle': localizedFallbackTitle!, + if (localizedFallbackTitle != null) 'localizedFallbackTitle': localizedFallbackTitle!, }; } @@ -42,8 +41,7 @@ class MacOSAuthMessages extends AuthMessages { localizedFallbackTitle == other.localizedFallbackTitle; @override - int get hashCode => - Object.hash(super.hashCode, cancelButton, localizedFallbackTitle); + int get hashCode => Object.hash(super.hashCode, cancelButton, localizedFallbackTitle); } // Default Strings for MacOSAuthMessages plugin. Currently supports English. diff --git a/packages/local_auth/local_auth_darwin/pigeons/messages.dart b/packages/local_auth/local_auth_darwin/pigeons/messages.dart index 74a767977dbf..ee7709033ded 100644 --- a/packages/local_auth/local_auth_darwin/pigeons/messages.dart +++ b/packages/local_auth/local_auth_darwin/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - swiftOut: - 'darwin/local_auth_darwin/Sources/local_auth_darwin/messages.g.swift', + swiftOut: 'darwin/local_auth_darwin/Sources/local_auth_darwin/messages.g.swift', copyrightHeader: 'pigeons/copyright.txt', ), ) @@ -64,11 +63,7 @@ class AuthOptions { } class AuthResultDetails { - AuthResultDetails({ - required this.result, - this.errorMessage, - this.errorDetails, - }); + AuthResultDetails({required this.result, this.errorMessage, this.errorDetails}); /// The result of authenticating. final AuthResult result; diff --git a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart index 169cb4677880..5df711388d6e 100644 --- a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart +++ b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart @@ -59,25 +59,17 @@ void main() { group('getEnrolledBiometrics', () { test('translates values', () async { - when(api.getEnrolledBiometrics()).thenAnswer( - (_) async => [ - AuthBiometric.face, - AuthBiometric.fingerprint, - ], - ); + when( + api.getEnrolledBiometrics(), + ).thenAnswer((_) async => [AuthBiometric.face, AuthBiometric.fingerprint]); final List result = await plugin.getEnrolledBiometrics(); - expect(result, [ - BiometricType.face, - BiometricType.fingerprint, - ]); + expect(result, [BiometricType.face, BiometricType.fingerprint]); }); test('handles empty', () async { - when( - api.getEnrolledBiometrics(), - ).thenAnswer((_) async => []); + when(api.getEnrolledBiometrics()).thenAnswer((_) async => []); final List result = await plugin.getEnrolledBiometrics(); @@ -90,19 +82,14 @@ void main() { test('passes default values when nothing is provided', () async { plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); const reason = 'test reason'; - await plugin.authenticate( - localizedReason: reason, - authMessages: [], - ); + await plugin.authenticate(localizedReason: reason, authMessages: []); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from @@ -111,47 +98,36 @@ void main() { expect(strings.localizedFallbackTitle, null); }); - test( - 'passes default values when only other platform values are provided', - () async { - plugin = LocalAuthDarwin( - api: api, - overrideUseMacOSAuthMessages: false, - ); + test('passes default values when only other platform values are provided', () async { + plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); - const reason = 'test reason'; - await plugin.authenticate( - localizedReason: reason, - authMessages: [AnotherPlatformAuthMessages()], - ); + const reason = 'test reason'; + await plugin.authenticate( + localizedReason: reason, + authMessages: [AnotherPlatformAuthMessages()], + ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); - final strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - // These should all be the default values from - // auth_messages_ios.dart - expect(strings.cancelButton, iOSCancelButton); - expect(strings.localizedFallbackTitle, null); - }, - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); + final strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + // These should all be the default values from + // auth_messages_ios.dart + expect(strings.cancelButton, iOSCancelButton); + expect(strings.localizedFallbackTitle, null); + }); test( 'passes default values when only MacOSAuthMessages platform values are provided', () async { - plugin = LocalAuthDarwin( - api: api, - overrideUseMacOSAuthMessages: true, - ); + plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: true); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); const reason = 'test reason'; await plugin.authenticate( @@ -159,9 +135,7 @@ void main() { authMessages: [const MacOSAuthMessages()], ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from @@ -171,90 +145,74 @@ void main() { }, ); - test( - 'passes all non-default values correctly with IOSAuthMessages', - () async { - plugin = LocalAuthDarwin( - api: api, - overrideUseMacOSAuthMessages: false, - ); + test('passes all non-default values correctly with IOSAuthMessages', () async { + plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); - // These are arbitrary values; all that matters is that: - // - they are different from the defaults, and - // - they are different from each other. - const reason = 'A'; - const cancel = 'B'; - const localizedFallbackTitle = 'C'; + // These are arbitrary values; all that matters is that: + // - they are different from the defaults, and + // - they are different from each other. + const reason = 'A'; + const cancel = 'B'; + const localizedFallbackTitle = 'C'; - await plugin.authenticate( - localizedReason: reason, - authMessages: [ - const IOSAuthMessages( - cancelButton: cancel, - localizedFallbackTitle: localizedFallbackTitle, - ), - AnotherPlatformAuthMessages(), - ], - ); + await plugin.authenticate( + localizedReason: reason, + authMessages: [ + const IOSAuthMessages( + cancelButton: cancel, + localizedFallbackTitle: localizedFallbackTitle, + ), + AnotherPlatformAuthMessages(), + ], + ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); - final strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - expect(strings.cancelButton, cancel); - expect(strings.localizedFallbackTitle, localizedFallbackTitle); - }, - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); + final strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + expect(strings.cancelButton, cancel); + expect(strings.localizedFallbackTitle, localizedFallbackTitle); + }); - test( - 'passes all non-default values correctly with MacOSAuthMessages', - () async { - plugin = LocalAuthDarwin( - api: api, - overrideUseMacOSAuthMessages: true, - ); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + test('passes all non-default values correctly with MacOSAuthMessages', () async { + plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: true); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); - // These are arbitrary values; all that matters is that: - // - they are different from the defaults, and - // - they are different from each other. - const reason = 'A'; - const cancel = 'B'; - const localizedFallbackTitle = 'C'; - await plugin.authenticate( - localizedReason: reason, - authMessages: [ - const MacOSAuthMessages( - cancelButton: cancel, - localizedFallbackTitle: localizedFallbackTitle, - ), - AnotherPlatformAuthMessages(), - ], - ); + // These are arbitrary values; all that matters is that: + // - they are different from the defaults, and + // - they are different from each other. + const reason = 'A'; + const cancel = 'B'; + const localizedFallbackTitle = 'C'; + await plugin.authenticate( + localizedReason: reason, + authMessages: [ + const MacOSAuthMessages( + cancelButton: cancel, + localizedFallbackTitle: localizedFallbackTitle, + ), + AnotherPlatformAuthMessages(), + ], + ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); - final strings = result.captured[0] as AuthStrings; - expect(strings.reason, reason); - expect(strings.cancelButton, cancel); - expect(strings.localizedFallbackTitle, localizedFallbackTitle); - }, - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); + final strings = result.captured[0] as AuthStrings; + expect(strings.reason, reason); + expect(strings.cancelButton, cancel); + expect(strings.localizedFallbackTitle, localizedFallbackTitle); + }); test('passes provided messages with default fallbacks', () async { plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); // These are arbitrary values; all that matters is that: // - they are different from the defaults, and @@ -264,15 +222,11 @@ void main() { await plugin.authenticate( localizedReason: reason, authMessages: [ - const IOSAuthMessages( - localizedFallbackTitle: localizedFallbackTitle, - ), + const IOSAuthMessages(localizedFallbackTitle: localizedFallbackTitle), ], ); - final VerificationResult result = verify( - api.authenticate(any, captureAny), - ); + final VerificationResult result = verify(api.authenticate(any, captureAny)); final strings = result.captured[0] as AuthStrings; // These should all be the provided values. expect(strings.reason, reason); @@ -287,40 +241,30 @@ void main() { test('passes default values', () async { plugin = LocalAuthDarwin(api: api, overrideUseMacOSAuthMessages: false); - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); - await plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ); + await plugin.authenticate(localizedReason: 'reason', authMessages: []); - final VerificationResult result = verify( - api.authenticate(captureAny, any), - ); + final VerificationResult result = verify(api.authenticate(captureAny, any)); final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, false); expect(options.sticky, false); }); test('passes provided non-default values', () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); await plugin.authenticate( localizedReason: 'reason', authMessages: [], - options: const AuthenticationOptions( - biometricOnly: true, - stickyAuth: true, - ), + options: const AuthenticationOptions(biometricOnly: true, stickyAuth: true), ); - final VerificationResult result = verify( - api.authenticate(captureAny, any), - ); + final VerificationResult result = verify(api.authenticate(captureAny, any)); final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, true); expect(options.sticky, true); @@ -329,9 +273,9 @@ void main() { group('return values', () { test('handles success', () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.success), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.success)); final bool result = await plugin.authenticate( localizedReason: 'reason', @@ -342,10 +286,9 @@ void main() { }); test('handles failure', () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => - AuthResultDetails(result: AuthResult.authenticationFailed), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.authenticationFailed)); final bool result = await plugin.authenticate( localizedReason: 'reason', @@ -356,9 +299,9 @@ void main() { }); test('handles appCancel as failure', () async { - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails(result: AuthResult.appCancel), - ); + when( + api.authenticate(any, any), + ).thenAnswer((_) async => AuthResultDetails(result: AuthResult.appCancel)); final bool result = await plugin.authenticate( localizedReason: 'reason', @@ -368,125 +311,86 @@ void main() { expect(result, false); }); - test( - 'converts uiUnavailable to LocalAuthExceptionCode.uiUnavailable', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.uiUnavailable, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts uiUnavailable to LocalAuthExceptionCode.uiUnavailable', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.uiUnavailable, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.uiUnavailable, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.uiUnavailable, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts systemCancel to LocalAuthExceptionCode.systemCanceled', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.systemCancel, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts systemCancel to LocalAuthExceptionCode.systemCanceled', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.systemCancel, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.systemCanceled, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.systemCanceled, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts userCancel to LocalAuthExceptionCode.userCanceled', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.userCancel, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts userCancel to LocalAuthExceptionCode.userCanceled', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.userCancel, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.userCanceled, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.userCanceled, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); test( 'converts biometryDisconnected to LocalAuthExceptionCode.biometricHardwareTemporarilyUnavailable', @@ -502,432 +406,291 @@ void main() { ); expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), throwsA( isA() .having( (LocalAuthException e) => e.code, 'code', - LocalAuthExceptionCode - .biometricHardwareTemporarilyUnavailable, + LocalAuthExceptionCode.biometricHardwareTemporarilyUnavailable, ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), ), ); }, ); - test( - 'converts biometryLockout to LocalAuthExceptionCode.biometricLockout', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.biometryLockout, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts biometryLockout to LocalAuthExceptionCode.biometricLockout', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.biometryLockout, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.biometricLockout, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.biometricLockout, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts biometryNotAvailable to LocalAuthExceptionCode.noBiometricHardware', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.biometryNotAvailable, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts biometryNotAvailable to LocalAuthExceptionCode.noBiometricHardware', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.biometryNotAvailable, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.noBiometricHardware, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.noBiometricHardware, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts biometryNotPaired to LocalAuthExceptionCode.noBiometricHardware', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.biometryNotPaired, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts biometryNotPaired to LocalAuthExceptionCode.noBiometricHardware', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.biometryNotPaired, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.noBiometricHardware, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.noBiometricHardware, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts biometryNotEnrolled to LocalAuthExceptionCode.noBiometricsEnrolled', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.biometryNotEnrolled, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts biometryNotEnrolled to LocalAuthExceptionCode.noBiometricsEnrolled', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.biometryNotEnrolled, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.noBiometricsEnrolled, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.noBiometricsEnrolled, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts invalidContext to LocalAuthExceptionCode.uiUnavailable', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.invalidContext, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts invalidContext to LocalAuthExceptionCode.uiUnavailable', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.invalidContext, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.uiUnavailable, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.uiUnavailable, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts invalidDimensions to LocalAuthExceptionCode.uiUnavailable', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.invalidDimensions, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts invalidDimensions to LocalAuthExceptionCode.uiUnavailable', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.invalidDimensions, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.uiUnavailable, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.uiUnavailable, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts notInteractive to LocalAuthExceptionCode.uiUnavailable', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.notInteractive, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts notInteractive to LocalAuthExceptionCode.uiUnavailable', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.notInteractive, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.uiUnavailable, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.uiUnavailable, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts passcodeNotSet to LocalAuthExceptionCode.noCredentialsSet', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.passcodeNotSet, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts passcodeNotSet to LocalAuthExceptionCode.noCredentialsSet', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.passcodeNotSet, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.noCredentialsSet, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.noCredentialsSet, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts userFallback to LocalAuthExceptionCode.userRequestedFallback', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.userFallback, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts userFallback to LocalAuthExceptionCode.userRequestedFallback', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.userFallback, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.userRequestedFallback, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.userRequestedFallback, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); - test( - 'converts unknownError to LocalAuthExceptionCode.unknownError', - () async { - const errorMessage = 'a message'; - const errorDetails = 'some details'; - when(api.authenticate(any, any)).thenAnswer( - (_) async => AuthResultDetails( - result: AuthResult.unknownError, - errorMessage: errorMessage, - errorDetails: errorDetails, - ), - ); + test('converts unknownError to LocalAuthExceptionCode.unknownError', () async { + const errorMessage = 'a message'; + const errorDetails = 'some details'; + when(api.authenticate(any, any)).thenAnswer( + (_) async => AuthResultDetails( + result: AuthResult.unknownError, + errorMessage: errorMessage, + errorDetails: errorDetails, + ), + ); - expect( - () async => plugin.authenticate( - localizedReason: 'reason', - authMessages: [], - ), - throwsA( - isA() - .having( - (LocalAuthException e) => e.code, - 'code', - LocalAuthExceptionCode.unknownError, - ) - .having( - (LocalAuthException e) => e.description, - 'description', - errorMessage, - ) - .having( - (LocalAuthException e) => e.details, - 'details', - errorDetails, - ), - ), - ); - }, - ); + expect( + () async => + plugin.authenticate(localizedReason: 'reason', authMessages: []), + throwsA( + isA() + .having( + (LocalAuthException e) => e.code, + 'code', + LocalAuthExceptionCode.unknownError, + ) + .having((LocalAuthException e) => e.description, 'description', errorMessage) + .having((LocalAuthException e) => e.details, 'details', errorDetails), + ), + ); + }); }); }); } diff --git a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart index 1c93c29927e7..9408c7f96258 100644 --- a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart +++ b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart @@ -23,8 +23,7 @@ import 'package:mockito/src/dummies.dart' as _i3; // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class -class _FakeAuthResultDetails_0 extends _i1.SmartFake - implements _i2.AuthResultDetails { +class _FakeAuthResultDetails_0 extends _i1.SmartFake implements _i2.AuthResultDetails { _FakeAuthResultDetails_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -38,55 +37,37 @@ class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { } @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + ) as String); @override - _i4.Future isDeviceSupported() => - (super.noSuchMethod( - Invocation.method(#isDeviceSupported, []), - returnValue: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future isDeviceSupported() => (super.noSuchMethod( + Invocation.method(#isDeviceSupported, []), + returnValue: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future deviceCanSupportBiometrics() => - (super.noSuchMethod( - Invocation.method(#deviceCanSupportBiometrics, []), - returnValue: _i4.Future.value(false), - ) - as _i4.Future); + _i4.Future deviceCanSupportBiometrics() => (super.noSuchMethod( + Invocation.method(#deviceCanSupportBiometrics, []), + returnValue: _i4.Future.value(false), + ) as _i4.Future); @override - _i4.Future> getEnrolledBiometrics() => - (super.noSuchMethod( - Invocation.method(#getEnrolledBiometrics, []), - returnValue: _i4.Future>.value( - <_i2.AuthBiometric>[], - ), - ) - as _i4.Future>); + _i4.Future> getEnrolledBiometrics() => (super.noSuchMethod( + Invocation.method(#getEnrolledBiometrics, []), + returnValue: _i4.Future>.value(<_i2.AuthBiometric>[]), + ) as _i4.Future>); @override _i4.Future<_i2.AuthResultDetails> authenticate( _i2.AuthOptions? options, _i2.AuthStrings? strings, - ) => - (super.noSuchMethod( - Invocation.method(#authenticate, [options, strings]), - returnValue: _i4.Future<_i2.AuthResultDetails>.value( - _FakeAuthResultDetails_0( - this, - Invocation.method(#authenticate, [options, strings]), - ), - ), - ) - as _i4.Future<_i2.AuthResultDetails>); + ) => (super.noSuchMethod( + Invocation.method(#authenticate, [options, strings]), + returnValue: _i4.Future<_i2.AuthResultDetails>.value( + _FakeAuthResultDetails_0(this, Invocation.method(#authenticate, [options, strings])), + ), + ) as _i4.Future<_i2.AuthResultDetails>); } diff --git a/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart b/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart index ec4606f89797..9270346f1056 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart @@ -38,8 +38,7 @@ class DefaultLocalAuthPlatform extends LocalAuthPlatform { @override Future> getEnrolledBiometrics() async { final List result = - (await _channel.invokeListMethod('getAvailableBiometrics')) ?? - []; + (await _channel.invokeListMethod('getAvailableBiometrics')) ?? []; final biometrics = []; for (final value in result) { switch (value) { @@ -61,8 +60,7 @@ class DefaultLocalAuthPlatform extends LocalAuthPlatform { @override Future deviceSupportsBiometrics() async { final List availableBiometrics = - (await _channel.invokeListMethod('getAvailableBiometrics')) ?? - []; + (await _channel.invokeListMethod('getAvailableBiometrics')) ?? []; // If anything, including the 'undefined' sentinel, is returned, then there // is device support for biometrics. return availableBiometrics.isNotEmpty; diff --git a/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart b/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart index a4a087177610..af788c552dc7 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/local_auth_platform_interface.dart @@ -80,9 +80,7 @@ abstract class LocalAuthPlatform extends PlatformInterface { /// - BiometricType.strong /// - BiometricType.weak Future> getEnrolledBiometrics() async { - throw UnimplementedError( - 'getAvailableBiometrics() has not been implemented.', - ); + throw UnimplementedError('getAvailableBiometrics() has not been implemented.'); } /// Returns true if device is capable of checking biometrics or is able to diff --git a/packages/local_auth/local_auth_platform_interface/lib/types/auth_exception.dart b/packages/local_auth/local_auth_platform_interface/lib/types/auth_exception.dart index dc751726a66b..241aca6e5725 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/types/auth_exception.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/types/auth_exception.dart @@ -9,11 +9,7 @@ import 'package:flutter/foundation.dart'; @immutable class LocalAuthException implements Exception { /// Creates a new exception with the given information. - const LocalAuthException({ - required this.code, - this.description, - this.details, - }); + const LocalAuthException({required this.code, this.description, this.details}); /// The type of failure. final LocalAuthExceptionCode code; diff --git a/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart b/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart index ad1b4e1e6db5..b987a1c465a1 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/types/auth_options.dart @@ -55,10 +55,5 @@ class AuthenticationOptions { biometricOnly == other.biometricOnly; @override - int get hashCode => Object.hash( - useErrorDialogs, - stickyAuth, - sensitiveTransaction, - biometricOnly, - ); + int get hashCode => Object.hash(useErrorDialogs, stickyAuth, sensitiveTransaction, biometricOnly); } diff --git a/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart b/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart index 5372ca1b1510..b41c7d31fb2d 100644 --- a/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart +++ b/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart @@ -19,27 +19,21 @@ void main() { log = []; }); - test( - 'DefaultLocalAuthPlatform is registered as the default platform implementation', - () async { - expect( - LocalAuthPlatform.instance, - const TypeMatcher(), - ); - }, - ); + test('DefaultLocalAuthPlatform is registered as the default platform implementation', () async { + expect(LocalAuthPlatform.instance, const TypeMatcher()); + }); test('getAvailableBiometrics', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (MethodCall methodCall) { - log.add(methodCall); - return Future.value([]); - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (MethodCall methodCall) { + log.add(methodCall); + return Future.value([]); + }, + ); localAuthentication = DefaultLocalAuthPlatform(); await localAuthentication.getEnrolledBiometrics(); - expect(log, [ - isMethodCall('getAvailableBiometrics', arguments: null), - ]); + expect(log, [isMethodCall('getAvailableBiometrics', arguments: null)]); }); test('deviceSupportsBiometrics handles special sentinal value', () async { @@ -48,43 +42,40 @@ void main() { // existing unendorsed implementations, used 'undefined' as a special // return value from `getAvailableBiometrics` to indicate that nothing was // enrolled, but that the hardware does support biometrics. - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (MethodCall methodCall) { - log.add(methodCall); - return Future.value(['undefined']); - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (MethodCall methodCall) { + log.add(methodCall); + return Future.value(['undefined']); + }, + ); localAuthentication = DefaultLocalAuthPlatform(); - final bool supportsBiometrics = await localAuthentication - .deviceSupportsBiometrics(); + final bool supportsBiometrics = await localAuthentication.deviceSupportsBiometrics(); expect(supportsBiometrics, true); - expect(log, [ - isMethodCall('getAvailableBiometrics', arguments: null), - ]); + expect(log, [isMethodCall('getAvailableBiometrics', arguments: null)]); }); group('Boolean returning methods', () { setUp(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (MethodCall methodCall) { - log.add(methodCall); - return Future.value(true); - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (MethodCall methodCall) { + log.add(methodCall); + return Future.value(true); + }, + ); localAuthentication = DefaultLocalAuthPlatform(); }); test('isDeviceSupported', () async { await localAuthentication.isDeviceSupported(); - expect(log, [ - isMethodCall('isDeviceSupported', arguments: null), - ]); + expect(log, [isMethodCall('isDeviceSupported', arguments: null)]); }); test('stopAuthentication', () async { await localAuthentication.stopAuthentication(); - expect(log, [ - isMethodCall('stopAuthentication', arguments: null), - ]); + expect(log, [isMethodCall('stopAuthentication', arguments: null)]); }); group('authenticate with device auth fail over', () { @@ -112,10 +103,7 @@ void main() { await localAuthentication.authenticate( authMessages: [], localizedReason: 'Insecure', - options: const AuthenticationOptions( - sensitiveTransaction: false, - biometricOnly: true, - ), + options: const AuthenticationOptions(sensitiveTransaction: false, biometricOnly: true), ); expect(log, [ isMethodCall( @@ -172,28 +160,25 @@ void main() { ]); }); - test( - 'legacy useErrorDialogs is passed for backward compatibility.', - () async { - await localAuthentication.authenticate( - authMessages: [], - localizedReason: 'Insecure', - options: const AuthenticationOptions(useErrorDialogs: false), - ); - expect(log, [ - isMethodCall( - 'authenticate', - arguments: { - 'localizedReason': 'Insecure', - 'useErrorDialogs': false, - 'stickyAuth': false, - 'sensitiveTransaction': true, - 'biometricOnly': false, - }, - ), - ]); - }, - ); + test('legacy useErrorDialogs is passed for backward compatibility.', () async { + await localAuthentication.authenticate( + authMessages: [], + localizedReason: 'Insecure', + options: const AuthenticationOptions(useErrorDialogs: false), + ); + expect(log, [ + isMethodCall( + 'authenticate', + arguments: { + 'localizedReason': 'Insecure', + 'useErrorDialogs': false, + 'stickyAuth': false, + 'sensitiveTransaction': true, + 'biometricOnly': false, + }, + ), + ]); + }); }); }); } diff --git a/packages/local_auth/local_auth_windows/example/lib/main.dart b/packages/local_auth/local_auth_windows/example/lib/main.dart index 5d76d8a34de2..25a6336d4460 100644 --- a/packages/local_auth/local_auth_windows/example/lib/main.dart +++ b/packages/local_auth/local_auth_windows/example/lib/main.dart @@ -34,9 +34,7 @@ class _MyAppState extends State { super.initState(); LocalAuthPlatform.instance.isDeviceSupported().then( (bool isSupported) => setState( - () => _supportState = isSupported - ? _SupportState.supported - : _SupportState.unsupported, + () => _supportState = isSupported ? _SupportState.supported : _SupportState.unsupported, ), ); } @@ -44,8 +42,7 @@ class _MyAppState extends State { Future _checkBiometrics() async { late bool deviceSupportsBiometrics; try { - deviceSupportsBiometrics = await LocalAuthPlatform.instance - .deviceSupportsBiometrics(); + deviceSupportsBiometrics = await LocalAuthPlatform.instance.deviceSupportsBiometrics(); } on PlatformException catch (e) { deviceSupportsBiometrics = false; print(e); @@ -62,8 +59,7 @@ class _MyAppState extends State { Future _getEnrolledBiometrics() async { late List availableBiometrics; try { - availableBiometrics = await LocalAuthPlatform.instance - .getEnrolledBiometrics(); + availableBiometrics = await LocalAuthPlatform.instance.getEnrolledBiometrics(); } on PlatformException catch (e) { availableBiometrics = []; print(e); @@ -111,9 +107,7 @@ class _MyAppState extends State { return; } - setState( - () => _authorized = authenticated ? 'Authorized' : 'Not Authorized', - ); + setState(() => _authorized = authenticated ? 'Authorized' : 'Not Authorized'); } @override @@ -134,13 +128,8 @@ class _MyAppState extends State { else const Text('This device is not supported'), const Divider(height: 100), - Text( - 'Device supports biometrics: $_deviceSupportsBiometrics\n', - ), - ElevatedButton( - onPressed: _checkBiometrics, - child: const Text('Check biometrics'), - ), + Text('Device supports biometrics: $_deviceSupportsBiometrics\n'), + ElevatedButton(onPressed: _checkBiometrics, child: const Text('Check biometrics')), const Divider(height: 100), Text('Enrolled biometrics: $_enrolledBiometrics\n'), ElevatedButton( diff --git a/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart b/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart index f7255719b8c8..3d9cf4550c61 100644 --- a/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart +++ b/packages/local_auth/local_auth_windows/lib/local_auth_windows.dart @@ -15,8 +15,7 @@ export 'package:local_auth_windows/types/auth_messages_windows.dart'; /// The implementation of [LocalAuthPlatform] for Windows. class LocalAuthWindows extends LocalAuthPlatform { /// Creates a new plugin implementation instance. - LocalAuthWindows({@visibleForTesting LocalAuthApi? api}) - : _api = api ?? LocalAuthApi(); + LocalAuthWindows({@visibleForTesting LocalAuthApi? api}) : _api = api ?? LocalAuthApi(); final LocalAuthApi _api; @@ -34,9 +33,7 @@ class LocalAuthWindows extends LocalAuthPlatform { assert(localizedReason.isNotEmpty); if (options.biometricOnly) { - throw UnsupportedError( - "Windows doesn't support the biometricOnly parameter.", - ); + throw UnsupportedError("Windows doesn't support the biometricOnly parameter."); } return switch (await _api.authenticate(localizedReason)) { diff --git a/packages/local_auth/local_auth_windows/lib/src/messages.g.dart b/packages/local_auth/local_auth_windows/lib/src/messages.g.dart index a36d96022421..d7481151ec48 100644 --- a/packages/local_auth/local_auth_windows/lib/src/messages.g.dart +++ b/packages/local_auth/local_auth_windows/lib/src/messages.g.dart @@ -73,13 +73,11 @@ class LocalAuthApi { /// Constructor for [LocalAuthApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - LocalAuthApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + LocalAuthApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -90,15 +88,13 @@ class LocalAuthApi { Future isDeviceSupported() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_windows.LocalAuthApi.isDeviceSupported$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -122,17 +118,13 @@ class LocalAuthApi { Future authenticate(String localizedReason) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.local_auth_windows.LocalAuthApi.authenticate$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [localizedReason], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([localizedReason]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/local_auth/local_auth_windows/test/local_auth_test.dart b/packages/local_auth/local_auth_windows/test/local_auth_test.dart index 106310591ab5..98ecfa37ac5b 100644 --- a/packages/local_auth/local_auth_windows/test/local_auth_test.dart +++ b/packages/local_auth/local_auth_windows/test/local_auth_test.dart @@ -183,19 +183,13 @@ void main() { expect(result, false); }); - test( - 'getEnrolledBiometrics returns expected values when supported', - () async { - api.supportedReturnValue = true; - - final List result = await plugin.getEnrolledBiometrics(); - - expect(result, [ - BiometricType.weak, - BiometricType.strong, - ]); - }, - ); + test('getEnrolledBiometrics returns expected values when supported', () async { + api.supportedReturnValue = true; + + final List result = await plugin.getEnrolledBiometrics(); + + expect(result, [BiometricType.weak, BiometricType.strong]); + }); test('getEnrolledBiometrics returns nothing when unsupported', () async { api.supportedReturnValue = false; diff --git a/packages/material_ui/test/flutter_test_config.dart b/packages/material_ui/test/flutter_test_config.dart index 89496e15a775..decec135ddd1 100644 --- a/packages/material_ui/test/flutter_test_config.dart +++ b/packages/material_ui/test/flutter_test_config.dart @@ -4,9 +4,7 @@ import 'dart:async'; -import 'goldens_io.dart' - if (dart.library.js_interop) 'goldens_web.dart' - as flutter_goldens; +import 'goldens_io.dart' if (dart.library.js_interop) 'goldens_web.dart' as flutter_goldens; Future testExecutable(FutureOr Function() testMain) { // Enable golden file testing using Skia Gold. diff --git a/packages/material_ui/test/goldens/goldens_test.dart b/packages/material_ui/test/goldens/goldens_test.dart index c4270a026784..bd518a8ff154 100644 --- a/packages/material_ui/test/goldens/goldens_test.dart +++ b/packages/material_ui/test/goldens/goldens_test.dart @@ -11,9 +11,7 @@ void main() { testWidgets('Inconsequential golden test', (WidgetTester tester) async { // The test validates the Flutter Gold integration. Any changes to the // golden file can be approved at any time. - await tester.pumpWidget( - RepaintBoundary(child: Container(color: const Color(0xAFF61145))), - ); + await tester.pumpWidget(RepaintBoundary(child: Container(color: const Color(0xAFF61145)))); await tester.pumpAndSettle(); await expectLater( diff --git a/packages/material_ui/test/goldens_web.dart b/packages/material_ui/test/goldens_web.dart index 80945b782d2e..fd3ea2d23fb2 100644 --- a/packages/material_ui/test/goldens_web.dart +++ b/packages/material_ui/test/goldens_web.dart @@ -5,7 +5,5 @@ import 'dart:async'; // package:flutter_goldens is not used as part of the test process for web. -Future testExecutable( - FutureOr Function() testMain, { - String? namePrefix, -}) async => testMain(); +Future testExecutable(FutureOr Function() testMain, {String? namePrefix}) async => + testMain(); diff --git a/packages/metrics_center/lib/src/common.dart b/packages/metrics_center/lib/src/common.dart index ad2a1bc97443..ddd77a8a2c4b 100644 --- a/packages/metrics_center/lib/src/common.dart +++ b/packages/metrics_center/lib/src/common.dart @@ -19,8 +19,7 @@ class MetricPoint { final double? value; /// Test name, unit, timestamp, configs, git revision, ..., in sorted order. - UnmodifiableMapView get tags => - UnmodifiableMapView(_tags); + UnmodifiableMapView get tags => UnmodifiableMapView(_tags); final SplayTreeMap _tags; /// Unique identifier for updating existing data point. @@ -41,11 +40,7 @@ class MetricPoint { /// Interface to write [MetricPoint]. abstract class MetricDestination { /// Insert new data points or modify old ones with matching id. - Future update( - List points, - DateTime commitTime, - String taskName, - ); + Future update(List points, DateTime commitTime, String taskName); } /// Create `AuthClient` in case we only have an access token without the full diff --git a/packages/metrics_center/lib/src/flutter.dart b/packages/metrics_center/lib/src/flutter.dart index 00eff67ece72..11d7945c4c57 100644 --- a/packages/metrics_center/lib/src/flutter.dart +++ b/packages/metrics_center/lib/src/flutter.dart @@ -37,10 +37,7 @@ class FlutterDestination extends MetricDestination { bool isTesting = false, }) async { final SkiaPerfDestination skiaPerfDestination = - await SkiaPerfDestination.makeFromGcpCredentials( - json, - isTesting: isTesting, - ); + await SkiaPerfDestination.makeFromGcpCredentials(json, isTesting: isTesting); return FlutterDestination._(skiaPerfDestination); } @@ -50,21 +47,16 @@ class FlutterDestination extends MetricDestination { String projectId, { bool isTesting = false, }) async { - final SkiaPerfDestination skiaPerfDestination = - await SkiaPerfDestination.makeFromAccessToken( - accessToken, - projectId, - isTesting: isTesting, - ); + final SkiaPerfDestination skiaPerfDestination = await SkiaPerfDestination.makeFromAccessToken( + accessToken, + projectId, + isTesting: isTesting, + ); return FlutterDestination._(skiaPerfDestination); } @override - Future update( - List points, - DateTime commitTime, - String taskName, - ) async { + Future update(List points, DateTime commitTime, String taskName) async { await _skiaPerfDestination.update(points, commitTime, taskName); } diff --git a/packages/metrics_center/lib/src/gcs_lock.dart b/packages/metrics_center/lib/src/gcs_lock.dart index 74a41fa7e09e..931e5f16672e 100644 --- a/packages/metrics_center/lib/src/gcs_lock.dart +++ b/packages/metrics_center/lib/src/gcs_lock.dart @@ -27,10 +27,7 @@ class GcsLock { /// If the lock file is stuck (e.g., `_unlock` is interrupted unexpectedly), /// one may need to manually delete the lock file from GCS to unblock any /// [protectedRun] that may depend on it. - Future protectedRun( - String lockFileName, - Future Function() f, - ) async { + Future protectedRun(String lockFileName, Future Function() f) async { await _lock(lockFileName); try { await f(); diff --git a/packages/metrics_center/lib/src/google_benchmark.dart b/packages/metrics_center/lib/src/google_benchmark.dart index 75a1f8a44982..a2f31dd01987 100644 --- a/packages/metrics_center/lib/src/google_benchmark.dart +++ b/packages/metrics_center/lib/src/google_benchmark.dart @@ -30,20 +30,14 @@ const List _kNonNumericalValueSubResults = [ // Context has some keys such as 'host_name' which need to be ignored // so that we can group series together -const List _kContextIgnoreKeys = [ - 'host_name', - 'load_avg', - 'caches', -]; +const List _kContextIgnoreKeys = ['host_name', 'load_avg', 'caches']; // ignore: avoid_classes_with_only_static_members /// Parse the json result of https://github.com/google/benchmark. class GoogleBenchmarkParser { /// Given a Google benchmark json output, parse its content into a list of [MetricPoint]. static Future> parse(String jsonFileName) async { - final jsonResult = - jsonDecode(File(jsonFileName).readAsStringSync()) - as Map; + final jsonResult = jsonDecode(File(jsonFileName).readAsStringSync()) as Map; final rawContext = jsonResult['context'] as Map; final Map context = rawContext.map( @@ -65,8 +59,7 @@ void _parseAnItem( ) { final name = item[kNameKey] as String; final timeUnitMap = { - if (item.containsKey(_kTimeUnitKey)) - kUnitKey: item[_kTimeUnitKey] as String, + if (item.containsKey(_kTimeUnitKey)) kUnitKey: item[_kTimeUnitKey] as String, }; for (final String subResult in item.keys) { if (!_kNonNumericalValueSubResults.contains(subResult)) { @@ -81,17 +74,13 @@ void _parseAnItem( rethrow; } - final double? value = rawValue is int - ? rawValue.toDouble() - : rawValue as double?; + final double? value = rawValue is int ? rawValue.toDouble() : rawValue as double?; points.add( MetricPoint( value, {kNameKey: name, kSubResultKey: subResult} ..addAll(context) - ..addAll( - subResult.endsWith('time') ? timeUnitMap : {}, - ), + ..addAll(subResult.endsWith('time') ? timeUnitMap : {}), ), ); } diff --git a/packages/metrics_center/lib/src/skiaperf.dart b/packages/metrics_center/lib/src/skiaperf.dart index 7f3b98afee6b..1bbee35af7ed 100644 --- a/packages/metrics_center/lib/src/skiaperf.dart +++ b/packages/metrics_center/lib/src/skiaperf.dart @@ -7,8 +7,7 @@ import 'dart:convert'; import 'package:gcloud/storage.dart'; -import 'package:googleapis/storage/v1.dart' - show DetailedApiRequestError, StorageApi; +import 'package:googleapis/storage/v1.dart' show DetailedApiRequestError, StorageApi; import 'package:googleapis_auth/auth_io.dart'; import 'common.dart'; @@ -115,15 +114,7 @@ class SkiaPerfPoint extends MetricPoint { ), ); - return SkiaPerfPoint._( - githubRepo, - gitHash, - name, - subResult, - p.value, - options, - null, - ); + return SkiaPerfPoint._(githubRepo, gitHash, name, subResult, p.value, options, null); } /// In the format of `/` such as 'flutter/flutter' or @@ -170,8 +161,7 @@ class SkiaPerfPoint extends MetricPoint { assert(points.isNotEmpty); assert(() { for (final p in points) { - if (p.githubRepo != points[0].githubRepo || - p.gitHash != points[0].gitHash) { + if (p.githubRepo != points[0].githubRepo || p.gitHash != points[0].gitHash) { return false; } } @@ -182,30 +172,22 @@ class SkiaPerfPoint extends MetricPoint { for (final p in points) { final Map subResultJson = p._toSubResultJson(); if (results[p.testName] == null) { - results[p.testName] = { - kSkiaPerfDefaultConfig: subResultJson, - }; + results[p.testName] = {kSkiaPerfDefaultConfig: subResultJson}; } else { // Flutter currently doesn't support having the same name but different // options/configurations. If this actually happens in the future, we // probably can use different values of config (currently there's only // one kSkiaPerfDefaultConfig) to resolve the conflict. assert( - results[p.testName][kSkiaPerfDefaultConfig][kSkiaPerfOptionsKey] - .toString() == + results[p.testName][kSkiaPerfDefaultConfig][kSkiaPerfOptionsKey].toString() == subResultJson[kSkiaPerfOptionsKey].toString(), ); - assert( - results[p.testName][kSkiaPerfDefaultConfig][p.subResult] == null, - ); + assert(results[p.testName][kSkiaPerfDefaultConfig][p.subResult] == null); results[p.testName][kSkiaPerfDefaultConfig][p.subResult] = p.value; } } - return { - kSkiaPerfGitHashKey: points[0].gitHash, - kSkiaPerfResultsKey: results, - }; + return {kSkiaPerfGitHashKey: points[0].gitHash, kSkiaPerfResultsKey: results}; } // Equivalent to tags without git repo, git hash, and name because those two @@ -230,10 +212,7 @@ class SkiaPerfGcsAdaptor { /// /// The read may retry multiple times if transient network errors with code /// 504 happens. - Future writePoints( - String objectName, - List points, - ) async { + Future writePoints(String objectName, List points) async { final String jsonString = jsonEncode(SkiaPerfPoint.toSkiaPerfJson(points)); final List content = utf8.encode(jsonString); @@ -294,9 +273,7 @@ class SkiaPerfGcsAdaptor { final Stream> stream = _gcsBucket.read(objectName); final Stream byteStream = stream.expand((List x) => x); - final decodedJson = - jsonDecode(utf8.decode(await byteStream.toList())) - as Map; + final decodedJson = jsonDecode(utf8.decode(await byteStream.toList())) as Map; final points = []; @@ -307,8 +284,7 @@ class SkiaPerfGcsAdaptor { final gitHash = decodedJson[kSkiaPerfGitHashKey] as String?; final results = decodedJson[kSkiaPerfResultsKey] as Map; for (final String name in results.keys) { - final subResultMap = - results[name][kSkiaPerfDefaultConfig] as Map; + final subResultMap = results[name][kSkiaPerfDefaultConfig] as Map; for (final String subResult in subResultMap.keys.where( (String s) => s != kSkiaPerfOptionsKey, )) { @@ -319,8 +295,7 @@ class SkiaPerfGcsAdaptor { name, subResult, subResultMap[subResult] as double?, - (subResultMap[kSkiaPerfOptionsKey] as Map) - .cast(), + (subResultMap[kSkiaPerfOptionsKey] as Map).cast(), info.downloadLink.toString(), ), ); @@ -388,11 +363,7 @@ class SkiaPerfDestination extends MetricDestination { ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES, ); - return make( - client, - credentialsJson[kProjectId] as String, - isTesting: isTesting, - ); + return make(client, credentialsJson[kProjectId] as String, isTesting: isTesting); } /// Create from an access token and its project id. @@ -424,19 +395,13 @@ class SkiaPerfDestination extends MetricDestination { } @override - Future update( - List points, - DateTime commitTime, - String taskName, - ) async { + Future update(List points, DateTime commitTime, String taskName) async { // 1st, create a map based on git repo, git revision, and point id. Git repo // and git revision are the top level components of the Skia perf GCS object // name. final Map>> pointMap = >>{}; - for (final SkiaPerfPoint p in points.map( - (MetricPoint x) => SkiaPerfPoint.fromPoint(x), - )) { + for (final SkiaPerfPoint p in points.map((MetricPoint x) => SkiaPerfPoint.fromPoint(x))) { pointMap[p.githubRepo] ??= >{}; pointMap[p.githubRepo]![p.gitHash] ??= {}; pointMap[p.githubRepo]![p.gitHash]![p.id] = p; @@ -462,9 +427,7 @@ class SkiaPerfDestination extends MetricDestination { // file names. lockFutures.add( _lock!.protectedRun('$objectName.lock', () async { - final List oldPoints = await _gcs.readPoints( - objectName, - ); + final List oldPoints = await _gcs.readPoints(objectName); for (final p in oldPoints) { if (newPoints![p.id] == null) { newPoints[p.id] = p; diff --git a/packages/metrics_center/test/flutter_test.dart b/packages/metrics_center/test/flutter_test.dart index 44cb155d41d2..fa805246a3bf 100644 --- a/packages/metrics_center/test/flutter_test.dart +++ b/packages/metrics_center/test/flutter_test.dart @@ -10,11 +10,7 @@ import 'utility.dart'; void main() { const gitRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112'; - final simplePoint = FlutterEngineMetricPoint( - 'BM_ParagraphLongLayout', - 287235, - gitRevision, - ); + final simplePoint = FlutterEngineMetricPoint('BM_ParagraphLongLayout', 287235, gitRevision); test('FlutterEngineMetricPoint works.', () { expect(simplePoint.value, equals(287235)); @@ -40,20 +36,15 @@ void main() { final Map? credentialsJson = getTestGcpCredentialsJson(); - test( - 'FlutterDestination integration test with update.', - () async { - final FlutterDestination dst = - await FlutterDestination.makeFromCredentialsJson( - credentialsJson!, - isTesting: true, - ); - await dst.update( - [simplePoint], - DateTime.fromMillisecondsSinceEpoch(123), - 'test', - ); - }, - skip: credentialsJson == null, - ); + test('FlutterDestination integration test with update.', () async { + final FlutterDestination dst = await FlutterDestination.makeFromCredentialsJson( + credentialsJson!, + isTesting: true, + ); + await dst.update( + [simplePoint], + DateTime.fromMillisecondsSinceEpoch(123), + 'test', + ); + }, skip: credentialsJson == null); } diff --git a/packages/metrics_center/test/gcs_lock_test.dart b/packages/metrics_center/test/gcs_lock_test.dart index 4dbbb2b1cd68..245344e54a84 100644 --- a/packages/metrics_center/test/gcs_lock_test.dart +++ b/packages/metrics_center/test/gcs_lock_test.dart @@ -32,19 +32,14 @@ void main() { test('GcsLock prints warnings for long waits', () { // Capture print to verify error messages. final prints = []; - final spec = ZoneSpecification( - print: (_, __, ___, String msg) => prints.add(msg), - ); + final spec = ZoneSpecification(print: (_, __, ___, String msg) => prints.add(msg)); Zone.current.fork(specification: spec).run(() { fakeAsync((FakeAsync fakeAsync) { final mockClient = MockAuthClient(); final lock = GcsLock(StorageApi(mockClient), 'mockBucket'); when(mockClient.send(any)).thenThrow(DetailedApiRequestError(412, '')); - final Future runFinished = lock.protectedRun( - 'mock.lock', - () async {}, - ); + final Future runFinished = lock.protectedRun('mock.lock', () async {}); fakeAsync.elapse(const Duration(seconds: 10)); when(mockClient.send(any)).thenThrow(AssertionError('Stop!')); runFinished.catchError((dynamic e) { @@ -66,63 +61,55 @@ void main() { expect(prints, equals([kExpectedErrorMessage, 'Stop!'])); }); - test( - 'GcsLock integration test: single protectedRun is successful', - () async { - final AutoRefreshingAuthClient client = await clientViaServiceAccount( - ServiceAccountCredentials.fromJson(credentialsJson), - Storage.SCOPES, - ); - final lock = GcsLock(StorageApi(client), kTestBucketName); - var testValue = 0; - await lock.protectedRun('test.lock', () async { - testValue = 1; - }); - expect(testValue, 1); - }, - skip: credentialsJson == null, - ); - - test( - 'GcsLock integration test: protectedRun is exclusive', - () async { - final AutoRefreshingAuthClient client = await clientViaServiceAccount( - ServiceAccountCredentials.fromJson(credentialsJson), - Storage.SCOPES, - ); - final lock1 = GcsLock(StorageApi(client), kTestBucketName); - final lock2 = GcsLock(StorageApi(client), kTestBucketName); - - TestPhase phase = TestPhase.run1; - final started1 = Completer(); - final Future finished1 = lock1.protectedRun('test.lock', () async { - started1.complete(); - while (phase == TestPhase.run1) { - await Future.delayed(kDelayStep); - } - }); + test('GcsLock integration test: single protectedRun is successful', () async { + final AutoRefreshingAuthClient client = await clientViaServiceAccount( + ServiceAccountCredentials.fromJson(credentialsJson), + Storage.SCOPES, + ); + final lock = GcsLock(StorageApi(client), kTestBucketName); + var testValue = 0; + await lock.protectedRun('test.lock', () async { + testValue = 1; + }); + expect(testValue, 1); + }, skip: credentialsJson == null); - await started1.future; + test('GcsLock integration test: protectedRun is exclusive', () async { + final AutoRefreshingAuthClient client = await clientViaServiceAccount( + ServiceAccountCredentials.fromJson(credentialsJson), + Storage.SCOPES, + ); + final lock1 = GcsLock(StorageApi(client), kTestBucketName); + final lock2 = GcsLock(StorageApi(client), kTestBucketName); + + TestPhase phase = TestPhase.run1; + final started1 = Completer(); + final Future finished1 = lock1.protectedRun('test.lock', () async { + started1.complete(); + while (phase == TestPhase.run1) { + await Future.delayed(kDelayStep); + } + }); - final started2 = Completer(); - final Future finished2 = lock2.protectedRun('test.lock', () async { - started2.complete(); - }); + await started1.future; + + final started2 = Completer(); + final Future finished2 = lock2.protectedRun('test.lock', () async { + started2.complete(); + }); + + // started2 should not be set even after a long wait because lock1 is + // holding the GCS lock file. + await Future.delayed(kDelayStep * 10); + expect(started2.isCompleted, false); - // started2 should not be set even after a long wait because lock1 is - // holding the GCS lock file. - await Future.delayed(kDelayStep * 10); - expect(started2.isCompleted, false); - - // When phase is switched to run2, lock1 should be released soon and - // lock2 should soon be able to proceed its protectedRun. - phase = TestPhase.run2; - await started2.future; - await finished1; - await finished2; - }, - skip: credentialsJson == null, - ); + // When phase is switched to run2, lock1 should be released soon and + // lock2 should soon be able to proceed its protectedRun. + phase = TestPhase.run2; + await started2.future; + await finished1; + await finished2; + }, skip: credentialsJson == null); test('GcsLock attempts to unlock again on a DetailedApiRequestError', () async { fakeAsync((FakeAsync fakeAsync) { @@ -141,14 +128,10 @@ void main() { // Allow time to pass by to ensure deleting the lock file is retried multiple times. fakeAsync.elapse(const Duration(milliseconds: 30)); - verify( - mockObjectsResource.delete(kTestBucketName, lockFileName), - ).called(3); + verify(mockObjectsResource.delete(kTestBucketName, lockFileName)).called(3); // Simulate a successful deletion of the lock file. - when( - mockObjectsResource.delete(kTestBucketName, lockFileName), - ).thenAnswer( + when(mockObjectsResource.delete(kTestBucketName, lockFileName)).thenAnswer( (_) => Future(() { return; }), @@ -156,9 +139,7 @@ void main() { // At this point, there should only be one more (successful) attempt to delete the lock file. fakeAsync.elapse(const Duration(minutes: 2)); - verify( - mockObjectsResource.delete(kTestBucketName, lockFileName), - ).called(1); + verify(mockObjectsResource.delete(kTestBucketName, lockFileName)).called(1); }); }); } diff --git a/packages/metrics_center/test/gcs_lock_test.mocks.dart b/packages/metrics_center/test/gcs_lock_test.mocks.dart index 7edc41812063..2ca8e123f399 100644 --- a/packages/metrics_center/test/gcs_lock_test.mocks.dart +++ b/packages/metrics_center/test/gcs_lock_test.mocks.dart @@ -29,97 +29,79 @@ import 'package:mockito/src/dummies.dart' as _i8; // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class -class _FakeAccessCredentials_0 extends _i1.SmartFake - implements _i2.AccessCredentials { +class _FakeAccessCredentials_0 extends _i1.SmartFake implements _i2.AccessCredentials { _FakeAccessCredentials_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeResponse_1 extends _i1.SmartFake implements _i3.Response { - _FakeResponse_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeResponse_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeStreamedResponse_2 extends _i1.SmartFake - implements _i3.StreamedResponse { +class _FakeStreamedResponse_2 extends _i1.SmartFake implements _i3.StreamedResponse { _FakeStreamedResponse_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeAnywhereCachesResource_3 extends _i1.SmartFake - implements _i4.AnywhereCachesResource { +class _FakeAnywhereCachesResource_3 extends _i1.SmartFake implements _i4.AnywhereCachesResource { _FakeAnywhereCachesResource_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeBucketAccessControlsResource_4 extends _i1.SmartFake implements _i4.BucketAccessControlsResource { - _FakeBucketAccessControlsResource_4( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeBucketAccessControlsResource_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeBucketsResource_5 extends _i1.SmartFake - implements _i4.BucketsResource { +class _FakeBucketsResource_5 extends _i1.SmartFake implements _i4.BucketsResource { _FakeBucketsResource_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeChannelsResource_6 extends _i1.SmartFake - implements _i4.ChannelsResource { +class _FakeChannelsResource_6 extends _i1.SmartFake implements _i4.ChannelsResource { _FakeChannelsResource_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeDefaultObjectAccessControlsResource_7 extends _i1.SmartFake implements _i4.DefaultObjectAccessControlsResource { - _FakeDefaultObjectAccessControlsResource_7( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeDefaultObjectAccessControlsResource_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeFoldersResource_8 extends _i1.SmartFake - implements _i4.FoldersResource { +class _FakeFoldersResource_8 extends _i1.SmartFake implements _i4.FoldersResource { _FakeFoldersResource_8(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeManagedFoldersResource_9 extends _i1.SmartFake - implements _i4.ManagedFoldersResource { +class _FakeManagedFoldersResource_9 extends _i1.SmartFake implements _i4.ManagedFoldersResource { _FakeManagedFoldersResource_9(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeNotificationsResource_10 extends _i1.SmartFake - implements _i4.NotificationsResource { +class _FakeNotificationsResource_10 extends _i1.SmartFake implements _i4.NotificationsResource { _FakeNotificationsResource_10(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeObjectAccessControlsResource_11 extends _i1.SmartFake implements _i4.ObjectAccessControlsResource { - _FakeObjectAccessControlsResource_11( - Object parent, - Invocation parentInvocation, - ) : super(parent, parentInvocation); + _FakeObjectAccessControlsResource_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeObjectsResource_12 extends _i1.SmartFake - implements _i4.ObjectsResource { +class _FakeObjectsResource_12 extends _i1.SmartFake implements _i4.ObjectsResource { _FakeObjectsResource_12(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeOperationsResource_13 extends _i1.SmartFake - implements _i4.OperationsResource { +class _FakeOperationsResource_13 extends _i1.SmartFake implements _i4.OperationsResource { _FakeOperationsResource_13(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeProjectsResource_14 extends _i1.SmartFake - implements _i4.ProjectsResource { +class _FakeProjectsResource_14 extends _i1.SmartFake implements _i4.ProjectsResource { _FakeProjectsResource_14(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -131,27 +113,22 @@ class _FakeGoogleLongrunningOperation_15 extends _i1.SmartFake } class _FakeObject_16 extends _i1.SmartFake implements _i4.Object { - _FakeObject_16(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeObject_16(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeObject_17 extends _i1.SmartFake implements Object { - _FakeObject_17(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeObject_17(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakePolicy_18 extends _i1.SmartFake implements _i4.Policy { - _FakePolicy_18(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakePolicy_18(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeObjects_19 extends _i1.SmartFake implements _i4.Objects { - _FakeObjects_19(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeObjects_19(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeRewriteResponse_20 extends _i1.SmartFake - implements _i4.RewriteResponse { +class _FakeRewriteResponse_20 extends _i1.SmartFake implements _i4.RewriteResponse { _FakeRewriteResponse_20(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -163,8 +140,7 @@ class _FakeTestIamPermissionsResponse_21 extends _i1.SmartFake } class _FakeChannel_22 extends _i1.SmartFake implements _i4.Channel { - _FakeChannel_22(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeChannel_22(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [AuthClient]. @@ -176,41 +152,26 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { } @override - _i2.AccessCredentials get credentials => - (super.noSuchMethod( - Invocation.getter(#credentials), - returnValue: _FakeAccessCredentials_0( - this, - Invocation.getter(#credentials), - ), - ) - as _i2.AccessCredentials); + _i2.AccessCredentials get credentials => (super.noSuchMethod( + Invocation.getter(#credentials), + returnValue: _FakeAccessCredentials_0(this, Invocation.getter(#credentials)), + ) as _i2.AccessCredentials); @override - _i6.Future<_i3.Response> head(Uri? url, {Map? headers}) => - (super.noSuchMethod( - Invocation.method(#head, [url], {#headers: headers}), - returnValue: _i6.Future<_i3.Response>.value( - _FakeResponse_1( - this, - Invocation.method(#head, [url], {#headers: headers}), - ), - ), - ) - as _i6.Future<_i3.Response>); + _i6.Future<_i3.Response> head(Uri? url, {Map? headers}) => (super.noSuchMethod( + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1(this, Invocation.method(#head, [url], {#headers: headers})), + ), + ) as _i6.Future<_i3.Response>); @override - _i6.Future<_i3.Response> get(Uri? url, {Map? headers}) => - (super.noSuchMethod( - Invocation.method(#get, [url], {#headers: headers}), - returnValue: _i6.Future<_i3.Response>.value( - _FakeResponse_1( - this, - Invocation.method(#get, [url], {#headers: headers}), - ), - ), - ) - as _i6.Future<_i3.Response>); + _i6.Future<_i3.Response> get(Uri? url, {Map? headers}) => (super.noSuchMethod( + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1(this, Invocation.method(#get, [url], {#headers: headers})), + ), + ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> post( @@ -218,25 +179,15 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { Map? headers, Object? body, _i7.Encoding? encoding, - }) => - (super.noSuchMethod( - Invocation.method( - #post, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - returnValue: _i6.Future<_i3.Response>.value( - _FakeResponse_1( - this, - Invocation.method( - #post, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - ), - ), - ) - as _i6.Future<_i3.Response>); + }) => (super.noSuchMethod( + Invocation.method(#post, [url], {#headers: headers, #body: body, #encoding: encoding}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method(#post, [url], {#headers: headers, #body: body, #encoding: encoding}), + ), + ), + ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> put( @@ -244,25 +195,15 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { Map? headers, Object? body, _i7.Encoding? encoding, - }) => - (super.noSuchMethod( - Invocation.method( - #put, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - returnValue: _i6.Future<_i3.Response>.value( - _FakeResponse_1( - this, - Invocation.method( - #put, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - ), - ), - ) - as _i6.Future<_i3.Response>); + }) => (super.noSuchMethod( + Invocation.method(#put, [url], {#headers: headers, #body: body, #encoding: encoding}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method(#put, [url], {#headers: headers, #body: body, #encoding: encoding}), + ), + ), + ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> patch( @@ -270,25 +211,15 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { Map? headers, Object? body, _i7.Encoding? encoding, - }) => - (super.noSuchMethod( - Invocation.method( - #patch, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - returnValue: _i6.Future<_i3.Response>.value( - _FakeResponse_1( - this, - Invocation.method( - #patch, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - ), - ), - ) - as _i6.Future<_i3.Response>); + }) => (super.noSuchMethod( + Invocation.method(#patch, [url], {#headers: headers, #body: body, #encoding: encoding}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method(#patch, [url], {#headers: headers, #body: body, #encoding: encoding}), + ), + ), + ) as _i6.Future<_i3.Response>); @override _i6.Future<_i3.Response> delete( @@ -296,68 +227,42 @@ class MockAuthClient extends _i1.Mock implements _i5.AuthClient { Map? headers, Object? body, _i7.Encoding? encoding, - }) => - (super.noSuchMethod( - Invocation.method( - #delete, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - returnValue: _i6.Future<_i3.Response>.value( - _FakeResponse_1( - this, - Invocation.method( - #delete, - [url], - {#headers: headers, #body: body, #encoding: encoding}, - ), - ), - ), - ) - as _i6.Future<_i3.Response>); + }) => (super.noSuchMethod( + Invocation.method(#delete, [url], {#headers: headers, #body: body, #encoding: encoding}), + returnValue: _i6.Future<_i3.Response>.value( + _FakeResponse_1( + this, + Invocation.method(#delete, [url], {#headers: headers, #body: body, #encoding: encoding}), + ), + ), + ) as _i6.Future<_i3.Response>); @override - _i6.Future read(Uri? url, {Map? headers}) => - (super.noSuchMethod( - Invocation.method(#read, [url], {#headers: headers}), - returnValue: _i6.Future.value( - _i8.dummyValue( - this, - Invocation.method(#read, [url], {#headers: headers}), - ), - ), - ) - as _i6.Future); + _i6.Future read(Uri? url, {Map? headers}) => (super.noSuchMethod( + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i6.Future.value( + _i8.dummyValue(this, Invocation.method(#read, [url], {#headers: headers})), + ), + ) as _i6.Future); @override - _i6.Future<_i9.Uint8List> readBytes( - Uri? url, { - Map? headers, - }) => + _i6.Future<_i9.Uint8List> readBytes(Uri? url, {Map? headers}) => (super.noSuchMethod( - Invocation.method(#readBytes, [url], {#headers: headers}), - returnValue: _i6.Future<_i9.Uint8List>.value(_i9.Uint8List(0)), - ) - as _i6.Future<_i9.Uint8List>); + Invocation.method(#readBytes, [url], {#headers: headers}), + returnValue: _i6.Future<_i9.Uint8List>.value(_i9.Uint8List(0)), + ) as _i6.Future<_i9.Uint8List>); @override - _i6.Future<_i3.StreamedResponse> send(_i3.BaseRequest? request) => - (super.noSuchMethod( - Invocation.method(#send, [request]), - returnValue: _i6.Future<_i3.StreamedResponse>.value( - _FakeStreamedResponse_2( - this, - Invocation.method(#send, [request]), - ), - ), - ) - as _i6.Future<_i3.StreamedResponse>); + _i6.Future<_i3.StreamedResponse> send(_i3.BaseRequest? request) => (super.noSuchMethod( + Invocation.method(#send, [request]), + returnValue: _i6.Future<_i3.StreamedResponse>.value( + _FakeStreamedResponse_2(this, Invocation.method(#send, [request])), + ), + ) as _i6.Future<_i3.StreamedResponse>); @override - void close() => super.noSuchMethod( - Invocation.method(#close, []), - returnValueForMissingStub: null, - ); + void close() => + super.noSuchMethod(Invocation.method(#close, []), returnValueForMissingStub: null); } /// A class which mocks [StorageApi]. @@ -369,136 +274,85 @@ class MockStorageApi extends _i1.Mock implements _i4.StorageApi { } @override - _i4.AnywhereCachesResource get anywhereCaches => - (super.noSuchMethod( - Invocation.getter(#anywhereCaches), - returnValue: _FakeAnywhereCachesResource_3( - this, - Invocation.getter(#anywhereCaches), - ), - ) - as _i4.AnywhereCachesResource); + _i4.AnywhereCachesResource get anywhereCaches => (super.noSuchMethod( + Invocation.getter(#anywhereCaches), + returnValue: _FakeAnywhereCachesResource_3(this, Invocation.getter(#anywhereCaches)), + ) as _i4.AnywhereCachesResource); @override - _i4.BucketAccessControlsResource get bucketAccessControls => - (super.noSuchMethod( - Invocation.getter(#bucketAccessControls), - returnValue: _FakeBucketAccessControlsResource_4( - this, - Invocation.getter(#bucketAccessControls), - ), - ) - as _i4.BucketAccessControlsResource); + _i4.BucketAccessControlsResource get bucketAccessControls => (super.noSuchMethod( + Invocation.getter(#bucketAccessControls), + returnValue: _FakeBucketAccessControlsResource_4( + this, + Invocation.getter(#bucketAccessControls), + ), + ) as _i4.BucketAccessControlsResource); @override - _i4.BucketsResource get buckets => - (super.noSuchMethod( - Invocation.getter(#buckets), - returnValue: _FakeBucketsResource_5( - this, - Invocation.getter(#buckets), - ), - ) - as _i4.BucketsResource); + _i4.BucketsResource get buckets => (super.noSuchMethod( + Invocation.getter(#buckets), + returnValue: _FakeBucketsResource_5(this, Invocation.getter(#buckets)), + ) as _i4.BucketsResource); @override - _i4.ChannelsResource get channels => - (super.noSuchMethod( - Invocation.getter(#channels), - returnValue: _FakeChannelsResource_6( - this, - Invocation.getter(#channels), - ), - ) - as _i4.ChannelsResource); + _i4.ChannelsResource get channels => (super.noSuchMethod( + Invocation.getter(#channels), + returnValue: _FakeChannelsResource_6(this, Invocation.getter(#channels)), + ) as _i4.ChannelsResource); @override - _i4.DefaultObjectAccessControlsResource get defaultObjectAccessControls => - (super.noSuchMethod( - Invocation.getter(#defaultObjectAccessControls), - returnValue: _FakeDefaultObjectAccessControlsResource_7( - this, - Invocation.getter(#defaultObjectAccessControls), - ), - ) - as _i4.DefaultObjectAccessControlsResource); + _i4.DefaultObjectAccessControlsResource get defaultObjectAccessControls => (super.noSuchMethod( + Invocation.getter(#defaultObjectAccessControls), + returnValue: _FakeDefaultObjectAccessControlsResource_7( + this, + Invocation.getter(#defaultObjectAccessControls), + ), + ) as _i4.DefaultObjectAccessControlsResource); @override - _i4.FoldersResource get folders => - (super.noSuchMethod( - Invocation.getter(#folders), - returnValue: _FakeFoldersResource_8( - this, - Invocation.getter(#folders), - ), - ) - as _i4.FoldersResource); + _i4.FoldersResource get folders => (super.noSuchMethod( + Invocation.getter(#folders), + returnValue: _FakeFoldersResource_8(this, Invocation.getter(#folders)), + ) as _i4.FoldersResource); @override - _i4.ManagedFoldersResource get managedFolders => - (super.noSuchMethod( - Invocation.getter(#managedFolders), - returnValue: _FakeManagedFoldersResource_9( - this, - Invocation.getter(#managedFolders), - ), - ) - as _i4.ManagedFoldersResource); + _i4.ManagedFoldersResource get managedFolders => (super.noSuchMethod( + Invocation.getter(#managedFolders), + returnValue: _FakeManagedFoldersResource_9(this, Invocation.getter(#managedFolders)), + ) as _i4.ManagedFoldersResource); @override - _i4.NotificationsResource get notifications => - (super.noSuchMethod( - Invocation.getter(#notifications), - returnValue: _FakeNotificationsResource_10( - this, - Invocation.getter(#notifications), - ), - ) - as _i4.NotificationsResource); + _i4.NotificationsResource get notifications => (super.noSuchMethod( + Invocation.getter(#notifications), + returnValue: _FakeNotificationsResource_10(this, Invocation.getter(#notifications)), + ) as _i4.NotificationsResource); @override - _i4.ObjectAccessControlsResource get objectAccessControls => - (super.noSuchMethod( - Invocation.getter(#objectAccessControls), - returnValue: _FakeObjectAccessControlsResource_11( - this, - Invocation.getter(#objectAccessControls), - ), - ) - as _i4.ObjectAccessControlsResource); + _i4.ObjectAccessControlsResource get objectAccessControls => (super.noSuchMethod( + Invocation.getter(#objectAccessControls), + returnValue: _FakeObjectAccessControlsResource_11( + this, + Invocation.getter(#objectAccessControls), + ), + ) as _i4.ObjectAccessControlsResource); @override - _i4.ObjectsResource get objects => - (super.noSuchMethod( - Invocation.getter(#objects), - returnValue: _FakeObjectsResource_12( - this, - Invocation.getter(#objects), - ), - ) - as _i4.ObjectsResource); + _i4.ObjectsResource get objects => (super.noSuchMethod( + Invocation.getter(#objects), + returnValue: _FakeObjectsResource_12(this, Invocation.getter(#objects)), + ) as _i4.ObjectsResource); @override - _i4.OperationsResource get operations => - (super.noSuchMethod( - Invocation.getter(#operations), - returnValue: _FakeOperationsResource_13( - this, - Invocation.getter(#operations), - ), - ) - as _i4.OperationsResource); + _i4.OperationsResource get operations => (super.noSuchMethod( + Invocation.getter(#operations), + returnValue: _FakeOperationsResource_13(this, Invocation.getter(#operations)), + ) as _i4.OperationsResource); @override - _i4.ProjectsResource get projects => - (super.noSuchMethod( - Invocation.getter(#projects), - returnValue: _FakeProjectsResource_14( - this, - Invocation.getter(#projects), - ), - ) - as _i4.ProjectsResource); + _i4.ProjectsResource get projects => (super.noSuchMethod( + Invocation.getter(#projects), + returnValue: _FakeProjectsResource_14(this, Invocation.getter(#projects)), + ) as _i4.ProjectsResource); } /// A class which mocks [ObjectsResource]. @@ -510,36 +364,21 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { _i4.BulkRestoreObjectsRequest? request, String? bucket, { String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #bulkRestore, - [request, bucket], - {#$fields: $fields}, - ), - returnValue: _i6.Future<_i4.GoogleLongrunningOperation>.value( - _FakeGoogleLongrunningOperation_15( - this, - Invocation.method( - #bulkRestore, - [request, bucket], - {#$fields: $fields}, - ), - ), - ), - returnValueForMissingStub: - _i6.Future<_i4.GoogleLongrunningOperation>.value( - _FakeGoogleLongrunningOperation_15( - this, - Invocation.method( - #bulkRestore, - [request, bucket], - {#$fields: $fields}, - ), - ), - ), - ) - as _i6.Future<_i4.GoogleLongrunningOperation>); + }) => (super.noSuchMethod( + Invocation.method(#bulkRestore, [request, bucket], {#$fields: $fields}), + returnValue: _i6.Future<_i4.GoogleLongrunningOperation>.value( + _FakeGoogleLongrunningOperation_15( + this, + Invocation.method(#bulkRestore, [request, bucket], {#$fields: $fields}), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.GoogleLongrunningOperation>.value( + _FakeGoogleLongrunningOperation_15( + this, + Invocation.method(#bulkRestore, [request, bucket], {#$fields: $fields}), + ), + ), + ) as _i6.Future<_i4.GoogleLongrunningOperation>); @override _i6.Future<_i4.Object> compose( @@ -552,56 +391,54 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? kmsKeyName, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #compose, - [request, destinationBucket, destinationObject], - { - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #kmsKeyName: kmsKeyName, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #compose, - [request, destinationBucket, destinationObject], - { - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #kmsKeyName: kmsKeyName, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #compose, - [request, destinationBucket, destinationObject], - { - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #kmsKeyName: kmsKeyName, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Object>); + }) => (super.noSuchMethod( + Invocation.method( + #compose, + [request, destinationBucket, destinationObject], + { + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #kmsKeyName: kmsKeyName, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #compose, + [request, destinationBucket, destinationObject], + { + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #kmsKeyName: kmsKeyName, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #compose, + [request, destinationBucket, destinationObject], + { + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #kmsKeyName: kmsKeyName, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> copy( @@ -624,100 +461,78 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? sourceGeneration, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #copy, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #projection: projection, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #copy, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: - ifSourceMetagenerationNotMatch, - #projection: projection, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #copy, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: - ifSourceMetagenerationNotMatch, - #projection: projection, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Object>); + }) => (super.noSuchMethod( + Invocation.method( + #copy, + [request, sourceBucket, sourceObject, destinationBucket, destinationObject], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #projection: projection, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #copy, + [request, sourceBucket, sourceObject, destinationBucket, destinationObject], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #projection: projection, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #copy, + [request, sourceBucket, sourceObject, destinationBucket, destinationObject], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #projection: projection, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Object>); @override _i6.Future delete( @@ -730,25 +545,23 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? ifMetagenerationNotMatch, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #delete, - [bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future.value(), - returnValueForMissingStub: _i6.Future.value(), - ) - as _i6.Future); + }) => (super.noSuchMethod( + Invocation.method( + #delete, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future.value(), + returnValueForMissingStub: _i6.Future.value(), + ) as _i6.Future); @override _i6.Future get( @@ -765,71 +578,69 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? userProject, String? $fields, _i10.DownloadOptions? downloadOptions = _i10.DownloadOptions.metadata, - }) => - (super.noSuchMethod( - Invocation.method( - #get, - [bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #softDeleted: softDeleted, - #userProject: userProject, - #$fields: $fields, - #downloadOptions: downloadOptions, - }, - ), - returnValue: _i6.Future.value( - _FakeObject_17( - this, - Invocation.method( - #get, - [bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #softDeleted: softDeleted, - #userProject: userProject, - #$fields: $fields, - #downloadOptions: downloadOptions, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future.value( - _FakeObject_17( - this, - Invocation.method( - #get, - [bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #softDeleted: softDeleted, - #userProject: userProject, - #$fields: $fields, - #downloadOptions: downloadOptions, - }, - ), - ), - ), - ) - as _i6.Future); + }) => (super.noSuchMethod( + Invocation.method( + #get, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #softDeleted: softDeleted, + #userProject: userProject, + #$fields: $fields, + #downloadOptions: downloadOptions, + }, + ), + returnValue: _i6.Future.value( + _FakeObject_17( + this, + Invocation.method( + #get, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #softDeleted: softDeleted, + #userProject: userProject, + #$fields: $fields, + #downloadOptions: downloadOptions, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future.value( + _FakeObject_17( + this, + Invocation.method( + #get, + [bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #softDeleted: softDeleted, + #userProject: userProject, + #$fields: $fields, + #downloadOptions: downloadOptions, + }, + ), + ), + ), + ) as _i6.Future); @override _i6.Future<_i4.Policy> getIamPolicy( @@ -838,47 +649,33 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? generation, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #getIamPolicy, - [bucket, object], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Policy>.value( - _FakePolicy_18( - this, - Invocation.method( - #getIamPolicy, - [bucket, object], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Policy>.value( - _FakePolicy_18( - this, - Invocation.method( - #getIamPolicy, - [bucket, object], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Policy>); + }) => (super.noSuchMethod( + Invocation.method( + #getIamPolicy, + [bucket, object], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + returnValue: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #getIamPolicy, + [bucket, object], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #getIamPolicy, + [bucket, object], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + ), + ), + ) as _i6.Future<_i4.Policy>); @override _i6.Future<_i4.Object> insert( @@ -897,77 +694,75 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? $fields, _i10.UploadOptions? uploadOptions = _i10.UploadOptions.defaultOptions, _i10.Media? uploadMedia, - }) => - (super.noSuchMethod( - Invocation.method( - #insert, - [request, bucket], - { - #contentEncoding: contentEncoding, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #kmsKeyName: kmsKeyName, - #name: name, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - #uploadOptions: uploadOptions, - #uploadMedia: uploadMedia, - }, - ), - returnValue: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #insert, - [request, bucket], - { - #contentEncoding: contentEncoding, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #kmsKeyName: kmsKeyName, - #name: name, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - #uploadOptions: uploadOptions, - #uploadMedia: uploadMedia, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #insert, - [request, bucket], - { - #contentEncoding: contentEncoding, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #kmsKeyName: kmsKeyName, - #name: name, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - #uploadOptions: uploadOptions, - #uploadMedia: uploadMedia, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Object>); + }) => (super.noSuchMethod( + Invocation.method( + #insert, + [request, bucket], + { + #contentEncoding: contentEncoding, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #kmsKeyName: kmsKeyName, + #name: name, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + #uploadOptions: uploadOptions, + #uploadMedia: uploadMedia, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #insert, + [request, bucket], + { + #contentEncoding: contentEncoding, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #kmsKeyName: kmsKeyName, + #name: name, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + #uploadOptions: uploadOptions, + #uploadMedia: uploadMedia, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #insert, + [request, bucket], + { + #contentEncoding: contentEncoding, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #kmsKeyName: kmsKeyName, + #name: name, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + #uploadOptions: uploadOptions, + #uploadMedia: uploadMedia, + }, + ), + ), + ), + ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Objects> list( @@ -986,80 +781,78 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? userProject, bool? versions, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #list, - [bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeFoldersAsPrefixes: includeFoldersAsPrefixes, - #includeTrailingDelimiter: includeTrailingDelimiter, - #matchGlob: matchGlob, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #softDeleted: softDeleted, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Objects>.value( - _FakeObjects_19( - this, - Invocation.method( - #list, - [bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeFoldersAsPrefixes: includeFoldersAsPrefixes, - #includeTrailingDelimiter: includeTrailingDelimiter, - #matchGlob: matchGlob, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #softDeleted: softDeleted, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Objects>.value( - _FakeObjects_19( - this, - Invocation.method( - #list, - [bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeFoldersAsPrefixes: includeFoldersAsPrefixes, - #includeTrailingDelimiter: includeTrailingDelimiter, - #matchGlob: matchGlob, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #softDeleted: softDeleted, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Objects>); + }) => (super.noSuchMethod( + Invocation.method( + #list, + [bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeFoldersAsPrefixes: includeFoldersAsPrefixes, + #includeTrailingDelimiter: includeTrailingDelimiter, + #matchGlob: matchGlob, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #softDeleted: softDeleted, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Objects>.value( + _FakeObjects_19( + this, + Invocation.method( + #list, + [bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeFoldersAsPrefixes: includeFoldersAsPrefixes, + #includeTrailingDelimiter: includeTrailingDelimiter, + #matchGlob: matchGlob, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #softDeleted: softDeleted, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Objects>.value( + _FakeObjects_19( + this, + Invocation.method( + #list, + [bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeFoldersAsPrefixes: includeFoldersAsPrefixes, + #includeTrailingDelimiter: includeTrailingDelimiter, + #matchGlob: matchGlob, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #softDeleted: softDeleted, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Objects>); @override _i6.Future<_i4.Object> move( @@ -1076,70 +869,66 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? ifSourceMetagenerationNotMatch, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #move, - [bucket, sourceObject, destinationObject], - { - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #move, - [bucket, sourceObject, destinationObject], - { - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: - ifSourceMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #move, - [bucket, sourceObject, destinationObject], - { - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: - ifSourceMetagenerationNotMatch, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Object>); + }) => (super.noSuchMethod( + Invocation.method( + #move, + [bucket, sourceObject, destinationObject], + { + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #move, + [bucket, sourceObject, destinationObject], + { + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #move, + [bucket, sourceObject, destinationObject], + { + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> patch( @@ -1156,68 +945,66 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? projection, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #patch, - [request, bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #patch, - [request, bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #patch, - [request, bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Object>); + }) => (super.noSuchMethod( + Invocation.method( + #patch, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #patch, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #patch, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Object> restore( @@ -1233,65 +1020,63 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? restoreToken, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #restore, - [bucket, object, generation], - { - #copySourceAcl: copySourceAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #restore, - [bucket, object, generation], - { - #copySourceAcl: copySourceAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #restore, - [bucket, object, generation], - { - #copySourceAcl: copySourceAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #projection: projection, - #restoreToken: restoreToken, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Object>); + }) => (super.noSuchMethod( + Invocation.method( + #restore, + [bucket, object, generation], + { + #copySourceAcl: copySourceAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #restore, + [bucket, object, generation], + { + #copySourceAcl: copySourceAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #restore, + [bucket, object, generation], + { + #copySourceAcl: copySourceAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #projection: projection, + #restoreToken: restoreToken, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.RewriteResponse> rewrite( @@ -1316,106 +1101,84 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? sourceGeneration, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #rewrite, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, - #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, - #projection: projection, - #rewriteToken: rewriteToken, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.RewriteResponse>.value( - _FakeRewriteResponse_20( - this, - Invocation.method( - #rewrite, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: - ifSourceMetagenerationNotMatch, - #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, - #projection: projection, - #rewriteToken: rewriteToken, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.RewriteResponse>.value( - _FakeRewriteResponse_20( - this, - Invocation.method( - #rewrite, - [ - request, - sourceBucket, - sourceObject, - destinationBucket, - destinationObject, - ], - { - #destinationKmsKeyName: destinationKmsKeyName, - #destinationPredefinedAcl: destinationPredefinedAcl, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #ifSourceGenerationMatch: ifSourceGenerationMatch, - #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, - #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, - #ifSourceMetagenerationNotMatch: - ifSourceMetagenerationNotMatch, - #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, - #projection: projection, - #rewriteToken: rewriteToken, - #sourceGeneration: sourceGeneration, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.RewriteResponse>); + }) => (super.noSuchMethod( + Invocation.method( + #rewrite, + [request, sourceBucket, sourceObject, destinationBucket, destinationObject], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, + #projection: projection, + #rewriteToken: rewriteToken, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.RewriteResponse>.value( + _FakeRewriteResponse_20( + this, + Invocation.method( + #rewrite, + [request, sourceBucket, sourceObject, destinationBucket, destinationObject], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, + #projection: projection, + #rewriteToken: rewriteToken, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.RewriteResponse>.value( + _FakeRewriteResponse_20( + this, + Invocation.method( + #rewrite, + [request, sourceBucket, sourceObject, destinationBucket, destinationObject], + { + #destinationKmsKeyName: destinationKmsKeyName, + #destinationPredefinedAcl: destinationPredefinedAcl, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #ifSourceGenerationMatch: ifSourceGenerationMatch, + #ifSourceGenerationNotMatch: ifSourceGenerationNotMatch, + #ifSourceMetagenerationMatch: ifSourceMetagenerationMatch, + #ifSourceMetagenerationNotMatch: ifSourceMetagenerationNotMatch, + #maxBytesRewrittenPerCall: maxBytesRewrittenPerCall, + #projection: projection, + #rewriteToken: rewriteToken, + #sourceGeneration: sourceGeneration, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.RewriteResponse>); @override _i6.Future<_i4.Policy> setIamPolicy( @@ -1425,47 +1188,33 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? generation, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #setIamPolicy, - [request, bucket, object], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Policy>.value( - _FakePolicy_18( - this, - Invocation.method( - #setIamPolicy, - [request, bucket, object], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Policy>.value( - _FakePolicy_18( - this, - Invocation.method( - #setIamPolicy, - [request, bucket, object], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Policy>); + }) => (super.noSuchMethod( + Invocation.method( + #setIamPolicy, + [request, bucket, object], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + returnValue: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #setIamPolicy, + [request, bucket, object], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Policy>.value( + _FakePolicy_18( + this, + Invocation.method( + #setIamPolicy, + [request, bucket, object], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + ), + ), + ) as _i6.Future<_i4.Policy>); @override _i6.Future<_i4.TestIamPermissionsResponse> testIamPermissions( @@ -1475,48 +1224,33 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? generation, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #testIamPermissions, - [bucket, object, permissions], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.TestIamPermissionsResponse>.value( - _FakeTestIamPermissionsResponse_21( - this, - Invocation.method( - #testIamPermissions, - [bucket, object, permissions], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: - _i6.Future<_i4.TestIamPermissionsResponse>.value( - _FakeTestIamPermissionsResponse_21( - this, - Invocation.method( - #testIamPermissions, - [bucket, object, permissions], - { - #generation: generation, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.TestIamPermissionsResponse>); + }) => (super.noSuchMethod( + Invocation.method( + #testIamPermissions, + [bucket, object, permissions], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + returnValue: _i6.Future<_i4.TestIamPermissionsResponse>.value( + _FakeTestIamPermissionsResponse_21( + this, + Invocation.method( + #testIamPermissions, + [bucket, object, permissions], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.TestIamPermissionsResponse>.value( + _FakeTestIamPermissionsResponse_21( + this, + Invocation.method( + #testIamPermissions, + [bucket, object, permissions], + {#generation: generation, #userProject: userProject, #$fields: $fields}, + ), + ), + ), + ) as _i6.Future<_i4.TestIamPermissionsResponse>); @override _i6.Future<_i4.Object> update( @@ -1533,68 +1267,66 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? projection, String? userProject, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #update, - [request, bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #update, - [request, bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Object>.value( - _FakeObject_16( - this, - Invocation.method( - #update, - [request, bucket, object], - { - #generation: generation, - #ifGenerationMatch: ifGenerationMatch, - #ifGenerationNotMatch: ifGenerationNotMatch, - #ifMetagenerationMatch: ifMetagenerationMatch, - #ifMetagenerationNotMatch: ifMetagenerationNotMatch, - #overrideUnlockedRetention: overrideUnlockedRetention, - #predefinedAcl: predefinedAcl, - #projection: projection, - #userProject: userProject, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Object>); + }) => (super.noSuchMethod( + Invocation.method( + #update, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #update, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Object>.value( + _FakeObject_16( + this, + Invocation.method( + #update, + [request, bucket, object], + { + #generation: generation, + #ifGenerationMatch: ifGenerationMatch, + #ifGenerationNotMatch: ifGenerationNotMatch, + #ifMetagenerationMatch: ifMetagenerationMatch, + #ifMetagenerationNotMatch: ifMetagenerationNotMatch, + #overrideUnlockedRetention: overrideUnlockedRetention, + #predefinedAcl: predefinedAcl, + #projection: projection, + #userProject: userProject, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Object>); @override _i6.Future<_i4.Channel> watchAll( @@ -1611,69 +1343,67 @@ class MockObjectsResource extends _i1.Mock implements _i4.ObjectsResource { String? userProject, bool? versions, String? $fields, - }) => - (super.noSuchMethod( - Invocation.method( - #watchAll, - [request, bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeTrailingDelimiter: includeTrailingDelimiter, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - returnValue: _i6.Future<_i4.Channel>.value( - _FakeChannel_22( - this, - Invocation.method( - #watchAll, - [request, bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeTrailingDelimiter: includeTrailingDelimiter, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - ), - ), - returnValueForMissingStub: _i6.Future<_i4.Channel>.value( - _FakeChannel_22( - this, - Invocation.method( - #watchAll, - [request, bucket], - { - #delimiter: delimiter, - #endOffset: endOffset, - #includeTrailingDelimiter: includeTrailingDelimiter, - #maxResults: maxResults, - #pageToken: pageToken, - #prefix: prefix, - #projection: projection, - #startOffset: startOffset, - #userProject: userProject, - #versions: versions, - #$fields: $fields, - }, - ), - ), - ), - ) - as _i6.Future<_i4.Channel>); + }) => (super.noSuchMethod( + Invocation.method( + #watchAll, + [request, bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeTrailingDelimiter: includeTrailingDelimiter, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + returnValue: _i6.Future<_i4.Channel>.value( + _FakeChannel_22( + this, + Invocation.method( + #watchAll, + [request, bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeTrailingDelimiter: includeTrailingDelimiter, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + returnValueForMissingStub: _i6.Future<_i4.Channel>.value( + _FakeChannel_22( + this, + Invocation.method( + #watchAll, + [request, bucket], + { + #delimiter: delimiter, + #endOffset: endOffset, + #includeTrailingDelimiter: includeTrailingDelimiter, + #maxResults: maxResults, + #pageToken: pageToken, + #prefix: prefix, + #projection: projection, + #startOffset: startOffset, + #userProject: userProject, + #versions: versions, + #$fields: $fields, + }, + ), + ), + ), + ) as _i6.Future<_i4.Channel>); } diff --git a/packages/metrics_center/test/google_benchmark_test.dart b/packages/metrics_center/test/google_benchmark_test.dart index 8e7a76257374..d16bb29df8b4 100644 --- a/packages/metrics_center/test/google_benchmark_test.dart +++ b/packages/metrics_center/test/google_benchmark_test.dart @@ -26,16 +26,13 @@ void main() { 3.89, 4.89, ]); - expectSetMatch( - points.map((MetricPoint p) => p.tags[kSubResultKey]), - [ - 'cpu_time', - 'real_time', - 'cpu_coefficient', - 'real_coefficient', - 'rms', - ], - ); + expectSetMatch(points.map((MetricPoint p) => p.tags[kSubResultKey]), [ + 'cpu_time', + 'real_time', + 'cpu_coefficient', + 'real_coefficient', + 'rms', + ]); expectSetMatch(points.map((MetricPoint p) => p.tags[kNameKey]), [ 'BM_PaintRecordInit', 'SkParagraphFixture/ShortLayout', diff --git a/packages/metrics_center/test/skiaperf_test.dart b/packages/metrics_center/test/skiaperf_test.dart index 864ac46cb7a5..52445de124dd 100644 --- a/packages/metrics_center/test/skiaperf_test.dart +++ b/packages/metrics_center/test/skiaperf_test.dart @@ -9,8 +9,7 @@ import 'dart:async'; import 'dart:convert'; import 'package:gcloud/storage.dart'; -import 'package:googleapis/storage/v1.dart' - show DetailedApiRequestError, StorageApi; +import 'package:googleapis/storage/v1.dart' show DetailedApiRequestError, StorageApi; import 'package:googleapis_auth/auth_io.dart'; import 'package:metrics_center/metrics_center.dart'; import 'package:metrics_center/src/gcs_lock.dart'; @@ -23,10 +22,7 @@ import 'utility.dart'; class MockGcsLock implements GcsLock { @override - Future protectedRun( - String exclusiveObjectName, - Future Function() f, - ) async { + Future protectedRun(String exclusiveObjectName, Future Function() f) async { await f(); } } @@ -42,10 +38,7 @@ class MockSkiaPerfGcsAdaptor implements SkiaPerfGcsAdaptor { } @override - Future writePoints( - String objectName, - List points, - ) async { + Future writePoints(String objectName, List points) async { if (writePointsOverride != null) { return writePointsOverride!(); } @@ -53,8 +46,7 @@ class MockSkiaPerfGcsAdaptor implements SkiaPerfGcsAdaptor { } // Map from the object name to the list of SkiaPoint that mocks the GCS. - final Map> _storage = - >{}; + final Map> _storage = >{}; } @GenerateMocks([Bucket, ObjectInfo]) @@ -95,20 +87,16 @@ Future main() async { kUnitKey: 's', }); - final cocoonPointBetaRev1Metric1 = - MetricPoint(kValue1, const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - kNameKey: 'beta/$kTaskName', - kSubResultKey: kMetric1, - kUnitKey: 's', - 'branch': 'beta', - }); - - final cocoonPointBetaRev1Metric1BadBranch = MetricPoint(kValue1, const < - String, - String - >{ + final cocoonPointBetaRev1Metric1 = MetricPoint(kValue1, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + kNameKey: 'beta/$kTaskName', + kSubResultKey: kMetric1, + kUnitKey: 's', + 'branch': 'beta', + }); + + final cocoonPointBetaRev1Metric1BadBranch = MetricPoint(kValue1, const { kGithubRepoKey: kFlutterFrameworkRepo, kGitRevisionKey: kFrameworkRevision1, kNameKey: kTaskName, @@ -174,10 +162,7 @@ Future main() async { }); expect(() => SkiaPerfPoint.fromPoint(noGithubRepoPoint), throwsA(anything)); - expect( - () => SkiaPerfPoint.fromPoint(noGitRevisionPoint), - throwsA(anything), - ); + expect(() => SkiaPerfPoint.fromPoint(noGitRevisionPoint), throwsA(anything)); expect(() => SkiaPerfPoint.fromPoint(noTestNamePoint), throwsA(anything)); }); @@ -198,9 +183,7 @@ Future main() async { const encoder = JsonEncoder.withIndent(' '); expect( - encoder.convert( - SkiaPerfPoint.toSkiaPerfJson([p1, p2, p3]), - ), + encoder.convert(SkiaPerfPoint.toSkiaPerfJson([p1, p2, p3])), equals(''' { "gitHash": "9011cece2595447eea5dd91adaa241c1c9ef9a33", @@ -259,57 +242,48 @@ Future main() async { ); }); - test( - 'Throw if engine points with the same test name but different options are converted to ' - 'Skia perf points', - () { - final enginePoint1 = FlutterEngineMetricPoint( - 'BM_PaintRecordInit', - 101, - 'ca799fa8b2254d09664b78ee80c43b434788d112', - moreTags: const { - kSubResultKey: 'cpu_time', - kUnitKey: 'ns', - 'cpu_scaling_enabled': 'true', - }, - ); - final enginePoint2 = FlutterEngineMetricPoint( - 'BM_PaintRecordInit', - 102, - 'ca799fa8b2254d09664b78ee80c43b434788d112', - moreTags: const { - kSubResultKey: 'real_time', - kUnitKey: 'ns', - 'cpu_scaling_enabled': 'false', - }, - ); - - const encoder = JsonEncoder.withIndent(' '); - expect( - () => encoder.convert( - SkiaPerfPoint.toSkiaPerfJson([ - SkiaPerfPoint.fromPoint(enginePoint1), - SkiaPerfPoint.fromPoint(enginePoint2), - ]), - ), - throwsA(anything), - ); - }, - ); + test('Throw if engine points with the same test name but different options are converted to ' + 'Skia perf points', () { + final enginePoint1 = FlutterEngineMetricPoint( + 'BM_PaintRecordInit', + 101, + 'ca799fa8b2254d09664b78ee80c43b434788d112', + moreTags: const { + kSubResultKey: 'cpu_time', + kUnitKey: 'ns', + 'cpu_scaling_enabled': 'true', + }, + ); + final enginePoint2 = FlutterEngineMetricPoint( + 'BM_PaintRecordInit', + 102, + 'ca799fa8b2254d09664b78ee80c43b434788d112', + moreTags: const { + kSubResultKey: 'real_time', + kUnitKey: 'ns', + 'cpu_scaling_enabled': 'false', + }, + ); - test( - 'Throw if two Cocoon metric points with the same name and subResult keys ' - 'but different options are converted to Skia perf points', - () { - final p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); - final p2 = SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1BadBranch); - - expect( - () => SkiaPerfPoint.toSkiaPerfJson([p1, p2]), - throwsA(anything), - ); - }, - ); + const encoder = JsonEncoder.withIndent(' '); + expect( + () => encoder.convert( + SkiaPerfPoint.toSkiaPerfJson([ + SkiaPerfPoint.fromPoint(enginePoint1), + SkiaPerfPoint.fromPoint(enginePoint2), + ]), + ), + throwsA(anything), + ); + }); + + test('Throw if two Cocoon metric points with the same name and subResult keys ' + 'but different options are converted to Skia perf points', () { + final p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); + final p2 = SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1BadBranch); + + expect(() => SkiaPerfPoint.toSkiaPerfJson([p1, p2]), throwsA(anything)); + }); test('SkiaPerfGcsAdaptor computes name correctly', () async { expect( @@ -319,9 +293,7 @@ Future main() async { DateTime.utc(2019, 12, 04, 23), 'test', ), - equals( - 'flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json', - ), + equals('flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json'), ); expect( await SkiaPerfGcsAdaptor.computeObjectName( @@ -354,12 +326,8 @@ Future main() async { 'test', ); - final writePoints = [ - SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1), - ]; - final String skiaPerfJson = jsonEncode( - SkiaPerfPoint.toSkiaPerfJson(writePoints), - ); + final writePoints = [SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1)]; + final String skiaPerfJson = jsonEncode(SkiaPerfPoint.toSkiaPerfJson(writePoints)); when( testBucket.writeBytes(testObjectName, utf8.encode(skiaPerfJson)), ).thenAnswer((_) async => FakeObjectInfo()); @@ -367,14 +335,10 @@ Future main() async { verify(testBucket.writeBytes(testObjectName, utf8.encode(skiaPerfJson))); // Emulate the first network request to fail with 504. - when( - testBucket.info(testObjectName), - ).thenThrow(DetailedApiRequestError(504, 'Test Failure')); + when(testBucket.info(testObjectName)).thenThrow(DetailedApiRequestError(504, 'Test Failure')); final mockObjectInfo = MockObjectInfo(); - when( - mockObjectInfo.downloadLink, - ).thenReturn(Uri.https('test.com', 'mock.json')); + when(mockObjectInfo.downloadLink).thenReturn(Uri.https('test.com', 'mock.json')); when( testBucket.info(testObjectName), ).thenAnswer((_) => Future.value(mockObjectInfo)); @@ -382,9 +346,7 @@ Future main() async { testBucket.read(testObjectName), ).thenAnswer((_) => Stream>.value(utf8.encode(skiaPerfJson))); - final List readPoints = await skiaPerfGcs.readPoints( - testObjectName, - ); + final List readPoints = await skiaPerfGcs.readPoints(testObjectName); expect(readPoints.length, equals(1)); expect(readPoints[0].testName, kTaskName); expect(readPoints[0].subResult, kMetric1); @@ -403,9 +365,7 @@ Future main() async { DateTime.fromMillisecondsSinceEpoch(123), 'test', ); - when( - testBucket.info(testObjectName), - ).thenThrow(Exception('No such object')); + when(testBucket.info(testObjectName)).thenThrow(Exception('No such object')); expect((await skiaPerfGcs.readPoints(testObjectName)).length, 0); }); @@ -444,27 +404,13 @@ Future main() async { SkiaPerfPoint.fromPoint(cocoonPointRev1Metric2), ]); - final List points = await skiaPerfGcs.readPoints( - testObjectName, - ); + final List points = await skiaPerfGcs.readPoints(testObjectName); expect(points.length, equals(2)); - expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [ - kTaskName, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), [ - kMetric1, - kMetric2, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ - kValue1, - kValue2, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo), [ - kFlutterFrameworkRepo, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [ - kFrameworkRevision1, - ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [kTaskName]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), [kMetric1, kMetric2]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [kValue1, kValue2]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo), [kFlutterFrameworkRepo]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [kFrameworkRevision1]); for (var i = 0; i < 2; i += 1) { expect(points[0].jsonUrl, startsWith('https://')); } @@ -485,24 +431,15 @@ Future main() async { SkiaPerfPoint.fromPoint(enginePoint2), ]); - final List points = await skiaPerfGcs.readPoints( - testObjectName, - ); + final List points = await skiaPerfGcs.readPoints(testObjectName); expect(points.length, equals(2)); expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [ engineMetricName, engineMetricName, ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ - engineValue1, - engineValue2, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo), [ - kFlutterEngineRepo, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [ - engineRevision, - ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [engineValue1, engineValue2]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.githubRepo), [kFlutterEngineRepo]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [engineRevision]); for (var i = 0; i < 2; i += 1) { expect(points[0].jsonUrl, startsWith('https://')); } @@ -527,45 +464,35 @@ Future main() async { // `SkiaPerfGcsAdaptor.computeObjectName` uses `GithubHelper` which requires // network connections. Hence we put them as integration tests instead of unit // tests. - test( - 'SkiaPerfGcsAdaptor integration test for name computations', - () async { - expect( - await SkiaPerfGcsAdaptor.computeObjectName( - kFlutterFrameworkRepo, - kFrameworkRevision1, - DateTime.utc(2019, 12, 04, 23), - 'test', - ), - equals( - 'flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json', - ), - ); - expect( - await SkiaPerfGcsAdaptor.computeObjectName( - kFlutterEngineRepo, - kEngineRevision1, - DateTime.utc(2019, 12, 03, 20), - 'test', - ), - equals( - 'flutter-engine/2019/12/03/20/$kEngineRevision1/test_values.json', - ), - ); - expect( - await SkiaPerfGcsAdaptor.computeObjectName( - kFlutterEngineRepo, - kEngineRevision2, - DateTime.utc(2020, 01, 03, 15), - 'test', - ), - equals( - 'flutter-engine/2020/01/03/15/$kEngineRevision2/test_values.json', - ), - ); - }, - skip: testBucket == null, - ); + test('SkiaPerfGcsAdaptor integration test for name computations', () async { + expect( + await SkiaPerfGcsAdaptor.computeObjectName( + kFlutterFrameworkRepo, + kFrameworkRevision1, + DateTime.utc(2019, 12, 04, 23), + 'test', + ), + equals('flutter-flutter/2019/12/04/23/$kFrameworkRevision1/test_values.json'), + ); + expect( + await SkiaPerfGcsAdaptor.computeObjectName( + kFlutterEngineRepo, + kEngineRevision1, + DateTime.utc(2019, 12, 03, 20), + 'test', + ), + equals('flutter-engine/2019/12/03/20/$kEngineRevision1/test_values.json'), + ); + expect( + await SkiaPerfGcsAdaptor.computeObjectName( + kFlutterEngineRepo, + kEngineRevision2, + DateTime.utc(2020, 01, 03, 15), + 'test', + ), + equals('flutter-engine/2020/01/03/15/$kEngineRevision2/test_values.json'), + ); + }, skip: testBucket == null); test('SkiaPerfDestination.update awaits locks', () async { var updateCompleted = false; @@ -617,17 +544,9 @@ Future main() async { ), ); expect(points.length, equals(2)); - expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [ - kTaskName, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), [ - kMetric1, - kMetric2, - ]); - expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ - kValue1, - kValue2, - ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.testName), [kTaskName]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.subResult), [kMetric1, kMetric2]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [kValue1, kValue2]); final updated = MetricPoint(kValue3, cocoonPointRev1Metric1.tags); @@ -657,17 +576,11 @@ Future main() async { 'test', ), ); - expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [ - kValue2, - kValue3, - ]); + expectSetMatch(points.map((SkiaPerfPoint p) => p.value), [kValue2, kValue3]); }); Future skiaPerfDestinationIntegrationTest() async { - final destination = SkiaPerfDestination( - SkiaPerfGcsAdaptor(testBucket!), - testLock, - ); + final destination = SkiaPerfDestination(SkiaPerfGcsAdaptor(testBucket!), testLock); await destination.update( [cocoonPointRev1Metric1], DateTime.fromMillisecondsSinceEpoch(123), diff --git a/packages/metrics_center/test/skiaperf_test.mocks.dart b/packages/metrics_center/test/skiaperf_test.mocks.dart index 6e4793b601f6..93a9faced606 100644 --- a/packages/metrics_center/test/skiaperf_test.mocks.dart +++ b/packages/metrics_center/test/skiaperf_test.mocks.dart @@ -25,38 +25,31 @@ import 'package:mockito/src/dummies.dart' as _i5; // ignore_for_file: subtype_of_sealed_class class _FakeStreamSink_0 extends _i1.SmartFake implements _i2.StreamSink { - _FakeStreamSink_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeStreamSink_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeObjectInfo_1 extends _i1.SmartFake implements _i3.ObjectInfo { - _FakeObjectInfo_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeObjectInfo_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakePage_2 extends _i1.SmartFake implements _i4.Page { - _FakePage_2(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakePage_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeDateTime_3 extends _i1.SmartFake implements DateTime { - _FakeDateTime_3(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeDateTime_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } class _FakeUri_4 extends _i1.SmartFake implements Uri { - _FakeUri_4(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeUri_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeObjectGeneration_5 extends _i1.SmartFake - implements _i3.ObjectGeneration { +class _FakeObjectGeneration_5 extends _i1.SmartFake implements _i3.ObjectGeneration { _FakeObjectGeneration_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeObjectMetadata_6 extends _i1.SmartFake - implements _i3.ObjectMetadata { +class _FakeObjectMetadata_6 extends _i1.SmartFake implements _i3.ObjectMetadata { _FakeObjectMetadata_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -70,26 +63,16 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { } @override - String get bucketName => - (super.noSuchMethod( - Invocation.getter(#bucketName), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#bucketName), - ), - ) - as String); + String get bucketName => (super.noSuchMethod( + Invocation.getter(#bucketName), + returnValue: _i5.dummyValue(this, Invocation.getter(#bucketName)), + ) as String); @override - String absoluteObjectName(String? objectName) => - (super.noSuchMethod( - Invocation.method(#absoluteObjectName, [objectName]), - returnValue: _i5.dummyValue( - this, - Invocation.method(#absoluteObjectName, [objectName]), - ), - ) - as String); + String absoluteObjectName(String? objectName) => (super.noSuchMethod( + Invocation.method(#absoluteObjectName, [objectName]), + returnValue: _i5.dummyValue(this, Invocation.method(#absoluteObjectName, [objectName])), + ) as String); @override _i2.StreamSink> write( @@ -99,35 +82,33 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { _i3.Acl? acl, _i3.PredefinedAcl? predefinedAcl, String? contentType, - }) => - (super.noSuchMethod( - Invocation.method( - #write, - [objectName], - { - #length: length, - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - returnValue: _FakeStreamSink_0>( - this, - Invocation.method( - #write, - [objectName], - { - #length: length, - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - ), - ) - as _i2.StreamSink>); + }) => (super.noSuchMethod( + Invocation.method( + #write, + [objectName], + { + #length: length, + #metadata: metadata, + #acl: acl, + #predefinedAcl: predefinedAcl, + #contentType: contentType, + }, + ), + returnValue: _FakeStreamSink_0>( + this, + Invocation.method( + #write, + [objectName], + { + #length: length, + #metadata: metadata, + #acl: acl, + #predefinedAcl: predefinedAcl, + #contentType: contentType, + }, + ), + ), + ) as _i2.StreamSink>); @override _i2.Future<_i3.ObjectInfo> writeBytes( @@ -137,112 +118,76 @@ class MockBucket extends _i1.Mock implements _i3.Bucket { _i3.Acl? acl, _i3.PredefinedAcl? predefinedAcl, String? contentType, - }) => - (super.noSuchMethod( - Invocation.method( - #writeBytes, - [name, bytes], - { - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - returnValue: _i2.Future<_i3.ObjectInfo>.value( - _FakeObjectInfo_1( - this, - Invocation.method( - #writeBytes, - [name, bytes], - { - #metadata: metadata, - #acl: acl, - #predefinedAcl: predefinedAcl, - #contentType: contentType, - }, - ), - ), - ), - ) - as _i2.Future<_i3.ObjectInfo>); - - @override - _i2.Stream> read(String? objectName, {int? offset, int? length}) => - (super.noSuchMethod( - Invocation.method( - #read, - [objectName], - {#offset: offset, #length: length}, - ), - returnValue: _i2.Stream>.empty(), - ) - as _i2.Stream>); - - @override - _i2.Future<_i3.ObjectInfo> info(String? name) => - (super.noSuchMethod( - Invocation.method(#info, [name]), - returnValue: _i2.Future<_i3.ObjectInfo>.value( - _FakeObjectInfo_1(this, Invocation.method(#info, [name])), - ), - ) - as _i2.Future<_i3.ObjectInfo>); - - @override - _i2.Future delete(String? name) => - (super.noSuchMethod( - Invocation.method(#delete, [name]), - returnValue: _i2.Future.value(), - ) - as _i2.Future); - - @override - _i2.Future updateMetadata( - String? objectName, - _i3.ObjectMetadata? metadata, - ) => - (super.noSuchMethod( - Invocation.method(#updateMetadata, [objectName, metadata]), - returnValue: _i2.Future.value(), - ) - as _i2.Future); - - @override - _i2.Stream<_i3.BucketEntry> list({String? prefix, String? delimiter}) => - (super.noSuchMethod( - Invocation.method(#list, [], { - #prefix: prefix, - #delimiter: delimiter, - }), - returnValue: _i2.Stream<_i3.BucketEntry>.empty(), - ) - as _i2.Stream<_i3.BucketEntry>); + }) => (super.noSuchMethod( + Invocation.method( + #writeBytes, + [name, bytes], + {#metadata: metadata, #acl: acl, #predefinedAcl: predefinedAcl, #contentType: contentType}, + ), + returnValue: _i2.Future<_i3.ObjectInfo>.value( + _FakeObjectInfo_1( + this, + Invocation.method( + #writeBytes, + [name, bytes], + { + #metadata: metadata, + #acl: acl, + #predefinedAcl: predefinedAcl, + #contentType: contentType, + }, + ), + ), + ), + ) as _i2.Future<_i3.ObjectInfo>); + + @override + _i2.Stream> read(String? objectName, {int? offset, int? length}) => (super.noSuchMethod( + Invocation.method(#read, [objectName], {#offset: offset, #length: length}), + returnValue: _i2.Stream>.empty(), + ) as _i2.Stream>); + + @override + _i2.Future<_i3.ObjectInfo> info(String? name) => (super.noSuchMethod( + Invocation.method(#info, [name]), + returnValue: _i2.Future<_i3.ObjectInfo>.value( + _FakeObjectInfo_1(this, Invocation.method(#info, [name])), + ), + ) as _i2.Future<_i3.ObjectInfo>); + + @override + _i2.Future delete(String? name) => (super.noSuchMethod( + Invocation.method(#delete, [name]), + returnValue: _i2.Future.value(), + ) as _i2.Future); + + @override + _i2.Future updateMetadata(String? objectName, _i3.ObjectMetadata? metadata) => + (super.noSuchMethod( + Invocation.method(#updateMetadata, [objectName, metadata]), + returnValue: _i2.Future.value(), + ) as _i2.Future); + + @override + _i2.Stream<_i3.BucketEntry> list({String? prefix, String? delimiter}) => (super.noSuchMethod( + Invocation.method(#list, [], {#prefix: prefix, #delimiter: delimiter}), + returnValue: _i2.Stream<_i3.BucketEntry>.empty(), + ) as _i2.Stream<_i3.BucketEntry>); @override _i2.Future<_i4.Page<_i3.BucketEntry>> page({ String? prefix, String? delimiter, int? pageSize = 50, - }) => - (super.noSuchMethod( - Invocation.method(#page, [], { - #prefix: prefix, - #delimiter: delimiter, - #pageSize: pageSize, - }), - returnValue: _i2.Future<_i4.Page<_i3.BucketEntry>>.value( - _FakePage_2<_i3.BucketEntry>( - this, - Invocation.method(#page, [], { - #prefix: prefix, - #delimiter: delimiter, - #pageSize: pageSize, - }), - ), - ), - ) - as _i2.Future<_i4.Page<_i3.BucketEntry>>); + }) => (super.noSuchMethod( + Invocation.method(#page, [], {#prefix: prefix, #delimiter: delimiter, #pageSize: pageSize}), + returnValue: _i2.Future<_i4.Page<_i3.BucketEntry>>.value( + _FakePage_2<_i3.BucketEntry>( + this, + Invocation.method(#page, [], {#prefix: prefix, #delimiter: delimiter, #pageSize: pageSize}), + ), + ), + ) as _i2.Future<_i4.Page<_i3.BucketEntry>>); } /// A class which mocks [ObjectInfo]. @@ -254,70 +199,49 @@ class MockObjectInfo extends _i1.Mock implements _i3.ObjectInfo { } @override - String get name => - (super.noSuchMethod( - Invocation.getter(#name), - returnValue: _i5.dummyValue(this, Invocation.getter(#name)), - ) - as String); + String get name => (super.noSuchMethod( + Invocation.getter(#name), + returnValue: _i5.dummyValue(this, Invocation.getter(#name)), + ) as String); @override - int get length => - (super.noSuchMethod(Invocation.getter(#length), returnValue: 0) as int); + int get length => (super.noSuchMethod(Invocation.getter(#length), returnValue: 0) as int); @override - DateTime get updated => - (super.noSuchMethod( - Invocation.getter(#updated), - returnValue: _FakeDateTime_3(this, Invocation.getter(#updated)), - ) - as DateTime); + DateTime get updated => (super.noSuchMethod( + Invocation.getter(#updated), + returnValue: _FakeDateTime_3(this, Invocation.getter(#updated)), + ) as DateTime); @override - String get etag => - (super.noSuchMethod( - Invocation.getter(#etag), - returnValue: _i5.dummyValue(this, Invocation.getter(#etag)), - ) - as String); + String get etag => (super.noSuchMethod( + Invocation.getter(#etag), + returnValue: _i5.dummyValue(this, Invocation.getter(#etag)), + ) as String); @override List get md5Hash => - (super.noSuchMethod(Invocation.getter(#md5Hash), returnValue: []) - as List); + (super.noSuchMethod(Invocation.getter(#md5Hash), returnValue: []) as List); @override int get crc32CChecksum => - (super.noSuchMethod(Invocation.getter(#crc32CChecksum), returnValue: 0) - as int); + (super.noSuchMethod(Invocation.getter(#crc32CChecksum), returnValue: 0) as int); @override - Uri get downloadLink => - (super.noSuchMethod( - Invocation.getter(#downloadLink), - returnValue: _FakeUri_4(this, Invocation.getter(#downloadLink)), - ) - as Uri); + Uri get downloadLink => (super.noSuchMethod( + Invocation.getter(#downloadLink), + returnValue: _FakeUri_4(this, Invocation.getter(#downloadLink)), + ) as Uri); @override - _i3.ObjectGeneration get generation => - (super.noSuchMethod( - Invocation.getter(#generation), - returnValue: _FakeObjectGeneration_5( - this, - Invocation.getter(#generation), - ), - ) - as _i3.ObjectGeneration); + _i3.ObjectGeneration get generation => (super.noSuchMethod( + Invocation.getter(#generation), + returnValue: _FakeObjectGeneration_5(this, Invocation.getter(#generation)), + ) as _i3.ObjectGeneration); @override - _i3.ObjectMetadata get metadata => - (super.noSuchMethod( - Invocation.getter(#metadata), - returnValue: _FakeObjectMetadata_6( - this, - Invocation.getter(#metadata), - ), - ) - as _i3.ObjectMetadata); + _i3.ObjectMetadata get metadata => (super.noSuchMethod( + Invocation.getter(#metadata), + returnValue: _FakeObjectMetadata_6(this, Invocation.getter(#metadata)), + ) as _i3.ObjectMetadata); } diff --git a/packages/multicast_dns/example/main.dart b/packages/multicast_dns/example/main.dart index bb441d7495d6..89d77d2afdb5 100644 --- a/packages/multicast_dns/example/main.dart +++ b/packages/multicast_dns/example/main.dart @@ -29,8 +29,7 @@ Future main() async { ResourceRecordQuery.service(ptr.domainName), )) { // Domain name will be something like "io.flutter.example@some-iphone.local._dartobservatory._tcp.local" - final String bundleId = - ptr.domainName; //.substring(0, ptr.domainName.indexOf('@')); + final String bundleId = ptr.domainName; //.substring(0, ptr.domainName.indexOf('@')); print( 'Dart observatory instance found at ' '${srv.target}:${srv.port} for "$bundleId".', diff --git a/packages/multicast_dns/example/mdns_resolve.dart b/packages/multicast_dns/example/mdns_resolve.dart index ed4301476c54..32f5d5bbbb3a 100644 --- a/packages/multicast_dns/example/mdns_resolve.dart +++ b/packages/multicast_dns/example/mdns_resolve.dart @@ -23,17 +23,15 @@ For example: final client = MDnsClient(); await client.start(); - await for (final IPAddressResourceRecord record - in client.lookup( - ResourceRecordQuery.addressIPv4(name), - )) { + await for (final IPAddressResourceRecord record in client.lookup( + ResourceRecordQuery.addressIPv4(name), + )) { print('Found address (${record.address}).'); } - await for (final IPAddressResourceRecord record - in client.lookup( - ResourceRecordQuery.addressIPv6(name), - )) { + await for (final IPAddressResourceRecord record in client.lookup( + ResourceRecordQuery.addressIPv6(name), + )) { print('Found address (${record.address}).'); } client.stop(); diff --git a/packages/multicast_dns/example/mdns_sd.dart b/packages/multicast_dns/example/mdns_sd.dart index 1d2f36230075..7fd541422b49 100644 --- a/packages/multicast_dns/example/mdns_sd.dart +++ b/packages/multicast_dns/example/mdns_sd.dart @@ -41,10 +41,9 @@ For example: .lookup(ResourceRecordQuery.text(ptr.domainName)) .forEach(print); } - await for (final IPAddressResourceRecord ip - in client.lookup( - ResourceRecordQuery.addressIPv4(srv.target), - )) { + await for (final IPAddressResourceRecord ip in client.lookup( + ResourceRecordQuery.addressIPv4(srv.target), + )) { if (verbose) { print(ip); } @@ -53,10 +52,9 @@ For example: '${srv.target}:${srv.port} with ${ip.address}.', ); } - await for (final IPAddressResourceRecord ip - in client.lookup( - ResourceRecordQuery.addressIPv6(srv.target), - )) { + await for (final IPAddressResourceRecord ip in client.lookup( + ResourceRecordQuery.addressIPv6(srv.target), + )) { if (verbose) { print(ip); } diff --git a/packages/multicast_dns/lib/multicast_dns.dart b/packages/multicast_dns/lib/multicast_dns.dart index 3b5b2b5fc8e0..7c1623eb57b5 100644 --- a/packages/multicast_dns/lib/multicast_dns.dart +++ b/packages/multicast_dns/lib/multicast_dns.dart @@ -21,21 +21,21 @@ export 'package:multicast_dns/src/resource_record.dart'; /// /// See also: /// * [MDnsQuerier.allInterfacesFactory] -typedef NetworkInterfacesFactory = - Future> Function(InternetAddressType type); +typedef NetworkInterfacesFactory = Future> Function( + InternetAddressType type, +); /// A factory for construction of datagram sockets. /// /// This can be injected into the [MDnsClient] to provide alternative /// implementations of [RawDatagramSocket.bind]. -typedef RawDatagramSocketFactory = - Future Function( - dynamic host, - int port, { - bool reuseAddress, - bool reusePort, - int ttl, - }); +typedef RawDatagramSocketFactory = Future Function( + dynamic host, + int port, { + bool reuseAddress, + bool reusePort, + int ttl, +}); /// Client for DNS lookup and publishing using the mDNS protocol. /// @@ -47,9 +47,8 @@ typedef RawDatagramSocketFactory = /// section 5.1 of [RFC 6762](https://tools.ietf.org/html/rfc6762). class MDnsClient { /// Create a new [MDnsClient]. - MDnsClient({ - RawDatagramSocketFactory rawDatagramSocketFactory = RawDatagramSocket.bind, - }) : _rawDatagramSocketFactory = rawDatagramSocketFactory; + MDnsClient({RawDatagramSocketFactory rawDatagramSocketFactory = RawDatagramSocket.bind}) + : _rawDatagramSocketFactory = rawDatagramSocketFactory; bool _starting = false; bool _started = false; @@ -63,14 +62,8 @@ class MDnsClient { int? _mDnsPort; /// Find all network interfaces with an the [InternetAddressType] specified. - Future> allInterfacesFactory( - InternetAddressType type, - ) { - return NetworkInterface.list( - includeLinkLocal: true, - type: type, - includeLoopback: true, - ); + Future> allInterfacesFactory(InternetAddressType type) { + return NetworkInterface.list(includeLinkLocal: true, type: type, includeLoopback: true); } /// Start the mDNS client. @@ -168,10 +161,7 @@ class MDnsClient { // Join multicast on this interface. incoming.joinMulticast(_mDnsAddress!, interface); } - incoming.listen( - (RawSocketEvent event) => _handleIncoming(event, incoming), - onError: onError, - ); + incoming.listen((RawSocketEvent event) => _handleIncoming(event, incoming), onError: onError); _started = true; _starting = false; } @@ -218,11 +208,7 @@ class MDnsClient { } // Look for entries in the cache. final cached = []; - _cache.lookup( - query.fullyQualifiedName, - query.resourceRecordType, - cached, - ); + _cache.lookup(query.fullyQualifiedName, query.resourceRecordType, cached); if (cached.isNotEmpty) { final controller = StreamController(); cached.forEach(controller.add); diff --git a/packages/multicast_dns/lib/src/lookup_resolver.dart b/packages/multicast_dns/lib/src/lookup_resolver.dart index bca9c16cbcbd..9a6add104800 100644 --- a/packages/multicast_dns/lib/src/lookup_resolver.dart +++ b/packages/multicast_dns/lib/src/lookup_resolver.dart @@ -31,15 +31,10 @@ base class PendingRequest extends LinkedListEntry { /// Class for keeping track of pending lookups and processing incoming /// query responses. class LookupResolver { - final LinkedList _pendingRequests = - LinkedList(); + final LinkedList _pendingRequests = LinkedList(); /// Adds a request and returns a [Stream] of [ResourceRecord] responses. - Stream addPendingRequest( - int type, - String name, - Duration timeout, - ) { + Stream addPendingRequest(int type, String name, Duration timeout) { final controller = StreamController(); final request = PendingRequest(type, name, controller); final timer = Timer(timeout, () { diff --git a/packages/multicast_dns/lib/src/native_protocol_client.dart b/packages/multicast_dns/lib/src/native_protocol_client.dart index 89ea986d33c0..96eb89f79dea 100644 --- a/packages/multicast_dns/lib/src/native_protocol_client.dart +++ b/packages/multicast_dns/lib/src/native_protocol_client.dart @@ -26,8 +26,7 @@ class ResourceRecordCache { /// The number of entries in the cache. int get entryCount { var count = 0; - for (final SplayTreeMap> map - in _cache.values) { + for (final SplayTreeMap> map in _cache.values) { for (final List records in map.values) { count += records.length; } @@ -46,12 +45,9 @@ class ResourceRecordCache { seenRecordTypes[record.resourceRecordType] ??= Set(); // ignore: prefer_collection_literals if (seenRecordTypes[record.resourceRecordType]!.add(record.name)) { - _cache[record.resourceRecordType] ??= - SplayTreeMap>(); + _cache[record.resourceRecordType] ??= SplayTreeMap>(); - _cache[record.resourceRecordType]![record.name] = [ - record, - ]; + _cache[record.resourceRecordType]![record.name] = [record]; } else { _cache[record.resourceRecordType]![record.name]!.add(record); } @@ -59,11 +55,7 @@ class ResourceRecordCache { } /// Get a record from this cache. - void lookup( - String name, - int type, - List results, - ) { + void lookup(String name, int type, List results) { assert(ResourceRecordType.debugAssertValid(type)); final int time = DateTime.now().millisecondsSinceEpoch; final SplayTreeMap>? candidates = _cache[type]; @@ -75,9 +67,7 @@ class ResourceRecordCache { if (candidateRecords == null) { return; } - candidateRecords.removeWhere( - (ResourceRecord candidate) => candidate.validUntil < time, - ); + candidateRecords.removeWhere((ResourceRecord candidate) => candidate.validUntil < time); results.addAll(candidateRecords.cast()); } } diff --git a/packages/multicast_dns/lib/src/packet.dart b/packages/multicast_dns/lib/src/packet.dart index a914370594f6..bbbe8dcdd399 100644 --- a/packages/multicast_dns/lib/src/packet.dart +++ b/packages/multicast_dns/lib/src/packet.dart @@ -89,8 +89,7 @@ List encodeMDnsQuery( offset += 2; packetByteData.setUint16( offset, - ResourceRecordClass.internet | - (multicast ? QuestionType.multicast : QuestionType.unicast), + ResourceRecordClass.internet | (multicast ? QuestionType.multicast : QuestionType.unicast), ); return data; @@ -116,9 +115,7 @@ class _FQDNReadResult { /// Reads a FQDN from raw packet data. String readFQDN(List packet, [int offset = 0]) { - final Uint8List data = packet is Uint8List - ? packet - : Uint8List.fromList(packet); + final Uint8List data = packet is Uint8List ? packet : Uint8List.fromList(packet); final byteData = ByteData.view(data.buffer); return _readFQDN(data, byteData, offset, data.length).fqdn; @@ -128,12 +125,7 @@ String readFQDN(List packet, [int offset = 0]) { // parts and the number of bytes consumed. // // If decoding fails (e.g. due to an invalid packet) `null` is returned. -_FQDNReadResult _readFQDN( - Uint8List data, - ByteData byteData, - int offset, - int length, -) { +_FQDNReadResult _readFQDN(Uint8List data, ByteData byteData, int offset, int length) { void checkLength(int required) { if (length < required) { throw MDnsDecodeException(required); @@ -203,9 +195,7 @@ List? decodeMDnsResponse(List packet) { return null; } - final Uint8List data = packet is Uint8List - ? packet - : Uint8List.fromList(packet); + final Uint8List data = packet is Uint8List ? packet : Uint8List.fromList(packet); final packetBytes = ByteData.view(data.buffer); final int answerCount = packetBytes.getUint16(_kAncountOffset); @@ -265,11 +255,7 @@ List? decodeMDnsResponse(List packet) { addr.write('.'); addr.write(packetBytes.getUint8(offset)); } - return IPAddressResourceRecord( - fqdn, - validUntil, - address: InternetAddress(addr.toString()), - ); + return IPAddressResourceRecord(fqdn, validUntil, address: InternetAddress(addr.toString())); case ResourceRecordType.addressIPv6: checkLength(offset + readDataLength); final addr = StringBuffer(); @@ -280,11 +266,7 @@ List? decodeMDnsResponse(List packet) { addr.write(':'); addr.write(packetBytes.getUint16(offset).toRadixString(16)); } - return IPAddressResourceRecord( - fqdn, - validUntil, - address: InternetAddress(addr.toString()), - ); + return IPAddressResourceRecord(fqdn, validUntil, address: InternetAddress(addr.toString())); case ResourceRecordType.service: checkLength(offset + 2); final int priority = packetBytes.getUint16(offset); @@ -295,12 +277,7 @@ List? decodeMDnsResponse(List packet) { checkLength(offset + 2); final int port = packetBytes.getUint16(offset); offset += 2; - final _FQDNReadResult result = _readFQDN( - data, - packetBytes, - offset, - length, - ); + final _FQDNReadResult result = _readFQDN(data, packetBytes, offset, length); offset += result.bytesRead; return SrvResourceRecord( fqdn, @@ -312,12 +289,7 @@ List? decodeMDnsResponse(List packet) { ); case ResourceRecordType.serverPointer: checkLength(offset + readDataLength); - final _FQDNReadResult result = _readFQDN( - data, - packetBytes, - offset, - length, - ); + final _FQDNReadResult result = _readFQDN(data, packetBytes, offset, length); offset += readDataLength; return PtrResourceRecord(fqdn, validUntil, domainName: result.fqdn); case ResourceRecordType.text: @@ -356,12 +328,7 @@ List? decodeMDnsResponse(List packet) { try { for (var i = 0; i < questionCount; i++) { - final _FQDNReadResult result = _readFQDN( - data, - packetBytes, - offset, - length, - ); + final _FQDNReadResult result = _readFQDN(data, packetBytes, offset, length); offset += result.bytesRead; checkLength(offset + 4); offset += 4; diff --git a/packages/multicast_dns/lib/src/resource_record.dart b/packages/multicast_dns/lib/src/resource_record.dart index f16d9a163dcd..86a0a4e05a6b 100644 --- a/packages/multicast_dns/lib/src/resource_record.dart +++ b/packages/multicast_dns/lib/src/resource_record.dart @@ -73,11 +73,8 @@ class ResourceRecordQuery { /// Creates a new ResourceRecordQuery. /// /// Most callers should prefer one of the named constructors. - ResourceRecordQuery( - this.resourceRecordType, - this.fullyQualifiedName, - this.questionType, - ) : assert(ResourceRecordType.debugAssertValid(resourceRecordType)); + ResourceRecordQuery(this.resourceRecordType, this.fullyQualifiedName, this.questionType) + : assert(ResourceRecordType.debugAssertValid(resourceRecordType)); /// An A (IPv4) query. ResourceRecordQuery.addressIPv4(String name, {bool isMulticast = true}) @@ -136,16 +133,11 @@ class ResourceRecordQuery { /// Encodes this query to the raw wire format. List encode() { - return encodeMDnsQuery( - fullyQualifiedName, - type: resourceRecordType, - multicast: isMulticast, - ); + return encodeMDnsQuery(fullyQualifiedName, type: resourceRecordType, multicast: isMulticast); } @override - int get hashCode => - Object.hash(resourceRecordType, fullyQualifiedName, questionType); + int get hashCode => Object.hash(resourceRecordType, fullyQualifiedName, questionType); @override bool operator ==(Object other) { @@ -203,11 +195,8 @@ abstract class ResourceRecord { /// A Service Pointer for reverse mapping an IP address (DNS "PTR"). class PtrResourceRecord extends ResourceRecord { /// Creates a new PtrResourceRecord. - const PtrResourceRecord( - String name, - int validUntil, { - required this.domainName, - }) : super(ResourceRecordType.serverPointer, name, validUntil); + const PtrResourceRecord(String name, int validUntil, {required this.domainName}) + : super(ResourceRecordType.serverPointer, name, validUntil); /// The FQDN for this record. final String domainName; @@ -220,9 +209,7 @@ class PtrResourceRecord extends ResourceRecord { @override bool operator ==(Object other) { - return super == other && - other is PtrResourceRecord && - other.domainName == domainName; + return super == other && other is PtrResourceRecord && other.domainName == domainName; } @override @@ -254,9 +241,7 @@ class IPAddressResourceRecord extends ResourceRecord { @override bool operator ==(Object other) { - return super == other && - other is IPAddressResourceRecord && - other.address == address; + return super == other && other is IPAddressResourceRecord && other.address == address; } @override @@ -294,8 +279,7 @@ class SrvResourceRecord extends ResourceRecord { 'target: $target, port: $port, priority: $priority, weight: $weight'; @override - int get hashCode => - Object.hash(target, port, priority, weight, super.hashCode); + int get hashCode => Object.hash(target, port, priority, weight, super.hashCode); @override bool operator ==(Object other) { diff --git a/packages/multicast_dns/test/client_test.dart b/packages/multicast_dns/test/client_test.dart index 44a46269ddf9..1250802006a0 100644 --- a/packages/multicast_dns/test/client_test.dart +++ b/packages/multicast_dns/test/client_test.dart @@ -30,8 +30,7 @@ void main() { await client.start( mDnsPort: 1234, - interfacesFactory: (InternetAddressType type) async => - [], + interfacesFactory: (InternetAddressType type) async => [], ); expect(lastPort, 1234); @@ -54,8 +53,7 @@ void main() { await client.start( mDnsPort: 1234, - interfacesFactory: (InternetAddressType type) async => - [], + interfacesFactory: (InternetAddressType type) async => [], ); expect(datagramSocket.closed, false); client.stop(); @@ -80,8 +78,7 @@ void main() { await client.start( mDnsPort: 1234, - interfacesFactory: (InternetAddressType type) async => - [], + interfacesFactory: (InternetAddressType type) async => [], ); expect(datagramSocket.closed, false); client.stop(); @@ -104,10 +101,7 @@ void main() { }, ); - await client.start( - interfacesFactory: (InternetAddressType type) async => - [], - ); + await client.start(interfacesFactory: (InternetAddressType type) async => []); await client.start(); await client.lookup(ResourceRecordQuery.serverPointer('_')).toList(); }); @@ -209,8 +203,7 @@ void main() { final onErrorCalledCompleter = Completer(); await client.start( mDnsPort: 1234, - interfacesFactory: (InternetAddressType type) async => - [], + interfacesFactory: (InternetAddressType type) async => [], onError: (Object e) { expect(e, 'Error'); onErrorCalledCompleter.complete(); @@ -262,8 +255,7 @@ class FakeRawDatagramSocket extends Fake implements RawDatagramSocket { } } -class FakeRawDatagramSocketThatSendsError extends Fake - implements RawDatagramSocket { +class FakeRawDatagramSocketThatSendsError extends Fake implements RawDatagramSocket { @override InternetAddress address = InternetAddress.anyIPv4; @@ -274,12 +266,9 @@ class FakeRawDatagramSocketThatSendsError extends Fake void Function()? onDone, bool? cancelOnError, }) { - return Stream.error('Error').listen( - onData, - onError: onError, - cancelOnError: cancelOnError, - onDone: onDone, - ); + return Stream.error( + 'Error', + ).listen(onData, onError: onError, cancelOnError: cancelOnError, onDone: onDone); } } diff --git a/packages/multicast_dns/test/decode_test.dart b/packages/multicast_dns/test/decode_test.dart index b4712c881cc8..930a4b9abd95 100644 --- a/packages/multicast_dns/test/decode_test.dart +++ b/packages/multicast_dns/test/decode_test.dart @@ -58,11 +58,7 @@ void testValidPackages() { priority: 0, weight: 0, ), - TxtResourceRecord( - 'raspberrypi._udisks-ssh._tcp.local', - result[3].validUntil, - text: '', - ), + TxtResourceRecord('raspberrypi._udisks-ssh._tcp.local', result[3].validUntil, text: ''), PtrResourceRecord( '_services._dns-sd._udp.local', result[4].validUntil, @@ -129,9 +125,7 @@ void testValidPackages() { // Fixes https://github.com/flutter/flutter/issues/31854 test('Can decode packages with question, answer and additional', () { - final List result = decodeMDnsResponse( - packetWithQuestionAnArCount, - )!; + final List result = decodeMDnsResponse(packetWithQuestionAnArCount)!; expect(result, isNotNull); expect(result.length, 2); expect(result, [ @@ -149,28 +143,23 @@ void testValidPackages() { }); // Fixes https://github.com/flutter/flutter/issues/31854 - test( - 'Can decode packages without question and with answer and additional', - () { - final List result = decodeMDnsResponse( - packetWithoutQuestionWithAnArCount, - )!; - expect(result, isNotNull); - expect(result.length, 2); - expect(result, [ - PtrResourceRecord( - '_______________.____._____', - result[0].validUntil, - domainName: '______________________._______________.____._____', - ), - TxtResourceRecord( - '______________________.____________.____._____', - result[1].validUntil, - text: 'model=MacBookPro14,3\nosxvers=18\necolor=225,225,223\n', - ), - ]); - }, - ); + test('Can decode packages without question and with answer and additional', () { + final List result = decodeMDnsResponse(packetWithoutQuestionWithAnArCount)!; + expect(result, isNotNull); + expect(result.length, 2); + expect(result, [ + PtrResourceRecord( + '_______________.____._____', + result[0].validUntil, + domainName: '______________________._______________.____._____', + ), + TxtResourceRecord( + '______________________.____________.____._____', + result[1].validUntil, + text: 'model=MacBookPro14,3\nosxvers=18\necolor=225,225,223\n', + ), + ]); + }); test('Can decode packages with a long text resource', () { final List result = decodeMDnsResponse(packetWithLongTxt)!; @@ -207,10 +196,7 @@ void testBadPackages() { void testPTRRData() { test('Can read FQDN from PTR data', () { - expect( - 'sgjesse-macbookpro2 [78:31:c1:b8:55:38]._workstation._tcp.local', - readFQDN(ptrRData), - ); + expect('sgjesse-macbookpro2 [78:31:c1:b8:55:38]._workstation._tcp.local', readFQDN(ptrRData)); expect('fletch-agent._fletch_agent._tcp.local', readFQDN(ptrRData2)); }); } diff --git a/packages/multicast_dns/test/lookup_resolver_test.dart b/packages/multicast_dns/test/lookup_resolver_test.dart index f67549b8bc09..6346c07880e5 100644 --- a/packages/multicast_dns/test/lookup_resolver_test.dart +++ b/packages/multicast_dns/test/lookup_resolver_test.dart @@ -43,10 +43,7 @@ void testResult() { 'xxx.local', noTimeout, ); - final ResourceRecord response = ip4Result( - 'xxx.local', - InternetAddress('1.2.3.4'), - ); + final ResourceRecord response = ip4Result('xxx.local', InternetAddress('1.2.3.4')); resolver.handleResponse([response]); final result = await futureResult.first as IPAddressResourceRecord; expect('1.2.3.4', result.address.address); @@ -68,14 +65,8 @@ void testResult2() { 'yyy.local', noTimeout, ); - final ResourceRecord response1 = ip4Result( - 'xxx.local', - InternetAddress('1.2.3.4'), - ); - final ResourceRecord response2 = ip4Result( - 'yyy.local', - InternetAddress('2.3.4.5'), - ); + final ResourceRecord response1 = ip4Result('xxx.local', InternetAddress('1.2.3.4')); + final ResourceRecord response2 = ip4Result('yyy.local', InternetAddress('2.3.4.5')); resolver.handleResponse([response2, response1]); final result1 = await futureResult1.first as IPAddressResourceRecord; final result2 = await futureResult2.first as IPAddressResourceRecord; @@ -89,10 +80,7 @@ void testResult3() { test('Multiple requests', () async { const noTimeout = Duration(days: 1); final resolver = LookupResolver(); - final ResourceRecord response0 = ip4Result( - 'zzz.local', - InternetAddress('2.3.4.5'), - ); + final ResourceRecord response0 = ip4Result('zzz.local', InternetAddress('2.3.4.5')); resolver.handleResponse([response0]); final Stream futureResult1 = resolver.addPendingRequest( ResourceRecordType.addressIPv4, @@ -106,15 +94,9 @@ void testResult3() { noTimeout, ); resolver.handleResponse([response0]); - final ResourceRecord response1 = ip4Result( - 'xxx.local', - InternetAddress('1.2.3.4'), - ); + final ResourceRecord response1 = ip4Result('xxx.local', InternetAddress('1.2.3.4')); resolver.handleResponse([response0]); - final ResourceRecord response2 = ip4Result( - 'yyy.local', - InternetAddress('2.3.4.5'), - ); + final ResourceRecord response2 = ip4Result('yyy.local', InternetAddress('2.3.4.5')); resolver.handleResponse([response0]); resolver.handleResponse([response2, response1]); resolver.handleResponse([response0]); diff --git a/packages/multicast_dns/test/resource_record_cache_test.dart b/packages/multicast_dns/test/resource_record_cache_test.dart index 9ecb88d1eabb..5b4ad994b36f 100644 --- a/packages/multicast_dns/test/resource_record_cache_test.dart +++ b/packages/multicast_dns/test/resource_record_cache_test.dart @@ -8,8 +8,7 @@ import 'dart:io'; -import 'package:multicast_dns/src/native_protocol_client.dart' - show ResourceRecordCache; +import 'package:multicast_dns/src/native_protocol_client.dart' show ResourceRecordCache; import 'package:multicast_dns/src/resource_record.dart'; import 'package:test/test.dart'; @@ -49,9 +48,7 @@ void testOverwrite() { expect(cache.entryCount, 3); // Overwrite the two cached entries with one with the same name. - cache.updateRecords([ - IPAddressResourceRecord('hest', valid, address: ip1), - ]); + cache.updateRecords([IPAddressResourceRecord('hest', valid, address: ip1)]); expect(cache.entryCount, 2); }); } @@ -64,14 +61,10 @@ void testTimeout() { final cache = ResourceRecordCache(); - cache.updateRecords([ - IPAddressResourceRecord('hest', valid, address: ip1), - ]); + cache.updateRecords([IPAddressResourceRecord('hest', valid, address: ip1)]); expect(cache.entryCount, 1); - cache.updateRecords([ - IPAddressResourceRecord('fisk', notValid, address: ip1), - ]); + cache.updateRecords([IPAddressResourceRecord('fisk', notValid, address: ip1)]); var results = []; cache.lookup('hest', ResourceRecordType.addressIPv4, results); diff --git a/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart index 69647b68dce6..a45c96f3eac8 100644 --- a/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart @@ -83,15 +83,12 @@ void main() { ]; for (final type in allDirs) { - testWidgets('getExternalStorageDirectories (type: $type)', ( - WidgetTester tester, - ) async { + testWidgets('getExternalStorageDirectories (type: $type)', (WidgetTester tester) async { if (Platform.isIOS) { final Future?> result = getExternalStorageDirectories(); await expectLater(result, throwsA(isInstanceOf())); } else if (Platform.isAndroid) { - final List? directories = - await getExternalStorageDirectories(type: type); + final List? directories = await getExternalStorageDirectories(type: type); expect(directories, isNotNull); for (final Directory result in directories!) { _verifySampleFile(result, '$type'); @@ -129,10 +126,7 @@ void _verifySampleFile(Directory? directory, String name) { // This check intentionally avoids using Directory.listSync on Android due to // https://github.com/dart-lang/sdk/issues/54287. if (Platform.isAndroid) { - expect( - Process.runSync('ls', [directory.path]).stdout, - contains(name), - ); + expect(Process.runSync('ls', [directory.path]).stdout, contains(name)); } else { expect(directory.listSync(), isNotEmpty); } diff --git a/packages/path_provider/path_provider/example/lib/main.dart b/packages/path_provider/path_provider/example/lib/main.dart index a3aeb6cc6575..a86eb7faf8f9 100644 --- a/packages/path_provider/path_provider/example/lib/main.dart +++ b/packages/path_provider/path_provider/example/lib/main.dart @@ -51,10 +51,7 @@ class _MyHomePageState extends State { }); } - Widget _buildDirectory( - BuildContext context, - AsyncSnapshot snapshot, - ) { + Widget _buildDirectory(BuildContext context, AsyncSnapshot snapshot) { var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { @@ -68,18 +65,13 @@ class _MyHomePageState extends State { return Padding(padding: const EdgeInsets.all(16.0), child: text); } - Widget _buildDirectories( - BuildContext context, - AsyncSnapshot?> snapshot, - ) { + Widget _buildDirectories(BuildContext context, AsyncSnapshot?> snapshot) { var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); } else if (snapshot.hasData) { - final String combined = snapshot.data! - .map((Directory d) => d.path) - .join(', '); + final String combined = snapshot.data!.map((Directory d) => d.path).join(', '); text = Text('paths: $combined'); } else { text = const Text('path unavailable'); @@ -152,10 +144,7 @@ class _MyHomePageState extends State { child: const Text('Get Temporary Directory'), ), ), - FutureBuilder( - future: _tempDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _tempDirectory, builder: _buildDirectory), ], ), Column( @@ -167,10 +156,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Documents Directory'), ), ), - FutureBuilder( - future: _appDocumentsDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appDocumentsDirectory, builder: _buildDirectory), ], ), Column( @@ -182,10 +168,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Support Directory'), ), ), - FutureBuilder( - future: _appSupportDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appSupportDirectory, builder: _buildDirectory), ], ), Column( @@ -193,9 +176,7 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: Platform.isAndroid - ? null - : _requestAppLibraryDirectory, + onPressed: Platform.isAndroid ? null : _requestAppLibraryDirectory, child: Text( Platform.isAndroid ? 'Application Library Directory unavailable' @@ -203,10 +184,7 @@ class _MyHomePageState extends State { ), ), ), - FutureBuilder( - future: _appLibraryDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appLibraryDirectory, builder: _buildDirectory), ], ), Column( @@ -218,10 +196,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Cache Directory'), ), ), - FutureBuilder( - future: _appCacheDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appCacheDirectory, builder: _buildDirectory), ], ), Column( @@ -229,9 +204,7 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: !Platform.isAndroid - ? null - : _requestExternalStorageDirectory, + onPressed: !Platform.isAndroid ? null : _requestExternalStorageDirectory, child: Text( !Platform.isAndroid ? 'External storage is unavailable' @@ -253,9 +226,7 @@ class _MyHomePageState extends State { onPressed: !Platform.isAndroid ? null : () { - _requestExternalStorageDirectories( - StorageDirectory.music, - ); + _requestExternalStorageDirectories(StorageDirectory.music); }, child: Text( !Platform.isAndroid @@ -275,9 +246,7 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: !Platform.isAndroid - ? null - : _requestExternalCacheDirectories, + onPressed: !Platform.isAndroid ? null : _requestExternalCacheDirectories, child: Text( !Platform.isAndroid ? 'External directories are unavailable' @@ -306,10 +275,7 @@ class _MyHomePageState extends State { ), ), ), - FutureBuilder( - future: _downloadsDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _downloadsDirectory, builder: _buildDirectory), ], ), ], diff --git a/packages/path_provider/path_provider/lib/path_provider.dart b/packages/path_provider/path_provider/lib/path_provider.dart index d855c260889e..2883d042fa00 100644 --- a/packages/path_provider/path_provider/lib/path_provider.dart +++ b/packages/path_provider/path_provider/lib/path_provider.dart @@ -54,9 +54,7 @@ PathProviderPlatform get _platform => PathProviderPlatform.instance; Future getTemporaryDirectory() async { final String? path = await _platform.getTemporaryPath(); if (path == null) { - throw MissingPlatformDirectoryException( - 'Unable to get temporary directory', - ); + throw MissingPlatformDirectoryException('Unable to get temporary directory'); } return Directory(path); } @@ -78,9 +76,7 @@ Future getTemporaryDirectory() async { Future getApplicationSupportDirectory() async { final String? path = await _platform.getApplicationSupportPath(); if (path == null) { - throw MissingPlatformDirectoryException( - 'Unable to get application support directory', - ); + throw MissingPlatformDirectoryException('Unable to get application support directory'); } return Directory(path); @@ -122,9 +118,7 @@ Future getLibraryDirectory() async { Future getApplicationDocumentsDirectory() async { final String? path = await _platform.getApplicationDocumentsPath(); if (path == null) { - throw MissingPlatformDirectoryException( - 'Unable to get application documents directory', - ); + throw MissingPlatformDirectoryException('Unable to get application documents directory'); } return Directory(path); } @@ -139,9 +133,7 @@ Future getApplicationDocumentsDirectory() async { Future getApplicationCacheDirectory() async { final String? path = await _platform.getApplicationCachePath(); if (path == null) { - throw MissingPlatformDirectoryException( - 'Unable to get application cache directory', - ); + throw MissingPlatformDirectoryException('Unable to get application cache directory'); } return Directory(path); } @@ -202,9 +194,7 @@ Future?> getExternalStorageDirectories({ /// how this type translates to Android storage directories. StorageDirectory? type, }) async { - final List? paths = await _platform.getExternalStoragePaths( - type: type, - ); + final List? paths = await _platform.getExternalStoragePaths(type: type); if (paths == null) { return null; } diff --git a/packages/path_provider/path_provider/test/path_provider_test.dart b/packages/path_provider/path_provider/test/path_provider_test.dart index 2e5eace8aeb2..77214c900b4a 100644 --- a/packages/path_provider/path_provider/test/path_provider_test.dart +++ b/packages/path_provider/path_provider/test/path_provider_test.dart @@ -73,31 +73,19 @@ void main() { }); test('getTemporaryDirectory throws on null', () async { - expect( - getTemporaryDirectory(), - throwsA(isA()), - ); + expect(getTemporaryDirectory(), throwsA(isA())); }); test('getApplicationSupportDirectory throws on null', () async { - expect( - getApplicationSupportDirectory(), - throwsA(isA()), - ); + expect(getApplicationSupportDirectory(), throwsA(isA())); }); test('getLibraryDirectory throws on null', () async { - expect( - getLibraryDirectory(), - throwsA(isA()), - ); + expect(getLibraryDirectory(), throwsA(isA())); }); test('getApplicationDocumentsDirectory throws on null', () async { - expect( - getApplicationDocumentsDirectory(), - throwsA(isA()), - ); + expect(getApplicationDocumentsDirectory(), throwsA(isA())); }); test('getExternalStorageDirectory passes null through', () async { @@ -156,9 +144,7 @@ class FakePathProviderPlatform extends Fake } @override - Future?> getExternalStoragePaths({ - StorageDirectory? type, - }) async { + Future?> getExternalStoragePaths({StorageDirectory? type}) async { return [kExternalStoragePath]; } @@ -202,9 +188,7 @@ class AllNullFakePathProviderPlatform extends Fake } @override - Future?> getExternalStoragePaths({ - StorageDirectory? type, - }) async { + Future?> getExternalStoragePaths({StorageDirectory? type}) async { return null; } diff --git a/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart index ab6b1b76eaf7..52dc3d2d9df2 100644 --- a/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart @@ -36,10 +36,7 @@ void main() { testWidgets('getLibraryDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; - expect( - () => provider.getLibraryPath(), - throwsA(isInstanceOf()), - ); + expect(() => provider.getLibraryPath(), throwsA(isInstanceOf())); }); testWidgets('getExternalStorageDirectory', (WidgetTester tester) async { @@ -69,14 +66,10 @@ void main() { ]; for (final type in allDirs) { - testWidgets('getExternalStorageDirectories (type: $type)', ( - WidgetTester tester, - ) async { + testWidgets('getExternalStorageDirectories (type: $type)', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; - final List? directories = await provider.getExternalStoragePaths( - type: type, - ); + final List? directories = await provider.getExternalStoragePaths(type: type); expect(directories, isNotNull); expect(directories, isNotEmpty); for (final String result in directories!) { @@ -105,9 +98,6 @@ void _verifySampleFile(String? directoryPath, String name) { expect(file.readAsStringSync(), 'Hello world!'); // This check intentionally avoids using Directory.listSync due to // https://github.com/dart-lang/sdk/issues/54287. - expect( - Process.runSync('ls', [directory.path]).stdout, - contains(name), - ); + expect(Process.runSync('ls', [directory.path]).stdout, contains(name)); file.deleteSync(); } diff --git a/packages/path_provider/path_provider_android/example/lib/main.dart b/packages/path_provider/path_provider_android/example/lib/main.dart index 1bec8806abbc..70bb9ff2573b 100644 --- a/packages/path_provider/path_provider_android/example/lib/main.dart +++ b/packages/path_provider/path_provider_android/example/lib/main.dart @@ -49,10 +49,7 @@ class _MyHomePageState extends State { }); } - Widget _buildDirectory( - BuildContext context, - AsyncSnapshot snapshot, - ) { + Widget _buildDirectory(BuildContext context, AsyncSnapshot snapshot) { var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { @@ -66,10 +63,7 @@ class _MyHomePageState extends State { return Padding(padding: const EdgeInsets.all(16.0), child: text); } - Widget _buildDirectories( - BuildContext context, - AsyncSnapshot?> snapshot, - ) { + Widget _buildDirectories(BuildContext context, AsyncSnapshot?> snapshot) { var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { @@ -110,9 +104,7 @@ class _MyHomePageState extends State { void _requestExternalStorageDirectories(StorageDirectory type) { setState(() { - _externalStorageDirectories = provider.getExternalStoragePaths( - type: type, - ); + _externalStorageDirectories = provider.getExternalStoragePaths(type: type); }); } @@ -142,10 +134,7 @@ class _MyHomePageState extends State { child: const Text('Get Temporary Directory'), ), ), - FutureBuilder( - future: _tempDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _tempDirectory, builder: _buildDirectory), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -153,10 +142,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Documents Directory'), ), ), - FutureBuilder( - future: _appDocumentsDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appDocumentsDirectory, builder: _buildDirectory), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -164,10 +150,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Support Directory'), ), ), - FutureBuilder( - future: _appSupportDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appSupportDirectory, builder: _buildDirectory), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -175,10 +158,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Cache Directory'), ), ), - FutureBuilder( - future: _appCacheDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appCacheDirectory, builder: _buildDirectory), Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( @@ -186,10 +166,7 @@ class _MyHomePageState extends State { child: const Text('Get External Storage Directory'), ), ), - FutureBuilder( - future: _externalDocumentsDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _externalDocumentsDirectory, builder: _buildDirectory), Column( children: [ Padding( @@ -197,9 +174,7 @@ class _MyHomePageState extends State { child: ElevatedButton( child: const Text('Get External Storage Directories'), onPressed: () { - _requestExternalStorageDirectories( - StorageDirectory.music, - ); + _requestExternalStorageDirectories(StorageDirectory.music); }, ), ), @@ -231,10 +206,7 @@ class _MyHomePageState extends State { child: const Text('Get Downloads Directory'), ), ), - FutureBuilder( - future: _externalDownloadsDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _externalDownloadsDirectory, builder: _buildDirectory), ], ), ), diff --git a/packages/path_provider/path_provider_android/lib/src/path_provider.g.dart b/packages/path_provider/path_provider_android/lib/src/path_provider.g.dart index e8b4f3deeeae..5abfcc8ef5a4 100644 --- a/packages/path_provider/path_provider_android/lib/src/path_provider.g.dart +++ b/packages/path_provider/path_provider_android/lib/src/path_provider.g.dart @@ -39,15 +39,11 @@ import 'package:jni/jni.dart' as jni$_; const _$jniVersionCheck = jni$_.JniVersionCheck(1, 0); /// from: `android.content.Context$BindServiceFlags` -extension type Context$BindServiceFlags._(jni$_.JObject _$this) - implements jni$_.JObject { - static final _class = jni$_.JClass.forName( - r'android/content/Context$BindServiceFlags', - ); +extension type Context$BindServiceFlags._(jni$_.JObject _$this) implements jni$_.JObject { + static final _class = jni$_.JClass.forName(r'android/content/Context$BindServiceFlags'); /// The type which includes information such as the signature of this class. - static const jni$_.JType type = - $Context$BindServiceFlags$Type$(); + static const jni$_.JType type = $Context$BindServiceFlags$Type$(); static final _id_of = _class.staticMethodId( r'of', r'(J)Landroid/content/Context$BindServiceFlags;', @@ -64,26 +60,17 @@ extension type Context$BindServiceFlags._(jni$_.JObject _$this) > >('globalEnv_CallStaticObjectMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `static public android.content.Context$BindServiceFlags of(long j)` /// The returned object must be released after use, by calling the [release] method. static Context$BindServiceFlags? of(core$_.int j) { - return _of( - _class.reference.pointer, - _id_of.pointer, - j, - ).object(); + return _of(_class.reference.pointer, _id_of.pointer, j).object(); } } -final class $Context$BindServiceFlags$Type$ - extends jni$_.JType { +final class $Context$BindServiceFlags$Type$ extends jni$_.JType { @jni$_.internal const $Context$BindServiceFlags$Type$(); @@ -106,8 +93,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String ACCESSIBILITY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get ACCESSIBILITY_SERVICE => - _id_ACCESSIBILITY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_ACCESSIBILITY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_ACCOUNT_SERVICE = _class.staticFieldId( r'ACCOUNT_SERVICE', @@ -117,8 +103,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String ACCOUNT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get ACCOUNT_SERVICE => - _id_ACCOUNT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_ACCOUNT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_ACTIVITY_SERVICE = _class.staticFieldId( r'ACTIVITY_SERVICE', @@ -128,8 +113,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String ACTIVITY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get ACTIVITY_SERVICE => - _id_ACTIVITY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_ACTIVITY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_ADVANCED_PROTECTION_SERVICE = _class.staticFieldId( r'ADVANCED_PROTECTION_SERVICE', @@ -139,19 +123,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String ADVANCED_PROTECTION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get ADVANCED_PROTECTION_SERVICE => - _id_ADVANCED_PROTECTION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_ADVANCED_PROTECTION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_ALARM_SERVICE = _class.staticFieldId( - r'ALARM_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_ALARM_SERVICE = _class.staticFieldId(r'ALARM_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String ALARM_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get ALARM_SERVICE => - _id_ALARM_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_ALARM_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_APPWIDGET_SERVICE = _class.staticFieldId( r'APPWIDGET_SERVICE', @@ -161,8 +140,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String APPWIDGET_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get APPWIDGET_SERVICE => - _id_APPWIDGET_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_APPWIDGET_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_APP_FUNCTION_SERVICE = _class.staticFieldId( r'APP_FUNCTION_SERVICE', @@ -172,8 +150,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String APP_FUNCTION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get APP_FUNCTION_SERVICE => - _id_APP_FUNCTION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_APP_FUNCTION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_APP_OPS_SERVICE = _class.staticFieldId( r'APP_OPS_SERVICE', @@ -183,8 +160,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String APP_OPS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get APP_OPS_SERVICE => - _id_APP_OPS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_APP_OPS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_APP_SEARCH_SERVICE = _class.staticFieldId( r'APP_SEARCH_SERVICE', @@ -194,19 +170,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String APP_SEARCH_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get APP_SEARCH_SERVICE => - _id_APP_SEARCH_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_APP_SEARCH_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_AUDIO_SERVICE = _class.staticFieldId( - r'AUDIO_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_AUDIO_SERVICE = _class.staticFieldId(r'AUDIO_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String AUDIO_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get AUDIO_SERVICE => - _id_AUDIO_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_AUDIO_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_BATTERY_SERVICE = _class.staticFieldId( r'BATTERY_SERVICE', @@ -216,8 +187,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String BATTERY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get BATTERY_SERVICE => - _id_BATTERY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_BATTERY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public final int BIND_ABOVE_CLIENT` static const BIND_ABOVE_CLIENT = 8; @@ -271,8 +241,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String BIOMETRIC_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get BIOMETRIC_SERVICE => - _id_BIOMETRIC_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_BIOMETRIC_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_BLOB_STORE_SERVICE = _class.staticFieldId( r'BLOB_STORE_SERVICE', @@ -282,8 +251,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String BLOB_STORE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get BLOB_STORE_SERVICE => - _id_BLOB_STORE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_BLOB_STORE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_BLUETOOTH_SERVICE = _class.staticFieldId( r'BLUETOOTH_SERVICE', @@ -293,8 +261,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String BLUETOOTH_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get BLUETOOTH_SERVICE => - _id_BLUETOOTH_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_BLUETOOTH_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_BUGREPORT_SERVICE = _class.staticFieldId( r'BUGREPORT_SERVICE', @@ -304,19 +271,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String BUGREPORT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get BUGREPORT_SERVICE => - _id_BUGREPORT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_BUGREPORT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_CAMERA_SERVICE = _class.staticFieldId( - r'CAMERA_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_CAMERA_SERVICE = _class.staticFieldId(r'CAMERA_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String CAMERA_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CAMERA_SERVICE => - _id_CAMERA_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CAMERA_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CAPTIONING_SERVICE = _class.staticFieldId( r'CAPTIONING_SERVICE', @@ -326,8 +288,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CAPTIONING_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CAPTIONING_SERVICE => - _id_CAPTIONING_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CAPTIONING_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CARRIER_CONFIG_SERVICE = _class.staticFieldId( r'CARRIER_CONFIG_SERVICE', @@ -337,8 +298,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CARRIER_CONFIG_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CARRIER_CONFIG_SERVICE => - _id_CARRIER_CONFIG_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CARRIER_CONFIG_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CLIPBOARD_SERVICE = _class.staticFieldId( r'CLIPBOARD_SERVICE', @@ -348,8 +308,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CLIPBOARD_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CLIPBOARD_SERVICE => - _id_CLIPBOARD_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CLIPBOARD_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_COMPANION_DEVICE_SERVICE = _class.staticFieldId( r'COMPANION_DEVICE_SERVICE', @@ -359,8 +318,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String COMPANION_DEVICE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get COMPANION_DEVICE_SERVICE => - _id_COMPANION_DEVICE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_COMPANION_DEVICE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CONNECTIVITY_DIAGNOSTICS_SERVICE = _class.staticFieldId( r'CONNECTIVITY_DIAGNOSTICS_SERVICE', @@ -370,10 +328,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CONNECTIVITY_DIAGNOSTICS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CONNECTIVITY_DIAGNOSTICS_SERVICE => - _id_CONNECTIVITY_DIAGNOSTICS_SERVICE.getNullable( - _class, - jni$_.JString.type, - ) + _id_CONNECTIVITY_DIAGNOSTICS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CONNECTIVITY_SERVICE = _class.staticFieldId( @@ -384,8 +339,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CONNECTIVITY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CONNECTIVITY_SERVICE => - _id_CONNECTIVITY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CONNECTIVITY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CONSUMER_IR_SERVICE = _class.staticFieldId( r'CONSUMER_IR_SERVICE', @@ -395,8 +349,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CONSUMER_IR_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CONSUMER_IR_SERVICE => - _id_CONSUMER_IR_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CONSUMER_IR_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CONTACT_KEYS_SERVICE = _class.staticFieldId( r'CONTACT_KEYS_SERVICE', @@ -406,8 +359,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CONTACT_KEYS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CONTACT_KEYS_SERVICE => - _id_CONTACT_KEYS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CONTACT_KEYS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public final int CONTEXT_IGNORE_SECURITY` static const CONTEXT_IGNORE_SECURITY = 2; @@ -425,8 +377,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CREDENTIAL_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CREDENTIAL_SERVICE => - _id_CREDENTIAL_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CREDENTIAL_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_CROSS_PROFILE_APPS_SERVICE = _class.staticFieldId( r'CROSS_PROFILE_APPS_SERVICE', @@ -436,8 +387,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String CROSS_PROFILE_APPS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get CROSS_PROFILE_APPS_SERVICE => - _id_CROSS_PROFILE_APPS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_CROSS_PROFILE_APPS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public final int DEVICE_ID_DEFAULT` static const DEVICE_ID_DEFAULT = 0; @@ -452,8 +402,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String DEVICE_LOCK_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DEVICE_LOCK_SERVICE => - _id_DEVICE_LOCK_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DEVICE_LOCK_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_DEVICE_POLICY_SERVICE = _class.staticFieldId( r'DEVICE_POLICY_SERVICE', @@ -463,8 +412,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String DEVICE_POLICY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DEVICE_POLICY_SERVICE => - _id_DEVICE_POLICY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DEVICE_POLICY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_DISPLAY_HASH_SERVICE = _class.staticFieldId( r'DISPLAY_HASH_SERVICE', @@ -474,8 +422,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String DISPLAY_HASH_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DISPLAY_HASH_SERVICE => - _id_DISPLAY_HASH_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DISPLAY_HASH_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_DISPLAY_SERVICE = _class.staticFieldId( r'DISPLAY_SERVICE', @@ -485,8 +432,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String DISPLAY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DISPLAY_SERVICE => - _id_DISPLAY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DISPLAY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_DOMAIN_VERIFICATION_SERVICE = _class.staticFieldId( r'DOMAIN_VERIFICATION_SERVICE', @@ -496,8 +442,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String DOMAIN_VERIFICATION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DOMAIN_VERIFICATION_SERVICE => - _id_DOMAIN_VERIFICATION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DOMAIN_VERIFICATION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_DOWNLOAD_SERVICE = _class.staticFieldId( r'DOWNLOAD_SERVICE', @@ -507,8 +452,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String DOWNLOAD_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DOWNLOAD_SERVICE => - _id_DOWNLOAD_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DOWNLOAD_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_DROPBOX_SERVICE = _class.staticFieldId( r'DROPBOX_SERVICE', @@ -518,19 +462,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String DROPBOX_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DROPBOX_SERVICE => - _id_DROPBOX_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DROPBOX_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_EUICC_SERVICE = _class.staticFieldId( - r'EUICC_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_EUICC_SERVICE = _class.staticFieldId(r'EUICC_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String EUICC_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get EUICC_SERVICE => - _id_EUICC_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_EUICC_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_FILE_INTEGRITY_SERVICE = _class.staticFieldId( r'FILE_INTEGRITY_SERVICE', @@ -540,8 +479,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String FILE_INTEGRITY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get FILE_INTEGRITY_SERVICE => - _id_FILE_INTEGRITY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_FILE_INTEGRITY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_FINGERPRINT_SERVICE = _class.staticFieldId( r'FINGERPRINT_SERVICE', @@ -551,19 +489,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String FINGERPRINT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get FINGERPRINT_SERVICE => - _id_FINGERPRINT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_FINGERPRINT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_GAME_SERVICE = _class.staticFieldId( - r'GAME_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_GAME_SERVICE = _class.staticFieldId(r'GAME_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String GAME_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get GAME_SERVICE => - _id_GAME_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_GAME_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_GRAMMATICAL_INFLECTION_SERVICE = _class.staticFieldId( r'GRAMMATICAL_INFLECTION_SERVICE', @@ -573,8 +506,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String GRAMMATICAL_INFLECTION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get GRAMMATICAL_INFLECTION_SERVICE => - _id_GRAMMATICAL_INFLECTION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_GRAMMATICAL_INFLECTION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_HARDWARE_PROPERTIES_SERVICE = _class.staticFieldId( r'HARDWARE_PROPERTIES_SERVICE', @@ -584,8 +516,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String HARDWARE_PROPERTIES_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get HARDWARE_PROPERTIES_SERVICE => - _id_HARDWARE_PROPERTIES_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_HARDWARE_PROPERTIES_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_HEALTHCONNECT_SERVICE = _class.staticFieldId( r'HEALTHCONNECT_SERVICE', @@ -595,8 +526,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String HEALTHCONNECT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get HEALTHCONNECT_SERVICE => - _id_HEALTHCONNECT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_HEALTHCONNECT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_INPUT_METHOD_SERVICE = _class.staticFieldId( r'INPUT_METHOD_SERVICE', @@ -606,30 +536,21 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String INPUT_METHOD_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get INPUT_METHOD_SERVICE => - _id_INPUT_METHOD_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_INPUT_METHOD_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_INPUT_SERVICE = _class.staticFieldId( - r'INPUT_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_INPUT_SERVICE = _class.staticFieldId(r'INPUT_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String INPUT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get INPUT_SERVICE => - _id_INPUT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_INPUT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_IPSEC_SERVICE = _class.staticFieldId( - r'IPSEC_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_IPSEC_SERVICE = _class.staticFieldId(r'IPSEC_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String IPSEC_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get IPSEC_SERVICE => - _id_IPSEC_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_IPSEC_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_JOB_SCHEDULER_SERVICE = _class.staticFieldId( r'JOB_SCHEDULER_SERVICE', @@ -639,8 +560,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String JOB_SCHEDULER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get JOB_SCHEDULER_SERVICE => - _id_JOB_SCHEDULER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_JOB_SCHEDULER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_KEYGUARD_SERVICE = _class.staticFieldId( r'KEYGUARD_SERVICE', @@ -650,8 +570,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String KEYGUARD_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get KEYGUARD_SERVICE => - _id_KEYGUARD_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_KEYGUARD_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_KEYSTORE_SERVICE = _class.staticFieldId( r'KEYSTORE_SERVICE', @@ -661,8 +580,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String KEYSTORE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get KEYSTORE_SERVICE => - _id_KEYSTORE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_KEYSTORE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_LAUNCHER_APPS_SERVICE = _class.staticFieldId( r'LAUNCHER_APPS_SERVICE', @@ -672,8 +590,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String LAUNCHER_APPS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get LAUNCHER_APPS_SERVICE => - _id_LAUNCHER_APPS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_LAUNCHER_APPS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_LAYOUT_INFLATER_SERVICE = _class.staticFieldId( r'LAYOUT_INFLATER_SERVICE', @@ -683,19 +600,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String LAYOUT_INFLATER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get LAYOUT_INFLATER_SERVICE => - _id_LAYOUT_INFLATER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_LAYOUT_INFLATER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_LOCALE_SERVICE = _class.staticFieldId( - r'LOCALE_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_LOCALE_SERVICE = _class.staticFieldId(r'LOCALE_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String LOCALE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get LOCALE_SERVICE => - _id_LOCALE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_LOCALE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_LOCATION_SERVICE = _class.staticFieldId( r'LOCATION_SERVICE', @@ -705,8 +617,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String LOCATION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get LOCATION_SERVICE => - _id_LOCATION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_LOCATION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_COMMUNICATION_SERVICE = _class.staticFieldId( r'MEDIA_COMMUNICATION_SERVICE', @@ -716,8 +627,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_COMMUNICATION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_COMMUNICATION_SERVICE => - _id_MEDIA_COMMUNICATION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_COMMUNICATION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_METRICS_SERVICE = _class.staticFieldId( r'MEDIA_METRICS_SERVICE', @@ -727,8 +637,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_METRICS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_METRICS_SERVICE => - _id_MEDIA_METRICS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_METRICS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_PROJECTION_SERVICE = _class.staticFieldId( r'MEDIA_PROJECTION_SERVICE', @@ -738,8 +647,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_PROJECTION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_PROJECTION_SERVICE => - _id_MEDIA_PROJECTION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_PROJECTION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_QUALITY_SERVICE = _class.staticFieldId( r'MEDIA_QUALITY_SERVICE', @@ -749,8 +657,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_QUALITY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_QUALITY_SERVICE => - _id_MEDIA_QUALITY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_QUALITY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_ROUTER_SERVICE = _class.staticFieldId( r'MEDIA_ROUTER_SERVICE', @@ -760,8 +667,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_ROUTER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_ROUTER_SERVICE => - _id_MEDIA_ROUTER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_ROUTER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_SESSION_SERVICE = _class.staticFieldId( r'MEDIA_SESSION_SERVICE', @@ -771,19 +677,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_SESSION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_SESSION_SERVICE => - _id_MEDIA_SESSION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_SESSION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MIDI_SERVICE = _class.staticFieldId( - r'MIDI_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_MIDI_SERVICE = _class.staticFieldId(r'MIDI_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MIDI_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MIDI_SERVICE => - _id_MIDI_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MIDI_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public final int MODE_APPEND` static const MODE_APPEND = 32768; @@ -813,13 +714,9 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String NETWORK_STATS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get NETWORK_STATS_SERVICE => - _id_NETWORK_STATS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_NETWORK_STATS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_NFC_SERVICE = _class.staticFieldId( - r'NFC_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_NFC_SERVICE = _class.staticFieldId(r'NFC_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String NFC_SERVICE` /// The returned object must be released after use, by calling the [release] method. @@ -834,13 +731,9 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String NOTIFICATION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get NOTIFICATION_SERVICE => - _id_NOTIFICATION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_NOTIFICATION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_NSD_SERVICE = _class.staticFieldId( - r'NSD_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_NSD_SERVICE = _class.staticFieldId(r'NSD_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String NSD_SERVICE` /// The returned object must be released after use, by calling the [release] method. @@ -855,19 +748,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String OVERLAY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get OVERLAY_SERVICE => - _id_OVERLAY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_OVERLAY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_PEOPLE_SERVICE = _class.staticFieldId( - r'PEOPLE_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_PEOPLE_SERVICE = _class.staticFieldId(r'PEOPLE_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String PEOPLE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get PEOPLE_SERVICE => - _id_PEOPLE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_PEOPLE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_PERFORMANCE_HINT_SERVICE = _class.staticFieldId( r'PERFORMANCE_HINT_SERVICE', @@ -877,8 +765,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String PERFORMANCE_HINT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get PERFORMANCE_HINT_SERVICE => - _id_PERFORMANCE_HINT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_PERFORMANCE_HINT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_PERSISTENT_DATA_BLOCK_SERVICE = _class.staticFieldId( r'PERSISTENT_DATA_BLOCK_SERVICE', @@ -888,30 +775,21 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String PERSISTENT_DATA_BLOCK_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get PERSISTENT_DATA_BLOCK_SERVICE => - _id_PERSISTENT_DATA_BLOCK_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_PERSISTENT_DATA_BLOCK_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_POWER_SERVICE = _class.staticFieldId( - r'POWER_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_POWER_SERVICE = _class.staticFieldId(r'POWER_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String POWER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get POWER_SERVICE => - _id_POWER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_POWER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_PRINT_SERVICE = _class.staticFieldId( - r'PRINT_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_PRINT_SERVICE = _class.staticFieldId(r'PRINT_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String PRINT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get PRINT_SERVICE => - _id_PRINT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_PRINT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_PROFILING_SERVICE = _class.staticFieldId( r'PROFILING_SERVICE', @@ -921,8 +799,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String PROFILING_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get PROFILING_SERVICE => - _id_PROFILING_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_PROFILING_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public final int RECEIVER_EXPORTED` static const RECEIVER_EXPORTED = 2; @@ -940,19 +817,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String RESTRICTIONS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get RESTRICTIONS_SERVICE => - _id_RESTRICTIONS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_RESTRICTIONS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_ROLE_SERVICE = _class.staticFieldId( - r'ROLE_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_ROLE_SERVICE = _class.staticFieldId(r'ROLE_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String ROLE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get ROLE_SERVICE => - _id_ROLE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_ROLE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_SATELLITE_SERVICE = _class.staticFieldId( r'SATELLITE_SERVICE', @@ -962,19 +834,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String SATELLITE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get SATELLITE_SERVICE => - _id_SATELLITE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_SATELLITE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_SEARCH_SERVICE = _class.staticFieldId( - r'SEARCH_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_SEARCH_SERVICE = _class.staticFieldId(r'SEARCH_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String SEARCH_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get SEARCH_SERVICE => - _id_SEARCH_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_SEARCH_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_SECURITY_STATE_SERVICE = _class.staticFieldId( r'SECURITY_STATE_SERVICE', @@ -984,19 +851,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String SECURITY_STATE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get SECURITY_STATE_SERVICE => - _id_SECURITY_STATE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_SECURITY_STATE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_SENSOR_SERVICE = _class.staticFieldId( - r'SENSOR_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_SENSOR_SERVICE = _class.staticFieldId(r'SENSOR_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String SENSOR_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get SENSOR_SERVICE => - _id_SENSOR_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_SENSOR_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_SHORTCUT_SERVICE = _class.staticFieldId( r'SHORTCUT_SERVICE', @@ -1006,8 +868,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String SHORTCUT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get SHORTCUT_SERVICE => - _id_SHORTCUT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_SHORTCUT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_STATUS_BAR_SERVICE = _class.staticFieldId( r'STATUS_BAR_SERVICE', @@ -1017,8 +878,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String STATUS_BAR_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get STATUS_BAR_SERVICE => - _id_STATUS_BAR_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_STATUS_BAR_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_STORAGE_SERVICE = _class.staticFieldId( r'STORAGE_SERVICE', @@ -1028,8 +888,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String STORAGE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get STORAGE_SERVICE => - _id_STORAGE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_STORAGE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_STORAGE_STATS_SERVICE = _class.staticFieldId( r'STORAGE_STATS_SERVICE', @@ -1039,8 +898,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String STORAGE_STATS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get STORAGE_STATS_SERVICE => - _id_STORAGE_STATS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_STORAGE_STATS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_SYSTEM_HEALTH_SERVICE = _class.staticFieldId( r'SYSTEM_HEALTH_SERVICE', @@ -1050,8 +908,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String SYSTEM_HEALTH_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get SYSTEM_HEALTH_SERVICE => - _id_SYSTEM_HEALTH_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_SYSTEM_HEALTH_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TELECOM_SERVICE = _class.staticFieldId( r'TELECOM_SERVICE', @@ -1061,8 +918,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TELECOM_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TELECOM_SERVICE => - _id_TELECOM_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TELECOM_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TELEPHONY_IMS_SERVICE = _class.staticFieldId( r'TELEPHONY_IMS_SERVICE', @@ -1072,8 +928,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TELEPHONY_IMS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TELEPHONY_IMS_SERVICE => - _id_TELEPHONY_IMS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TELEPHONY_IMS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TELEPHONY_SERVICE = _class.staticFieldId( r'TELEPHONY_SERVICE', @@ -1083,8 +938,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TELEPHONY_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TELEPHONY_SERVICE => - _id_TELEPHONY_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TELEPHONY_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TELEPHONY_SUBSCRIPTION_SERVICE = _class.staticFieldId( r'TELEPHONY_SUBSCRIPTION_SERVICE', @@ -1094,8 +948,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TELEPHONY_SUBSCRIPTION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TELEPHONY_SUBSCRIPTION_SERVICE => - _id_TELEPHONY_SUBSCRIPTION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TELEPHONY_SUBSCRIPTION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TETHERING_SERVICE = _class.staticFieldId( r'TETHERING_SERVICE', @@ -1105,8 +958,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TETHERING_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TETHERING_SERVICE => - _id_TETHERING_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TETHERING_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TEXT_CLASSIFICATION_SERVICE = _class.staticFieldId( r'TEXT_CLASSIFICATION_SERVICE', @@ -1116,8 +968,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TEXT_CLASSIFICATION_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TEXT_CLASSIFICATION_SERVICE => - _id_TEXT_CLASSIFICATION_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TEXT_CLASSIFICATION_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TEXT_SERVICES_MANAGER_SERVICE = _class.staticFieldId( r'TEXT_SERVICES_MANAGER_SERVICE', @@ -1127,19 +978,14 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TEXT_SERVICES_MANAGER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TEXT_SERVICES_MANAGER_SERVICE => - _id_TEXT_SERVICES_MANAGER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TEXT_SERVICES_MANAGER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_TV_AD_SERVICE = _class.staticFieldId( - r'TV_AD_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_TV_AD_SERVICE = _class.staticFieldId(r'TV_AD_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String TV_AD_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TV_AD_SERVICE => - _id_TV_AD_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TV_AD_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TV_INPUT_SERVICE = _class.staticFieldId( r'TV_INPUT_SERVICE', @@ -1149,8 +995,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TV_INPUT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TV_INPUT_SERVICE => - _id_TV_INPUT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TV_INPUT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_TV_INTERACTIVE_APP_SERVICE = _class.staticFieldId( r'TV_INTERACTIVE_APP_SERVICE', @@ -1160,8 +1005,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String TV_INTERACTIVE_APP_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get TV_INTERACTIVE_APP_SERVICE => - _id_TV_INTERACTIVE_APP_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_TV_INTERACTIVE_APP_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_UI_MODE_SERVICE = _class.staticFieldId( r'UI_MODE_SERVICE', @@ -1171,8 +1015,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String UI_MODE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get UI_MODE_SERVICE => - _id_UI_MODE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_UI_MODE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_USAGE_STATS_SERVICE = _class.staticFieldId( r'USAGE_STATS_SERVICE', @@ -1182,29 +1025,21 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String USAGE_STATS_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get USAGE_STATS_SERVICE => - _id_USAGE_STATS_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_USAGE_STATS_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_USB_SERVICE = _class.staticFieldId( - r'USB_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_USB_SERVICE = _class.staticFieldId(r'USB_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String USB_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get USB_SERVICE => _id_USB_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_USER_SERVICE = _class.staticFieldId( - r'USER_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_USER_SERVICE = _class.staticFieldId(r'USER_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String USER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get USER_SERVICE => - _id_USER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_USER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_VIBRATOR_MANAGER_SERVICE = _class.staticFieldId( r'VIBRATOR_MANAGER_SERVICE', @@ -1214,8 +1049,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String VIBRATOR_MANAGER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get VIBRATOR_MANAGER_SERVICE => - _id_VIBRATOR_MANAGER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_VIBRATOR_MANAGER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_VIBRATOR_SERVICE = _class.staticFieldId( r'VIBRATOR_SERVICE', @@ -1225,8 +1059,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String VIBRATOR_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get VIBRATOR_SERVICE => - _id_VIBRATOR_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_VIBRATOR_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_VIRTUAL_DEVICE_SERVICE = _class.staticFieldId( r'VIRTUAL_DEVICE_SERVICE', @@ -1236,8 +1069,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String VIRTUAL_DEVICE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get VIRTUAL_DEVICE_SERVICE => - _id_VIRTUAL_DEVICE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_VIRTUAL_DEVICE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_VPN_MANAGEMENT_SERVICE = _class.staticFieldId( r'VPN_MANAGEMENT_SERVICE', @@ -1247,8 +1079,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String VPN_MANAGEMENT_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get VPN_MANAGEMENT_SERVICE => - _id_VPN_MANAGEMENT_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_VPN_MANAGEMENT_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_WALLPAPER_SERVICE = _class.staticFieldId( r'WALLPAPER_SERVICE', @@ -1258,8 +1089,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String WALLPAPER_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get WALLPAPER_SERVICE => - _id_WALLPAPER_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_WALLPAPER_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_WIFI_AWARE_SERVICE = _class.staticFieldId( r'WIFI_AWARE_SERVICE', @@ -1269,8 +1099,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String WIFI_AWARE_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get WIFI_AWARE_SERVICE => - _id_WIFI_AWARE_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_WIFI_AWARE_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_WIFI_P2P_SERVICE = _class.staticFieldId( r'WIFI_P2P_SERVICE', @@ -1280,8 +1109,7 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String WIFI_P2P_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get WIFI_P2P_SERVICE => - _id_WIFI_P2P_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_WIFI_P2P_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_WIFI_RTT_RANGING_SERVICE = _class.staticFieldId( r'WIFI_RTT_RANGING_SERVICE', @@ -1291,30 +1119,21 @@ extension type Context._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String WIFI_RTT_RANGING_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get WIFI_RTT_RANGING_SERVICE => - _id_WIFI_RTT_RANGING_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_WIFI_RTT_RANGING_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_WIFI_SERVICE = _class.staticFieldId( - r'WIFI_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_WIFI_SERVICE = _class.staticFieldId(r'WIFI_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String WIFI_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get WIFI_SERVICE => - _id_WIFI_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_WIFI_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_WINDOW_SERVICE = _class.staticFieldId( - r'WINDOW_SERVICE', - r'Ljava/lang/String;', - ); + static final _id_WINDOW_SERVICE = _class.staticFieldId(r'WINDOW_SERVICE', r'Ljava/lang/String;'); /// from: `static public final java.lang.String WINDOW_SERVICE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get WINDOW_SERVICE => - _id_WINDOW_SERVICE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_WINDOW_SERVICE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; } extension Context$$Methods on Context { @@ -1362,12 +1181,10 @@ extension Context$$Methods on Context { jni$_.JObject? serviceConnection, ) { final _$intent = intent?.reference ?? jni$_.jNullReference; - final _$bindServiceFlags = - bindServiceFlags?.reference ?? jni$_.jNullReference; + final _$bindServiceFlags = bindServiceFlags?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$executor = executor?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; return _bindIsolatedService( reference.pointer, _id_bindIsolatedService.pointer, @@ -1425,8 +1242,7 @@ extension Context$$Methods on Context { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$executor = executor?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; return _bindIsolatedService$1( reference.pointer, _id_bindIsolatedService$1.pointer, @@ -1479,11 +1295,9 @@ extension Context$$Methods on Context { jni$_.JObject? serviceConnection, ) { final _$intent = intent?.reference ?? jni$_.jNullReference; - final _$bindServiceFlags = - bindServiceFlags?.reference ?? jni$_.jNullReference; + final _$bindServiceFlags = bindServiceFlags?.reference ?? jni$_.jNullReference; final _$executor = executor?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; return _bindService( reference.pointer, _id_bindService.pointer, @@ -1506,11 +1320,7 @@ extension Context$$Methods on Context { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Pointer, - ) + (jni$_.Pointer, jni$_.Pointer, jni$_.Pointer) >, ) > @@ -1532,10 +1342,8 @@ extension Context$$Methods on Context { Context$BindServiceFlags? bindServiceFlags, ) { final _$intent = intent?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; - final _$bindServiceFlags = - bindServiceFlags?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; + final _$bindServiceFlags = bindServiceFlags?.reference ?? jni$_.jNullReference; return _bindService$1( reference.pointer, _id_bindService$1.pointer, @@ -1556,13 +1364,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Int32, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer, jni$_.Int32)>, ) > >('globalEnv_CallBooleanMethod') @@ -1577,14 +1379,9 @@ extension Context$$Methods on Context { >(); /// from: `public abstract boolean bindService(android.content.Intent intent, android.content.ServiceConnection serviceConnection, int i)` - core$_.bool bindService$2( - jni$_.JObject? intent, - jni$_.JObject? serviceConnection, - core$_.int i, - ) { + core$_.bool bindService$2(jni$_.JObject? intent, jni$_.JObject? serviceConnection, core$_.int i) { final _$intent = intent?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; return _bindService$2( reference.pointer, _id_bindService$2.pointer, @@ -1636,8 +1433,7 @@ extension Context$$Methods on Context { ) { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$executor = executor?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; return _bindService$3( reference.pointer, _id_bindService$3.pointer, @@ -1689,10 +1485,8 @@ extension Context$$Methods on Context { jni$_.JObject? userHandle, ) { final _$intent = intent?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; - final _$bindServiceFlags = - bindServiceFlags?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; + final _$bindServiceFlags = bindServiceFlags?.reference ?? jni$_.jNullReference; final _$userHandle = userHandle?.reference ?? jni$_.jNullReference; return _bindServiceAsUser( reference.pointer, @@ -1745,8 +1539,7 @@ extension Context$$Methods on Context { jni$_.JObject? userHandle, ) { final _$intent = intent?.reference ?? jni$_.jNullReference; - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; final _$userHandle = userHandle?.reference ?? jni$_.jNullReference; return _bindServiceAsUser$1( reference.pointer, @@ -1758,11 +1551,10 @@ extension Context$$Methods on Context { ).boolean; } - static final _id_checkCallingOrSelfPermission = Context._class - .instanceMethodId( - r'checkCallingOrSelfPermission', - r'(Ljava/lang/String;)I', - ); + static final _id_checkCallingOrSelfPermission = Context._class.instanceMethodId( + r'checkCallingOrSelfPermission', + r'(Ljava/lang/String;)I', + ); static final _checkCallingOrSelfPermission = jni$_.ProtectedJniExtensions.lookup< @@ -1792,11 +1584,10 @@ extension Context$$Methods on Context { ).integer; } - static final _id_checkCallingOrSelfUriPermission = Context._class - .instanceMethodId( - r'checkCallingOrSelfUriPermission', - r'(Landroid/net/Uri;I)I', - ); + static final _id_checkCallingOrSelfUriPermission = Context._class.instanceMethodId( + r'checkCallingOrSelfUriPermission', + r'(Landroid/net/Uri;I)I', + ); static final _checkCallingOrSelfUriPermission = jni$_.ProtectedJniExtensions.lookup< @@ -1828,11 +1619,10 @@ extension Context$$Methods on Context { ).integer; } - static final _id_checkCallingOrSelfUriPermissions = Context._class - .instanceMethodId( - r'checkCallingOrSelfUriPermissions', - r'(Ljava/util/List;I)[I', - ); + static final _id_checkCallingOrSelfUriPermissions = Context._class.instanceMethodId( + r'checkCallingOrSelfUriPermissions', + r'(Ljava/util/List;I)[I', + ); static final _checkCallingOrSelfUriPermissions = jni$_.ProtectedJniExtensions.lookup< @@ -1962,10 +1752,7 @@ extension Context$$Methods on Context { /// from: `public int[] checkCallingUriPermissions(java.util.List list, int i)` /// The returned object must be released after use, by calling the [release] method. - jni$_.JIntArray? checkCallingUriPermissions( - jni$_.JList? list, - core$_.int i, - ) { + jni$_.JIntArray? checkCallingUriPermissions(jni$_.JList? list, core$_.int i) { final _$list = list?.reference ?? jni$_.jNullReference; return _checkCallingUriPermissions( reference.pointer, @@ -1975,11 +1762,10 @@ extension Context$$Methods on Context { ).object(); } - static final _id_checkContentUriPermissionFull = Context._class - .instanceMethodId( - r'checkContentUriPermissionFull', - r'(Landroid/net/Uri;III)I', - ); + static final _id_checkContentUriPermissionFull = Context._class.instanceMethodId( + r'checkContentUriPermissionFull', + r'(Landroid/net/Uri;III)I', + ); static final _checkContentUriPermissionFull = jni$_.ProtectedJniExtensions.lookup< @@ -1987,14 +1773,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Int32, - jni$_.Int32, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Int32, jni$_.Int32)>, ) > >('globalEnv_CallIntMethod') @@ -2038,9 +1817,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Int32, jni$_.Int32) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Int32)>, ) > >('globalEnv_CallIntMethod') @@ -2055,11 +1832,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract int checkPermission(java.lang.String string, int i, int i1)` - core$_.int checkPermission( - jni$_.JString? string, - core$_.int i, - core$_.int i1, - ) { + core$_.int checkPermission(jni$_.JString? string, core$_.int i, core$_.int i1) { final _$string = string?.reference ?? jni$_.jNullReference; return _checkPermission( reference.pointer, @@ -2114,14 +1887,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Int32, - jni$_.Int32, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Int32, jni$_.Int32)>, ) > >('globalEnv_CallIntMethod') @@ -2137,12 +1903,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract int checkUriPermission(android.net.Uri uri, int i, int i1, int i2)` - core$_.int checkUriPermission( - jni$_.JObject? uri, - core$_.int i, - core$_.int i1, - core$_.int i2, - ) { + core$_.int checkUriPermission(jni$_.JObject? uri, core$_.int i, core$_.int i1, core$_.int i2) { final _$uri = uri?.reference ?? jni$_.jNullReference; return _checkUriPermission( reference.pointer, @@ -2226,14 +1987,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Int32, - jni$_.Int32, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Int32, jni$_.Int32)>, ) > >('globalEnv_CallObjectMethod') @@ -2267,25 +2021,16 @@ extension Context$$Methods on Context { ).object(); } - static final _id_clearWallpaper = Context._class.instanceMethodId( - r'clearWallpaper', - r'()V', - ); + static final _id_clearWallpaper = Context._class.instanceMethodId(r'clearWallpaper', r'()V'); static final _clearWallpaper = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JThrowablePtr Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JThrowablePtr Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallVoidMethod') .asFunction< - jni$_.JThrowablePtr Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JThrowablePtr Function(jni$_.Pointer, jni$_.JMethodIDPtr) >(); /// from: `public abstract void clearWallpaper()` @@ -2445,11 +2190,7 @@ extension Context$$Methods on Context { > >('globalEnv_CallObjectMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public android.content.Context createDeviceContext(int i)` @@ -2462,27 +2203,18 @@ extension Context$$Methods on Context { ).object(); } - static final _id_createDeviceProtectedStorageContext = Context._class - .instanceMethodId( - r'createDeviceProtectedStorageContext', - r'()Landroid/content/Context;', - ); + static final _id_createDeviceProtectedStorageContext = Context._class.instanceMethodId( + r'createDeviceProtectedStorageContext', + r'()Landroid/content/Context;', + ); static final _createDeviceProtectedStorageContext = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.Context createDeviceProtectedStorageContext()` /// The returned object must be released after use, by calling the [release] method. @@ -2574,13 +2306,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Pointer, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Pointer)>, ) > >('globalEnv_CallObjectMethod') @@ -2596,11 +2322,7 @@ extension Context$$Methods on Context { /// from: `public android.content.Context createWindowContext(android.view.Display display, int i, android.os.Bundle bundle)` /// The returned object must be released after use, by calling the [release] method. - Context? createWindowContext( - jni$_.JObject? display, - core$_.int i, - jni$_.JObject? bundle, - ) { + Context? createWindowContext(jni$_.JObject? display, core$_.int i, jni$_.JObject? bundle) { final _$display = display?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; return _createWindowContext( @@ -2656,18 +2378,10 @@ extension Context$$Methods on Context { static final _databaseList = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.lang.String[] databaseList()` /// The returned object must be released after use, by calling the [release] method. @@ -2704,11 +2418,7 @@ extension Context$$Methods on Context { /// from: `public abstract boolean deleteDatabase(java.lang.String string)` core$_.bool deleteDatabase(jni$_.JString? string) { final _$string = string?.reference ?? jni$_.jNullReference; - return _deleteDatabase( - reference.pointer, - _id_deleteDatabase.pointer, - _$string.pointer, - ).boolean; + return _deleteDatabase(reference.pointer, _id_deleteDatabase.pointer, _$string.pointer).boolean; } static final _id_deleteFile = Context._class.instanceMethodId( @@ -2737,11 +2447,7 @@ extension Context$$Methods on Context { /// from: `public abstract boolean deleteFile(java.lang.String string)` core$_.bool deleteFile(jni$_.JString? string) { final _$string = string?.reference ?? jni$_.jNullReference; - return _deleteFile( - reference.pointer, - _id_deleteFile.pointer, - _$string.pointer, - ).boolean; + return _deleteFile(reference.pointer, _id_deleteFile.pointer, _$string.pointer).boolean; } static final _id_deleteSharedPreferences = Context._class.instanceMethodId( @@ -2777,11 +2483,10 @@ extension Context$$Methods on Context { ).boolean; } - static final _id_enforceCallingOrSelfPermission = Context._class - .instanceMethodId( - r'enforceCallingOrSelfPermission', - r'(Ljava/lang/String;Ljava/lang/String;)V', - ); + static final _id_enforceCallingOrSelfPermission = Context._class.instanceMethodId( + r'enforceCallingOrSelfPermission', + r'(Ljava/lang/String;Ljava/lang/String;)V', + ); static final _enforceCallingOrSelfPermission = jni$_.ProtectedJniExtensions.lookup< @@ -2789,9 +2494,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -2805,10 +2508,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void enforceCallingOrSelfPermission(java.lang.String string, java.lang.String string1)` - void enforceCallingOrSelfPermission( - jni$_.JString? string, - jni$_.JString? string1, - ) { + void enforceCallingOrSelfPermission(jni$_.JString? string, jni$_.JString? string1) { final _$string = string?.reference ?? jni$_.jNullReference; final _$string1 = string1?.reference ?? jni$_.jNullReference; _enforceCallingOrSelfPermission( @@ -2819,11 +2519,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_enforceCallingOrSelfUriPermission = Context._class - .instanceMethodId( - r'enforceCallingOrSelfUriPermission', - r'(Landroid/net/Uri;ILjava/lang/String;)V', - ); + static final _id_enforceCallingOrSelfUriPermission = Context._class.instanceMethodId( + r'enforceCallingOrSelfUriPermission', + r'(Landroid/net/Uri;ILjava/lang/String;)V', + ); static final _enforceCallingOrSelfUriPermission = jni$_.ProtectedJniExtensions.lookup< @@ -2831,13 +2530,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Pointer, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -2852,11 +2545,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void enforceCallingOrSelfUriPermission(android.net.Uri uri, int i, java.lang.String string)` - void enforceCallingOrSelfUriPermission( - jni$_.JObject? uri, - core$_.int i, - jni$_.JString? string, - ) { + void enforceCallingOrSelfUriPermission(jni$_.JObject? uri, core$_.int i, jni$_.JString? string) { final _$uri = uri?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; _enforceCallingOrSelfUriPermission( @@ -2879,9 +2568,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -2906,11 +2593,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_enforceCallingUriPermission = Context._class - .instanceMethodId( - r'enforceCallingUriPermission', - r'(Landroid/net/Uri;ILjava/lang/String;)V', - ); + static final _id_enforceCallingUriPermission = Context._class.instanceMethodId( + r'enforceCallingUriPermission', + r'(Landroid/net/Uri;ILjava/lang/String;)V', + ); static final _enforceCallingUriPermission = jni$_.ProtectedJniExtensions.lookup< @@ -2918,13 +2604,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Pointer, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -2939,11 +2619,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void enforceCallingUriPermission(android.net.Uri uri, int i, java.lang.String string)` - void enforceCallingUriPermission( - jni$_.JObject? uri, - core$_.int i, - jni$_.JString? string, - ) { + void enforceCallingUriPermission(jni$_.JObject? uri, core$_.int i, jni$_.JString? string) { final _$uri = uri?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; _enforceCallingUriPermission( @@ -2967,12 +2643,7 @@ extension Context$$Methods on Context { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Int32, - jni$_.Pointer, - ) + (jni$_.Pointer, jni$_.Int32, jni$_.Int32, jni$_.Pointer) >, ) > @@ -3137,18 +2808,10 @@ extension Context$$Methods on Context { static final _fileList = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.lang.String[] fileList()` /// The returned object must be released after use, by calling the [release] method. @@ -3167,18 +2830,10 @@ extension Context$$Methods on Context { static final _get$applicationContext = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.Context getApplicationContext()` /// The returned object must be released after use, by calling the [release] method. @@ -3197,18 +2852,10 @@ extension Context$$Methods on Context { static final _get$applicationInfo = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.pm.ApplicationInfo getApplicationInfo()` /// The returned object must be released after use, by calling the [release] method. @@ -3227,26 +2874,15 @@ extension Context$$Methods on Context { static final _get$assets = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.res.AssetManager getAssets()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? get assets { - return _get$assets( - reference.pointer, - _id_get$assets.pointer, - ).object(); + return _get$assets(reference.pointer, _id_get$assets.pointer).object(); } static final _id_get$attributionSource = Context._class.instanceMethodId( @@ -3257,18 +2893,10 @@ extension Context$$Methods on Context { static final _get$attributionSource = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public android.content.AttributionSource getAttributionSource()` /// The returned object must be released after use, by calling the [release] method. @@ -3287,18 +2915,10 @@ extension Context$$Methods on Context { static final _get$attributionTag = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String getAttributionTag()` /// The returned object must be released after use, by calling the [release] method. @@ -3317,26 +2937,15 @@ extension Context$$Methods on Context { static final _get$cacheDir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File getCacheDir()` /// The returned object must be released after use, by calling the [release] method. File? get cacheDir { - return _get$cacheDir( - reference.pointer, - _id_get$cacheDir.pointer, - ).object(); + return _get$cacheDir(reference.pointer, _id_get$cacheDir.pointer).object(); } static final _id_get$classLoader = Context._class.instanceMethodId( @@ -3347,18 +2956,10 @@ extension Context$$Methods on Context { static final _get$classLoader = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.lang.ClassLoader getClassLoader()` /// The returned object must be released after use, by calling the [release] method. @@ -3377,32 +2978,18 @@ extension Context$$Methods on Context { static final _get$codeCacheDir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File getCodeCacheDir()` /// The returned object must be released after use, by calling the [release] method. File? get codeCacheDir { - return _get$codeCacheDir( - reference.pointer, - _id_get$codeCacheDir.pointer, - ).object(); + return _get$codeCacheDir(reference.pointer, _id_get$codeCacheDir.pointer).object(); } - static final _id_getColor = Context._class.instanceMethodId( - r'getColor', - r'(I)I', - ); + static final _id_getColor = Context._class.instanceMethodId(r'getColor', r'(I)I'); static final _getColor = jni$_.ProtectedJniExtensions.lookup< @@ -3415,11 +3002,7 @@ extension Context$$Methods on Context { > >('globalEnv_CallIntMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public final int getColor(int i)` @@ -3443,11 +3026,7 @@ extension Context$$Methods on Context { > >('globalEnv_CallObjectMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public final android.content.res.ColorStateList getColorStateList(int i)` @@ -3468,18 +3047,10 @@ extension Context$$Methods on Context { static final _get$contentResolver = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.ContentResolver getContentResolver()` /// The returned object must be released after use, by calling the [release] method. @@ -3498,26 +3069,15 @@ extension Context$$Methods on Context { static final _get$dataDir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File getDataDir()` /// The returned object must be released after use, by calling the [release] method. File? get dataDir { - return _get$dataDir( - reference.pointer, - _id_get$dataDir.pointer, - ).object(); + return _get$dataDir(reference.pointer, _id_get$dataDir.pointer).object(); } static final _id_getDatabasePath = Context._class.instanceMethodId( @@ -3554,26 +3114,15 @@ extension Context$$Methods on Context { ).object(); } - static final _id_get$deviceId = Context._class.instanceMethodId( - r'getDeviceId', - r'()I', - ); + static final _id_get$deviceId = Context._class.instanceMethodId(r'getDeviceId', r'()I'); static final _get$deviceId = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallIntMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public int getDeviceId()` core$_.int get deviceId { @@ -3608,12 +3157,7 @@ extension Context$$Methods on Context { /// The returned object must be released after use, by calling the [release] method. File? getDir(jni$_.JString? string, core$_.int i) { final _$string = string?.reference ?? jni$_.jNullReference; - return _getDir( - reference.pointer, - _id_getDir.pointer, - _$string.pointer, - i, - ).object(); + return _getDir(reference.pointer, _id_getDir.pointer, _$string.pointer, i).object(); } static final _id_get$display = Context._class.instanceMethodId( @@ -3624,26 +3168,15 @@ extension Context$$Methods on Context { static final _get$display = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public android.view.Display getDisplay()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? get display { - return _get$display( - reference.pointer, - _id_get$display.pointer, - ).object(); + return _get$display(reference.pointer, _id_get$display.pointer).object(); } static final _id_getDrawable = Context._class.instanceMethodId( @@ -3662,21 +3195,13 @@ extension Context$$Methods on Context { > >('globalEnv_CallObjectMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public final android.graphics.drawable.Drawable getDrawable(int i)` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? getDrawable(core$_.int i) { - return _getDrawable( - reference.pointer, - _id_getDrawable.pointer, - i, - ).object(); + return _getDrawable(reference.pointer, _id_getDrawable.pointer, i).object(); } static final _id_get$externalCacheDir = Context._class.instanceMethodId( @@ -3687,18 +3212,10 @@ extension Context$$Methods on Context { static final _get$externalCacheDir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File getExternalCacheDir()` /// The returned object must be released after use, by calling the [release] method. @@ -3717,18 +3234,10 @@ extension Context$$Methods on Context { static final _get$externalCacheDirs = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File[] getExternalCacheDirs()` /// The returned object must be released after use, by calling the [release] method. @@ -3815,18 +3324,10 @@ extension Context$$Methods on Context { static final _get$externalMediaDirs = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File[] getExternalMediaDirs()` /// The returned object must be released after use, by calling the [release] method. @@ -3879,26 +3380,15 @@ extension Context$$Methods on Context { static final _get$filesDir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File getFilesDir()` /// The returned object must be released after use, by calling the [release] method. File? get filesDir { - return _get$filesDir( - reference.pointer, - _id_get$filesDir.pointer, - ).object(); + return _get$filesDir(reference.pointer, _id_get$filesDir.pointer).object(); } static final _id_get$mainExecutor = Context._class.instanceMethodId( @@ -3909,18 +3399,10 @@ extension Context$$Methods on Context { static final _get$mainExecutor = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.util.concurrent.Executor getMainExecutor()` /// The returned object must be released after use, by calling the [release] method. @@ -3939,26 +3421,15 @@ extension Context$$Methods on Context { static final _get$mainLooper = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.os.Looper getMainLooper()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? get mainLooper { - return _get$mainLooper( - reference.pointer, - _id_get$mainLooper.pointer, - ).object(); + return _get$mainLooper(reference.pointer, _id_get$mainLooper.pointer).object(); } static final _id_get$noBackupFilesDir = Context._class.instanceMethodId( @@ -3969,18 +3440,10 @@ extension Context$$Methods on Context { static final _get$noBackupFilesDir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File getNoBackupFilesDir()` /// The returned object must be released after use, by calling the [release] method. @@ -3991,34 +3454,20 @@ extension Context$$Methods on Context { ).object(); } - static final _id_get$obbDir = Context._class.instanceMethodId( - r'getObbDir', - r'()Ljava/io/File;', - ); + static final _id_get$obbDir = Context._class.instanceMethodId(r'getObbDir', r'()Ljava/io/File;'); static final _get$obbDir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File getObbDir()` /// The returned object must be released after use, by calling the [release] method. File? get obbDir { - return _get$obbDir( - reference.pointer, - _id_get$obbDir.pointer, - ).object(); + return _get$obbDir(reference.pointer, _id_get$obbDir.pointer).object(); } static final _id_get$obbDirs = Context._class.instanceMethodId( @@ -4029,26 +3478,15 @@ extension Context$$Methods on Context { static final _get$obbDirs = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.io.File[] getObbDirs()` /// The returned object must be released after use, by calling the [release] method. jni$_.JArray? get obbDirs { - return _get$obbDirs( - reference.pointer, - _id_get$obbDirs.pointer, - ).object?>(); + return _get$obbDirs(reference.pointer, _id_get$obbDirs.pointer).object?>(); } static final _id_get$opPackageName = Context._class.instanceMethodId( @@ -4059,18 +3497,10 @@ extension Context$$Methods on Context { static final _get$opPackageName = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String getOpPackageName()` /// The returned object must be released after use, by calling the [release] method. @@ -4089,18 +3519,10 @@ extension Context$$Methods on Context { static final _get$packageCodePath = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.lang.String getPackageCodePath()` /// The returned object must be released after use, by calling the [release] method. @@ -4119,18 +3541,10 @@ extension Context$$Methods on Context { static final _get$packageManager = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.pm.PackageManager getPackageManager()` /// The returned object must be released after use, by calling the [release] method. @@ -4149,18 +3563,10 @@ extension Context$$Methods on Context { static final _get$packageName = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.lang.String getPackageName()` /// The returned object must be released after use, by calling the [release] method. @@ -4179,18 +3585,10 @@ extension Context$$Methods on Context { static final _get$packageResourcePath = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract java.lang.String getPackageResourcePath()` /// The returned object must be released after use, by calling the [release] method. @@ -4209,26 +3607,15 @@ extension Context$$Methods on Context { static final _get$params = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public android.content.ContextParams getParams()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? get params { - return _get$params( - reference.pointer, - _id_get$params.pointer, - ).object(); + return _get$params(reference.pointer, _id_get$params.pointer).object(); } static final _id_get$resources = Context._class.instanceMethodId( @@ -4239,26 +3626,15 @@ extension Context$$Methods on Context { static final _get$resources = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.res.Resources getResources()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? get resources { - return _get$resources( - reference.pointer, - _id_get$resources.pointer, - ).object(); + return _get$resources(reference.pointer, _id_get$resources.pointer).object(); } static final _id_getSharedPreferences = Context._class.instanceMethodId( @@ -4313,21 +3689,13 @@ extension Context$$Methods on Context { > >('globalEnv_CallObjectMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public final java.lang.String getString(int i)` /// The returned object must be released after use, by calling the [release] method. jni$_.JString? getString(core$_.int i) { - return _getString( - reference.pointer, - _id_getString.pointer, - i, - ).object(); + return _getString(reference.pointer, _id_getString.pointer, i).object(); } static final _id_getString$1 = Context._class.instanceMethodId( @@ -4356,10 +3724,7 @@ extension Context$$Methods on Context { /// from: `public final java.lang.String getString(int i, java.lang.Object[] objects)` /// The returned object must be released after use, by calling the [release] method. - jni$_.JString? getString$1( - core$_.int i, - jni$_.JArray? objects, - ) { + jni$_.JString? getString$1(core$_.int i, jni$_.JArray? objects) { final _$objects = objects?.reference ?? jni$_.jNullReference; return _getString$1( reference.pointer, @@ -4487,21 +3852,13 @@ extension Context$$Methods on Context { > >('globalEnv_CallObjectMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public final java.lang.CharSequence getText(int i)` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? getText(core$_.int i) { - return _getText( - reference.pointer, - _id_getText.pointer, - i, - ).object(); + return _getText(reference.pointer, _id_getText.pointer, i).object(); } static final _id_get$theme = Context._class.instanceMethodId( @@ -4512,26 +3869,15 @@ extension Context$$Methods on Context { static final _get$theme = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.content.res.Resources$Theme getTheme()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? get theme { - return _get$theme( - reference.pointer, - _id_get$theme.pointer, - ).object(); + return _get$theme(reference.pointer, _id_get$theme.pointer).object(); } static final _id_get$wallpaper = Context._class.instanceMethodId( @@ -4542,46 +3888,29 @@ extension Context$$Methods on Context { static final _get$wallpaper = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.graphics.drawable.Drawable getWallpaper()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? get wallpaper { - return _get$wallpaper( - reference.pointer, - _id_get$wallpaper.pointer, - ).object(); + return _get$wallpaper(reference.pointer, _id_get$wallpaper.pointer).object(); } - static final _id_get$wallpaperDesiredMinimumHeight = Context._class - .instanceMethodId(r'getWallpaperDesiredMinimumHeight', r'()I'); + static final _id_get$wallpaperDesiredMinimumHeight = Context._class.instanceMethodId( + r'getWallpaperDesiredMinimumHeight', + r'()I', + ); static final _get$wallpaperDesiredMinimumHeight = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallIntMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract int getWallpaperDesiredMinimumHeight()` core$_.int get wallpaperDesiredMinimumHeight { @@ -4591,24 +3920,18 @@ extension Context$$Methods on Context { ).integer; } - static final _id_get$wallpaperDesiredMinimumWidth = Context._class - .instanceMethodId(r'getWallpaperDesiredMinimumWidth', r'()I'); + static final _id_get$wallpaperDesiredMinimumWidth = Context._class.instanceMethodId( + r'getWallpaperDesiredMinimumWidth', + r'()I', + ); static final _get$wallpaperDesiredMinimumWidth = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallIntMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract int getWallpaperDesiredMinimumWidth()` core$_.int get wallpaperDesiredMinimumWidth { @@ -4629,13 +3952,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Int32, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer, jni$_.Int32)>, ) > >('globalEnv_CallVoidMethod') @@ -4650,11 +3967,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void grantUriPermission(java.lang.String string, android.net.Uri uri, int i)` - void grantUriPermission( - jni$_.JString? string, - jni$_.JObject? uri, - core$_.int i, - ) { + void grantUriPermission(jni$_.JString? string, jni$_.JObject? uri, core$_.int i) { final _$string = string?.reference ?? jni$_.jNullReference; final _$uri = uri?.reference ?? jni$_.jNullReference; _grantUriPermission( @@ -4666,24 +3979,18 @@ extension Context$$Methods on Context { ).check(); } - static final _id_get$isDeviceProtectedStorage = Context._class - .instanceMethodId(r'isDeviceProtectedStorage', r'()Z'); + static final _id_get$isDeviceProtectedStorage = Context._class.instanceMethodId( + r'isDeviceProtectedStorage', + r'()Z', + ); static final _get$isDeviceProtectedStorage = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract boolean isDeviceProtectedStorage()` core$_.bool get isDeviceProtectedStorage { @@ -4693,62 +4000,34 @@ extension Context$$Methods on Context { ).boolean; } - static final _id_get$isRestricted = Context._class.instanceMethodId( - r'isRestricted', - r'()Z', - ); + static final _id_get$isRestricted = Context._class.instanceMethodId(r'isRestricted', r'()Z'); static final _get$isRestricted = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean isRestricted()` core$_.bool get isRestricted { - return _get$isRestricted( - reference.pointer, - _id_get$isRestricted.pointer, - ).boolean; + return _get$isRestricted(reference.pointer, _id_get$isRestricted.pointer).boolean; } - static final _id_get$isUiContext = Context._class.instanceMethodId( - r'isUiContext', - r'()Z', - ); + static final _id_get$isUiContext = Context._class.instanceMethodId(r'isUiContext', r'()Z'); static final _get$isUiContext = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean isUiContext()` core$_.bool get isUiContext { - return _get$isUiContext( - reference.pointer, - _id_get$isUiContext.pointer, - ).boolean; + return _get$isUiContext(reference.pointer, _id_get$isUiContext.pointer).boolean; } static final _id_moveDatabaseFrom = Context._class.instanceMethodId( @@ -4762,9 +4041,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallBooleanMethod') @@ -4800,9 +4077,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallBooleanMethod') @@ -4816,10 +4091,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract boolean moveSharedPreferencesFrom(android.content.Context context, java.lang.String string)` - core$_.bool moveSharedPreferencesFrom( - Context? context, - jni$_.JString? string, - ) { + core$_.bool moveSharedPreferencesFrom(Context? context, jni$_.JString? string) { final _$context = context?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; return _moveSharedPreferencesFrom( @@ -4841,9 +4113,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallObjectMethod') @@ -4858,10 +4128,7 @@ extension Context$$Methods on Context { /// from: `public final android.content.res.TypedArray obtainStyledAttributes(android.util.AttributeSet attributeSet, int[] is)` /// The returned object must be released after use, by calling the [release] method. - jni$_.JObject? obtainStyledAttributes( - jni$_.JObject? attributeSet, - jni$_.JIntArray? is$, - ) { + jni$_.JObject? obtainStyledAttributes(jni$_.JObject? attributeSet, jni$_.JIntArray? is$) { final _$attributeSet = attributeSet?.reference ?? jni$_.jNullReference; final _$is$ = is$?.reference ?? jni$_.jNullReference; return _obtainStyledAttributes( @@ -4884,12 +4151,7 @@ extension Context$$Methods on Context { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Int32, - jni$_.Int32, - ) + (jni$_.Pointer, jni$_.Pointer, jni$_.Int32, jni$_.Int32) >, ) > @@ -5076,13 +4338,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Int32, - jni$_.Pointer, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Pointer)>, ) > >('globalEnv_CallObjectMethod') @@ -5157,8 +4413,7 @@ extension Context$$Methods on Context { ) { final _$string = string?.reference ?? jni$_.jNullReference; final _$cursorFactory = cursorFactory?.reference ?? jni$_.jNullReference; - final _$databaseErrorHandler = - databaseErrorHandler?.reference ?? jni$_.jNullReference; + final _$databaseErrorHandler = databaseErrorHandler?.reference ?? jni$_.jNullReference; return _openOrCreateDatabase$1( reference.pointer, _id_openOrCreateDatabase$1.pointer, @@ -5177,26 +4432,15 @@ extension Context$$Methods on Context { static final _peekWallpaper = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public abstract android.graphics.drawable.Drawable peekWallpaper()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? peekWallpaper() { - return _peekWallpaper( - reference.pointer, - _id_peekWallpaper.pointer, - ).object(); + return _peekWallpaper(reference.pointer, _id_peekWallpaper.pointer).object(); } static final _id_registerComponentCallbacks = Context._class.instanceMethodId( @@ -5224,8 +4468,7 @@ extension Context$$Methods on Context { /// from: `public void registerComponentCallbacks(android.content.ComponentCallbacks componentCallbacks)` void registerComponentCallbacks(jni$_.JObject? componentCallbacks) { - final _$componentCallbacks = - componentCallbacks?.reference ?? jni$_.jNullReference; + final _$componentCallbacks = componentCallbacks?.reference ?? jni$_.jNullReference; _registerComponentCallbacks( reference.pointer, _id_registerComponentCallbacks.pointer, @@ -5233,11 +4476,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_registerDeviceIdChangeListener = Context._class - .instanceMethodId( - r'registerDeviceIdChangeListener', - r'(Ljava/util/concurrent/Executor;Ljava/util/function/IntConsumer;)V', - ); + static final _id_registerDeviceIdChangeListener = Context._class.instanceMethodId( + r'registerDeviceIdChangeListener', + r'(Ljava/util/concurrent/Executor;Ljava/util/function/IntConsumer;)V', + ); static final _registerDeviceIdChangeListener = jni$_.ProtectedJniExtensions.lookup< @@ -5245,9 +4487,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -5261,10 +4501,7 @@ extension Context$$Methods on Context { >(); /// from: `public void registerDeviceIdChangeListener(java.util.concurrent.Executor executor, java.util.function.IntConsumer intConsumer)` - void registerDeviceIdChangeListener( - jni$_.JObject? executor, - jni$_.JObject? intConsumer, - ) { + void registerDeviceIdChangeListener(jni$_.JObject? executor, jni$_.JObject? intConsumer) { final _$executor = executor?.reference ?? jni$_.jNullReference; final _$intConsumer = intConsumer?.reference ?? jni$_.jNullReference; _registerDeviceIdChangeListener( @@ -5286,9 +4523,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallObjectMethod') @@ -5303,12 +4538,8 @@ extension Context$$Methods on Context { /// from: `public abstract android.content.Intent registerReceiver(android.content.BroadcastReceiver broadcastReceiver, android.content.IntentFilter intentFilter)` /// The returned object must be released after use, by calling the [release] method. - jni$_.JObject? registerReceiver( - jni$_.JObject? broadcastReceiver, - jni$_.JObject? intentFilter, - ) { - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + jni$_.JObject? registerReceiver(jni$_.JObject? broadcastReceiver, jni$_.JObject? intentFilter) { + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$intentFilter = intentFilter?.reference ?? jni$_.jNullReference; return _registerReceiver( reference.pointer, @@ -5329,13 +4560,7 @@ extension Context$$Methods on Context { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Int32, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer, jni$_.Int32)>, ) > >('globalEnv_CallObjectMethod') @@ -5356,8 +4581,7 @@ extension Context$$Methods on Context { jni$_.JObject? intentFilter, core$_.int i, ) { - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$intentFilter = intentFilter?.reference ?? jni$_.jNullReference; return _registerReceiver$1( reference.pointer, @@ -5409,8 +4633,7 @@ extension Context$$Methods on Context { jni$_.JString? string, jni$_.JObject? handler, ) { - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$intentFilter = intentFilter?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; @@ -5468,8 +4691,7 @@ extension Context$$Methods on Context { jni$_.JObject? handler, core$_.int i, ) { - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$intentFilter = intentFilter?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; @@ -5517,11 +4739,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_removeStickyBroadcastAsUser = Context._class - .instanceMethodId( - r'removeStickyBroadcastAsUser', - r'(Landroid/content/Intent;Landroid/os/UserHandle;)V', - ); + static final _id_removeStickyBroadcastAsUser = Context._class.instanceMethodId( + r'removeStickyBroadcastAsUser', + r'(Landroid/content/Intent;Landroid/os/UserHandle;)V', + ); static final _removeStickyBroadcastAsUser = jni$_.ProtectedJniExtensions.lookup< @@ -5529,9 +4750,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -5545,10 +4764,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void removeStickyBroadcastAsUser(android.content.Intent intent, android.os.UserHandle userHandle)` - void removeStickyBroadcastAsUser( - jni$_.JObject? intent, - jni$_.JObject? userHandle, - ) { + void removeStickyBroadcastAsUser(jni$_.JObject? intent, jni$_.JObject? userHandle) { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$userHandle = userHandle?.reference ?? jni$_.jNullReference; _removeStickyBroadcastAsUser( @@ -5592,11 +4808,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_revokeSelfPermissionsOnKill = Context._class - .instanceMethodId( - r'revokeSelfPermissionsOnKill', - r'(Ljava/util/Collection;)V', - ); + static final _id_revokeSelfPermissionsOnKill = Context._class.instanceMethodId( + r'revokeSelfPermissionsOnKill', + r'(Ljava/util/Collection;)V', + ); static final _revokeSelfPermissionsOnKill = jni$_.ProtectedJniExtensions.lookup< @@ -5672,13 +4887,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Int32, - ) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer, jni$_.Int32)>, ) > >('globalEnv_CallVoidMethod') @@ -5693,11 +4902,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void revokeUriPermission(java.lang.String string, android.net.Uri uri, int i)` - void revokeUriPermission$1( - jni$_.JString? string, - jni$_.JObject? uri, - core$_.int i, - ) { + void revokeUriPermission$1(jni$_.JString? string, jni$_.JObject? uri, core$_.int i) { final _$string = string?.reference ?? jni$_.jNullReference; final _$uri = uri?.reference ?? jni$_.jNullReference; _revokeUriPermission$1( @@ -5735,11 +4940,7 @@ extension Context$$Methods on Context { /// from: `public abstract void sendBroadcast(android.content.Intent intent)` void sendBroadcast(jni$_.JObject? intent) { final _$intent = intent?.reference ?? jni$_.jNullReference; - _sendBroadcast( - reference.pointer, - _id_sendBroadcast.pointer, - _$intent.pointer, - ).check(); + _sendBroadcast(reference.pointer, _id_sendBroadcast.pointer, _$intent.pointer).check(); } static final _id_sendBroadcast$1 = Context._class.instanceMethodId( @@ -5753,9 +4954,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -5792,11 +4991,7 @@ extension Context$$Methods on Context { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Pointer, - ) + (jni$_.Pointer, jni$_.Pointer, jni$_.Pointer) >, ) > @@ -5812,11 +5007,7 @@ extension Context$$Methods on Context { >(); /// from: `public void sendBroadcast(android.content.Intent intent, java.lang.String string, android.os.Bundle bundle)` - void sendBroadcast$2( - jni$_.JObject? intent, - jni$_.JString? string, - jni$_.JObject? bundle, - ) { + void sendBroadcast$2(jni$_.JObject? intent, jni$_.JString? string, jni$_.JObject? bundle) { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; @@ -5840,9 +5031,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -5879,11 +5068,7 @@ extension Context$$Methods on Context { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Pointer, - ) + (jni$_.Pointer, jni$_.Pointer, jni$_.Pointer) >, ) > @@ -5916,11 +5101,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_sendBroadcastWithMultiplePermissions = Context._class - .instanceMethodId( - r'sendBroadcastWithMultiplePermissions', - r'(Landroid/content/Intent;[Ljava/lang/String;)V', - ); + static final _id_sendBroadcastWithMultiplePermissions = Context._class.instanceMethodId( + r'sendBroadcastWithMultiplePermissions', + r'(Landroid/content/Intent;[Ljava/lang/String;)V', + ); static final _sendBroadcastWithMultiplePermissions = jni$_.ProtectedJniExtensions.lookup< @@ -5928,9 +5112,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -5969,9 +5151,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -6047,8 +5227,7 @@ extension Context$$Methods on Context { ) { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; final _$string1 = string1?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; @@ -6077,11 +5256,7 @@ extension Context$$Methods on Context { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Pointer, - ) + (jni$_.Pointer, jni$_.Pointer, jni$_.Pointer) >, ) > @@ -6097,11 +5272,7 @@ extension Context$$Methods on Context { >(); /// from: `public void sendOrderedBroadcast(android.content.Intent intent, java.lang.String string, android.os.Bundle bundle)` - void sendOrderedBroadcast$2( - jni$_.JObject? intent, - jni$_.JString? string, - jni$_.JObject? bundle, - ) { + void sendOrderedBroadcast$2(jni$_.JObject? intent, jni$_.JString? string, jni$_.JObject? bundle) { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; @@ -6169,8 +5340,7 @@ extension Context$$Methods on Context { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; final _$string1 = string1?.reference ?? jni$_.jNullReference; final _$bundle1 = bundle1?.reference ?? jni$_.jNullReference; @@ -6243,8 +5413,7 @@ extension Context$$Methods on Context { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$string1 = string1?.reference ?? jni$_.jNullReference; - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; final _$string2 = string2?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; @@ -6317,8 +5486,7 @@ extension Context$$Methods on Context { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$userHandle = userHandle?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; final _$string1 = string1?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; @@ -6380,9 +5548,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -6418,9 +5584,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -6434,10 +5598,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void sendStickyBroadcastAsUser(android.content.Intent intent, android.os.UserHandle userHandle)` - void sendStickyBroadcastAsUser( - jni$_.JObject? intent, - jni$_.JObject? userHandle, - ) { + void sendStickyBroadcastAsUser(jni$_.JObject? intent, jni$_.JObject? userHandle) { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$userHandle = userHandle?.reference ?? jni$_.jNullReference; _sendStickyBroadcastAsUser( @@ -6495,8 +5656,7 @@ extension Context$$Methods on Context { jni$_.JObject? bundle, ) { final _$intent = intent?.reference ?? jni$_.jNullReference; - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; @@ -6512,11 +5672,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_sendStickyOrderedBroadcastAsUser = Context._class - .instanceMethodId( - r'sendStickyOrderedBroadcastAsUser', - r'(Landroid/content/Intent;Landroid/os/UserHandle;Landroid/content/BroadcastReceiver;Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V', - ); + static final _id_sendStickyOrderedBroadcastAsUser = Context._class.instanceMethodId( + r'sendStickyOrderedBroadcastAsUser', + r'(Landroid/content/Intent;Landroid/os/UserHandle;Landroid/content/BroadcastReceiver;Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V', + ); static final _sendStickyOrderedBroadcastAsUser = jni$_.ProtectedJniExtensions.lookup< @@ -6564,8 +5723,7 @@ extension Context$$Methods on Context { ) { final _$intent = intent?.reference ?? jni$_.jNullReference; final _$userHandle = userHandle?.reference ?? jni$_.jNullReference; - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; final _$handler = handler?.reference ?? jni$_.jNullReference; final _$string = string?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; @@ -6582,10 +5740,7 @@ extension Context$$Methods on Context { ).check(); } - static final _id_set$theme$1 = Context._class.instanceMethodId( - r'setTheme', - r'(I)V', - ); + static final _id_set$theme$1 = Context._class.instanceMethodId(r'setTheme', r'(I)V'); static final _set$theme$1 = jni$_.ProtectedJniExtensions.lookup< @@ -6598,11 +5753,7 @@ extension Context$$Methods on Context { > >('globalEnv_CallVoidMethod') .asFunction< - jni$_.JThrowablePtr Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JThrowablePtr Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public abstract void setTheme(int i)` @@ -6636,11 +5787,7 @@ extension Context$$Methods on Context { /// from: `public abstract void setWallpaper(android.graphics.Bitmap bitmap)` set wallpaper$1(jni$_.JObject? bitmap) { final _$bitmap = bitmap?.reference ?? jni$_.jNullReference; - _set$wallpaper$1( - reference.pointer, - _id_set$wallpaper$1.pointer, - _$bitmap.pointer, - ).check(); + _set$wallpaper$1(reference.pointer, _id_set$wallpaper$1.pointer, _$bitmap.pointer).check(); } static final _id_set$wallpaper$2 = Context._class.instanceMethodId( @@ -6669,11 +5816,7 @@ extension Context$$Methods on Context { /// from: `public abstract void setWallpaper(java.io.InputStream inputStream)` set wallpaper$2(jni$_.JObject? inputStream) { final _$inputStream = inputStream?.reference ?? jni$_.jNullReference; - _set$wallpaper$2( - reference.pointer, - _id_set$wallpaper$2.pointer, - _$inputStream.pointer, - ).check(); + _set$wallpaper$2(reference.pointer, _id_set$wallpaper$2.pointer, _$inputStream.pointer).check(); } static final _id_startActivities = Context._class.instanceMethodId( @@ -6702,11 +5845,7 @@ extension Context$$Methods on Context { /// from: `public abstract void startActivities(android.content.Intent[] intents)` void startActivities(jni$_.JArray? intents) { final _$intents = intents?.reference ?? jni$_.jNullReference; - _startActivities( - reference.pointer, - _id_startActivities.pointer, - _$intents.pointer, - ).check(); + _startActivities(reference.pointer, _id_startActivities.pointer, _$intents.pointer).check(); } static final _id_startActivities$1 = Context._class.instanceMethodId( @@ -6720,9 +5859,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -6736,10 +5873,7 @@ extension Context$$Methods on Context { >(); /// from: `public abstract void startActivities(android.content.Intent[] intents, android.os.Bundle bundle)` - void startActivities$1( - jni$_.JArray? intents, - jni$_.JObject? bundle, - ) { + void startActivities$1(jni$_.JArray? intents, jni$_.JObject? bundle) { final _$intents = intents?.reference ?? jni$_.jNullReference; final _$bundle = bundle?.reference ?? jni$_.jNullReference; _startActivities$1( @@ -6776,11 +5910,7 @@ extension Context$$Methods on Context { /// from: `public abstract void startActivity(android.content.Intent intent)` void startActivity(jni$_.JObject? intent) { final _$intent = intent?.reference ?? jni$_.jNullReference; - _startActivity( - reference.pointer, - _id_startActivity.pointer, - _$intent.pointer, - ).check(); + _startActivity(reference.pointer, _id_startActivity.pointer, _$intent.pointer).check(); } static final _id_startActivity$1 = Context._class.instanceMethodId( @@ -6794,9 +5924,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallVoidMethod') @@ -6867,11 +5995,7 @@ extension Context$$Methods on Context { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Pointer, - ) + (jni$_.Pointer, jni$_.Pointer, jni$_.Pointer) >, ) > @@ -7081,11 +6205,7 @@ extension Context$$Methods on Context { /// from: `public abstract boolean stopService(android.content.Intent intent)` core$_.bool stopService(jni$_.JObject? intent) { final _$intent = intent?.reference ?? jni$_.jNullReference; - return _stopService( - reference.pointer, - _id_stopService.pointer, - _$intent.pointer, - ).boolean; + return _stopService(reference.pointer, _id_stopService.pointer, _$intent.pointer).boolean; } static final _id_unbindService = Context._class.instanceMethodId( @@ -7113,8 +6233,7 @@ extension Context$$Methods on Context { /// from: `public abstract void unbindService(android.content.ServiceConnection serviceConnection)` void unbindService(jni$_.JObject? serviceConnection) { - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; _unbindService( reference.pointer, _id_unbindService.pointer, @@ -7122,11 +6241,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_unregisterComponentCallbacks = Context._class - .instanceMethodId( - r'unregisterComponentCallbacks', - r'(Landroid/content/ComponentCallbacks;)V', - ); + static final _id_unregisterComponentCallbacks = Context._class.instanceMethodId( + r'unregisterComponentCallbacks', + r'(Landroid/content/ComponentCallbacks;)V', + ); static final _unregisterComponentCallbacks = jni$_.ProtectedJniExtensions.lookup< @@ -7148,8 +6266,7 @@ extension Context$$Methods on Context { /// from: `public void unregisterComponentCallbacks(android.content.ComponentCallbacks componentCallbacks)` void unregisterComponentCallbacks(jni$_.JObject? componentCallbacks) { - final _$componentCallbacks = - componentCallbacks?.reference ?? jni$_.jNullReference; + final _$componentCallbacks = componentCallbacks?.reference ?? jni$_.jNullReference; _unregisterComponentCallbacks( reference.pointer, _id_unregisterComponentCallbacks.pointer, @@ -7157,11 +6274,10 @@ extension Context$$Methods on Context { ).check(); } - static final _id_unregisterDeviceIdChangeListener = Context._class - .instanceMethodId( - r'unregisterDeviceIdChangeListener', - r'(Ljava/util/function/IntConsumer;)V', - ); + static final _id_unregisterDeviceIdChangeListener = Context._class.instanceMethodId( + r'unregisterDeviceIdChangeListener', + r'(Ljava/util/function/IntConsumer;)V', + ); static final _unregisterDeviceIdChangeListener = jni$_.ProtectedJniExtensions.lookup< @@ -7216,8 +6332,7 @@ extension Context$$Methods on Context { /// from: `public abstract void unregisterReceiver(android.content.BroadcastReceiver broadcastReceiver)` void unregisterReceiver(jni$_.JObject? broadcastReceiver) { - final _$broadcastReceiver = - broadcastReceiver?.reference ?? jni$_.jNullReference; + final _$broadcastReceiver = broadcastReceiver?.reference ?? jni$_.jNullReference; _unregisterReceiver( reference.pointer, _id_unregisterReceiver.pointer, @@ -7236,9 +6351,7 @@ extension Context$$Methods on Context { jni$_.JThrowablePtr Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Int32, jni$_.Int32) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Int32, jni$_.Int32)>, ) > >('globalEnv_CallVoidMethod') @@ -7253,13 +6366,8 @@ extension Context$$Methods on Context { >(); /// from: `public void updateServiceGroup(android.content.ServiceConnection serviceConnection, int i, int i1)` - void updateServiceGroup( - jni$_.JObject? serviceConnection, - core$_.int i, - core$_.int i1, - ) { - final _$serviceConnection = - serviceConnection?.reference ?? jni$_.jNullReference; + void updateServiceGroup(jni$_.JObject? serviceConnection, core$_.int i, core$_.int i1) { + final _$serviceConnection = serviceConnection?.reference ?? jni$_.jNullReference; _updateServiceGroup( reference.pointer, _id_updateServiceGroup.pointer, @@ -7285,30 +6393,20 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { /// The type which includes information such as the signature of this class. static const jni$_.JType type = $File$Type$(); - static final _id_pathSeparator = _class.staticFieldId( - r'pathSeparator', - r'Ljava/lang/String;', - ); + static final _id_pathSeparator = _class.staticFieldId(r'pathSeparator', r'Ljava/lang/String;'); /// from: `static public final java.lang.String pathSeparator` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get pathSeparator => - _id_pathSeparator.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_pathSeparator.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_pathSeparatorChar = _class.staticFieldId( - r'pathSeparatorChar', - r'C', - ); + static final _id_pathSeparatorChar = _class.staticFieldId(r'pathSeparatorChar', r'C'); /// from: `static public final char pathSeparatorChar` static core$_.int get pathSeparatorChar => _id_pathSeparatorChar.getNullable(_class, jni$_.jchar.type) as core$_.int; - static final _id_separator = _class.staticFieldId( - r'separator', - r'Ljava/lang/String;', - ); + static final _id_separator = _class.staticFieldId(r'separator', r'Ljava/lang/String;'); /// from: `static public final java.lang.String separator` /// The returned object must be released after use, by calling the [release] method. @@ -7321,9 +6419,7 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { static core$_.int get separatorChar => _id_separatorChar.getNullable(_class, jni$_.jchar.type) as core$_.int; - static final _id_new$ = _class.constructorId( - r'(Ljava/io/File;Ljava/lang/String;)V', - ); + static final _id_new$ = _class.constructorId(r'(Ljava/io/File;Ljava/lang/String;)V'); static final _new$ = jni$_.ProtectedJniExtensions.lookup< @@ -7331,9 +6427,7 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_NewObject') @@ -7383,16 +6477,10 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { /// The returned object must be released after use, by calling the [release] method. factory File.new$1(jni$_.JString? string) { final _$string = string?.reference ?? jni$_.jNullReference; - return _new$1( - _class.reference.pointer, - _id_new$1.pointer, - _$string.pointer, - ).object(); + return _new$1(_class.reference.pointer, _id_new$1.pointer, _$string.pointer).object(); } - static final _id_new$2 = _class.constructorId( - r'(Ljava/lang/String;Ljava/lang/String;)V', - ); + static final _id_new$2 = _class.constructorId(r'(Ljava/lang/String;Ljava/lang/String;)V'); static final _new$2 = jni$_.ProtectedJniExtensions.lookup< @@ -7400,9 +6488,7 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_NewObject') @@ -7452,11 +6538,7 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { /// The returned object must be released after use, by calling the [release] method. factory File.new$3(jni$_.JObject? uRI) { final _$uRI = uRI?.reference ?? jni$_.jNullReference; - return _new$3( - _class.reference.pointer, - _id_new$3.pointer, - _$uRI.pointer, - ).object(); + return _new$3(_class.reference.pointer, _id_new$3.pointer, _$uRI.pointer).object(); } static final _id_createTempFile = _class.staticMethodId( @@ -7470,9 +6552,7 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { jni$_.JniResult Function( jni$_.Pointer, jni$_.JMethodIDPtr, - jni$_.VarArgs< - (jni$_.Pointer, jni$_.Pointer) - >, + jni$_.VarArgs<(jni$_.Pointer, jni$_.Pointer)>, ) > >('globalEnv_CallStaticObjectMethod') @@ -7510,11 +6590,7 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { jni$_.Pointer, jni$_.JMethodIDPtr, jni$_.VarArgs< - ( - jni$_.Pointer, - jni$_.Pointer, - jni$_.Pointer, - ) + (jni$_.Pointer, jni$_.Pointer, jni$_.Pointer) >, ) > @@ -7531,11 +6607,7 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.io.File createTempFile(java.lang.String string, java.lang.String string1, java.io.File file)` /// The returned object must be released after use, by calling the [release] method. - static File? createTempFile$1( - jni$_.JString? string, - jni$_.JString? string1, - File? file, - ) { + static File? createTempFile$1(jni$_.JString? string, jni$_.JString? string1, File? file) { final _$string = string?.reference ?? jni$_.jNullReference; final _$string1 = string1?.reference ?? jni$_.jNullReference; final _$file = file?.reference ?? jni$_.jNullReference; @@ -7548,26 +6620,15 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { ).object(); } - static final _id_listRoots = _class.staticMethodId( - r'listRoots', - r'()[Ljava/io/File;', - ); + static final _id_listRoots = _class.staticMethodId(r'listRoots', r'()[Ljava/io/File;'); static final _listRoots = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public java.io.File[] listRoots()` /// The returned object must be released after use, by calling the [release] method. @@ -7580,26 +6641,15 @@ extension type File._(jni$_.JObject _$this) implements jni$_.JObject { } extension File$$Methods on File { - static final _id_canExecute = File._class.instanceMethodId( - r'canExecute', - r'()Z', - ); + static final _id_canExecute = File._class.instanceMethodId(r'canExecute', r'()Z'); static final _canExecute = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean canExecute()` core$_.bool canExecute() { @@ -7611,18 +6661,10 @@ extension File$$Methods on File { static final _canRead = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean canRead()` core$_.bool canRead() { @@ -7634,28 +6676,17 @@ extension File$$Methods on File { static final _canWrite = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean canWrite()` core$_.bool canWrite() { return _canWrite(reference.pointer, _id_canWrite.pointer).boolean; } - static final _id_compareTo = File._class.instanceMethodId( - r'compareTo', - r'(Ljava/io/File;)I', - ); + static final _id_compareTo = File._class.instanceMethodId(r'compareTo', r'(Ljava/io/File;)I'); static final _compareTo = jni$_.ProtectedJniExtensions.lookup< @@ -7678,33 +6709,18 @@ extension File$$Methods on File { /// from: `public int compareTo(java.io.File file)` core$_.int compareTo(File? file) { final _$file = file?.reference ?? jni$_.jNullReference; - return _compareTo( - reference.pointer, - _id_compareTo.pointer, - _$file.pointer, - ).integer; + return _compareTo(reference.pointer, _id_compareTo.pointer, _$file.pointer).integer; } - static final _id_createNewFile = File._class.instanceMethodId( - r'createNewFile', - r'()Z', - ); + static final _id_createNewFile = File._class.instanceMethodId(r'createNewFile', r'()Z'); static final _createNewFile = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean createNewFile()` core$_.bool createNewFile() { @@ -7716,43 +6732,26 @@ extension File$$Methods on File { static final _delete = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean delete()` core$_.bool delete() { return _delete(reference.pointer, _id_delete.pointer).boolean; } - static final _id_deleteOnExit = File._class.instanceMethodId( - r'deleteOnExit', - r'()V', - ); + static final _id_deleteOnExit = File._class.instanceMethodId(r'deleteOnExit', r'()V'); static final _deleteOnExit = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JThrowablePtr Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JThrowablePtr Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallVoidMethod') .asFunction< - jni$_.JThrowablePtr Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JThrowablePtr Function(jni$_.Pointer, jni$_.JMethodIDPtr) >(); /// from: `public void deleteOnExit()` @@ -7760,10 +6759,7 @@ extension File$$Methods on File { _deleteOnExit(reference.pointer, _id_deleteOnExit.pointer).check(); } - static final _id_equals = File._class.instanceMethodId( - r'equals', - r'(Ljava/lang/Object;)Z', - ); + static final _id_equals = File._class.instanceMethodId(r'equals', r'(Ljava/lang/Object;)Z'); static final _equals = jni$_.ProtectedJniExtensions.lookup< @@ -7786,11 +6782,7 @@ extension File$$Methods on File { /// from: `public boolean equals(java.lang.Object object)` core$_.bool equals(jni$_.JObject? object) { final _$object = object?.reference ?? jni$_.jNullReference; - return _equals( - reference.pointer, - _id_equals.pointer, - _$object.pointer, - ).boolean; + return _equals(reference.pointer, _id_equals.pointer, _$object.pointer).boolean; } static final _id_exists = File._class.instanceMethodId(r'exists', r'()Z'); @@ -7798,18 +6790,10 @@ extension File$$Methods on File { static final _exists = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean exists()` core$_.bool exists() { @@ -7824,26 +6808,15 @@ extension File$$Methods on File { static final _get$absoluteFile = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.io.File getAbsoluteFile()` /// The returned object must be released after use, by calling the [release] method. File? get absoluteFile { - return _get$absoluteFile( - reference.pointer, - _id_get$absoluteFile.pointer, - ).object(); + return _get$absoluteFile(reference.pointer, _id_get$absoluteFile.pointer).object(); } static final _id_get$absolutePath = File._class.instanceMethodId( @@ -7854,18 +6827,10 @@ extension File$$Methods on File { static final _get$absolutePath = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String getAbsolutePath()` /// The returned object must be released after use, by calling the [release] method. @@ -7884,26 +6849,15 @@ extension File$$Methods on File { static final _get$canonicalFile = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.io.File getCanonicalFile()` /// The returned object must be released after use, by calling the [release] method. File? get canonicalFile { - return _get$canonicalFile( - reference.pointer, - _id_get$canonicalFile.pointer, - ).object(); + return _get$canonicalFile(reference.pointer, _id_get$canonicalFile.pointer).object(); } static final _id_get$canonicalPath = File._class.instanceMethodId( @@ -7914,18 +6868,10 @@ extension File$$Methods on File { static final _get$canonicalPath = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String getCanonicalPath()` /// The returned object must be released after use, by calling the [release] method. @@ -7936,90 +6882,51 @@ extension File$$Methods on File { ).object(); } - static final _id_get$freeSpace = File._class.instanceMethodId( - r'getFreeSpace', - r'()J', - ); + static final _id_get$freeSpace = File._class.instanceMethodId(r'getFreeSpace', r'()J'); static final _get$freeSpace = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallLongMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public long getFreeSpace()` core$_.int get freeSpace { return _get$freeSpace(reference.pointer, _id_get$freeSpace.pointer).long; } - static final _id_get$name = File._class.instanceMethodId( - r'getName', - r'()Ljava/lang/String;', - ); + static final _id_get$name = File._class.instanceMethodId(r'getName', r'()Ljava/lang/String;'); static final _get$name = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String getName()` /// The returned object must be released after use, by calling the [release] method. jni$_.JString? get name { - return _get$name( - reference.pointer, - _id_get$name.pointer, - ).object(); + return _get$name(reference.pointer, _id_get$name.pointer).object(); } - static final _id_get$parent = File._class.instanceMethodId( - r'getParent', - r'()Ljava/lang/String;', - ); + static final _id_get$parent = File._class.instanceMethodId(r'getParent', r'()Ljava/lang/String;'); static final _get$parent = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String getParent()` /// The returned object must be released after use, by calling the [release] method. jni$_.JString? get parent { - return _get$parent( - reference.pointer, - _id_get$parent.pointer, - ).object(); + return _get$parent(reference.pointer, _id_get$parent.pointer).object(); } static final _id_get$parentFile = File._class.instanceMethodId( @@ -8030,195 +6937,106 @@ extension File$$Methods on File { static final _get$parentFile = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.io.File getParentFile()` /// The returned object must be released after use, by calling the [release] method. File? get parentFile { - return _get$parentFile( - reference.pointer, - _id_get$parentFile.pointer, - ).object(); + return _get$parentFile(reference.pointer, _id_get$parentFile.pointer).object(); } - static final _id_get$path = File._class.instanceMethodId( - r'getPath', - r'()Ljava/lang/String;', - ); + static final _id_get$path = File._class.instanceMethodId(r'getPath', r'()Ljava/lang/String;'); static final _get$path = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String getPath()` /// The returned object must be released after use, by calling the [release] method. jni$_.JString? get path { - return _get$path( - reference.pointer, - _id_get$path.pointer, - ).object(); + return _get$path(reference.pointer, _id_get$path.pointer).object(); } - static final _id_get$totalSpace = File._class.instanceMethodId( - r'getTotalSpace', - r'()J', - ); + static final _id_get$totalSpace = File._class.instanceMethodId(r'getTotalSpace', r'()J'); static final _get$totalSpace = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallLongMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public long getTotalSpace()` core$_.int get totalSpace { return _get$totalSpace(reference.pointer, _id_get$totalSpace.pointer).long; } - static final _id_get$usableSpace = File._class.instanceMethodId( - r'getUsableSpace', - r'()J', - ); + static final _id_get$usableSpace = File._class.instanceMethodId(r'getUsableSpace', r'()J'); static final _get$usableSpace = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallLongMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public long getUsableSpace()` core$_.int get usableSpace { - return _get$usableSpace( - reference.pointer, - _id_get$usableSpace.pointer, - ).long; + return _get$usableSpace(reference.pointer, _id_get$usableSpace.pointer).long; } - static final _id_hashCode$1 = File._class.instanceMethodId( - r'hashCode', - r'()I', - ); + static final _id_hashCode$1 = File._class.instanceMethodId(r'hashCode', r'()I'); static final _hashCode$1 = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallIntMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public int hashCode()` core$_.int hashCode$1() { return _hashCode$1(reference.pointer, _id_hashCode$1.pointer).integer; } - static final _id_get$isAbsolute = File._class.instanceMethodId( - r'isAbsolute', - r'()Z', - ); + static final _id_get$isAbsolute = File._class.instanceMethodId(r'isAbsolute', r'()Z'); static final _get$isAbsolute = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean isAbsolute()` core$_.bool get isAbsolute { - return _get$isAbsolute( - reference.pointer, - _id_get$isAbsolute.pointer, - ).boolean; + return _get$isAbsolute(reference.pointer, _id_get$isAbsolute.pointer).boolean; } - static final _id_get$isDirectory = File._class.instanceMethodId( - r'isDirectory', - r'()Z', - ); + static final _id_get$isDirectory = File._class.instanceMethodId(r'isDirectory', r'()Z'); static final _get$isDirectory = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean isDirectory()` core$_.bool get isDirectory { - return _get$isDirectory( - reference.pointer, - _id_get$isDirectory.pointer, - ).boolean; + return _get$isDirectory(reference.pointer, _id_get$isDirectory.pointer).boolean; } static final _id_get$isFile = File._class.instanceMethodId(r'isFile', r'()Z'); @@ -8226,70 +7044,40 @@ extension File$$Methods on File { static final _get$isFile = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean isFile()` core$_.bool get isFile { return _get$isFile(reference.pointer, _id_get$isFile.pointer).boolean; } - static final _id_get$isHidden = File._class.instanceMethodId( - r'isHidden', - r'()Z', - ); + static final _id_get$isHidden = File._class.instanceMethodId(r'isHidden', r'()Z'); static final _get$isHidden = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean isHidden()` core$_.bool get isHidden { return _get$isHidden(reference.pointer, _id_get$isHidden.pointer).boolean; } - static final _id_lastModified = File._class.instanceMethodId( - r'lastModified', - r'()J', - ); + static final _id_lastModified = File._class.instanceMethodId(r'lastModified', r'()J'); static final _lastModified = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallLongMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public long lastModified()` core$_.int lastModified() { @@ -8301,52 +7089,30 @@ extension File$$Methods on File { static final _length = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallLongMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public long length()` core$_.int length() { return _length(reference.pointer, _id_length.pointer).long; } - static final _id_list = File._class.instanceMethodId( - r'list', - r'()[Ljava/lang/String;', - ); + static final _id_list = File._class.instanceMethodId(r'list', r'()[Ljava/lang/String;'); static final _list = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String[] list()` /// The returned object must be released after use, by calling the [release] method. jni$_.JArray? list() { - return _list( - reference.pointer, - _id_list.pointer, - ).object?>(); + return _list(reference.pointer, _id_list.pointer).object?>(); } static final _id_list$1 = File._class.instanceMethodId( @@ -8383,34 +7149,20 @@ extension File$$Methods on File { ).object?>(); } - static final _id_listFiles = File._class.instanceMethodId( - r'listFiles', - r'()[Ljava/io/File;', - ); + static final _id_listFiles = File._class.instanceMethodId(r'listFiles', r'()[Ljava/io/File;'); static final _listFiles = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.io.File[] listFiles()` /// The returned object must be released after use, by calling the [release] method. jni$_.JArray? listFiles() { - return _listFiles( - reference.pointer, - _id_listFiles.pointer, - ).object?>(); + return _listFiles(reference.pointer, _id_listFiles.pointer).object?>(); } static final _id_listFiles$1 = File._class.instanceMethodId( @@ -8486,18 +7238,10 @@ extension File$$Methods on File { static final _mkdir = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean mkdir()` core$_.bool mkdir() { @@ -8509,28 +7253,17 @@ extension File$$Methods on File { static final _mkdirs = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean mkdirs()` core$_.bool mkdirs() { return _mkdirs(reference.pointer, _id_mkdirs.pointer).boolean; } - static final _id_renameTo = File._class.instanceMethodId( - r'renameTo', - r'(Ljava/io/File;)Z', - ); + static final _id_renameTo = File._class.instanceMethodId(r'renameTo', r'(Ljava/io/File;)Z'); static final _renameTo = jni$_.ProtectedJniExtensions.lookup< @@ -8552,18 +7285,11 @@ extension File$$Methods on File { /// from: `public boolean renameTo(java.io.File file)` core$_.bool renameTo(File? file) { - final _$file = file?.reference ?? jni$_.jNullReference; - return _renameTo( - reference.pointer, - _id_renameTo.pointer, - _$file.pointer, - ).boolean; + final _$file = file?.reference ?? jni$_.jNullReference; + return _renameTo(reference.pointer, _id_renameTo.pointer, _$file.pointer).boolean; } - static final _id_setExecutable = File._class.instanceMethodId( - r'setExecutable', - r'(Z)Z', - ); + static final _id_setExecutable = File._class.instanceMethodId(r'setExecutable', r'(Z)Z'); static final _setExecutable = jni$_.ProtectedJniExtensions.lookup< @@ -8576,26 +7302,15 @@ extension File$$Methods on File { > >('globalEnv_CallBooleanMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public boolean setExecutable(boolean z)` core$_.bool setExecutable(core$_.bool z) { - return _setExecutable( - reference.pointer, - _id_setExecutable.pointer, - z ? 1 : 0, - ).boolean; + return _setExecutable(reference.pointer, _id_setExecutable.pointer, z ? 1 : 0).boolean; } - static final _id_setExecutable$1 = File._class.instanceMethodId( - r'setExecutable', - r'(ZZ)Z', - ); + static final _id_setExecutable$1 = File._class.instanceMethodId(r'setExecutable', r'(ZZ)Z'); static final _setExecutable$1 = jni$_.ProtectedJniExtensions.lookup< @@ -8626,10 +7341,7 @@ extension File$$Methods on File { ).boolean; } - static final _id_setLastModified = File._class.instanceMethodId( - r'setLastModified', - r'(J)Z', - ); + static final _id_setLastModified = File._class.instanceMethodId(r'setLastModified', r'(J)Z'); static final _setLastModified = jni$_.ProtectedJniExtensions.lookup< @@ -8642,52 +7354,30 @@ extension File$$Methods on File { > >('globalEnv_CallBooleanMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public boolean setLastModified(long j)` core$_.bool setLastModified(core$_.int j) { - return _setLastModified( - reference.pointer, - _id_setLastModified.pointer, - j, - ).boolean; + return _setLastModified(reference.pointer, _id_setLastModified.pointer, j).boolean; } - static final _id_setReadOnly = File._class.instanceMethodId( - r'setReadOnly', - r'()Z', - ); + static final _id_setReadOnly = File._class.instanceMethodId(r'setReadOnly', r'()Z'); static final _setReadOnly = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public boolean setReadOnly()` core$_.bool setReadOnly() { return _setReadOnly(reference.pointer, _id_setReadOnly.pointer).boolean; } - static final _id_setReadable = File._class.instanceMethodId( - r'setReadable', - r'(Z)Z', - ); + static final _id_setReadable = File._class.instanceMethodId(r'setReadable', r'(Z)Z'); static final _setReadable = jni$_.ProtectedJniExtensions.lookup< @@ -8700,26 +7390,15 @@ extension File$$Methods on File { > >('globalEnv_CallBooleanMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public boolean setReadable(boolean z)` core$_.bool setReadable(core$_.bool z) { - return _setReadable( - reference.pointer, - _id_setReadable.pointer, - z ? 1 : 0, - ).boolean; + return _setReadable(reference.pointer, _id_setReadable.pointer, z ? 1 : 0).boolean; } - static final _id_setReadable$1 = File._class.instanceMethodId( - r'setReadable', - r'(ZZ)Z', - ); + static final _id_setReadable$1 = File._class.instanceMethodId(r'setReadable', r'(ZZ)Z'); static final _setReadable$1 = jni$_.ProtectedJniExtensions.lookup< @@ -8750,10 +7429,7 @@ extension File$$Methods on File { ).boolean; } - static final _id_setWritable = File._class.instanceMethodId( - r'setWritable', - r'(Z)Z', - ); + static final _id_setWritable = File._class.instanceMethodId(r'setWritable', r'(Z)Z'); static final _setWritable = jni$_.ProtectedJniExtensions.lookup< @@ -8766,26 +7442,15 @@ extension File$$Methods on File { > >('globalEnv_CallBooleanMethod') .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - core$_.int, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr, core$_.int) >(); /// from: `public boolean setWritable(boolean z)` core$_.bool setWritable(core$_.bool z) { - return _setWritable( - reference.pointer, - _id_setWritable.pointer, - z ? 1 : 0, - ).boolean; + return _setWritable(reference.pointer, _id_setWritable.pointer, z ? 1 : 0).boolean; } - static final _id_setWritable$1 = File._class.instanceMethodId( - r'setWritable', - r'(ZZ)Z', - ); + static final _id_setWritable$1 = File._class.instanceMethodId(r'setWritable', r'(ZZ)Z'); static final _setWritable$1 = jni$_.ProtectedJniExtensions.lookup< @@ -8816,124 +7481,68 @@ extension File$$Methods on File { ).boolean; } - static final _id_toPath = File._class.instanceMethodId( - r'toPath', - r'()Ljava/nio/file/Path;', - ); + static final _id_toPath = File._class.instanceMethodId(r'toPath', r'()Ljava/nio/file/Path;'); static final _toPath = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.nio.file.Path toPath()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? toPath() { - return _toPath( - reference.pointer, - _id_toPath.pointer, - ).object(); + return _toPath(reference.pointer, _id_toPath.pointer).object(); } - static final _id_toString$1 = File._class.instanceMethodId( - r'toString', - r'()Ljava/lang/String;', - ); + static final _id_toString$1 = File._class.instanceMethodId(r'toString', r'()Ljava/lang/String;'); static final _toString$1 = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.lang.String toString()` /// The returned object must be released after use, by calling the [release] method. jni$_.JString? toString$1() { - return _toString$1( - reference.pointer, - _id_toString$1.pointer, - ).object(); + return _toString$1(reference.pointer, _id_toString$1.pointer).object(); } - static final _id_toURI = File._class.instanceMethodId( - r'toURI', - r'()Ljava/net/URI;', - ); + static final _id_toURI = File._class.instanceMethodId(r'toURI', r'()Ljava/net/URI;'); static final _toURI = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.net.URI toURI()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? toURI() { - return _toURI( - reference.pointer, - _id_toURI.pointer, - ).object(); + return _toURI(reference.pointer, _id_toURI.pointer).object(); } - static final _id_toURL = File._class.instanceMethodId( - r'toURL', - r'()Ljava/net/URL;', - ); + static final _id_toURL = File._class.instanceMethodId(r'toURL', r'()Ljava/net/URL;'); static final _toURL = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public java.net.URL toURL()` /// The returned object must be released after use, by calling the [release] method. jni$_.JObject? toURL() { - return _toURL( - reference.pointer, - _id_toURL.pointer, - ).object(); + return _toURL(reference.pointer, _id_toURL.pointer).object(); } core$_.bool operator <(File? file) { @@ -8976,8 +7585,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_ALARMS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_ALARMS => - _id_DIRECTORY_ALARMS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_ALARMS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_ALARMS` /// The returned object must be released after use, by calling the [release] method. @@ -8992,24 +7600,19 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_AUDIOBOOKS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_AUDIOBOOKS => - _id_DIRECTORY_AUDIOBOOKS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_AUDIOBOOKS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_AUDIOBOOKS` /// The returned object must be released after use, by calling the [release] method. static set DIRECTORY_AUDIOBOOKS(jni$_.JString? value) => _id_DIRECTORY_AUDIOBOOKS.set(_class, jni$_.JString.type, value); - static final _id_DIRECTORY_DCIM = _class.staticFieldId( - r'DIRECTORY_DCIM', - r'Ljava/lang/String;', - ); + static final _id_DIRECTORY_DCIM = _class.staticFieldId(r'DIRECTORY_DCIM', r'Ljava/lang/String;'); /// from: `static public java.lang.String DIRECTORY_DCIM` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_DCIM => - _id_DIRECTORY_DCIM.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_DCIM.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_DCIM` /// The returned object must be released after use, by calling the [release] method. @@ -9024,8 +7627,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_DOCUMENTS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_DOCUMENTS => - _id_DIRECTORY_DOCUMENTS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_DOCUMENTS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_DOCUMENTS` /// The returned object must be released after use, by calling the [release] method. @@ -9040,8 +7642,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_DOWNLOADS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_DOWNLOADS => - _id_DIRECTORY_DOWNLOADS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_DOWNLOADS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_DOWNLOADS` /// The returned object must be released after use, by calling the [release] method. @@ -9056,8 +7657,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_MOVIES` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_MOVIES => - _id_DIRECTORY_MOVIES.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_MOVIES.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_MOVIES` /// The returned object must be released after use, by calling the [release] method. @@ -9072,8 +7672,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_MUSIC` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_MUSIC => - _id_DIRECTORY_MUSIC.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_MUSIC.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_MUSIC` /// The returned object must be released after use, by calling the [release] method. @@ -9088,8 +7687,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_NOTIFICATIONS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_NOTIFICATIONS => - _id_DIRECTORY_NOTIFICATIONS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_NOTIFICATIONS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_NOTIFICATIONS` /// The returned object must be released after use, by calling the [release] method. @@ -9104,8 +7702,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_PICTURES` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_PICTURES => - _id_DIRECTORY_PICTURES.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_PICTURES.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_PICTURES` /// The returned object must be released after use, by calling the [release] method. @@ -9120,8 +7717,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_PODCASTS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_PODCASTS => - _id_DIRECTORY_PODCASTS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_PODCASTS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_PODCASTS` /// The returned object must be released after use, by calling the [release] method. @@ -9136,8 +7732,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_RECORDINGS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_RECORDINGS => - _id_DIRECTORY_RECORDINGS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_RECORDINGS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_RECORDINGS` /// The returned object must be released after use, by calling the [release] method. @@ -9152,8 +7747,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_RINGTONES` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_RINGTONES => - _id_DIRECTORY_RINGTONES.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_RINGTONES.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_RINGTONES` /// The returned object must be released after use, by calling the [release] method. @@ -9168,8 +7762,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public java.lang.String DIRECTORY_SCREENSHOTS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get DIRECTORY_SCREENSHOTS => - _id_DIRECTORY_SCREENSHOTS.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_DIRECTORY_SCREENSHOTS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; /// from: `static public java.lang.String DIRECTORY_SCREENSHOTS` /// The returned object must be released after use, by calling the [release] method. @@ -9184,41 +7777,28 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_BAD_REMOVAL` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_BAD_REMOVAL => - _id_MEDIA_BAD_REMOVAL.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_BAD_REMOVAL.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MEDIA_CHECKING = _class.staticFieldId( - r'MEDIA_CHECKING', - r'Ljava/lang/String;', - ); + static final _id_MEDIA_CHECKING = _class.staticFieldId(r'MEDIA_CHECKING', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MEDIA_CHECKING` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_CHECKING => - _id_MEDIA_CHECKING.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_CHECKING.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MEDIA_EJECTING = _class.staticFieldId( - r'MEDIA_EJECTING', - r'Ljava/lang/String;', - ); + static final _id_MEDIA_EJECTING = _class.staticFieldId(r'MEDIA_EJECTING', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MEDIA_EJECTING` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_EJECTING => - _id_MEDIA_EJECTING.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_EJECTING.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MEDIA_MOUNTED = _class.staticFieldId( - r'MEDIA_MOUNTED', - r'Ljava/lang/String;', - ); + static final _id_MEDIA_MOUNTED = _class.staticFieldId(r'MEDIA_MOUNTED', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MEDIA_MOUNTED` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_MOUNTED => - _id_MEDIA_MOUNTED.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_MOUNTED.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_MOUNTED_READ_ONLY = _class.staticFieldId( r'MEDIA_MOUNTED_READ_ONLY', @@ -9228,51 +7808,35 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_MOUNTED_READ_ONLY` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_MOUNTED_READ_ONLY => - _id_MEDIA_MOUNTED_READ_ONLY.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_MOUNTED_READ_ONLY.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MEDIA_NOFS = _class.staticFieldId( - r'MEDIA_NOFS', - r'Ljava/lang/String;', - ); + static final _id_MEDIA_NOFS = _class.staticFieldId(r'MEDIA_NOFS', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MEDIA_NOFS` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_NOFS => _id_MEDIA_NOFS.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MEDIA_REMOVED = _class.staticFieldId( - r'MEDIA_REMOVED', - r'Ljava/lang/String;', - ); + static final _id_MEDIA_REMOVED = _class.staticFieldId(r'MEDIA_REMOVED', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MEDIA_REMOVED` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_REMOVED => - _id_MEDIA_REMOVED.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_REMOVED.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MEDIA_SHARED = _class.staticFieldId( - r'MEDIA_SHARED', - r'Ljava/lang/String;', - ); + static final _id_MEDIA_SHARED = _class.staticFieldId(r'MEDIA_SHARED', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MEDIA_SHARED` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_SHARED => - _id_MEDIA_SHARED.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_SHARED.getNullable(_class, jni$_.JString.type) as jni$_.JString?; - static final _id_MEDIA_UNKNOWN = _class.staticFieldId( - r'MEDIA_UNKNOWN', - r'Ljava/lang/String;', - ); + static final _id_MEDIA_UNKNOWN = _class.staticFieldId(r'MEDIA_UNKNOWN', r'Ljava/lang/String;'); /// from: `static public final java.lang.String MEDIA_UNKNOWN` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_UNKNOWN => - _id_MEDIA_UNKNOWN.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_UNKNOWN.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_UNMOUNTABLE = _class.staticFieldId( r'MEDIA_UNMOUNTABLE', @@ -9282,8 +7846,7 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_UNMOUNTABLE` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_UNMOUNTABLE => - _id_MEDIA_UNMOUNTABLE.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_UNMOUNTABLE.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_MEDIA_UNMOUNTED = _class.staticFieldId( r'MEDIA_UNMOUNTED', @@ -9293,34 +7856,22 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { /// from: `static public final java.lang.String MEDIA_UNMOUNTED` /// The returned object must be released after use, by calling the [release] method. static jni$_.JString? get MEDIA_UNMOUNTED => - _id_MEDIA_UNMOUNTED.getNullable(_class, jni$_.JString.type) - as jni$_.JString?; + _id_MEDIA_UNMOUNTED.getNullable(_class, jni$_.JString.type) as jni$_.JString?; static final _id_new$ = _class.constructorId(r'()V'); static final _new$ = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_NewObject') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `public void ()` /// The returned object must be released after use, by calling the [release] method. factory Environment() { - return _new$( - _class.reference.pointer, - _id_new$.pointer, - ).object(); + return _new$(_class.reference.pointer, _id_new$.pointer).object(); } static final _id_get$dataDirectory = _class.staticMethodId( @@ -9331,18 +7882,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$dataDirectory = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public java.io.File getDataDirectory()` /// The returned object must be released after use, by calling the [release] method. @@ -9361,18 +7904,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$downloadCacheDirectory = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public java.io.File getDownloadCacheDirectory()` /// The returned object must be released after use, by calling the [release] method. @@ -9391,18 +7926,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$externalStorageDirectory = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public java.io.File getExternalStorageDirectory()` /// The returned object must be released after use, by calling the [release] method. @@ -9455,18 +7982,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$externalStorageState = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public java.lang.String getExternalStorageState()` /// The returned object must be released after use, by calling the [release] method. @@ -9519,18 +8038,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$rootDirectory = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public java.io.File getRootDirectory()` /// The returned object must be released after use, by calling the [release] method. @@ -9549,18 +8060,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$storageDirectory = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticObjectMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public java.io.File getStorageDirectory()` /// The returned object must be released after use, by calling the [release] method. @@ -9613,18 +8116,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$isExternalStorageEmulated = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public boolean isExternalStorageEmulated()` static core$_.bool get isExternalStorageEmulated { @@ -9675,18 +8170,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$isExternalStorageLegacy = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public boolean isExternalStorageLegacy()` static core$_.bool get isExternalStorageLegacy { @@ -9737,18 +8224,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$isExternalStorageManager = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public boolean isExternalStorageManager()` static core$_.bool get isExternalStorageManager { @@ -9799,18 +8278,10 @@ extension type Environment._(jni$_.JObject _$this) implements jni$_.JObject { static final _get$isExternalStorageRemovable = jni$_.ProtectedJniExtensions.lookup< jni$_.NativeFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) + jni$_.JniResult Function(jni$_.Pointer, jni$_.JMethodIDPtr) > >('globalEnv_CallStaticBooleanMethod') - .asFunction< - jni$_.JniResult Function( - jni$_.Pointer, - jni$_.JMethodIDPtr, - ) - >(); + .asFunction, jni$_.JMethodIDPtr)>(); /// from: `static public boolean isExternalStorageRemovable()` static core$_.bool get isExternalStorageRemovable { diff --git a/packages/path_provider/path_provider_android/lib/src/path_provider_android_real.dart b/packages/path_provider/path_provider_android/lib/src/path_provider_android_real.dart index 5430103f8523..dfb5107f9f22 100644 --- a/packages/path_provider/path_provider_android/lib/src/path_provider_android_real.dart +++ b/packages/path_provider/path_provider_android/lib/src/path_provider_android_real.dart @@ -10,9 +10,7 @@ import 'path_provider.g.dart'; /// The Android implementation of [PathProviderPlatform]. class PathProviderAndroid extends PathProviderPlatform { - late final Context _applicationContext = androidApplicationContext.as( - Context.type, - ); + late final Context _applicationContext = androidApplicationContext.as(Context.type); /// Registers this class as the default instance of [PathProviderPlatform]. static void registerWith() { @@ -35,10 +33,7 @@ class PathProviderAndroid extends PathProviderPlatform { @override Future getApplicationDocumentsPath() async { final JString directory = 'flutter'.toJString(); - final File? file = _applicationContext.getDir( - directory, - Context.MODE_PRIVATE, - ); + final File? file = _applicationContext.getDir(directory, Context.MODE_PRIVATE); final String? path = file?.path?.toDartString(releaseOriginal: true); file?.release(); directory.release(); @@ -57,9 +52,7 @@ class PathProviderAndroid extends PathProviderPlatform { Future getExternalStoragePath() async { final File? dir = _applicationContext.getExternalFilesDir(null); if (dir != null) { - final String? path = dir.absolutePath?.toDartString( - releaseOriginal: true, - ); + final String? path = dir.absolutePath?.toDartString(releaseOriginal: true); dir.release(); return path; } @@ -80,15 +73,9 @@ class PathProviderAndroid extends PathProviderPlatform { } @override - Future?> getExternalStoragePaths({ - StorageDirectory? type, - }) async { - final JString? directory = type != null - ? _toNativeStorageDirectory(type) - : null; - final JArray? files = _applicationContext.getExternalFilesDirs( - directory, - ); + Future?> getExternalStoragePaths({StorageDirectory? type}) async { + final JString? directory = type != null ? _toNativeStorageDirectory(type) : null; + final JArray? files = _applicationContext.getExternalFilesDirs(directory); directory?.release(); if (files != null) { final List paths = _toStringList(files); @@ -101,9 +88,7 @@ class PathProviderAndroid extends PathProviderPlatform { @override Future getDownloadsPath() async { - final List? paths = await getExternalStoragePaths( - type: StorageDirectory.downloads, - ); + final List? paths = await getExternalStoragePaths(type: StorageDirectory.downloads); return paths?.firstOrNull; } } @@ -138,9 +123,7 @@ List _toStringList(JArray files) { final paths = []; for (final file in dartList) { if (file != null) { - final String? path = file.absolutePath?.toDartString( - releaseOriginal: true, - ); + final String? path = file.absolutePath?.toDartString(releaseOriginal: true); if (path != null) { paths.add(path); } diff --git a/packages/path_provider/path_provider_android/tool/jnigen.dart b/packages/path_provider/path_provider_android/tool/jnigen.dart index 9a626afe1cc0..e782df2e6075 100644 --- a/packages/path_provider/path_provider_android/tool/jnigen.dart +++ b/packages/path_provider/path_provider_android/tool/jnigen.dart @@ -16,15 +16,8 @@ void main() { structure: OutputStructure.singleFile, ), ), - androidSdkConfig: AndroidSdkConfig( - addGradleDeps: true, - androidExample: 'example/', - ), - classes: [ - 'android.content.Context', - 'java.io.File', - 'android.os.Environment', - ], + androidSdkConfig: AndroidSdkConfig(addGradleDeps: true, androidExample: 'example/'), + classes: ['android.content.Context', 'java.io.File', 'android.os.Environment'], ), ); } diff --git a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart index 9ad8b748b972..4ef539e1b1ee 100644 --- a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart @@ -32,9 +32,7 @@ void main() { _verifySampleFile(result, 'temporaryDirectory'); }); - testWidgets('getApplicationDocumentsDirectory', ( - WidgetTester tester, - ) async { + testWidgets('getApplicationDocumentsDirectory', (WidgetTester tester) async { final PathProviderPlatform provider = PathProviderPlatform.instance; final String? result = await provider.getApplicationDocumentsPath(); if (Platform.isMacOS) { @@ -90,12 +88,10 @@ void main() { // NSString, etc.) that aren't available in an actual unit test. For these // tests, the platform is stubbed out. group('unit', () { - final platformVariants = ValueVariant( - { - FakePlatformProvider(isIOS: true), - FakePlatformProvider(isMacOS: true), - }, - ); + final platformVariants = ValueVariant({ + FakePlatformProvider(isIOS: true), + FakePlatformProvider(isMacOS: true), + }); // These tests use the actual filesystem, since an injectable filesystem // would add a runtime dependency to the package, so everything is contained @@ -160,12 +156,7 @@ void main() { platform: FakePlatformProvider(isIOS: true), ); - final String applicationSupportPath = p.join( - testRoot.path, - 'application', - 'support', - 'path', - ); + final String applicationSupportPath = p.join(testRoot.path, 'application', 'support', 'path'); when( mockFfiLib.NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.NSApplicationSupportDirectory, @@ -186,12 +177,7 @@ void main() { platform: FakePlatformProvider(isMacOS: true), ); - final String applicationSupportPath = p.join( - testRoot.path, - 'application', - 'support', - 'path', - ); + final String applicationSupportPath = p.join(testRoot.path, 'application', 'support', 'path'); when( mockFfiLib.NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.NSApplicationSupportDirectory, @@ -203,41 +189,29 @@ void main() { final String? path = await pathProvider.getApplicationSupportPath(); // On macOS, the bundle ID should be appended to the path. - expect( - path, - '$applicationSupportPath/dev.flutter.plugins.pathProviderExample', - ); + expect(path, '$applicationSupportPath/dev.flutter.plugins.pathProviderExample'); }); - testWidgets( - 'getApplicationSupportPath creates the directory if necessary', - (_) async { - final mockFfiLib = MockFoundationFFI(); - final pathProvider = PathProviderFoundation( - ffiLib: mockFfiLib, - platform: platformVariants.currentValue, - ); + testWidgets('getApplicationSupportPath creates the directory if necessary', (_) async { + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( + ffiLib: mockFfiLib, + platform: platformVariants.currentValue, + ); - final String applicationSupportPath = p.join( - testRoot.path, - 'application', - 'support', - 'path', - ); - when( - mockFfiLib.NSSearchPathForDirectoriesInDomains( - NSSearchPathDirectory.NSApplicationSupportDirectory, - NSSearchPathDomainMask.NSUserDomainMask, - true, - ), - ).thenReturn(_arrayWithString(applicationSupportPath)); + final String applicationSupportPath = p.join(testRoot.path, 'application', 'support', 'path'); + when( + mockFfiLib.NSSearchPathForDirectoriesInDomains( + NSSearchPathDirectory.NSApplicationSupportDirectory, + NSSearchPathDomainMask.NSUserDomainMask, + true, + ), + ).thenReturn(_arrayWithString(applicationSupportPath)); - final String? path = await pathProvider.getApplicationSupportPath(); + final String? path = await pathProvider.getApplicationSupportPath(); - expect(Directory(path!).existsSync(), isTrue); - }, - variant: platformVariants, - ); + expect(Directory(path!).existsSync(), isTrue); + }, variant: platformVariants); testWidgets('getLibraryPath', (_) async { final mockFfiLib = MockFoundationFFI(); @@ -293,12 +267,7 @@ void main() { platform: FakePlatformProvider(isIOS: true), ); - final String applicationCachePath = p.join( - testRoot.path, - 'application', - 'cache', - 'path', - ); + final String applicationCachePath = p.join(testRoot.path, 'application', 'cache', 'path'); when( mockFfiLib.NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.NSCachesDirectory, @@ -319,12 +288,7 @@ void main() { platform: FakePlatformProvider(isMacOS: true), ); - final String applicationCachePath = p.join( - testRoot.path, - 'application', - 'cache', - 'path', - ); + final String applicationCachePath = p.join(testRoot.path, 'application', 'cache', 'path'); when( mockFfiLib.NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.NSCachesDirectory, @@ -336,41 +300,29 @@ void main() { final String? path = await pathProvider.getApplicationCachePath(); // On macOS, the bundle ID should be appended to the path. - expect( - path, - '$applicationCachePath/dev.flutter.plugins.pathProviderExample', - ); + expect(path, '$applicationCachePath/dev.flutter.plugins.pathProviderExample'); }); - testWidgets( - 'getApplicationCachePath creates the directory if necessary', - (_) async { - final mockFfiLib = MockFoundationFFI(); - final pathProvider = PathProviderFoundation( - ffiLib: mockFfiLib, - platform: platformVariants.currentValue, - ); + testWidgets('getApplicationCachePath creates the directory if necessary', (_) async { + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( + ffiLib: mockFfiLib, + platform: platformVariants.currentValue, + ); - final String applicationCachePath = p.join( - testRoot.path, - 'application', - 'cache', - 'path', - ); - when( - mockFfiLib.NSSearchPathForDirectoriesInDomains( - NSSearchPathDirectory.NSCachesDirectory, - NSSearchPathDomainMask.NSUserDomainMask, - true, - ), - ).thenReturn(_arrayWithString(applicationCachePath)); + final String applicationCachePath = p.join(testRoot.path, 'application', 'cache', 'path'); + when( + mockFfiLib.NSSearchPathForDirectoriesInDomains( + NSSearchPathDirectory.NSCachesDirectory, + NSSearchPathDomainMask.NSUserDomainMask, + true, + ), + ).thenReturn(_arrayWithString(applicationCachePath)); - final String? path = await pathProvider.getApplicationCachePath(); + final String? path = await pathProvider.getApplicationCachePath(); - expect(Directory(path!).existsSync(), isTrue); - }, - variant: platformVariants, - ); + expect(Directory(path!).existsSync(), isTrue); + }, variant: platformVariants); testWidgets('getDownloadsPath', (_) async { final mockFfiLib = MockFoundationFFI(); @@ -443,8 +395,7 @@ void _verifySampleFile(String? directoryPath, String name) { /// Fake implementation of PathProviderPlatformProvider. class FakePlatformProvider implements PathProviderPlatformProvider { - FakePlatformProvider({this.isIOS = false, this.isMacOS = false}) - : assert(isIOS != isMacOS); + FakePlatformProvider({this.isIOS = false, this.isMacOS = false}) : assert(isIOS != isMacOS); @override bool isIOS; diff --git a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.mocks.dart b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.mocks.dart index 24980d636be9..b9e2562d5e99 100644 --- a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.mocks.dart +++ b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.mocks.dart @@ -7,8 +7,7 @@ import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i4; import 'package:objective_c/objective_c.dart' as _i2; import 'package:path_provider_foundation/src/ffi_bindings.g.dart' as _i3; -import 'package:path_provider_foundation/src/path_provider_foundation_real.dart' - as _i5; +import 'package:path_provider_foundation/src/path_provider_foundation_real.dart' as _i5; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -26,8 +25,7 @@ import 'package:path_provider_foundation/src/path_provider_foundation_real.dart' // ignore_for_file: invalid_use_of_internal_member class _FakeObjCObject_0 extends _i1.SmartFake implements _i2.ObjCObject { - _FakeObjCObject_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeObjCObject_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [FoundationFFI]. @@ -39,31 +37,17 @@ class MockFoundationFFI extends _i1.Mock implements _i3.FoundationFFI { _i3.NSSearchPathDirectory? directory, int? domainMask, bool? expandTilde, - ) => - (super.noSuchMethod( - Invocation.method(#NSSearchPathForDirectoriesInDomains, [ - directory, - domainMask, - expandTilde, - ]), - returnValue: _FakeObjCObject_0( - this, - Invocation.method(#NSSearchPathForDirectoriesInDomains, [ - directory, - domainMask, - expandTilde, - ]), - ), - returnValueForMissingStub: _FakeObjCObject_0( - this, - Invocation.method(#NSSearchPathForDirectoriesInDomains, [ - directory, - domainMask, - expandTilde, - ]), - ), - ) - as _i2.NSArray); + ) => (super.noSuchMethod( + Invocation.method(#NSSearchPathForDirectoriesInDomains, [directory, domainMask, expandTilde]), + returnValue: _FakeObjCObject_0( + this, + Invocation.method(#NSSearchPathForDirectoriesInDomains, [directory, domainMask, expandTilde]), + ), + returnValueForMissingStub: _FakeObjCObject_0( + this, + Invocation.method(#NSSearchPathForDirectoriesInDomains, [directory, domainMask, expandTilde]), + ), + ) as _i2.NSArray); } /// A class which mocks [ObjCObject]. @@ -71,19 +55,11 @@ class MockFoundationFFI extends _i1.Mock implements _i3.FoundationFFI { /// See the documentation for Mockito's code generation for more information. class MockObjCObject extends _i1.Mock implements _i2.ObjCObject { @override - _i2.ObjCObjectRef get ref => - (super.noSuchMethod( - Invocation.getter(#ref), - returnValue: _i4.dummyValue<_i2.ObjCObjectRef>( - this, - Invocation.getter(#ref), - ), - returnValueForMissingStub: _i4.dummyValue<_i2.ObjCObjectRef>( - this, - Invocation.getter(#ref), - ), - ) - as _i2.ObjCObjectRef); + _i2.ObjCObjectRef get ref => (super.noSuchMethod( + Invocation.getter(#ref), + returnValue: _i4.dummyValue<_i2.ObjCObjectRef>(this, Invocation.getter(#ref)), + returnValueForMissingStub: _i4.dummyValue<_i2.ObjCObjectRef>(this, Invocation.getter(#ref)), + ) as _i2.ObjCObjectRef); } /// A class which mocks [PathProviderPlatformProvider]. @@ -92,20 +68,16 @@ class MockObjCObject extends _i1.Mock implements _i2.ObjCObject { class MockPathProviderPlatformProvider extends _i1.Mock implements _i5.PathProviderPlatformProvider { @override - bool get isIOS => - (super.noSuchMethod( - Invocation.getter(#isIOS), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isIOS => (super.noSuchMethod( + Invocation.getter(#isIOS), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - bool get isMacOS => - (super.noSuchMethod( - Invocation.getter(#isMacOS), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isMacOS => (super.noSuchMethod( + Invocation.getter(#isMacOS), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); } diff --git a/packages/path_provider/path_provider_foundation/example/lib/main.dart b/packages/path_provider/path_provider_foundation/example/lib/main.dart index ca2af824df43..e26b349e2d80 100644 --- a/packages/path_provider/path_provider_foundation/example/lib/main.dart +++ b/packages/path_provider/path_provider_foundation/example/lib/main.dart @@ -81,8 +81,7 @@ class _MyAppState extends State { appGroupIdentifier: 'group.flutter.appGroupTest', ); } catch (exception) { - containerDirectory = - 'Failed to get app group container directory: $exception'; + containerDirectory = 'Failed to get app group container directory: $exception'; } try { diff --git a/packages/path_provider/path_provider_foundation/lib/src/ffi_bindings.g.dart b/packages/path_provider/path_provider_foundation/lib/src/ffi_bindings.g.dart index e0e01ffa9f00..32d90188fa7f 100644 --- a/packages/path_provider/path_provider_foundation/lib/src/ffi_bindings.g.dart +++ b/packages/path_provider/path_provider_foundation/lib/src/ffi_bindings.g.dart @@ -9,12 +9,10 @@ import 'package:ffi/ffi.dart' as pkg_ffi; /// Bindings for NSFileManager. class FoundationFFI { /// Holds the symbol lookup function. - final ffi.Pointer Function(String symbolName) - _lookup; + final ffi.Pointer Function(String symbolName) _lookup; /// The symbols are looked up in [dynamicLibrary]. - FoundationFFI(ffi.DynamicLibrary dynamicLibrary) - : _lookup = dynamicLibrary.lookup; + FoundationFFI(ffi.DynamicLibrary dynamicLibrary) : _lookup = dynamicLibrary.lookup; /// The symbols are looked up with [lookup]. FoundationFFI.fromLookup( @@ -27,11 +25,7 @@ class FoundationFFI { bool expandTilde, ) { return objc.NSArray.fromPointer( - _NSSearchPathForDirectoriesInDomains( - directory.value, - domainMask, - expandTilde, - ), + _NSSearchPathForDirectoriesInDomains(directory.value, domainMask, expandTilde), retain: true, release: true, ); @@ -40,11 +34,7 @@ class FoundationFFI { late final _NSSearchPathForDirectoriesInDomainsPtr = _lookup< ffi.NativeFunction< - ffi.Pointer Function( - ffi.UnsignedLong, - ffi.UnsignedLong, - ffi.Bool, - ) + ffi.Pointer Function(ffi.UnsignedLong, ffi.UnsignedLong, ffi.Bool) > >('NSSearchPathForDirectoriesInDomains'); late final _NSSearchPathForDirectoriesInDomains = @@ -126,9 +116,7 @@ sealed class NSSearchPathDomainMask { } late final _class_NSURL = objc.getClass("NSURL"); -late final _sel_fileURLWithPathComponents_ = objc.registerName( - "fileURLWithPathComponents:", -); +late final _sel_fileURLWithPathComponents_ = objc.registerName("fileURLWithPathComponents:"); final _objc_msgSend_1sotr3r = objc.msgSendPointer .cast< ffi.NativeFunction< @@ -164,9 +152,7 @@ final _objc_msgSend_151sglz = objc.msgSendPointer >(); late final _sel_lastPathComponent = objc.registerName("lastPathComponent"); late final _sel_pathExtension = objc.registerName("pathExtension"); -late final _sel_URLByAppendingPathComponent_ = objc.registerName( - "URLByAppendingPathComponent:", -); +late final _sel_URLByAppendingPathComponent_ = objc.registerName("URLByAppendingPathComponent:"); late final _sel_URLByAppendingPathComponent_isDirectory_ = objc.registerName( "URLByAppendingPathComponent:isDirectory:", ); @@ -192,12 +178,8 @@ final _objc_msgSend_17amj0z = objc.msgSendPointer late final _sel_URLByDeletingLastPathComponent = objc.registerName( "URLByDeletingLastPathComponent", ); -late final _sel_URLByAppendingPathExtension_ = objc.registerName( - "URLByAppendingPathExtension:", -); -late final _sel_URLByDeletingPathExtension = objc.registerName( - "URLByDeletingPathExtension", -); +late final _sel_URLByAppendingPathExtension_ = objc.registerName("URLByAppendingPathExtension:"); +late final _sel_URLByDeletingPathExtension = objc.registerName("URLByDeletingPathExtension"); late final _sel_checkResourceIsReachableAndReturnError_ = objc.registerName( "checkResourceIsReachableAndReturnError:", ); @@ -218,12 +200,8 @@ final _objc_msgSend_1dom33q = objc.msgSendPointer ffi.Pointer>, ) >(); -late final _sel_URLByStandardizingPath = objc.registerName( - "URLByStandardizingPath", -); -late final _sel_URLByResolvingSymlinksInPath = objc.registerName( - "URLByResolvingSymlinksInPath", -); +late final _sel_URLByStandardizingPath = objc.registerName("URLByStandardizingPath"); +late final _sel_URLByResolvingSymlinksInPath = objc.registerName("URLByResolvingSymlinksInPath"); /// NSURLPathUtilities extension NSURLPathUtilities on objc.NSURL { @@ -239,9 +217,7 @@ extension NSURLPathUtilities on objc.NSURL { _sel_URLByAppendingPathComponent_, pathComponent.ref.pointer, ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } /// URLByAppendingPathComponent:isDirectory: @@ -260,9 +236,7 @@ extension NSURLPathUtilities on objc.NSURL { pathComponent.ref.pointer, isDirectory, ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } /// URLByAppendingPathExtension: @@ -277,9 +251,7 @@ extension NSURLPathUtilities on objc.NSURL { _sel_URLByAppendingPathExtension_, pathExtension.ref.pointer, ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } /// URLByDeletingLastPathComponent @@ -289,13 +261,8 @@ extension NSURLPathUtilities on objc.NSURL { iOS: (false, (4, 0, 0)), macOS: (false, (10, 6, 0)), ); - final $ret = _objc_msgSend_151sglz( - object$.ref.pointer, - _sel_URLByDeletingLastPathComponent, - ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + final $ret = _objc_msgSend_151sglz(object$.ref.pointer, _sel_URLByDeletingLastPathComponent); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } /// URLByDeletingPathExtension @@ -305,13 +272,8 @@ extension NSURLPathUtilities on objc.NSURL { iOS: (false, (4, 0, 0)), macOS: (false, (10, 6, 0)), ); - final $ret = _objc_msgSend_151sglz( - object$.ref.pointer, - _sel_URLByDeletingPathExtension, - ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + final $ret = _objc_msgSend_151sglz(object$.ref.pointer, _sel_URLByDeletingPathExtension); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } /// URLByResolvingSymlinksInPath @@ -321,13 +283,8 @@ extension NSURLPathUtilities on objc.NSURL { iOS: (false, (4, 0, 0)), macOS: (false, (10, 6, 0)), ); - final $ret = _objc_msgSend_151sglz( - object$.ref.pointer, - _sel_URLByResolvingSymlinksInPath, - ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + final $ret = _objc_msgSend_151sglz(object$.ref.pointer, _sel_URLByResolvingSymlinksInPath); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } /// URLByStandardizingPath @@ -337,13 +294,8 @@ extension NSURLPathUtilities on objc.NSURL { iOS: (false, (4, 0, 0)), macOS: (false, (10, 6, 0)), ); - final $ret = _objc_msgSend_151sglz( - object$.ref.pointer, - _sel_URLByStandardizingPath, - ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + final $ret = _objc_msgSend_151sglz(object$.ref.pointer, _sel_URLByStandardizingPath); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } /// checkResourceIsReachableAndReturnError: @@ -374,13 +326,8 @@ extension NSURLPathUtilities on objc.NSURL { iOS: (false, (4, 0, 0)), macOS: (false, (10, 6, 0)), ); - final $ret = _objc_msgSend_151sglz( - object$.ref.pointer, - _sel_lastPathComponent, - ); - return $ret.address == 0 - ? null - : objc.NSString.fromPointer($ret, retain: true, release: true); + final $ret = _objc_msgSend_151sglz(object$.ref.pointer, _sel_lastPathComponent); + return $ret.address == 0 ? null : objc.NSString.fromPointer($ret, retain: true, release: true); } /// pathComponents @@ -390,13 +337,8 @@ extension NSURLPathUtilities on objc.NSURL { iOS: (false, (4, 0, 0)), macOS: (false, (10, 6, 0)), ); - final $ret = _objc_msgSend_151sglz( - object$.ref.pointer, - _sel_pathComponents, - ); - return $ret.address == 0 - ? null - : objc.NSArray.fromPointer($ret, retain: true, release: true); + final $ret = _objc_msgSend_151sglz(object$.ref.pointer, _sel_pathComponents); + return $ret.address == 0 ? null : objc.NSArray.fromPointer($ret, retain: true, release: true); } /// pathExtension @@ -407,9 +349,7 @@ extension NSURLPathUtilities on objc.NSURL { macOS: (false, (10, 6, 0)), ); final $ret = _objc_msgSend_151sglz(object$.ref.pointer, _sel_pathExtension); - return $ret.address == 0 - ? null - : objc.NSString.fromPointer($ret, retain: true, release: true); + return $ret.address == 0 ? null : objc.NSString.fromPointer($ret, retain: true, release: true); } /// fileURLWithPathComponents: @@ -424,9 +364,7 @@ extension NSURLPathUtilities on objc.NSURL { _sel_fileURLWithPathComponents_, components.ref.pointer, ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } } @@ -450,12 +388,12 @@ final _objc_msgSend_19nvye5 = objc.msgSendPointer ) >(); late final _sel_defaultManager = objc.registerName("defaultManager"); -late final _sel_containerURLForSecurityApplicationGroupIdentifier_ = objc - .registerName("containerURLForSecurityApplicationGroupIdentifier:"); +late final _sel_containerURLForSecurityApplicationGroupIdentifier_ = objc.registerName( + "containerURLForSecurityApplicationGroupIdentifier:", +); /// NSFileManager -extension type NSFileManager._(objc.ObjCObject object$) - implements objc.ObjCObject, objc.NSObject { +extension type NSFileManager._(objc.ObjCObject object$) implements objc.ObjCObject, objc.NSObject { /// Constructs a [NSFileManager] that points to the same underlying object as [other]. NSFileManager.as(objc.ObjCObject other) : object$ = other { assert(isA(object$)); @@ -471,27 +409,19 @@ extension type NSFileManager._(objc.ObjCObject object$) } /// Returns whether [obj] is an instance of [NSFileManager]. - static bool isA(objc.ObjCObject obj) => _objc_msgSend_19nvye5( - obj.ref.pointer, - _sel_isKindOfClass_, - _class_NSFileManager, - ); + static bool isA(objc.ObjCObject obj) => + _objc_msgSend_19nvye5(obj.ref.pointer, _sel_isKindOfClass_, _class_NSFileManager); /// defaultManager static NSFileManager getDefaultManager() { - final $ret = _objc_msgSend_151sglz( - _class_NSFileManager, - _sel_defaultManager, - ); + final $ret = _objc_msgSend_151sglz(_class_NSFileManager, _sel_defaultManager); return NSFileManager.fromPointer($ret, retain: true, release: true); } } extension NSFileManager$Methods on NSFileManager { /// containerURLForSecurityApplicationGroupIdentifier: - objc.NSURL? containerURLForSecurityApplicationGroupIdentifier( - objc.NSString groupIdentifier, - ) { + objc.NSURL? containerURLForSecurityApplicationGroupIdentifier(objc.NSString groupIdentifier) { objc.checkOsVersionInternal( 'NSFileManager.containerURLForSecurityApplicationGroupIdentifier:', iOS: (false, (7, 0, 0)), @@ -502,8 +432,6 @@ extension NSFileManager$Methods on NSFileManager { _sel_containerURLForSecurityApplicationGroupIdentifier_, groupIdentifier.ref.pointer, ); - return $ret.address == 0 - ? null - : objc.NSURL.fromPointer($ret, retain: true, release: true); + return $ret.address == 0 ? null : objc.NSURL.fromPointer($ret, retain: true, release: true); } } diff --git a/packages/path_provider/path_provider_foundation/lib/src/path_provider_foundation_real.dart b/packages/path_provider/path_provider_foundation/lib/src/path_provider_foundation_real.dart index 8be02bac2f7e..22750c36319b 100644 --- a/packages/path_provider/path_provider_foundation/lib/src/path_provider_foundation_real.dart +++ b/packages/path_provider/path_provider_foundation/lib/src/path_provider_foundation_real.dart @@ -17,9 +17,7 @@ class PathProviderFoundation extends PathProviderPlatform { PathProviderFoundation({ @visibleForTesting PathProviderPlatformProvider? platform, @visibleForTesting FoundationFFI? ffiLib, - @visibleForTesting - NSURL? Function(NSString)? - containerURLForSecurityApplicationGroupIdentifier, + @visibleForTesting NSURL? Function(NSString)? containerURLForSecurityApplicationGroupIdentifier, }) : _platformProvider = platform ?? PathProviderPlatformProvider(), _ffiLib = ffiLib ?? _lib, _containerURLForSecurityApplicationGroupIdentifier = @@ -28,8 +26,7 @@ class PathProviderFoundation extends PathProviderPlatform { final PathProviderPlatformProvider _platformProvider; final FoundationFFI _ffiLib; - final NSURL? Function(NSString) - _containerURLForSecurityApplicationGroupIdentifier; + final NSURL? Function(NSString) _containerURLForSecurityApplicationGroupIdentifier; /// Registers this class as the default instance of [PathProviderPlatform]. static void registerWith() { @@ -43,9 +40,7 @@ class PathProviderFoundation extends PathProviderPlatform { @override Future getApplicationSupportPath() async { - final String? path = _getDirectoryPath( - NSSearchPathDirectory.NSApplicationSupportDirectory, - ); + final String? path = _getDirectoryPath(NSSearchPathDirectory.NSApplicationSupportDirectory); if (path != null) { // Ensure the directory exists before returning it, for consistency with // other platforms. @@ -66,9 +61,7 @@ class PathProviderFoundation extends PathProviderPlatform { @override Future getApplicationCachePath() async { - final String? path = _getDirectoryPath( - NSSearchPathDirectory.NSCachesDirectory, - ); + final String? path = _getDirectoryPath(NSSearchPathDirectory.NSCachesDirectory); if (path != null) { // Ensure the directory exists before returning it, for consistency with // other platforms. @@ -79,25 +72,17 @@ class PathProviderFoundation extends PathProviderPlatform { @override Future getExternalStoragePath() async { - throw UnsupportedError( - 'getExternalStoragePath is not supported on this platform', - ); + throw UnsupportedError('getExternalStoragePath is not supported on this platform'); } @override Future?> getExternalCachePaths() async { - throw UnsupportedError( - 'getExternalCachePaths is not supported on this platform', - ); + throw UnsupportedError('getExternalCachePaths is not supported on this platform'); } @override - Future?> getExternalStoragePaths({ - StorageDirectory? type, - }) async { - throw UnsupportedError( - 'getExternalStoragePaths is not supported on this platform', - ); + Future?> getExternalStoragePaths({StorageDirectory? type}) async { + throw UnsupportedError('getExternalStoragePaths is not supported on this platform'); } @override @@ -109,9 +94,7 @@ class PathProviderFoundation extends PathProviderPlatform { /// This is only supported for iOS. Future getContainerPath({required String appGroupIdentifier}) async { if (!_platformProvider.isIOS) { - throw UnsupportedError( - 'getContainerPath is not supported on this platform', - ); + throw UnsupportedError('getContainerPath is not supported on this platform'); } return _containerURLForSecurityApplicationGroupIdentifier( NSString(appGroupIdentifier), @@ -128,13 +111,10 @@ class PathProviderFoundation extends PathProviderPlatform { // plugin. if (directory == NSSearchPathDirectory.NSApplicationSupportDirectory || directory == NSSearchPathDirectory.NSCachesDirectory) { - final NSString? bundleIdentifier = - NSBundle.getMainBundle().bundleIdentifier; + final NSString? bundleIdentifier = NSBundle.getMainBundle().bundleIdentifier; if (bundleIdentifier != null) { final NSURL basePathURL = NSURL.fileURLWithPath(path); - path = basePathURL.URLByAppendingPathComponent( - bundleIdentifier, - )?.path; + path = basePathURL.URLByAppendingPathComponent(bundleIdentifier)?.path; } } } @@ -165,13 +145,12 @@ class PathProviderPlatformProvider { NSURL? _sharedNSFileManagerContainerURLForSecurityApplicationGroupIdentifier( NSString groupIdentifier, -) => NSFileManager.getDefaultManager() - .containerURLForSecurityApplicationGroupIdentifier(groupIdentifier); +) => NSFileManager.getDefaultManager().containerURLForSecurityApplicationGroupIdentifier( + groupIdentifier, +); final ffi.DynamicLibrary _dylib = () { - return ffi.DynamicLibrary.open( - '/System/Library/Frameworks/Foundation.framework/Foundation', - ); + return ffi.DynamicLibrary.open('/System/Library/Frameworks/Foundation.framework/Foundation'); }(); /// The bindings to the native functions in [_dylib]. diff --git a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart index 506e135768da..9d20a4e712cb 100644 --- a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart +++ b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart @@ -36,18 +36,12 @@ void main() { test('getExternalStoragePath throws', () async { final pathProvider = PathProviderFoundation(ffiLib: FakeFoundationFFI()); - expect( - pathProvider.getExternalStoragePath(), - throwsA(isUnsupportedError), - ); + expect(pathProvider.getExternalStoragePath(), throwsA(isUnsupportedError)); }); test('getExternalStoragePaths throws', () async { final pathProvider = PathProviderFoundation(ffiLib: FakeFoundationFFI()); - expect( - pathProvider.getExternalStoragePaths(), - throwsA(isUnsupportedError), - ); + expect(pathProvider.getExternalStoragePaths(), throwsA(isUnsupportedError)); }); test('getContainerPath throws on macOS', () async { diff --git a/packages/path_provider/path_provider_foundation/tool/ffigen.dart b/packages/path_provider/path_provider_foundation/tool/ffigen.dart index e07f848581e8..2ee645ec489d 100644 --- a/packages/path_provider/path_provider_foundation/tool/ffigen.dart +++ b/packages/path_provider/path_provider_foundation/tool/ffigen.dart @@ -26,10 +26,7 @@ void main() { objectiveC: ObjectiveC( interfaces: Interfaces( include: (Declaration declaration) { - return { - 'NSFileManager', - 'NSURL', - }.contains(declaration.originalName); + return {'NSFileManager', 'NSURL'}.contains(declaration.originalName); }, includeMember: (Declaration declaration, String member) { final String interfaceName = declaration.originalName; @@ -55,8 +52,6 @@ void main() { includeTransitive: false, ), ), - functions: Functions.includeSet({ - 'NSSearchPathForDirectoriesInDomains', - }), + functions: Functions.includeSet({'NSSearchPathForDirectoriesInDomains'}), ).generate(); } diff --git a/packages/path_provider/path_provider_linux/lib/src/get_application_id.dart b/packages/path_provider/path_provider_linux/lib/src/get_application_id.dart index 3c15c75c9b18..ec389db594f7 100644 --- a/packages/path_provider/path_provider_linux/lib/src/get_application_id.dart +++ b/packages/path_provider/path_provider_linux/lib/src/get_application_id.dart @@ -5,5 +5,4 @@ // getApplicationId() is implemented using FFI; export a stub for platforms // that don't support FFI (e.g., web) to avoid having transitive dependencies // break web compilation. -export 'get_application_id_stub.dart' - if (dart.library.ffi) 'get_application_id_real.dart'; +export 'get_application_id_stub.dart' if (dart.library.ffi) 'get_application_id_real.dart'; diff --git a/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart b/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart index c4cb828a626f..e6519e0c10aa 100644 --- a/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart +++ b/packages/path_provider/path_provider_linux/lib/src/get_application_id_real.dart @@ -49,10 +49,9 @@ class GioUtils { return nullptr; } final _GApplicationGetApplicationIdDart gApplicationGetApplicationId = _gio! - .lookupFunction< - _GApplicationGetApplicationIdC, - _GApplicationGetApplicationIdDart - >('g_application_get_application_id'); + .lookupFunction<_GApplicationGetApplicationIdC, _GApplicationGetApplicationIdDart>( + 'g_application_get_application_id', + ); return gApplicationGetApplicationId(app); } } diff --git a/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart b/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart index 20c4226cdac7..d8db0ac75ab8 100644 --- a/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart +++ b/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart @@ -40,9 +40,7 @@ class PathProviderLinux extends PathProviderPlatform { @override Future getTemporaryPath() { final String environmentTmpDir = _environment['TMPDIR'] ?? ''; - return Future.value( - environmentTmpDir.isEmpty ? '/tmp' : environmentTmpDir, - ); + return Future.value(environmentTmpDir.isEmpty ? '/tmp' : environmentTmpDir); } @override @@ -54,9 +52,7 @@ class PathProviderLinux extends PathProviderPlatform { // This plugin originally used the executable name as a directory. // Use that if it exists for backwards compatibility. - final legacyDirectory = Directory( - path.join(xdg.dataHome.path, await _getExecutableName()), - ); + final legacyDirectory = Directory(path.join(xdg.dataHome.path, await _getExecutableName())); if (legacyDirectory.existsSync()) { return legacyDirectory.path; } diff --git a/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart b/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart index a3aa825e4c1e..35f9392441fe 100644 --- a/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart +++ b/packages/path_provider/path_provider_linux/test/path_provider_linux_test.dart @@ -29,9 +29,7 @@ void main() { }); test('getTemporaryPath uses fallback if TMPDIR is unset', () async { - final PathProviderPlatform plugin = PathProviderLinux.private( - environment: {}, - ); + final PathProviderPlatform plugin = PathProviderLinux.private(environment: {}); expect(await plugin.getTemporaryPath(), '/tmp'); }); @@ -41,25 +39,19 @@ void main() { applicationId: 'com.example.Test', ); // Note this will fail if ${xdg.dataHome.path}/path_provider_linux_test_binary exists on the local filesystem. + expect(await plugin.getApplicationSupportPath(), '${xdg.dataHome.path}/com.example.Test'); + }); + + test('getApplicationSupportPath uses executable name if no application Id', () async { + final PathProviderPlatform plugin = PathProviderLinux.private( + executableName: 'path_provider_linux_test_binary', + ); expect( await plugin.getApplicationSupportPath(), - '${xdg.dataHome.path}/com.example.Test', + '${xdg.dataHome.path}/path_provider_linux_test_binary', ); }); - test( - 'getApplicationSupportPath uses executable name if no application Id', - () async { - final PathProviderPlatform plugin = PathProviderLinux.private( - executableName: 'path_provider_linux_test_binary', - ); - expect( - await plugin.getApplicationSupportPath(), - '${xdg.dataHome.path}/path_provider_linux_test_binary', - ); - }, - ); - test('getApplicationDocumentsPath', () async { final PathProviderPlatform plugin = PathProviderPlatform.instance; expect(await plugin.getApplicationDocumentsPath(), startsWith('/')); diff --git a/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart b/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart index 22a1676cc84b..ba2bba443adb 100644 --- a/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart +++ b/packages/path_provider/path_provider_platform_interface/lib/path_provider_platform_interface.dart @@ -45,9 +45,7 @@ abstract class PathProviderPlatform extends PlatformInterface { /// Path to a directory where the application may place application support /// files. Future getApplicationSupportPath() { - throw UnimplementedError( - 'getApplicationSupportPath() has not been implemented.', - ); + throw UnimplementedError('getApplicationSupportPath() has not been implemented.'); } /// Path to the directory where application can store files that are persistent, @@ -59,25 +57,19 @@ abstract class PathProviderPlatform extends PlatformInterface { /// Path to a directory where the application may place data that is /// user-generated, or that cannot otherwise be recreated by your application. Future getApplicationDocumentsPath() { - throw UnimplementedError( - 'getApplicationDocumentsPath() has not been implemented.', - ); + throw UnimplementedError('getApplicationDocumentsPath() has not been implemented.'); } /// Path to a directory where application specific cache data can be stored. Future getApplicationCachePath() { - throw UnimplementedError( - 'getApplicationCachePath() has not been implemented.', - ); + throw UnimplementedError('getApplicationCachePath() has not been implemented.'); } /// Path to a directory where the application may access top level storage. /// The current operating system should be determined before issuing this /// function call, as this functionality is only available on Android. Future getExternalStoragePath() { - throw UnimplementedError( - 'getExternalStoragePath() has not been implemented.', - ); + throw UnimplementedError('getExternalStoragePath() has not been implemented.'); } /// Paths to directories where application specific external cache data can be @@ -85,9 +77,7 @@ abstract class PathProviderPlatform extends PlatformInterface { /// partitions or SD cards. Phones may have multiple storage directories /// available. Future?> getExternalCachePaths() { - throw UnimplementedError( - 'getExternalCachePaths() has not been implemented.', - ); + throw UnimplementedError('getExternalCachePaths() has not been implemented.'); } /// Paths to directories where application specific data can be stored. @@ -98,9 +88,7 @@ abstract class PathProviderPlatform extends PlatformInterface { /// how this type translates to Android storage directories. StorageDirectory? type, }) { - throw UnimplementedError( - 'getExternalStoragePaths() has not been implemented.', - ); + throw UnimplementedError('getExternalStoragePaths() has not been implemented.'); } /// Path to the directory where downloaded files can be stored. diff --git a/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart b/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart index 286337243962..05c19e716309 100644 --- a/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart +++ b/packages/path_provider/path_provider_platform_interface/lib/src/method_channel_path_provider.dart @@ -12,9 +12,7 @@ import '../path_provider_platform_interface.dart'; class MethodChannelPathProvider extends PathProviderPlatform { /// The method channel used to interact with the native platform. @visibleForTesting - MethodChannel methodChannel = const MethodChannel( - 'plugins.flutter.io/path_provider', - ); + MethodChannel methodChannel = const MethodChannel('plugins.flutter.io/path_provider'); // Ideally, this property shouldn't exist, and each platform should // just implement the supported methods. Once all the platforms are @@ -49,9 +47,7 @@ class MethodChannelPathProvider extends PathProviderPlatform { @override Future getApplicationDocumentsPath() { - return methodChannel.invokeMethod( - 'getApplicationDocumentsDirectory', - ); + return methodChannel.invokeMethod('getApplicationDocumentsDirectory'); } @override @@ -72,15 +68,11 @@ class MethodChannelPathProvider extends PathProviderPlatform { if (!_platform.isAndroid) { throw UnsupportedError('Functionality only available on Android'); } - return methodChannel.invokeListMethod( - 'getExternalCacheDirectories', - ); + return methodChannel.invokeListMethod('getExternalCacheDirectories'); } @override - Future?> getExternalStoragePaths({ - StorageDirectory? type, - }) async { + Future?> getExternalStoragePaths({StorageDirectory? type}) async { if (!_platform.isAndroid) { throw UnsupportedError('Functionality only available on Android'); } diff --git a/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart b/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart index 77e199495979..0087a056cb73 100644 --- a/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart +++ b/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart @@ -26,32 +26,32 @@ void main() { setUp(() async { methodChannelPathProvider = MethodChannelPathProvider(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(methodChannelPathProvider.methodChannel, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - switch (methodCall.method) { - case 'getTemporaryDirectory': - return kTemporaryPath; - case 'getApplicationSupportDirectory': - return kApplicationSupportPath; - case 'getLibraryDirectory': - return kLibraryPath; - case 'getApplicationDocumentsDirectory': - return kApplicationDocumentsPath; - case 'getApplicationCacheDirectory': - return kApplicationCachePath; - case 'getExternalStorageDirectories': - return [kExternalStoragePaths]; - case 'getExternalCacheDirectories': - return [kExternalCachePaths]; - case 'getDownloadsDirectory': - return kDownloadsPath; - default: - return null; - } - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + methodChannelPathProvider.methodChannel, + (MethodCall methodCall) async { + log.add(methodCall); + switch (methodCall.method) { + case 'getTemporaryDirectory': + return kTemporaryPath; + case 'getApplicationSupportDirectory': + return kApplicationSupportPath; + case 'getLibraryDirectory': + return kLibraryPath; + case 'getApplicationDocumentsDirectory': + return kApplicationDocumentsPath; + case 'getApplicationCacheDirectory': + return kApplicationCachePath; + case 'getExternalStorageDirectories': + return [kExternalStoragePaths]; + case 'getExternalCacheDirectories': + return [kExternalCachePaths]; + case 'getDownloadsDirectory': + return kDownloadsPath; + default: + return null; + } + }, + ); }); setUp(() { @@ -66,18 +66,13 @@ void main() { test('getTemporaryPath', () async { final String? path = await methodChannelPathProvider.getTemporaryPath(); - expect(log, [ - isMethodCall('getTemporaryDirectory', arguments: null), - ]); + expect(log, [isMethodCall('getTemporaryDirectory', arguments: null)]); expect(path, kTemporaryPath); }); test('getApplicationSupportPath', () async { - final String? path = await methodChannelPathProvider - .getApplicationSupportPath(); - expect(log, [ - isMethodCall('getApplicationSupportDirectory', arguments: null), - ]); + final String? path = await methodChannelPathProvider.getApplicationSupportPath(); + expect(log, [isMethodCall('getApplicationSupportDirectory', arguments: null)]); expect(path, kApplicationSupportPath); }); @@ -91,61 +86,42 @@ void main() { }); test('getLibraryPath iOS succeeds', () async { - methodChannelPathProvider.setMockPathProviderPlatform( - FakePlatform(operatingSystem: 'ios'), - ); + methodChannelPathProvider.setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); final String? path = await methodChannelPathProvider.getLibraryPath(); - expect(log, [ - isMethodCall('getLibraryDirectory', arguments: null), - ]); + expect(log, [isMethodCall('getLibraryDirectory', arguments: null)]); expect(path, kLibraryPath); }); test('getLibraryPath macOS succeeds', () async { - methodChannelPathProvider.setMockPathProviderPlatform( - FakePlatform(operatingSystem: 'macos'), - ); + methodChannelPathProvider.setMockPathProviderPlatform(FakePlatform(operatingSystem: 'macos')); final String? path = await methodChannelPathProvider.getLibraryPath(); - expect(log, [ - isMethodCall('getLibraryDirectory', arguments: null), - ]); + expect(log, [isMethodCall('getLibraryDirectory', arguments: null)]); expect(path, kLibraryPath); }); test('getApplicationDocumentsPath', () async { - final String? path = await methodChannelPathProvider - .getApplicationDocumentsPath(); - expect(log, [ - isMethodCall('getApplicationDocumentsDirectory', arguments: null), - ]); + final String? path = await methodChannelPathProvider.getApplicationDocumentsPath(); + expect(log, [isMethodCall('getApplicationDocumentsDirectory', arguments: null)]); expect(path, kApplicationDocumentsPath); }); test('getApplicationCachePath succeeds', () async { - final String? result = await methodChannelPathProvider - .getApplicationCachePath(); - expect(log, [ - isMethodCall('getApplicationCacheDirectory', arguments: null), - ]); + final String? result = await methodChannelPathProvider.getApplicationCachePath(); + expect(log, [isMethodCall('getApplicationCacheDirectory', arguments: null)]); expect(result, kApplicationCachePath); }); test('getExternalCachePaths android succeeds', () async { - final List? result = await methodChannelPathProvider - .getExternalCachePaths(); - expect(log, [ - isMethodCall('getExternalCacheDirectories', arguments: null), - ]); + final List? result = await methodChannelPathProvider.getExternalCachePaths(); + expect(log, [isMethodCall('getExternalCacheDirectories', arguments: null)]); expect(result!.length, 1); expect(result.first, kExternalCachePaths); }); test('getExternalCachePaths non-android fails', () async { - methodChannelPathProvider.setMockPathProviderPlatform( - FakePlatform(operatingSystem: 'ios'), - ); + methodChannelPathProvider.setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); try { await methodChannelPathProvider.getExternalCachePaths(); @@ -157,8 +133,9 @@ void main() { for (final type in [null, ...StorageDirectory.values]) { test('getExternalStoragePaths (type: $type) android succeeds', () async { - final List? result = await methodChannelPathProvider - .getExternalStoragePaths(type: type); + final List? result = await methodChannelPathProvider.getExternalStoragePaths( + type: type, + ); expect(log, [ isMethodCall( 'getExternalStorageDirectories', @@ -171,9 +148,7 @@ void main() { }); test('getExternalStoragePaths (type: $type) non-android fails', () async { - methodChannelPathProvider.setMockPathProviderPlatform( - FakePlatform(operatingSystem: 'ios'), - ); + methodChannelPathProvider.setMockPathProviderPlatform(FakePlatform(operatingSystem: 'ios')); try { await methodChannelPathProvider.getExternalStoragePaths(); @@ -185,13 +160,9 @@ void main() { } // end of for-loop test('getDownloadsPath macos succeeds', () async { - methodChannelPathProvider.setMockPathProviderPlatform( - FakePlatform(operatingSystem: 'macos'), - ); + methodChannelPathProvider.setMockPathProviderPlatform(FakePlatform(operatingSystem: 'macos')); final String? result = await methodChannelPathProvider.getDownloadsPath(); - expect(log, [ - isMethodCall('getDownloadsDirectory', arguments: null), - ]); + expect(log, [isMethodCall('getDownloadsDirectory', arguments: null)]); expect(result, kDownloadsPath); }); diff --git a/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart b/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart index f38d94ee94b5..c60b11425fa3 100644 --- a/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart +++ b/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart @@ -17,10 +17,7 @@ void main() { test('getApplicationCachePath throws unimplemented error', () { final pathProviderPlatform = ExtendsPathProviderPlatform(); - expect( - () => pathProviderPlatform.getApplicationCachePath(), - throwsUnimplementedError, - ); + expect(() => pathProviderPlatform.getApplicationCachePath(), throwsUnimplementedError); }); }); } diff --git a/packages/path_provider/path_provider_windows/lib/src/folders.dart b/packages/path_provider/path_provider_windows/lib/src/folders.dart index e3820dbb2ec1..877e5e30c419 100644 --- a/packages/path_provider/path_provider_windows/lib/src/folders.dart +++ b/packages/path_provider/path_provider_windows/lib/src/folders.dart @@ -24,8 +24,7 @@ class WindowsKnownFolder { /// The file system directory that contains administrative tools for all users /// of the computer. - static String get CommonAdminTools => - '{D0384E7D-BAC3-4797-8F14-CBA229B392B5}'; + static String get CommonAdminTools => '{D0384E7D-BAC3-4797-8F14-CBA229B392B5}'; /// The file system directory that contains the directories for the common /// program groups that appear on the Start menu for all users. A typical path @@ -54,12 +53,10 @@ class WindowsKnownFolder { /// The virtual folder that represents Network Connections, that contains /// network and dial-up connections. - static String get ConnectionsFolder => - '{6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD}'; + static String get ConnectionsFolder => '{6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD}'; /// The virtual folder that contains icons for the Control Panel applications. - static String get ControlPanelFolder => - '{82A74AEB-AEB4-465C-A014-D097EE346D63}'; + static String get ControlPanelFolder => '{82A74AEB-AEB4-465C-A014-D097EE346D63}'; /// The file system directory that serves as a common repository for Internet /// cookies. A typical path is C:\Documents and Settings\username\Cookies. @@ -144,19 +141,16 @@ class WindowsKnownFolder { /// The common Program Files folder. A typical path is C:\Program /// Files\Common. - static String get ProgramFilesCommon => - '{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}'; + static String get ProgramFilesCommon => '{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}'; /// On 64-bit systems, a link to the common Program Files folder. A typical path is /// C:\Program Files\Common Files. - static String get ProgramFilesCommonX64 => - '{6365D5A7-0F0D-45e5-87F6-0DA56B6A4F7D}'; + static String get ProgramFilesCommonX64 => '{6365D5A7-0F0D-45e5-87F6-0DA56B6A4F7D}'; /// On 64-bit systems, a link to the 32-bit common Program Files folder. A /// typical path is C:\Program Files (x86)\Common Files. On 32-bit systems, a /// link to the Common Program Files folder. - static String get ProgramFilesCommonX86 => - '{DE974D24-D9C6-4D3E-BF91-F4455120B917}'; + static String get ProgramFilesCommonX86 => '{DE974D24-D9C6-4D3E-BF91-F4455120B917}'; /// On 64-bit systems, a link to the Program Files folder. A typical path is /// C:\Program Files. @@ -201,8 +195,7 @@ class WindowsKnownFolder { static String get Recent => '{AE50C081-EBD2-438A-8655-8A092E34987A}'; /// The virtual folder that contains the objects in the user's Recycle Bin. - static String get RecycleBinFolder => - '{B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC}'; + static String get RecycleBinFolder => '{B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC}'; /// The file system directory that contains resource data. A typical path is /// C:\Windows\Resources. diff --git a/packages/path_provider/path_provider_windows/lib/src/guid.dart b/packages/path_provider/path_provider_windows/lib/src/guid.dart index c240b8098061..a90cb0950319 100644 --- a/packages/path_provider/path_provider_windows/lib/src/guid.dart +++ b/packages/path_provider/path_provider_windows/lib/src/guid.dart @@ -36,10 +36,7 @@ base class GUID extends Struct { } final bytes = ByteData(16); for (var i = 0; i < 16; ++i) { - bytes.setUint8( - i, - int.parse(hexOnly.substring(i * 2, i * 2 + 2), radix: 16), - ); + bytes.setUint8(i, int.parse(hexOnly.substring(i * 2, i * 2 + 2), radix: 16)); } data1 = bytes.getInt32(0); data2 = bytes.getInt16(4); diff --git a/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart b/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart index e82bafc6332d..f2dfce9b5956 100644 --- a/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart +++ b/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart @@ -50,8 +50,7 @@ class VersionInfoQuerier { if (versionInfo == null) { return null; } - final Pointer keyPath = '\\StringFileInfo\\$language$encoding\\$key' - .toNativeUtf16(); + final Pointer keyPath = '\\StringFileInfo\\$language$encoding\\$key'.toNativeUtf16(); final Pointer length = calloc(); final Pointer> valueAddress = calloc>(); try { @@ -120,8 +119,7 @@ class PathProviderWindows extends PathProviderPlatform { _createApplicationSubdirectory(WindowsKnownFolder.RoamingAppData); @override - Future getApplicationDocumentsPath() => - getPath(WindowsKnownFolder.Documents); + Future getApplicationDocumentsPath() => getPath(WindowsKnownFolder.Documents); @override Future getApplicationCachePath() => @@ -139,12 +137,7 @@ class PathProviderWindows extends PathProviderPlatform { final Pointer knownFolderID = calloc()..ref.parse(folderID); try { - final int hr = SHGetKnownFolderPath( - knownFolderID, - KF_FLAG_DEFAULT, - NULL, - pathPtrPtr, - ); + final int hr = SHGetKnownFolderPath(knownFolderID, KF_FLAG_DEFAULT, NULL, pathPtrPtr); if (FAILED(hr)) { if (hr == E_INVALIDARG || hr == E_FAIL) { @@ -189,18 +182,12 @@ class PathProviderWindows extends PathProviderPlatform { String? companyName; String? productName; - final Pointer moduleNameBuffer = calloc( - MAX_PATH + 1, - ).cast(); + final Pointer moduleNameBuffer = calloc(MAX_PATH + 1).cast(); final Pointer unused = calloc(); Pointer? infoBuffer; try { // Get the module name. - final int moduleNameLength = GetModuleFileName( - 0, - moduleNameBuffer, - MAX_PATH, - ); + final int moduleNameLength = GetModuleFileName(0, moduleNameBuffer, MAX_PATH); if (moduleNameLength == 0) { final int error = GetLastError(); throw _createWin32Exception(error); @@ -210,27 +197,18 @@ class PathProviderWindows extends PathProviderPlatform { final int infoSize = GetFileVersionInfoSize(moduleNameBuffer, unused); if (infoSize != 0) { infoBuffer = calloc(infoSize); - if (GetFileVersionInfo(moduleNameBuffer, 0, infoSize, infoBuffer) == - 0) { + if (GetFileVersionInfo(moduleNameBuffer, 0, infoSize, infoBuffer) == 0) { calloc.free(infoBuffer); infoBuffer = null; } } - companyName = _sanitizedDirectoryName( - _getStringValue(infoBuffer, 'CompanyName'), - ); - productName = _sanitizedDirectoryName( - _getStringValue(infoBuffer, 'ProductName'), - ); + companyName = _sanitizedDirectoryName(_getStringValue(infoBuffer, 'CompanyName')); + productName = _sanitizedDirectoryName(_getStringValue(infoBuffer, 'ProductName')); // If there was no product name, use the executable name. - productName ??= path.basenameWithoutExtension( - moduleNameBuffer.toDartString(), - ); + productName ??= path.basenameWithoutExtension(moduleNameBuffer.toDartString()); - return companyName != null - ? path.join(companyName, productName) - : productName; + return companyName != null ? path.join(companyName, productName) : productName; } finally { calloc.free(moduleNameBuffer); calloc.free(unused); @@ -267,9 +245,7 @@ class PathProviderWindows extends PathProviderPlatform { if (baseDir == null) { return null; } - final directory = Directory( - path.join(baseDir, _getApplicationSpecificSubdirectory()), - ); + final directory = Directory(path.join(baseDir, _getApplicationSpecificSubdirectory())); // Ensure that the directory exists if possible, since it will on other // platforms. If the name is longer than MAXPATH, creating will fail, so // skip that step; it's up to the client to decide what to do with the path diff --git a/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart b/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart index 01d6ffc522b0..85f603fe17b4 100644 --- a/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart +++ b/packages/path_provider/path_provider_windows/lib/src/win32_wrappers.dart @@ -52,38 +52,34 @@ final DynamicLibrary _dllVersion = DynamicLibrary.open('version.dll'); final DynamicLibrary _dllShell32 = DynamicLibrary.open('shell32.dll'); // https://learn.microsoft.com/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath -typedef _FFITypeSHGetKnownFolderPath = - HRESULT Function(Pointer, DWORD, HANDLE, PWSTR); -typedef FFITypeSHGetKnownFolderPathDart = - int Function(Pointer, int, int, Pointer>); +typedef _FFITypeSHGetKnownFolderPath = HRESULT Function(Pointer, DWORD, HANDLE, PWSTR); +typedef FFITypeSHGetKnownFolderPathDart = int Function( + Pointer, + int, + int, + Pointer>, +); // ignore: non_constant_identifier_names final FFITypeSHGetKnownFolderPathDart SHGetKnownFolderPath = _dllShell32 - .lookupFunction< - _FFITypeSHGetKnownFolderPath, - FFITypeSHGetKnownFolderPathDart - >('SHGetKnownFolderPath'); + .lookupFunction<_FFITypeSHGetKnownFolderPath, FFITypeSHGetKnownFolderPathDart>( + 'SHGetKnownFolderPath', + ); // https://learn.microsoft.com/windows/win32/api/winver/nf-winver-getfileversioninfow -typedef _FFITypeGetFileVersionInfoW = - BOOL Function(LPCWSTR, DWORD, DWORD, LPVOID); -typedef FFITypeGetFileVersionInfoW = - int Function(Pointer, int, int, Pointer); +typedef _FFITypeGetFileVersionInfoW = BOOL Function(LPCWSTR, DWORD, DWORD, LPVOID); +typedef FFITypeGetFileVersionInfoW = int Function(Pointer, int, int, Pointer); // ignore: non_constant_identifier_names final FFITypeGetFileVersionInfoW GetFileVersionInfo = _dllVersion - .lookupFunction<_FFITypeGetFileVersionInfoW, FFITypeGetFileVersionInfoW>( - 'GetFileVersionInfoW', - ); + .lookupFunction<_FFITypeGetFileVersionInfoW, FFITypeGetFileVersionInfoW>('GetFileVersionInfoW'); // https://learn.microsoft.com/windows/win32/api/winver/nf-winver-getfileversioninfosizew typedef _FFITypeGetFileVersionInfoSizeW = DWORD Function(LPCWSTR, LPDWORD); -typedef FFITypeGetFileVersionInfoSizeW = - int Function(Pointer, Pointer); +typedef FFITypeGetFileVersionInfoSizeW = int Function(Pointer, Pointer); // ignore: non_constant_identifier_names final FFITypeGetFileVersionInfoSizeW GetFileVersionInfoSize = _dllVersion - .lookupFunction< - _FFITypeGetFileVersionInfoSizeW, - FFITypeGetFileVersionInfoSizeW - >('GetFileVersionInfoSizeW'); + .lookupFunction<_FFITypeGetFileVersionInfoSizeW, FFITypeGetFileVersionInfoSizeW>( + 'GetFileVersionInfoSizeW', + ); // https://learn.microsoft.com/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror typedef _FFITypeGetLastError = DWORD Function(); @@ -97,24 +93,19 @@ typedef _FFITypeGetModuleFileNameW = DWORD Function(HMODULE, LPWSTR, DWORD); typedef FFITypeGetModuleFileNameW = int Function(int, Pointer, int); // ignore: non_constant_identifier_names final FFITypeGetModuleFileNameW GetModuleFileName = _dllKernel32 - .lookupFunction<_FFITypeGetModuleFileNameW, FFITypeGetModuleFileNameW>( - 'GetModuleFileNameW', - ); + .lookupFunction<_FFITypeGetModuleFileNameW, FFITypeGetModuleFileNameW>('GetModuleFileNameW'); // https://learn.microsoft.com/windows/win32/api/winver/nf-winver-verqueryvaluew typedef _FFITypeVerQueryValueW = BOOL Function(LPCVOID, LPCWSTR, LPVOID, PUINT); -typedef FFITypeVerQueryValueW = - int Function( - Pointer, - Pointer, - Pointer, - Pointer, - ); +typedef FFITypeVerQueryValueW = int Function( + Pointer, + Pointer, + Pointer, + Pointer, +); // ignore: non_constant_identifier_names final FFITypeVerQueryValueW VerQueryValue = _dllVersion - .lookupFunction<_FFITypeVerQueryValueW, FFITypeVerQueryValueW>( - 'VerQueryValueW', - ); + .lookupFunction<_FFITypeVerQueryValueW, FFITypeVerQueryValueW>('VerQueryValueW'); // https://learn.microsoft.com/windows/win32/api/fileapi/nf-fileapi-gettemppathw typedef _FFITypeGetTempPathW = DWORD Function(DWORD, LPWSTR); diff --git a/packages/path_provider/path_provider_windows/test/guid_test.dart b/packages/path_provider/path_provider_windows/test/guid_test.dart index dbb64d407ca6..c7daa02f25d7 100644 --- a/packages/path_provider/path_provider_windows/test/guid_test.dart +++ b/packages/path_provider/path_provider_windows/test/guid_test.dart @@ -11,8 +11,7 @@ import 'package:path_provider_windows/src/guid.dart'; void main() { test('has correct byte representation', () async { - final Pointer guid = calloc() - ..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); + final Pointer guid = calloc()..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); final data = ByteData(16) ..setInt32(0, guid.ref.data1, Endian.little) ..setInt16(4, guid.ref.data2, Endian.little) @@ -39,10 +38,8 @@ void main() { }); test('handles alternate forms', () async { - final Pointer guid1 = calloc() - ..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); - final Pointer guid2 = calloc() - ..ref.parse('00112233445566778899AABBCCDDEEFF'); + final Pointer guid1 = calloc()..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); + final Pointer guid2 = calloc()..ref.parse('00112233445566778899AABBCCDDEEFF'); expect(guid1.ref.data1, guid2.ref.data1); expect(guid1.ref.data2, guid2.ref.data2); diff --git a/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart b/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart index 5ef6c87299a6..74bb2492b3f3 100644 --- a/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart +++ b/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart @@ -50,9 +50,49 @@ void main() { }, skip: !Platform.isWindows); test('getApplicationSupportPath with no version info', () async { + final pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({}); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, contains(r'C:\')); + expect(path, contains(r'AppData')); + // The last path component should be the executable name. + expect(path, endsWith(r'flutter_tester')); + }, skip: !Platform.isWindows); + + test('getApplicationSupportPath with full version info in CP1252', () async { + final pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ + 'CompanyName': 'A Company', + 'ProductName': 'Amazing App', + }, encoding: encodingCP1252); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, isNotNull); + if (path != null) { + expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); + expect(Directory(path).existsSync(), isTrue); + } + }, skip: !Platform.isWindows); + + test('getApplicationSupportPath with full version info in Unicode', () async { + final pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ + 'CompanyName': 'A Company', + 'ProductName': 'Amazing App', + }); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, isNotNull); + if (path != null) { + expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); + expect(Directory(path).existsSync(), isTrue); + } + }, skip: !Platform.isWindows); + + test('getApplicationSupportPath with full version info in Unsupported Encoding', () async { final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier( - {}, + {'CompanyName': 'A Company', 'ProductName': 'Amazing App'}, + language: '0000', + encoding: '0000', ); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, contains(r'C:\')); @@ -61,63 +101,6 @@ void main() { expect(path, endsWith(r'flutter_tester')); }, skip: !Platform.isWindows); - test( - 'getApplicationSupportPath with full version info in CP1252', - () async { - final pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ - 'CompanyName': 'A Company', - 'ProductName': 'Amazing App', - }, encoding: encodingCP1252); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, isNotNull); - if (path != null) { - expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); - expect(Directory(path).existsSync(), isTrue); - } - }, - skip: !Platform.isWindows, - ); - - test( - 'getApplicationSupportPath with full version info in Unicode', - () async { - final pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ - 'CompanyName': 'A Company', - 'ProductName': 'Amazing App', - }); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, isNotNull); - if (path != null) { - expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); - expect(Directory(path).existsSync(), isTrue); - } - }, - skip: !Platform.isWindows, - ); - - test( - 'getApplicationSupportPath with full version info in Unsupported Encoding', - () async { - final pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier( - { - 'CompanyName': 'A Company', - 'ProductName': 'Amazing App', - }, - language: '0000', - encoding: '0000', - ); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, contains(r'C:\')); - expect(path, contains(r'AppData')); - // The last path component should be the executable name. - expect(path, endsWith(r'flutter_tester')); - }, - skip: !Platform.isWindows, - ); - test('getApplicationSupportPath with missing company', () async { final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ @@ -140,33 +123,24 @@ void main() { final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { - expect( - path, - endsWith( - r'AppData\Roaming\A _Bad_ Company_ Name\A__Terrible__App__Name', - ), - ); + expect(path, endsWith(r'AppData\Roaming\A _Bad_ Company_ Name\A__Terrible__App__Name')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); - test( - 'getApplicationSupportPath with a completely invalid company', - () async { - final pathProvider = PathProviderWindows(); - pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ - 'CompanyName': r'..', - 'ProductName': r'Amazing App', - }); - final String? path = await pathProvider.getApplicationSupportPath(); - expect(path, isNotNull); - if (path != null) { - expect(path, endsWith(r'AppData\Roaming\Amazing App')); - expect(Directory(path).existsSync(), isTrue); - } - }, - skip: !Platform.isWindows, - ); + test('getApplicationSupportPath with a completely invalid company', () async { + final pathProvider = PathProviderWindows(); + pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ + 'CompanyName': r'..', + 'ProductName': r'Amazing App', + }); + final String? path = await pathProvider.getApplicationSupportPath(); + expect(path, isNotNull); + if (path != null) { + expect(path, endsWith(r'AppData\Roaming\Amazing App')); + expect(Directory(path).existsSync(), isTrue); + } + }, skip: !Platform.isWindows); test('getApplicationSupportPath with very long app name', () async { final pathProvider = PathProviderWindows(); diff --git a/packages/pigeon/example/app/lib/main.dart b/packages/pigeon/example/app/lib/main.dart index eeb193aa1f6a..0af0dd738335 100644 --- a/packages/pigeon/example/app/lib/main.dart +++ b/packages/pigeon/example/app/lib/main.dart @@ -19,6 +19,7 @@ class _ExampleFlutterApi implements MessageFlutterApi { return aString ?? ''; } } + // #enddocregion main-dart-flutter void main() { @@ -86,6 +87,7 @@ class _MyHomePageState extends State { return Future(() => true); } } + // #enddocregion main-dart // #docregion main-dart-event @@ -102,6 +104,7 @@ class _MyHomePageState extends State { } } } + // #enddocregion main-dart-event @override @@ -137,14 +140,13 @@ class _MyHomePageState extends State { if (Platform.isAndroid || Platform.isIOS) StreamBuilder( stream: getEventStream(), - builder: - (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.hasData) { - return Text(snapshot.data ?? ''); - } else { - return const CircularProgressIndicator(); - } - }, + builder: (BuildContext context, AsyncSnapshot snapshot) { + if (snapshot.hasData) { + return Text(snapshot.data ?? ''); + } else { + return const CircularProgressIndicator(); + } + }, ) else const Text('event channels are not supported on this platform'), diff --git a/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart b/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart index 8fdd1c22e5c5..a7e34a0ed60a 100644 --- a/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart +++ b/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart @@ -24,9 +24,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -178,9 +176,7 @@ class _PigeonCodec extends StandardMessageCodec { } } -const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( - _PigeonCodec(), -); +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec(_PigeonCodec()); Stream streamEvents({String instanceName = ''}) { if (instanceName.isNotEmpty) { diff --git a/packages/pigeon/example/app/lib/src/messages.g.dart b/packages/pigeon/example/app/lib/src/messages.g.dart index 699368ba5b3d..2a200ae7a8b1 100644 --- a/packages/pigeon/example/app/lib/src/messages.g.dart +++ b/packages/pigeon/example/app/lib/src/messages.g.dart @@ -37,11 +37,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -63,9 +59,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -117,12 +111,7 @@ int _deepHash(Object? value) { enum Code { one, two } class MessageData { - MessageData({ - this.name, - this.description, - required this.code, - required this.data, - }); + MessageData({this.name, this.description, required this.code, required this.data}); String? name; @@ -206,13 +195,11 @@ class ExampleHostApi { /// Constructor for [ExampleHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - ExampleHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + ExampleHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -246,9 +233,7 @@ class ExampleHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [a, b], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([a, b]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -267,9 +252,7 @@ class ExampleHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [message], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([message]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -291,9 +274,7 @@ abstract class MessageFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod$messageChannelSuffix', diff --git a/packages/pigeon/example/app/pigeons/event_channel_messages.dart b/packages/pigeon/example/app/pigeons/event_channel_messages.dart index c786e8204f9a..39e7b0faf4ab 100644 --- a/packages/pigeon/example/app/pigeons/event_channel_messages.dart +++ b/packages/pigeon/example/app/pigeons/event_channel_messages.dart @@ -30,6 +30,7 @@ class StringEvent extends PlatformEvent { StringEvent(this.data); String data; } + // #enddocregion sealed-definitions // #docregion event-definitions diff --git a/packages/pigeon/example/app/pigeons/messages.dart b/packages/pigeon/example/app/pigeons/messages.dart index 7e3d08a799e2..71aa704f22bf 100644 --- a/packages/pigeon/example/app/pigeons/messages.dart +++ b/packages/pigeon/example/app/pigeons/messages.dart @@ -15,8 +15,7 @@ import 'package:pigeon/pigeon.dart'; gobjectHeaderOut: 'linux/messages.g.h', gobjectSourceOut: 'linux/messages.g.cc', gobjectOptions: GObjectOptions(), - kotlinOut: - 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt', + kotlinOut: 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt', kotlinOptions: KotlinOptions(), javaOut: 'android/app/src/main/java/io/flutter/plugins/Messages.java', javaOptions: JavaOptions(), @@ -54,6 +53,7 @@ abstract class ExampleHostApi { @async bool sendMessage(MessageData message); } + // #enddocregion host-definitions // #docregion flutter-definitions diff --git a/packages/pigeon/lib/src/ast.dart b/packages/pigeon/lib/src/ast.dart index aba0e0891cae..29e5c34cfd4d 100644 --- a/packages/pigeon/lib/src/ast.dart +++ b/packages/pigeon/lib/src/ast.dart @@ -6,11 +6,9 @@ import 'package:collection/collection.dart' show ListEquality; import 'package:meta/meta.dart'; import 'generator_tools.dart'; -import 'kotlin/kotlin_generator.dart' - show KotlinEventChannelOptions, KotlinProxyApiOptions; +import 'kotlin/kotlin_generator.dart' show KotlinEventChannelOptions, KotlinProxyApiOptions; import 'pigeon_lib.dart'; -import 'swift/swift_generator.dart' - show SwiftEventChannelOptions, SwiftProxyApiOptions; +import 'swift/swift_generator.dart' show SwiftEventChannelOptions, SwiftProxyApiOptions; typedef _ListEquals = bool Function(List, List); @@ -91,12 +89,8 @@ class Method extends Node { @override String toString() { - final objcSelectorStr = objcSelector.isEmpty - ? '' - : ' objcSelector:$objcSelector'; - final swiftFunctionStr = swiftFunction.isEmpty - ? '' - : ' swiftFunction:$swiftFunction'; + final objcSelectorStr = objcSelector.isEmpty ? '' : ' objcSelector:$objcSelector'; + final swiftFunctionStr = swiftFunction.isEmpty ? '' : ' swiftFunction:$swiftFunction'; return '(Method name:$name returnType:$returnType parameters:$parameters isAsynchronous:$isAsynchronous$objcSelectorStr$swiftFunctionStr documentationComments:$documentationComments)'; } } @@ -182,14 +176,12 @@ class AstProxyApi extends Api { /// All fields that are attached. /// /// See [attached]. - Iterable get attachedFields => - fields.where((ApiField field) => field.isAttached); + Iterable get attachedFields => fields.where((ApiField field) => field.isAttached); /// All fields that are not attached. /// /// See [attached]. - Iterable get unattachedFields => - fields.where((ApiField field) => !field.isAttached); + Iterable get unattachedFields => fields.where((ApiField field) => !field.isAttached); /// A list of [AstProxyApi]s where each is the [superClass] of the one /// proceeding it. @@ -205,9 +197,7 @@ class AstProxyApi extends Api { final superClassChain = []; if (superClass != null && !superClass!.isProxyApi) { - throw ArgumentError( - 'Could not find a ProxyApi for super class: ${superClass!.baseName}', - ); + throw ArgumentError('Could not find a ProxyApi for super class: ${superClass!.baseName}'); } AstProxyApi? currentProxyApi = superClass?.associatedProxyApi; @@ -221,8 +211,7 @@ class AstProxyApi extends Api { superClassChain.add(currentProxyApi); - if (currentProxyApi.superClass != null && - !currentProxyApi.superClass!.isProxyApi) { + if (currentProxyApi.superClass != null && !currentProxyApi.superClass!.isProxyApi) { throw ArgumentError( 'Could not find a ProxyApi for super class: ' '${currentProxyApi.superClass!.baseName}', @@ -250,14 +239,12 @@ class AstProxyApi extends Api { /// Returns a record for each Flutter method inherited from [superClass]. /// /// This also includes methods that the [superClass] inherits from interfaces. - Iterable<(Method, AstProxyApi)> - flutterMethodsFromSuperClassesWithApis() sync* { + Iterable<(Method, AstProxyApi)> flutterMethodsFromSuperClassesWithApis() sync* { for (final AstProxyApi proxyApi in allSuperClasses().toList().reversed) { yield* proxyApi.flutterMethods.map((Method method) => (method, proxyApi)); } if (superClass != null) { - final Set interfaceApisFromSuperClasses = superClass! - .associatedProxyApi! + final Set interfaceApisFromSuperClasses = superClass!.associatedProxyApi! ._recursiveFindAllInterfaceApis(); for (final proxyApi in interfaceApisFromSuperClasses) { yield* proxyApi.methods.map((Method method) => (method, proxyApi)); @@ -267,9 +254,7 @@ class AstProxyApi extends Api { /// All methods inherited from interfaces. Iterable flutterMethodsFromInterfaces() sync* { - yield* flutterMethodsFromInterfacesWithApis().map( - ((Method, AstProxyApi) method) => method.$1, - ); + yield* flutterMethodsFromInterfacesWithApis().map(((Method, AstProxyApi) method) => method.$1); } /// A list of Flutter methods inherited from [superClass]. @@ -299,14 +284,11 @@ class AstProxyApi extends Api { /// Whether the Dart proxy class makes any message calls to the native type /// API. bool hasAnyHostMessageCalls() => - constructors.isNotEmpty || - attachedFields.isNotEmpty || - hostMethods.isNotEmpty; + constructors.isNotEmpty || attachedFields.isNotEmpty || hostMethods.isNotEmpty; /// Whether the native type API makes any message calls to the Dart proxy /// class or calls to instantiate a Dart proxy class instance. - bool hasAnyFlutterMessageCalls() => - hasCallbackConstructor() || flutterMethods.isNotEmpty; + bool hasAnyFlutterMessageCalls() => hasCallbackConstructor() || flutterMethods.isNotEmpty; /// Whether the native type API will have methods that need to be implemented. bool hasMethodsRequiringImplementation() => @@ -325,13 +307,9 @@ class AstProxyApi extends Api { allInterfaces.addAll( interfaces.map((TypeDeclaration type) { if (!type.isProxyApi) { - throw ArgumentError( - 'Could not find a valid ProxyApi for an interface: $type', - ); + throw ArgumentError('Could not find a valid ProxyApi for an interface: $type'); } else if (seenApis.contains(type.associatedProxyApi)) { - throw ArgumentError( - 'A ProxyApi cannot be a super class of itself: ${type.baseName}', - ); + throw ArgumentError('A ProxyApi cannot be a super class of itself: ${type.baseName}'); } return type.associatedProxyApi!; }), @@ -342,9 +320,7 @@ class AstProxyApi extends Api { final newSeenApis = {...seenApis, this}; for (final interfaceApi in {...allInterfaces}) { - allInterfaces.addAll( - interfaceApi._recursiveFindAllInterfaceApis(newSeenApis), - ); + allInterfaces.addAll(interfaceApi._recursiveFindAllInterfaceApis(newSeenApis)); } return allInterfaces; @@ -390,16 +366,11 @@ class Constructor extends Method { super.offset, super.swiftFunction = '', super.documentationComments = const [], - }) : super( - returnType: const TypeDeclaration.voidDeclaration(), - location: ApiLocation.host, - ); + }) : super(returnType: const TypeDeclaration.voidDeclaration(), location: ApiLocation.host); @override String toString() { - final swiftFunctionStr = swiftFunction.isEmpty - ? '' - : ' swiftFunction:$swiftFunction'; + final swiftFunctionStr = swiftFunction.isEmpty ? '' : ' swiftFunction:$swiftFunction'; return '(Constructor name:$name parameters:$parameters $swiftFunctionStr documentationComments:$documentationComments)'; } } @@ -449,11 +420,7 @@ class ApiField extends NamedType { /// Represents a collection of [Method]s. sealed class Api extends Node { /// Parametric constructor for [Api]. - Api({ - required this.name, - required this.methods, - this.documentationComments = const [], - }); + Api({required this.name, required this.methods, this.documentationComments = const []}); /// The name of the API. String name; @@ -602,9 +569,7 @@ class TypeDeclaration { @override String toString() { - final typeArgumentsStr = typeArguments.isEmpty - ? '' - : ' typeArguments:$typeArguments'; + final typeArgumentsStr = typeArguments.isEmpty ? '' : ' typeArguments:$typeArguments'; return '(TypeDeclaration baseName:$baseName isNullable:$isNullable$typeArgumentsStr isEnum:$isEnum isClass:$isClass isProxyApi:$isProxyApi)'; } } @@ -778,11 +743,7 @@ class Class extends Node { /// Represents a Enum. class Enum extends Node { /// Parametric constructor for [Enum]. - Enum({ - required this.name, - required this.members, - this.documentationComments = const [], - }); + Enum({required this.name, required this.members, this.documentationComments = const []}); /// The name of the enum. String name; @@ -806,10 +767,7 @@ class Enum extends Node { /// Represents a Enum member. class EnumMember extends Node { /// Parametric constructor for [EnumMember]. - EnumMember({ - required this.name, - this.documentationComments = const [], - }); + EnumMember({required this.name, this.documentationComments = const []}); /// The name of the enum member. final String name; @@ -869,8 +827,7 @@ class Root extends Node { /// Returns true if the number of custom types would exceed the available enumerations /// on the standard codec. bool get requiresOverflowClass => - classes.length - _numberOfSealedClasses() + enums.length >= - totalCustomCodecKeysAllowed; + classes.length - _numberOfSealedClasses() + enums.length >= totalCustomCodecKeysAllowed; int _numberOfSealedClasses() => classes.where((Class c) => c.isSealed).length; diff --git a/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart b/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart index 7a95b1327ea5..32589628cb2a 100644 --- a/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart +++ b/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart @@ -54,15 +54,12 @@ Iterable asConstructorParameters({ ); } - for (final (Method method, AstProxyApi api) - in flutterMethodsFromSuperClasses) { + for (final (Method method, AstProxyApi api) in flutterMethodsFromSuperClasses) { yield cb.Parameter( (cb.ParameterBuilder builder) => builder ..name = method.name ..named = true - ..type = defineType - ? methodAsFunctionType(method, apiName: api.name) - : null + ..type = defineType ? methodAsFunctionType(method, apiName: api.name) : null ..toSuper = !defineType ..required = method.isRequired, ); @@ -73,9 +70,7 @@ Iterable asConstructorParameters({ (cb.ParameterBuilder builder) => builder ..name = method.name ..named = true - ..type = defineType - ? methodAsFunctionType(method, apiName: api.name) - : null + ..type = defineType ? methodAsFunctionType(method, apiName: api.name) : null ..toThis = !defineType ..required = method.isRequired, ); @@ -86,9 +81,7 @@ Iterable asConstructorParameters({ (cb.ParameterBuilder builder) => builder ..name = method.name ..named = true - ..type = defineType - ? methodAsFunctionType(method, apiName: apiName) - : null + ..type = defineType ? methodAsFunctionType(method, apiName: apiName) : null ..toThis = !defineType ..required = method.isRequired, ); @@ -108,25 +101,19 @@ Iterable asConstructorParameters({ /// Converts all the constructors of each AstProxyApi into `code_builder` fields /// that are used to override the corresponding factory constructor of the /// generated Dart proxy class. -Iterable overridesClassConstructors( - Iterable proxyApis, -) sync* { +Iterable overridesClassConstructors(Iterable proxyApis) sync* { for (final api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); for (final Constructor constructor in api.constructors) { yield cb.Field((cb.FieldBuilder builder) { - final String constructorName = constructor.name.isEmpty - ? 'new' - : constructor.name; + final String constructorName = constructor.name.isEmpty ? 'new' : constructor.name; final Iterable parameters = asConstructorParameters( apiName: api.name, parameters: constructor.parameters, unattachedFields: api.unattachedFields, - flutterMethodsFromSuperClasses: api - .flutterMethodsFromSuperClassesWithApis(), - flutterMethodsFromInterfaces: api - .flutterMethodsFromInterfacesWithApis(), + flutterMethodsFromSuperClasses: api.flutterMethodsFromSuperClassesWithApis(), + flutterMethodsFromInterfaces: api.flutterMethodsFromInterfacesWithApis(), declaredFlutterMethods: api.flutterMethods, includeBinaryMessengerAndInstanceManager: false, ); @@ -161,15 +148,11 @@ Iterable overridesClassConstructors( /// Converts all the static fields of each AstProxyApi into `code_builder` /// fields that are used to override the corresponding static field of the /// generated Dart proxy class. -Iterable overridesClassStaticFields( - Iterable proxyApis, -) sync* { +Iterable overridesClassStaticFields(Iterable proxyApis) sync* { for (final api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); - for (final ApiField field in api.fields.where( - (ApiField field) => field.isStatic, - )) { + for (final ApiField field in api.fields.where((ApiField field) => field.isStatic)) { yield cb.Field((cb.FieldBuilder builder) { builder ..name = '${lowerCamelCaseApiName}_${field.name}' @@ -184,15 +167,11 @@ Iterable overridesClassStaticFields( /// Converts all the static methods of each AstProxyApi into `code_builder` /// fields that are used to override the corresponding static method of the /// generated Dart proxy class. -Iterable overridesClassStaticMethods( - Iterable proxyApis, -) sync* { +Iterable overridesClassStaticMethods(Iterable proxyApis) sync* { for (final api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); - for (final Method method in api.hostMethods.where( - (Method method) => method.isStatic, - )) { + for (final Method method in api.hostMethods.where((Method method) => method.isStatic)) { yield cb.Field((cb.FieldBuilder builder) { builder ..name = '${lowerCamelCaseApiName}_${method.name}' @@ -203,8 +182,7 @@ Iterable overridesClassStaticMethods( ..isNullable = true ..returnType = refer(method.returnType, asFuture: true) ..requiredParameters.addAll([ - for (final Parameter parameter in method.parameters) - refer(parameter.type), + for (final Parameter parameter in method.parameters) refer(parameter.type), ]); }); }); @@ -219,27 +197,17 @@ cb.Method overridesClassResetMethod(Iterable proxyApis) { builder ..name = '${classMemberNamePrefix}reset' ..static = true - ..docs.addAll([ - '/// Sets all overridden ProxyApi class members to null.', - ]) + ..docs.addAll(['/// Sets all overridden ProxyApi class members to null.']) ..body = cb.Block.of([ for (final AstProxyApi api in proxyApis) ...[ for (final Constructor constructor in api.constructors) cb.Code( '${toLowerCamelCase(api.name)}_${constructor.name.isEmpty ? 'new' : constructor.name} = null;', ), - for (final ApiField attachedField in api.fields.where( - (ApiField field) => field.isStatic, - )) - cb.Code( - '${toLowerCamelCase(api.name)}_${attachedField.name} = null;', - ), - for (final Method staticMethod in api.methods.where( - (Method method) => method.isStatic, - )) - cb.Code( - '${toLowerCamelCase(api.name)}_${staticMethod.name} = null;', - ), + for (final ApiField attachedField in api.fields.where((ApiField field) => field.isStatic)) + cb.Code('${toLowerCamelCase(api.name)}_${attachedField.name} = null;'), + for (final Method staticMethod in api.methods.where((Method method) => method.isStatic)) + cb.Code('${toLowerCamelCase(api.name)}_${staticMethod.name} = null;'), ], ]); }); @@ -286,9 +254,7 @@ Iterable staticAttachedFieldsGetters( ..type = cb.MethodType.getter ..static = true ..returns = cb.refer(addGenericTypes(field.type)) - ..docs.addAll( - asDocumentationComments(field.documentationComments, docCommentSpec), - ) + ..docs.addAll(asDocumentationComments(field.documentationComments, docCommentSpec)) ..lambda = true ..body = cb.Code( '$proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${field.name} ?? _${field.name}', @@ -351,9 +317,7 @@ Iterable constructors( ); for (final constructor in constructors) { - final String? factoryConstructorName = constructor.name.isNotEmpty - ? constructor.name - : null; + final String? factoryConstructorName = constructor.name.isNotEmpty ? constructor.name : null; final constructorName = '$classMemberNamePrefix${constructor.name.isNotEmpty ? constructor.name : 'new'}'; final overridesConstructorName = constructor.name.isNotEmpty @@ -371,53 +335,35 @@ Iterable constructors( flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, declaredFlutterMethods: declaredFlutterMethods, ); - final Iterable parametersWithoutMessengerAndManager = - asConstructorParameters( - apiName: apiName, - parameters: constructor.parameters, - unattachedFields: unattachedFields, - flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, - flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, - declaredFlutterMethods: declaredFlutterMethods, - includeBinaryMessengerAndInstanceManager: false, - ); + final Iterable parametersWithoutMessengerAndManager = asConstructorParameters( + apiName: apiName, + parameters: constructor.parameters, + unattachedFields: unattachedFields, + flutterMethodsFromSuperClasses: flutterMethodsFromSuperClasses, + flutterMethodsFromInterfaces: flutterMethodsFromInterfaces, + declaredFlutterMethods: declaredFlutterMethods, + includeBinaryMessengerAndInstanceManager: false, + ); builder ..name = factoryConstructorName ..factory = true - ..docs.addAll( - asDocumentationComments( - constructor.documentationComments, - docCommentSpec, - ), - ) + ..docs.addAll(asDocumentationComments(constructor.documentationComments, docCommentSpec)) ..optionalParameters.addAll(parameters) ..body = cb.Block((cb.BlockBuilder builder) { final forwardedParams = { for (final cb.Parameter parameter in parameters) parameter.name: cb.refer(parameter.name), }; - final forwardedParamsWithoutMessengerAndManager = - { - for (final cb.Parameter parameter - in parametersWithoutMessengerAndManager) - parameter.name: cb.refer(parameter.name), - }; + final forwardedParamsWithoutMessengerAndManager = { + for (final cb.Parameter parameter in parametersWithoutMessengerAndManager) + parameter.name: cb.refer(parameter.name), + }; builder.statements.addAll([ - cb.Code( - 'if ($proxyApiOverridesClassName.$overridesConstructorName != null) {', - ), + cb.Code('if ($proxyApiOverridesClassName.$overridesConstructorName != null) {'), cb.CodeExpression( - cb.Code( - '$proxyApiOverridesClassName.$overridesConstructorName!', - ), - ) - .call( - [], - forwardedParamsWithoutMessengerAndManager, - ) - .returned - .statement, + cb.Code('$proxyApiOverridesClassName.$overridesConstructorName!'), + ).call([], forwardedParamsWithoutMessengerAndManager).returned.statement, const cb.Code('}'), cb.CodeExpression( cb.Code('$apiName.$constructorName'), @@ -437,12 +383,7 @@ Iterable constructors( builder ..name = constructorName ..annotations.add(cb.refer('protected')) - ..docs.addAll( - asDocumentationComments( - constructor.documentationComments, - docCommentSpec, - ), - ) + ..docs.addAll(asDocumentationComments(constructor.documentationComments, docCommentSpec)) ..optionalParameters.addAll( asConstructorParameters( apiName: apiName, @@ -455,8 +396,7 @@ Iterable constructors( ), ) ..initializers.addAll([ - if (superClassApi != null) - const cb.Code('super.${classMemberNamePrefix}detached()'), + if (superClassApi != null) const cb.Code('super.${classMemberNamePrefix}detached()'), ]) ..body = cb.Block((cb.BlockBuilder builder) { final messageCallIndent = Indent(); @@ -471,8 +411,7 @@ Iterable constructors( type: const TypeDeclaration(baseName: 'int', isNullable: false), ), ...unattachedFields.map( - (ApiField field) => - Parameter(name: field.name, type: field.type), + (ApiField field) => Parameter(name: field.name, type: field.type), ), ...constructor.parameters, ], @@ -534,17 +473,13 @@ cb.Constructor detachedConstructor({ ), ) ..initializers.addAll([ - if (superClassApi != null) - const cb.Code('super.${classMemberNamePrefix}detached()'), + if (superClassApi != null) const cb.Code('super.${classMemberNamePrefix}detached()'), ]), ); } /// A private Field of the base codec. -cb.Field codecInstanceField({ - required String codecInstanceName, - required String codecName, -}) { +cb.Field codecInstanceField({required String codecInstanceName, required String codecName}) { return cb.Field( (cb.FieldBuilder builder) => builder ..name = codecInstanceName @@ -564,9 +499,7 @@ Iterable unattachedFields(Iterable fields) sync* { ..name = field.name ..type = cb.refer(addGenericTypes(field.type)) ..modifier = cb.FieldModifier.final$ - ..docs.addAll( - asDocumentationComments(field.documentationComments, docCommentSpec), - ), + ..docs.addAll(asDocumentationComments(field.documentationComments, docCommentSpec)), ); } } @@ -576,10 +509,7 @@ Iterable unattachedFields(Iterable fields) sync* { /// Flutter methods of a ProxyApi are represented as an anonymous function for /// an instance of a Dart proxy class, so this converts methods to a `Function` /// type field. -Iterable flutterMethodFields( - Iterable methods, { - required String apiName, -}) sync* { +Iterable flutterMethodFields(Iterable methods, {required String apiName}) sync* { for (final method in methods) { yield cb.Field( (cb.FieldBuilder builder) => builder @@ -626,9 +556,7 @@ Iterable flutterMethodFields( /// This is similar to [_proxyApiFlutterMethodFields] except all the methods are /// inherited from [AstProxyApi]s that are being implemented (following the /// `implements` keyword). -Iterable interfaceApiFields( - Iterable apisOfInterfaces, -) sync* { +Iterable interfaceApiFields(Iterable apisOfInterfaces) sync* { for (final proxyApi in apisOfInterfaces) { for (final Method method in proxyApi.methods) { yield cb.Field( @@ -636,25 +564,14 @@ Iterable interfaceApiFields( ..name = method.name ..modifier = cb.FieldModifier.final$ ..annotations.add(cb.refer('override')) - ..docs.addAll( - asDocumentationComments( - method.documentationComments, - docCommentSpec, - ), - ) + ..docs.addAll(asDocumentationComments(method.documentationComments, docCommentSpec)) ..type = cb.FunctionType( (cb.FunctionTypeBuilder builder) => builder - ..returnType = refer( - method.returnType, - asFuture: method.isAsynchronous, - ) + ..returnType = refer(method.returnType, asFuture: method.isAsynchronous) ..isNullable = !method.isRequired ..requiredParameters.addAll([ cb.refer('${proxyApi.name} ${classMemberNamePrefix}instance'), - ...method.parameters.mapIndexed(( - int index, - NamedType parameter, - ) { + ...method.parameters.mapIndexed((int index, NamedType parameter) { return cb.refer( '${addGenericTypes(parameter.type)} ${getParameterName(index, parameter)}', ); @@ -685,9 +602,7 @@ Iterable attachedFields(Iterable fields) sync* { ..modifier = cb.FieldModifier.final$ ..static = field.isStatic ..late = !field.isStatic - ..docs.addAll( - asDocumentationComments(field.documentationComments, docCommentSpec), - ) + ..docs.addAll(asDocumentationComments(field.documentationComments, docCommentSpec)) ..assignment = cb.Code('$varNamePrefix${field.name}()'), ); } @@ -709,8 +624,7 @@ cb.Method setUpMessageHandlerMethod({ required Iterable unattachedFields, required bool hasCallbackConstructor, }) { - final bool hasAnyMessageHandlers = - hasCallbackConstructor || flutterMethods.isNotEmpty; + final bool hasAnyMessageHandlers = hasCallbackConstructor || flutterMethods.isNotEmpty; return cb.Method.returnsVoid( (cb.MethodBuilder builder) => builder ..name = '${classMemberNamePrefix}setUpMessageHandlers' @@ -760,17 +674,11 @@ cb.Method setUpMessageHandlerMethod({ ..name = method.name ..type = cb.FunctionType( (cb.FunctionTypeBuilder builder) => builder - ..returnType = refer( - method.returnType, - asFuture: method.isAsynchronous, - ) + ..returnType = refer(method.returnType, asFuture: method.isAsynchronous) ..isNullable = true ..requiredParameters.addAll([ cb.refer('$apiName ${classMemberNamePrefix}instance'), - ...method.parameters.mapIndexed(( - int index, - NamedType parameter, - ) { + ...method.parameters.mapIndexed((int index, NamedType parameter) { return cb.refer( '${addGenericTypes(parameter.type)} ${getParameterName(index, parameter)}', ); @@ -798,10 +706,7 @@ cb.Method setUpMessageHandlerMethod({ parameters: [ Parameter( name: '${classMemberNamePrefix}instanceIdentifier', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), ...unattachedFields.map((ApiField field) { return Parameter(name: field.name, type: field.type); @@ -822,13 +727,12 @@ cb.Method setUpMessageHandlerMethod({ Iterable parameters, Iterable safeArgumentNames, ) { - final String argsAsNamedParams = map2( - parameters, - safeArgumentNames, - (Parameter parameter, String safeArgName) { - return '${parameter.name}: $safeArgName,\n'; - }, - ).skip(1).join(); + final String argsAsNamedParams = map2(parameters, safeArgumentNames, ( + Parameter parameter, + String safeArgName, + ) { + return '${parameter.name}: $safeArgName,\n'; + }).skip(1).join(); return '($instanceManagerVarName ?? $dartInstanceManagerClassName.instance)\n' ' .addHostCreatedInstance(\n' @@ -952,9 +856,7 @@ Iterable attachedFieldMethods( 'final int $identifierInstanceName = $instanceManagerVarName.addDartCreatedInstance($instanceName);', ), ] else ...[ - cb.Code( - 'final $type $instanceName = $type.${classMemberNamePrefix}detached();', - ), + cb.Code('final $type $instanceName = $type.${classMemberNamePrefix}detached();'), cb.Code( 'final $codecName $pigeonChannelCodec = $codecName($dartInstanceManagerClassName.instance);', ), @@ -1000,9 +902,7 @@ Iterable hostMethods( ..name = method.name ..static = method.isStatic ..modifier = cb.MethodModifier.async - ..docs.addAll( - asDocumentationComments(method.documentationComments, docCommentSpec), - ) + ..docs.addAll(asDocumentationComments(method.documentationComments, docCommentSpec)) ..returns = refer(method.returnType, asFuture: true) ..requiredParameters.addAll(parameters) ..optionalParameters.addAll([ @@ -1050,11 +950,7 @@ Iterable hostMethods( '$proxyApiOverridesClassName.${toLowerCamelCase(apiName)}_${method.name}!', ), ) - .call( - parameters.map( - (cb.Parameter parameter) => cb.refer(parameter.name), - ), - ) + .call(parameters.map((cb.Parameter parameter) => cb.refer(parameter.name))) .returned .statement, const cb.Code('}'), diff --git a/packages/pigeon/lib/src/dart/templates.dart b/packages/pigeon/lib/src/dart/templates.dart index 9fb01a90b52a..79d1004dec04 100644 --- a/packages/pigeon/lib/src/dart/templates.dart +++ b/packages/pigeon/lib/src/dart/templates.dart @@ -8,15 +8,13 @@ import '../generator_tools.dart'; /// /// This lowers the chances of variable name collisions with user defined /// parameters. -const String dartInstanceManagerClassName = - '${proxyApiClassNamePrefix}InstanceManager'; +const String dartInstanceManagerClassName = '${proxyApiClassNamePrefix}InstanceManager'; /// Name for the generated InstanceManager API. /// /// This lowers the chances of variable name collisions with user defined /// parameters. -const String dartInstanceManagerApiClassName = - '_${classNamePrefix}InstanceManagerApi'; +const String dartInstanceManagerApiClassName = '_${classNamePrefix}InstanceManagerApi'; /// Creates the `InstanceManager` with the passed string values. String instanceManagerTemplate({required Iterable allProxyApiNames}) { @@ -307,8 +305,6 @@ class $_proxyApiCodecName extends _PigeonCodec { /// Name of the base class of all Dart proxy classes. const String proxyApiBaseClassName = '${classNamePrefix}ProxyApiBaseClass'; -const String _proxyApiBaseClassMessengerVarName = - '${classMemberNamePrefix}binaryMessenger'; -const String _proxyApiBaseClassInstanceManagerVarName = - '${classMemberNamePrefix}instanceManager'; +const String _proxyApiBaseClassMessengerVarName = '${classMemberNamePrefix}binaryMessenger'; +const String _proxyApiBaseClassInstanceManagerVarName = '${classMemberNamePrefix}instanceManager'; const String _proxyApiCodecName = '_${classNamePrefix}ProxyApiBaseCodec'; diff --git a/packages/pigeon/lib/src/functional.dart b/packages/pigeon/lib/src/functional.dart index 01a9cf8b30a0..7ec9fd4eef3e 100644 --- a/packages/pigeon/lib/src/functional.dart +++ b/packages/pigeon/lib/src/functional.dart @@ -4,10 +4,7 @@ /// A [map] function that calls the function with an enumeration as well as the /// value. -Iterable indexMap( - Iterable iterable, - U Function(int index, T value) func, -) sync* { +Iterable indexMap(Iterable iterable, U Function(int index, T value) func) sync* { var index = 0; for (final value in iterable) { yield func(index, value); @@ -26,11 +23,7 @@ void enumerate(Iterable iterable, void Function(int, T) func) { /// A [map] function that takes in 2 iterables. The [Iterable]s must be of /// equal length. -Iterable map2( - Iterable ts, - Iterable us, - V Function(T t, U u) func, -) sync* { +Iterable map2(Iterable ts, Iterable us, V Function(T t, U u) func) sync* { final Iterator itt = ts.iterator; final Iterator itu = us.iterator; while (itu.moveNext() && itt.moveNext()) { diff --git a/packages/pigeon/lib/src/generator.dart b/packages/pigeon/lib/src/generator.dart index e0c240b9b794..f1e2568749f9 100644 --- a/packages/pigeon/lib/src/generator.dart +++ b/packages/pigeon/lib/src/generator.dart @@ -19,104 +19,43 @@ abstract class Generator { const Generator(); /// Generates files for specified language with specified [generatorOptions] - void generate( - T generatorOptions, - Root root, - StringSink sink, { - required String dartPackageName, - }); + void generate(T generatorOptions, Root root, StringSink sink, {required String dartPackageName}); } /// An abstract base class that enforces code generation across platforms. -abstract class StructuredGenerator - extends Generator { +abstract class StructuredGenerator extends Generator { /// Constructor. const StructuredGenerator(); @override - void generate( - T generatorOptions, - Root root, - StringSink sink, { - required String dartPackageName, - }) { + void generate(T generatorOptions, Root root, StringSink sink, {required String dartPackageName}) { final indent = Indent(); - writeFilePrologue( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); - - writeFileImports( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); - - writeOpenNamespace( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); - - writeGeneralUtilities( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); + writeFilePrologue(generatorOptions, root, indent, dartPackageName: dartPackageName); + + writeFileImports(generatorOptions, root, indent, dartPackageName: dartPackageName); + + writeOpenNamespace(generatorOptions, root, indent, dartPackageName: dartPackageName); + + writeGeneralUtilities(generatorOptions, root, indent, dartPackageName: dartPackageName); if (root.apis.any((Api api) => api is AstProxyApi)) { - writeInstanceManager( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); + writeInstanceManager(generatorOptions, root, indent, dartPackageName: dartPackageName); - writeInstanceManagerApi( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); + writeInstanceManagerApi(generatorOptions, root, indent, dartPackageName: dartPackageName); writeProxyApiBaseCodec(generatorOptions, root, indent); } - writeEnums( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); - - writeDataClasses( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); - - writeGeneralCodec( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); + writeEnums(generatorOptions, root, indent, dartPackageName: dartPackageName); + + writeDataClasses(generatorOptions, root, indent, dartPackageName: dartPackageName); + + writeGeneralCodec(generatorOptions, root, indent, dartPackageName: dartPackageName); writeApis(generatorOptions, root, indent, dartPackageName: dartPackageName); - writeCloseNamespace( - generatorOptions, - root, - indent, - dartPackageName: dartPackageName, - ); + writeCloseNamespace(generatorOptions, root, indent, dartPackageName: dartPackageName); sink.write(indent.toString()); } @@ -170,20 +109,9 @@ abstract class StructuredGenerator /// Writes all enums to [indent]. /// /// Can be overridden to add extra code before/after enums. - void writeEnums( - T generatorOptions, - Root root, - Indent indent, { - required String dartPackageName, - }) { + void writeEnums(T generatorOptions, Root root, Indent indent, {required String dartPackageName}) { for (final Enum anEnum in root.enums) { - writeEnum( - generatorOptions, - root, - indent, - anEnum, - dartPackageName: dartPackageName, - ); + writeEnum(generatorOptions, root, indent, anEnum, dartPackageName: dartPackageName); } } @@ -263,38 +191,15 @@ abstract class StructuredGenerator /// Writes all apis to [indent]. /// /// Can be overridden to add extra code before/after classes. - void writeApis( - T generatorOptions, - Root root, - Indent indent, { - required String dartPackageName, - }) { + void writeApis(T generatorOptions, Root root, Indent indent, {required String dartPackageName}) { for (final Api api in root.apis) { switch (api) { case AstHostApi(): - writeHostApi( - generatorOptions, - root, - indent, - api, - dartPackageName: dartPackageName, - ); + writeHostApi(generatorOptions, root, indent, api, dartPackageName: dartPackageName); case AstFlutterApi(): - writeFlutterApi( - generatorOptions, - root, - indent, - api, - dartPackageName: dartPackageName, - ); + writeFlutterApi(generatorOptions, root, indent, api, dartPackageName: dartPackageName); case AstProxyApi(): - writeProxyApi( - generatorOptions, - root, - indent, - api, - dartPackageName: dartPackageName, - ); + writeProxyApi(generatorOptions, root, indent, api, dartPackageName: dartPackageName); case AstEventChannelApi(): writeEventChannelApi( generatorOptions, diff --git a/packages/pigeon/lib/src/generator_tools.dart b/packages/pigeon/lib/src/generator_tools.dart index 55874a95684a..072b895eeddb 100644 --- a/packages/pigeon/lib/src/generator_tools.dart +++ b/packages/pigeon/lib/src/generator_tools.dart @@ -266,11 +266,7 @@ HostDatatype getHostDatatype( String? Function(TypeDeclaration) builtinResolver, { String Function(String)? customResolver, }) { - return _getHostDatatype( - type, - builtinResolver, - customResolver: customResolver, - ); + return _getHostDatatype(type, builtinResolver, customResolver: customResolver); } HostDatatype _getHostDatatype( @@ -329,9 +325,7 @@ const String generatedCodeWarning = /// Warning printed at the top of all generated code. String getGeneratedCodeWarning() { - final versionString = includeVersionInGeneratedWarning - ? ' (v$pigeonVersion)' - : ''; + final versionString = includeVersionInGeneratedWarning ? ' (v$pigeonVersion)' : ''; return 'Autogenerated from Pigeon$versionString, do not edit directly.'; } @@ -410,20 +404,14 @@ void addLines(Indent indent, Iterable lines, {String? linePrefix}) { /// /// In other words, whenever there is a conflict over the value of a key path, /// [modification]'s value for that key path is selected. -Map mergeMaps( - Map base, - Map modification, -) { +Map mergeMaps(Map base, Map modification) { final result = {}; for (final MapEntry entry in modification.entries) { if (base.containsKey(entry.key)) { final Object entryValue = entry.value; if (entryValue is Map) { assert(base[entry.key] is Map); - result[entry.key] = mergeMaps( - (base[entry.key] as Map?)!, - entryValue, - ); + result[entry.key] = mergeMaps((base[entry.key] as Map?)!, entryValue); } else { result[entry.key] = entry.value; } @@ -503,8 +491,7 @@ const int minimumCodecFieldKey = proxyApiCodecInstanceManagerKey + 1; const int maximumCodecFieldKey = 255; /// The total number of keys allowed in the custom codec. -const int totalCustomCodecKeysAllowed = - maximumCodecFieldKey - minimumCodecFieldKey; +const int totalCustomCodecKeysAllowed = maximumCodecFieldKey - minimumCodecFieldKey; Iterable _getTypeArguments(TypeDeclaration type) sync* { for (final TypeDeclaration typeArg in type.typeArguments) { @@ -513,12 +500,8 @@ Iterable _getTypeArguments(TypeDeclaration type) sync* { yield type; } -bool _isUnseenCustomType( - TypeDeclaration type, - Set referencedTypeNames, -) { - return !referencedTypeNames.contains(type.baseName) && - !validTypes.contains(type.baseName); +bool _isUnseenCustomType(TypeDeclaration type, Set referencedTypeNames) { + return !referencedTypeNames.contains(type.baseName) && !validTypes.contains(type.baseName); } class _Bag { @@ -542,10 +525,7 @@ class _Bag { /// Recurses into a list of [Api]s and produces a list of all referenced types /// and an associated [List] of the offsets where they are found. -Map> getReferencedTypes( - List apis, - List classes, -) { +Map> getReferencedTypes(List apis, List classes) { final references = _Bag(); for (final api in apis) { for (final Method method in api.methods) { @@ -557,10 +537,7 @@ Map> getReferencedTypes( if (api is AstProxyApi) { for (final Constructor constructor in api.constructors) { for (final NamedType parameter in constructor.parameters) { - references.addMany( - _getTypeArguments(parameter.type), - parameter.offset, - ); + references.addMany(_getTypeArguments(parameter.type), parameter.offset); } } for (final ApiField field in api.fields) { @@ -600,8 +577,7 @@ Map> getReferencedTypes( /// /// [T] depends on the language. For example, Android uses an int while iOS uses /// semantic versioning. -({TypeDeclaration type, T version})? -findHighestApiRequirement( +({TypeDeclaration type, T version})? findHighestApiRequirement( Iterable types, { required T? Function(TypeDeclaration) onGetApiRequirement, required Comparator onCompare, @@ -627,9 +603,7 @@ findHighestApiRequirement( TypeDeclaration one, TypeDeclaration two, ) { - return onCompare(onGetApiRequirement(one)!, onGetApiRequirement(two)!) > 0 - ? one - : two; + return onCompare(onGetApiRequirement(one)!, onGetApiRequirement(two)!) > 0 ? one : two; }); return ( @@ -649,10 +623,7 @@ enum CustomTypes { /// Return the enumerated types that must exist in the codec /// where the enumeration should be the key used in the buffer. -Iterable getEnumeratedTypes( - Root root, { - bool excludeSealedClasses = false, -}) sync* { +Iterable getEnumeratedTypes(Root root, {bool excludeSealedClasses = false}) sync* { var index = 0; for (final Enum customEnum in root.enums) { @@ -680,8 +651,7 @@ Iterable getEnumeratedTypes( /// Checks if [root] contains enough custom types to require overflow codec tools. bool customTypeOverflowCheck(Root root) { - return root.classes.length + root.enums.length > - maximumCodecFieldKey - minimumCodecFieldKey; + return root.classes.length + root.enums.length > maximumCodecFieldKey - minimumCodecFieldKey; } /// Describes how to format a document comment. @@ -844,9 +814,7 @@ class OutputFileOptions extends InternalOptions { String toUpperCamelCase(String text) { final separatorPattern = RegExp(r'[ _-]'); return text.split(separatorPattern).map((String word) { - return word.isEmpty - ? '' - : word.substring(0, 1).toUpperCase() + word.substring(1); + return word.isEmpty ? '' : word.substring(0, 1).toUpperCase() + word.substring(1); }).join(); } @@ -869,10 +837,7 @@ String toLowerCamelCase(String text) { /// Converts string to SCREAMING_SNAKE_CASE. String toScreamingSnakeCase(String string) { return string - .replaceAllMapped( - RegExp(r'(?<=[a-z])[A-Z]'), - (Match m) => '_${m.group(0)}', - ) + .replaceAllMapped(RegExp(r'(?<=[a-z])[A-Z]'), (Match m) => '_${m.group(0)}') .toUpperCase(); } diff --git a/packages/pigeon/lib/src/gobject/gobject_generator.dart b/packages/pigeon/lib/src/gobject/gobject_generator.dart index 0906c005d78a..8c3fa23481c8 100644 --- a/packages/pigeon/lib/src/gobject/gobject_generator.dart +++ b/packages/pigeon/lib/src/gobject/gobject_generator.dart @@ -9,12 +9,11 @@ import '../generator.dart'; import '../generator_tools.dart'; /// Documentation comment spec. -const DocumentCommentSpecification _docCommentSpec = - DocumentCommentSpecification( - '/**', - closeCommentToken: ' */', - blockContinuationToken: ' *', - ); +const DocumentCommentSpecification _docCommentSpec = DocumentCommentSpecification( + '/**', + closeCommentToken: ' */', + blockContinuationToken: ' *', +); /// Name for codec class. const String _codecBaseName = 'MessageCodec'; @@ -93,8 +92,7 @@ class InternalGObjectOptions extends InternalOptions { required this.gobjectHeaderOut, required this.gobjectSourceOut, Iterable? copyrightHeader, - }) : headerIncludePath = - options.headerIncludePath ?? path.basename(gobjectHeaderOut), + }) : headerIncludePath = options.headerIncludePath ?? path.basename(gobjectHeaderOut), module = options.module, copyrightHeader = options.copyrightHeader ?? copyrightHeader, headerOutPath = options.headerOutPath; @@ -120,8 +118,7 @@ class InternalGObjectOptions extends InternalOptions { } /// Class that manages all GObject code generation. -class GObjectGenerator - extends Generator> { +class GObjectGenerator extends Generator> { /// Constructor. const GObjectGenerator(); @@ -134,8 +131,7 @@ class GObjectGenerator required String dartPackageName, }) { assert( - generatorOptions.fileType == FileType.header || - generatorOptions.fileType == FileType.source, + generatorOptions.fileType == FileType.header || generatorOptions.fileType == FileType.source, ); if (generatorOptions.fileType == FileType.header) { const GObjectHeaderGenerator().generate( @@ -156,8 +152,7 @@ class GObjectGenerator } /// Writes GObject header (.h) file to sink. -class GObjectHeaderGenerator - extends StructuredGenerator { +class GObjectHeaderGenerator extends StructuredGenerator { /// Constructor. const GObjectHeaderGenerator(); @@ -217,11 +212,7 @@ class GObjectHeaderGenerator final enumValueCommentLines = []; for (var i = 0; i < anEnum.members.length; i++) { final EnumMember member = anEnum.members[i]; - final String itemName = _getEnumValue( - dartPackageName, - anEnum.name, - member.name, - ); + final String itemName = _getEnumValue(dartPackageName, anEnum.name, member.name); enumValueCommentLines.add('$itemName:'); enumValueCommentLines.addAll(member.documentationComments); } @@ -234,14 +225,8 @@ class GObjectHeaderGenerator indent.writeScoped('typedef enum {', '} $enumName;', () { for (var i = 0; i < anEnum.members.length; i++) { final EnumMember member = anEnum.members[i]; - final String itemName = _getEnumValue( - dartPackageName, - anEnum.name, - member.name, - ); - indent.writeln( - '$itemName = $i${i == anEnum.members.length - 1 ? '' : ','}', - ); + final String itemName = _getEnumValue(dartPackageName, anEnum.name, member.name); + indent.writeln('$itemName = $i${i == anEnum.members.length - 1 ? '' : ','}'); } }); } @@ -283,9 +268,7 @@ class GObjectHeaderGenerator final String fieldName = _getFieldName(field.name); constructorFieldCommentLines.add('$fieldName: field in this object.'); if (_isNumericListType(field.type)) { - constructorFieldCommentLines.add( - '${fieldName}_length: length of @$fieldName.', - ); + constructorFieldCommentLines.add('${fieldName}_length: length of @$fieldName.'); } } addDocumentationComments(indent, [ @@ -297,9 +280,7 @@ class GObjectHeaderGenerator 'Returns: a new #$className', ], _docCommentSpec); - indent.writeln( - "$className* ${methodPrefix}_new(${constructorArgs.join(', ')});", - ); + indent.writeln("$className* ${methodPrefix}_new(${constructorArgs.join(', ')});"); for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); @@ -309,8 +290,7 @@ class GObjectHeaderGenerator addDocumentationComments(indent, [ '${methodPrefix}_get_$fieldName', '@object: a #$className.', - if (_isNumericListType(field.type)) - '@length: location to write the length of this value.', + if (_isNumericListType(field.type)) '@length: location to write the length of this value.', '', if (field.documentationComments.isNotEmpty) ...field.documentationComments @@ -323,9 +303,7 @@ class GObjectHeaderGenerator '$className* object', if (_isNumericListType(field.type)) 'size_t* length', ]; - indent.writeln( - '$returnType ${methodPrefix}_get_$fieldName(${getterArgs.join(', ')});', - ); + indent.writeln('$returnType ${methodPrefix}_get_$fieldName(${getterArgs.join(', ')});'); } indent.newln(); @@ -338,9 +316,7 @@ class GObjectHeaderGenerator '', 'Returns: TRUE if @a and @b are equal.', ], _docCommentSpec); - indent.writeln( - 'gboolean ${methodPrefix}_equals($className* a, $className* b);', - ); + indent.writeln('gboolean ${methodPrefix}_equals($className* a, $className* b);'); indent.newln(); addDocumentationComments(indent, [ @@ -363,12 +339,7 @@ class GObjectHeaderGenerator }) { final String module = _getModule(generatorOptions, dartPackageName); indent.newln(); - _writeDeclareFinalType( - indent, - module, - _codecBaseName, - parentClassName: _standardCodecName, - ); + _writeDeclareFinalType(indent, module, _codecBaseName, parentClassName: _standardCodecName); final Iterable customTypes = getEnumeratedTypes( root, @@ -458,9 +429,7 @@ class GObjectHeaderGenerator '@$paramName: ${param.type.isNullable ? '(allow-none): ' : ''}parameter for this method.', ); if (_isNumericListType(param.type)) { - methodParameterCommentLines.add( - '@${paramName}_length: length of $paramName.', - ); + methodParameterCommentLines.add('@${paramName}_length: length of $paramName.'); } } addDocumentationComments(indent, [ @@ -473,15 +442,9 @@ class GObjectHeaderGenerator '', ...method.documentationComments, ], _docCommentSpec); - indent.writeln( - "void ${methodPrefix}_$methodName(${asyncArgs.join(', ')});", - ); + indent.writeln("void ${methodPrefix}_$methodName(${asyncArgs.join(', ')});"); - final finishArgs = [ - '$className* api', - 'GAsyncResult* result', - 'GError** error', - ]; + final finishArgs = ['$className* api', 'GAsyncResult* result', 'GError** error']; indent.newln(); addDocumentationComments(indent, [ '${methodPrefix}_${methodName}_finish:', @@ -500,20 +463,11 @@ class GObjectHeaderGenerator } // Write the API response classes. - void _writeFlutterApiRespondClass( - Indent indent, - String module, - Api api, - Method method, - ) { + void _writeFlutterApiRespondClass(Indent indent, String module, Api api, Method method) { final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); final String responseMethodPrefix = _getMethodPrefix(module, responseName); - final String primitiveType = _getType( - module, - method.returnType, - primitive: true, - ); + final String primitiveType = _getType(module, method.returnType, primitive: true); indent.newln(); _writeDeclareFinalType(indent, module, responseName); @@ -527,9 +481,7 @@ class GObjectHeaderGenerator '', 'Returns: a %TRUE if this response is an error.', ], _docCommentSpec); - indent.writeln( - 'gboolean ${responseMethodPrefix}_is_error($responseClassName* response);', - ); + indent.writeln('gboolean ${responseMethodPrefix}_is_error($responseClassName* response);'); indent.newln(); addDocumentationComments(indent, [ @@ -609,17 +561,13 @@ class GObjectHeaderGenerator indent.newln(); _writeDeclareFinalType(indent, module, api.name); - final bool hasAsyncMethod = api.methods.any( - (Method method) => method.isAsynchronous, - ); + final bool hasAsyncMethod = api.methods.any((Method method) => method.isAsynchronous); if (hasAsyncMethod) { indent.newln(); _writeDeclareFinalType(indent, module, '${api.name}ResponseHandle'); } - for (final Method method in api.methods.where( - (Method method) => !method.isAsynchronous, - )) { + for (final Method method in api.methods.where((Method method) => !method.isAsynchronous)) { _writeHostApiRespondClass(indent, module, api, method); } @@ -655,20 +603,13 @@ class GObjectHeaderGenerator 'void ${methodPrefix}_clear_method_handlers(FlBinaryMessenger* messenger, const gchar* suffix);', ); - for (final Method method in api.methods.where( - (Method method) => method.isAsynchronous, - )) { + for (final Method method in api.methods.where((Method method) => method.isAsynchronous)) { _writeHostApiRespondFunctionPrototype(indent, module, api, method); } } // Write the API response classes. - void _writeHostApiRespondClass( - Indent indent, - String module, - Api api, - Method method, - ) { + void _writeHostApiRespondClass(Indent indent, String module, Api api, Method method) { final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); final String responseMethodPrefix = _getMethodPrefix(module, responseName); @@ -734,25 +675,17 @@ class GObjectHeaderGenerator } } methodArgs.addAll([ - if (method.isAsynchronous) - '${className}ResponseHandle* response_handle', + if (method.isAsynchronous) '${className}ResponseHandle* response_handle', 'gpointer user_data', ]); - final returnType = method.isAsynchronous - ? 'void' - : '$responseClassName*'; + final returnType = method.isAsynchronous ? 'void' : '$responseClassName*'; indent.writeln("$returnType (*$methodName)(${methodArgs.join(', ')});"); } }); } // Write the function prototype for an API method response. - void _writeHostApiRespondFunctionPrototype( - Indent indent, - String module, - Api api, - Method method, - ) { + void _writeHostApiRespondFunctionPrototype(Indent indent, String module, Api api, Method method) { final String className = _getClassName(module, api.name); final String methodPrefix = _getMethodPrefix(module, api.name); final String methodName = _getMethodName(method.name); @@ -774,9 +707,7 @@ class GObjectHeaderGenerator '', 'Responds to ${api.name}.${method.name}. ', ], _docCommentSpec); - indent.writeln( - "void ${methodPrefix}_respond_$methodName(${respondArgs.join(', ')});", - ); + indent.writeln("void ${methodPrefix}_respond_$methodName(${respondArgs.join(', ')});"); indent.newln(); final respondErrorArgs = [ @@ -816,8 +747,7 @@ class GObjectHeaderGenerator } /// Writes GObject source (.cc) file to sink. -class GObjectSourceGenerator - extends StructuredGenerator { +class GObjectSourceGenerator extends StructuredGenerator { /// Constructor. const GObjectSourceGenerator(); @@ -915,62 +845,50 @@ class GObjectSourceGenerator } } indent.newln(); - indent.writeScoped( - "$className* ${methodPrefix}_new(${constructorArgs.join(', ')}) {", - '}', - () { - _writeObjectNew(indent, module, classDefinition.name); - for (final NamedType field in classDefinition.fields) { - final String fieldName = _getFieldName(field.name); - final String value = _referenceValue( - module, - field.type, - fieldName, - lengthVariableName: '${fieldName}_length', - ); + indent.writeScoped("$className* ${methodPrefix}_new(${constructorArgs.join(', ')}) {", '}', () { + _writeObjectNew(indent, module, classDefinition.name); + for (final NamedType field in classDefinition.fields) { + final String fieldName = _getFieldName(field.name); + final String value = _referenceValue( + module, + field.type, + fieldName, + lengthVariableName: '${fieldName}_length', + ); - if (_isNullablePrimitiveType(field.type)) { - final String primitiveType = _getType( - module, - field.type, - primitive: true, + if (_isNullablePrimitiveType(field.type)) { + final String primitiveType = _getType(module, field.type, primitive: true); + indent.writeScoped('if ($value != nullptr) {', '}', () { + indent.writeln( + 'self->$fieldName = static_cast<$primitiveType*>(malloc(sizeof($primitiveType)));', ); - indent.writeScoped('if ($value != nullptr) {', '}', () { - indent.writeln( - 'self->$fieldName = static_cast<$primitiveType*>(malloc(sizeof($primitiveType)));', - ); - indent.writeln('*self->$fieldName = *$value;'); - }); - indent.writeScoped('else {', '}', () { - indent.writeln('self->$fieldName = nullptr;'); - }); - } else if (field.type.isNullable) { - indent.writeScoped('if ($fieldName != nullptr) {', '}', () { - indent.writeln('self->$fieldName = $value;'); - if (_isNumericListType(field.type)) { - indent.writeln( - 'self->${fieldName}_length = ${fieldName}_length;', - ); - } - }); - indent.writeScoped('else {', '}', () { - indent.writeln('self->$fieldName = nullptr;'); - if (_isNumericListType(field.type)) { - indent.writeln('self->${fieldName}_length = 0;'); - } - }); - } else { + indent.writeln('*self->$fieldName = *$value;'); + }); + indent.writeScoped('else {', '}', () { + indent.writeln('self->$fieldName = nullptr;'); + }); + } else if (field.type.isNullable) { + indent.writeScoped('if ($fieldName != nullptr) {', '}', () { indent.writeln('self->$fieldName = $value;'); if (_isNumericListType(field.type)) { - indent.writeln( - 'self->${fieldName}_length = ${fieldName}_length;', - ); + indent.writeln('self->${fieldName}_length = ${fieldName}_length;'); + } + }); + indent.writeScoped('else {', '}', () { + indent.writeln('self->$fieldName = nullptr;'); + if (_isNumericListType(field.type)) { + indent.writeln('self->${fieldName}_length = 0;'); } + }); + } else { + indent.writeln('self->$fieldName = $value;'); + if (_isNumericListType(field.type)) { + indent.writeln('self->${fieldName}_length = ${fieldName}_length;'); } } - indent.writeln('return self;'); - }, - ); + } + indent.writeln('return self;'); + }); for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); @@ -997,20 +915,16 @@ class GObjectSourceGenerator } indent.newln(); - indent.writeScoped( - 'static FlValue* ${methodPrefix}_to_list($className* self) {', - '}', - () { - indent.writeln('FlValue* values = fl_value_new_list();'); - for (final NamedType field in classDefinition.fields) { - final String fieldName = _getFieldName(field.name); - indent.writeln( - 'fl_value_append_take(values, ${_makeFlValue(root, module, field.type, 'self->$fieldName', lengthVariableName: 'self->${fieldName}_length')});', - ); - } - indent.writeln('return values;'); - }, - ); + indent.writeScoped('static FlValue* ${methodPrefix}_to_list($className* self) {', '}', () { + indent.writeln('FlValue* values = fl_value_new_list();'); + for (final NamedType field in classDefinition.fields) { + final String fieldName = _getFieldName(field.name); + indent.writeln( + 'fl_value_append_take(values, ${_makeFlValue(root, module, field.type, 'self->$fieldName', lengthVariableName: 'self->${fieldName}_length')});', + ); + } + indent.writeln('return values;'); + }); indent.newln(); indent.writeScoped( @@ -1023,47 +937,33 @@ class GObjectSourceGenerator final String fieldName = _getFieldName(field.name); final String fieldType = _getType(module, field.type); final String fieldValue = _fromFlValue(module, field.type, 'value$i'); - indent.writeln( - 'FlValue* value$i = fl_value_get_list_value(values, $i);', - ); + indent.writeln('FlValue* value$i = fl_value_get_list_value(values, $i);'); args.add(fieldName); if (_isNullablePrimitiveType(field.type)) { indent.writeln('$fieldType $fieldName = nullptr;'); indent.writeln( '${_getType(module, field.type, isOutput: true, primitive: true)} ${fieldName}_value;', ); - indent.writeScoped( - 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', - '}', - () { - indent.writeln('${fieldName}_value = $fieldValue;'); - indent.writeln('$fieldName = &${fieldName}_value;'); - }, - ); + indent.writeScoped('if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', '}', () { + indent.writeln('${fieldName}_value = $fieldValue;'); + indent.writeln('$fieldName = &${fieldName}_value;'); + }); } else if (field.type.isNullable) { indent.writeln('$fieldType $fieldName = nullptr;'); if (_isNumericListType(field.type)) { indent.writeln('size_t ${fieldName}_length = 0;'); args.add('${fieldName}_length'); } - indent.writeScoped( - 'if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', - '}', - () { - indent.writeln('$fieldName = $fieldValue;'); - if (_isNumericListType(field.type)) { - indent.writeln( - '${fieldName}_length = fl_value_get_length(value$i);', - ); - } - }, - ); + indent.writeScoped('if (fl_value_get_type(value$i) != FL_VALUE_TYPE_NULL) {', '}', () { + indent.writeln('$fieldName = $fieldValue;'); + if (_isNumericListType(field.type)) { + indent.writeln('${fieldName}_length = fl_value_get_length(value$i);'); + } + }); } else { indent.writeln('$fieldType $fieldName = $fieldValue;'); if (_isNumericListType(field.type)) { - indent.writeln( - 'size_t ${fieldName}_length = fl_value_get_length(value$i);', - ); + indent.writeln('size_t ${fieldName}_length = fl_value_get_length(value$i);'); args.add('${fieldName}_length'); } } @@ -1107,10 +1007,7 @@ class GObjectSourceGenerator for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); if (field.type.isClass) { - final String fieldMethodPrefix = _getMethodPrefix( - module, - field.type.baseName, - ); + final String fieldMethodPrefix = _getMethodPrefix(module, field.type.baseName); indent.writeScoped( 'if (!${fieldMethodPrefix}_equals(a->$fieldName, b->$fieldName)) {', '}', @@ -1135,13 +1032,9 @@ class GObjectSourceGenerator }, ); } else { - indent.writeScoped( - 'if (a->$fieldName != b->$fieldName) {', - '}', - () { - indent.writeln('return FALSE;'); - }, - ); + indent.writeScoped('if (a->$fieldName != b->$fieldName) {', '}', () { + indent.writeln('return FALSE;'); + }); } } else if (_isNumericListType(field.type)) { indent.writeScoped('if (a->$fieldName != b->$fieldName) {', '}', () { @@ -1152,28 +1045,19 @@ class GObjectSourceGenerator indent.writeln('return FALSE;'); }, ); - indent.writeScoped( - 'if (a->${fieldName}_length != b->${fieldName}_length) {', - '}', - () { - indent.writeln('return FALSE;'); - }, - ); - if (field.type.baseName == 'Float32List' || - field.type.baseName == 'Float64List') { - indent.writeScoped( - 'for (size_t i = 0; i < a->${fieldName}_length; i++) {', - '}', - () { - indent.writeScoped( - 'if (!flpigeon_equals_double(a->$fieldName[i], b->$fieldName[i])) {', - '}', - () { - indent.writeln('return FALSE;'); - }, - ); - }, - ); + indent.writeScoped('if (a->${fieldName}_length != b->${fieldName}_length) {', '}', () { + indent.writeln('return FALSE;'); + }); + if (field.type.baseName == 'Float32List' || field.type.baseName == 'Float64List') { + indent.writeScoped('for (size_t i = 0; i < a->${fieldName}_length; i++) {', '}', () { + indent.writeScoped( + 'if (!flpigeon_equals_double(a->$fieldName[i], b->$fieldName[i])) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + }); } else { final elementSize = field.type.baseName == 'Uint8List' ? 'sizeof(uint8_t)' @@ -1189,8 +1073,7 @@ class GObjectSourceGenerator ); } }); - } else if (field.type.baseName == 'bool' || - field.type.baseName == 'int') { + } else if (field.type.baseName == 'bool' || field.type.baseName == 'int') { if (field.type.isNullable) { indent.writeScoped( 'if ((a->$fieldName == nullptr) != (b->$fieldName == nullptr)) {', @@ -1207,13 +1090,9 @@ class GObjectSourceGenerator }, ); } else { - indent.writeScoped( - 'if (a->$fieldName != b->$fieldName) {', - '}', - () { - indent.writeln('return FALSE;'); - }, - ); + indent.writeScoped('if (a->$fieldName != b->$fieldName) {', '}', () { + indent.writeln('return FALSE;'); + }); } } else if (field.type.baseName == 'double') { if (field.type.isNullable) { @@ -1241,21 +1120,13 @@ class GObjectSourceGenerator ); } } else if (field.type.baseName == 'String') { - indent.writeScoped( - 'if (g_strcmp0(a->$fieldName, b->$fieldName) != 0) {', - '}', - () { - indent.writeln('return FALSE;'); - }, - ); + indent.writeScoped('if (g_strcmp0(a->$fieldName, b->$fieldName) != 0) {', '}', () { + indent.writeln('return FALSE;'); + }); } else { - indent.writeScoped( - 'if (!flpigeon_deep_equals(a->$fieldName, b->$fieldName)) {', - '}', - () { - indent.writeln('return FALSE;'); - }, - ); + indent.writeScoped('if (!flpigeon_deep_equals(a->$fieldName, b->$fieldName)) {', '}', () { + indent.writeln('return FALSE;'); + }); } } indent.writeln('return TRUE;'); @@ -1268,31 +1139,20 @@ class GObjectSourceGenerator for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); if (field.type.isClass) { - final String fieldMethodPrefix = _getMethodPrefix( - module, - field.type.baseName, - ); - indent.writeln( - 'result = result * 31 + ${fieldMethodPrefix}_hash(self->$fieldName);', - ); + final String fieldMethodPrefix = _getMethodPrefix(module, field.type.baseName); + indent.writeln('result = result * 31 + ${fieldMethodPrefix}_hash(self->$fieldName);'); } else if (field.type.isEnum) { if (field.type.isNullable) { indent.writeln( 'result = result * 31 + (self->$fieldName != nullptr ? static_cast(*self->$fieldName) : 0);', ); } else { - indent.writeln( - 'result = result * 31 + static_cast(self->$fieldName);', - ); + indent.writeln('result = result * 31 + static_cast(self->$fieldName);'); } } else if (_isNumericListType(field.type)) { indent.writeScoped('{', '}', () { indent.writeln('size_t len = self->${fieldName}_length;'); - final String elementTypeName = _getType( - module, - field.type, - isElementType: true, - ); + final String elementTypeName = _getType(module, field.type, isElementType: true); indent.writeln('const $elementTypeName* data = self->$fieldName;'); indent.writeScoped('if (data != nullptr) {', '}', () { indent.writeScoped('for (size_t i = 0; i < len; i++) {', '}', () { @@ -1302,27 +1162,20 @@ class GObjectSourceGenerator ); } else if (field.type.baseName == 'Float32List' || field.type.baseName == 'Float64List') { - indent.writeln( - 'result = result * 31 + flpigeon_hash_double(data[i]);', - ); + indent.writeln('result = result * 31 + flpigeon_hash_double(data[i]);'); } else { - indent.writeln( - 'result = result * 31 + static_cast(data[i]);', - ); + indent.writeln('result = result * 31 + static_cast(data[i]);'); } }); }); }); - } else if (field.type.baseName == 'bool' || - field.type.baseName == 'int') { + } else if (field.type.baseName == 'bool' || field.type.baseName == 'int') { if (field.type.isNullable) { indent.writeln( 'result = result * 31 + (self->$fieldName != nullptr ? static_cast(*self->$fieldName) : 0);', ); } else { - indent.writeln( - 'result = result * 31 + static_cast(self->$fieldName);', - ); + indent.writeln('result = result * 31 + static_cast(self->$fieldName);'); } } else if (field.type.baseName == 'double') { if (field.type.isNullable) { @@ -1330,18 +1183,14 @@ class GObjectSourceGenerator 'result = result * 31 + (self->$fieldName != nullptr ? flpigeon_hash_double(*self->$fieldName) : 0);', ); } else { - indent.writeln( - 'result = result * 31 + flpigeon_hash_double(self->$fieldName);', - ); + indent.writeln('result = result * 31 + flpigeon_hash_double(self->$fieldName);'); } } else if (field.type.baseName == 'String') { indent.writeln( 'result = result * 31 + (self->$fieldName != nullptr ? g_str_hash(self->$fieldName) : 0);', ); } else { - indent.writeln( - 'result = result * 31 + flpigeon_deep_hash(self->$fieldName);', - ); + indent.writeln('result = result * 31 + flpigeon_deep_hash(self->$fieldName);'); } } indent.writeln('return result;'); @@ -1365,13 +1214,7 @@ class GObjectSourceGenerator ); indent.newln(); - _writeObjectStruct( - indent, - module, - _codecBaseName, - () {}, - parentClassName: _standardCodecName, - ); + _writeObjectStruct(indent, module, _codecBaseName, () {}, parentClassName: _standardCodecName); indent.newln(); _writeDefineType( @@ -1389,9 +1232,7 @@ class GObjectSourceGenerator for (final customType in customTypes) { final String customTypeName = _getClassName(module, customType.name); - final String snakeCustomTypeName = _snakeCaseFromCamelCase( - customTypeName, - ); + final String snakeCustomTypeName = _snakeCaseFromCamelCase(customTypeName); final String customTypeId = _getCustomTypeId(module, customType); indent.newln(); @@ -1403,13 +1244,9 @@ class GObjectSourceGenerator '}', () { indent.writeln('uint8_t type = $customTypeId;'); - indent.writeln( - 'g_byte_array_append(buffer, &type, sizeof(uint8_t));', - ); + indent.writeln('g_byte_array_append(buffer, &type, sizeof(uint8_t));'); if (customType.type == CustomTypes.customClass) { - indent.writeln( - 'g_autoptr(FlValue) values = ${snakeCustomTypeName}_to_list(value);', - ); + indent.writeln('g_autoptr(FlValue) values = ${snakeCustomTypeName}_to_list(value);'); indent.writeln( 'return fl_standard_message_codec_write_value(codec, buffer, values, error);', ); @@ -1427,47 +1264,28 @@ class GObjectSourceGenerator 'static gboolean ${codecMethodPrefix}_write_value($_standardCodecName* codec, GByteArray* buffer, FlValue* value, GError** error) {', '}', () { - indent.writeScoped( - 'if (fl_value_get_type(value) == FL_VALUE_TYPE_CUSTOM) {', - '}', - () { - indent.writeScoped( - 'switch (fl_value_get_custom_type(value)) {', - '}', - () { - for (final customType in customTypes) { - final String customTypeId = _getCustomTypeId( - module, - customType, + indent.writeScoped('if (fl_value_get_type(value) == FL_VALUE_TYPE_CUSTOM) {', '}', () { + indent.writeScoped('switch (fl_value_get_custom_type(value)) {', '}', () { + for (final customType in customTypes) { + final String customTypeId = _getCustomTypeId(module, customType); + indent.writeln('case $customTypeId:'); + indent.nest(1, () { + final String customTypeName = _getClassName(module, customType.name); + final String snakeCustomTypeName = _snakeCaseFromCamelCase(customTypeName); + final String castMacro = _getClassCastMacro(module, customType.name); + if (customType.type == CustomTypes.customClass) { + indent.writeln( + 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, $castMacro(fl_value_get_custom_value_object(value)), error);', + ); + } else if (customType.type == CustomTypes.customEnum) { + indent.writeln( + 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, reinterpret_cast(const_cast(fl_value_get_custom_value(value))), error);', ); - indent.writeln('case $customTypeId:'); - indent.nest(1, () { - final String customTypeName = _getClassName( - module, - customType.name, - ); - final String snakeCustomTypeName = _snakeCaseFromCamelCase( - customTypeName, - ); - final String castMacro = _getClassCastMacro( - module, - customType.name, - ); - if (customType.type == CustomTypes.customClass) { - indent.writeln( - 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, $castMacro(fl_value_get_custom_value_object(value)), error);', - ); - } else if (customType.type == CustomTypes.customEnum) { - indent.writeln( - 'return ${codecMethodPrefix}_write_$snakeCustomTypeName(codec, buffer, reinterpret_cast(const_cast(fl_value_get_custom_value(value))), error);', - ); - } - }); } - }, - ); - }, - ); + }); + } + }); + }); indent.newln(); indent.writeln( @@ -1478,9 +1296,7 @@ class GObjectSourceGenerator for (final customType in customTypes) { final String customTypeName = _getClassName(module, customType.name); - final String snakeCustomTypeName = _snakeCaseFromCamelCase( - customTypeName, - ); + final String snakeCustomTypeName = _snakeCaseFromCamelCase(customTypeName); final String customTypeId = _getCustomTypeId(module, customType); indent.newln(); indent.writeScoped( @@ -1505,9 +1321,7 @@ class GObjectSourceGenerator indent.writeln('return nullptr;'); }); indent.newln(); - indent.writeln( - 'return fl_value_new_custom_object($customTypeId, G_OBJECT(value));', - ); + indent.writeln('return fl_value_new_custom_object($customTypeId, G_OBJECT(value));'); } else if (customType.type == CustomTypes.customEnum) { indent.writeln( 'return fl_value_new_custom($customTypeId, fl_standard_message_codec_read_value(codec, buffer, offset, error), (GDestroyNotify)fl_value_unref);', @@ -1524,14 +1338,9 @@ class GObjectSourceGenerator () { indent.writeScoped('switch (type) {', '}', () { for (final customType in customTypes) { - final String customTypeName = _getClassName( - module, - customType.name, - ); + final String customTypeName = _getClassName(module, customType.name); final String customTypeId = _getCustomTypeId(module, customType); - final String snakeCustomTypeName = _snakeCaseFromCamelCase( - customTypeName, - ); + final String snakeCustomTypeName = _snakeCaseFromCamelCase(customTypeName); indent.writeln('case $customTypeId:'); indent.nest(1, () { indent.writeln( @@ -1564,14 +1373,10 @@ class GObjectSourceGenerator }, hasDispose: false); indent.newln(); - indent.writeScoped( - 'static $codecClassName* ${codecMethodPrefix}_new() {', - '}', - () { - _writeObjectNew(indent, module, _codecBaseName); - indent.writeln('return self;'); - }, - ); + indent.writeScoped('static $codecClassName* ${codecMethodPrefix}_new() {', '}', () { + _writeObjectNew(indent, module, _codecBaseName); + indent.writeln('return self;'); + }); } @override @@ -1616,9 +1421,7 @@ class GObjectSourceGenerator '}', () { _writeObjectNew(indent, module, api.name); - indent.writeln( - 'self->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger));', - ); + indent.writeln('self->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger));'); indent.writeln( 'self->suffix = suffix != nullptr ? g_strdup_printf(".%s", suffix) : g_strdup("");', ); @@ -1630,10 +1433,7 @@ class GObjectSourceGenerator final String methodName = _getMethodName(method.name); final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final String responseMethodPrefix = _getMethodPrefix( - module, - responseName, - ); + final String responseMethodPrefix = _getMethodPrefix(module, responseName); final String testResponseMacro = '${_snakeCaseFromCamelCase(module)}_IS_${_snakeCaseFromCamelCase(responseName)}' .toUpperCase(); @@ -1644,11 +1444,7 @@ class GObjectSourceGenerator if (!method.returnType.isVoid) { indent.writeln('FlValue* return_value;'); if (_isNullablePrimitiveType(method.returnType)) { - final String primitiveType = _getType( - module, - method.returnType, - primitive: true, - ); + final String primitiveType = _getType(module, method.returnType, primitive: true); indent.writeln('$primitiveType return_value_;'); } } @@ -1662,9 +1458,7 @@ class GObjectSourceGenerator _writeCastSelf(indent, module, responseName, 'object'); indent.writeln('g_clear_pointer(&self->error, fl_value_unref);'); if (!method.returnType.isVoid) { - indent.writeln( - 'g_clear_pointer(&self->return_value, fl_value_unref);', - ); + indent.writeln('g_clear_pointer(&self->return_value, fl_value_unref);'); } }); @@ -1680,18 +1474,12 @@ class GObjectSourceGenerator '}', () { _writeObjectNew(indent, module, responseName); - indent.writeScoped( - 'if (fl_value_get_length(response) > 1) {', - '}', - () { - indent.writeln('self->error = fl_value_ref(response);'); - }, - ); + indent.writeScoped('if (fl_value_get_length(response) > 1) {', '}', () { + indent.writeln('self->error = fl_value_ref(response);'); + }); if (!method.returnType.isVoid) { indent.writeScoped('else {', '}', () { - indent.writeln( - 'FlValue* value = fl_value_get_list_value(response, 0);', - ); + indent.writeln('FlValue* value = fl_value_get_list_value(response, 0);'); indent.writeln('self->return_value = fl_value_ref(value);'); }); } @@ -1704,9 +1492,7 @@ class GObjectSourceGenerator 'gboolean ${responseMethodPrefix}_is_error($responseClassName* self) {', '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), FALSE);', - ); + indent.writeln('g_return_val_if_fail($testResponseMacro(self), FALSE);'); indent.writeln('return self->error != nullptr;'); }, ); @@ -1716,13 +1502,9 @@ class GObjectSourceGenerator 'const gchar* ${responseMethodPrefix}_get_error_code($responseClassName* self) {', '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), nullptr);', - ); + indent.writeln('g_return_val_if_fail($testResponseMacro(self), nullptr);'); indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); - indent.writeln( - 'return fl_value_get_string(fl_value_get_list_value(self->error, 0));', - ); + indent.writeln('return fl_value_get_string(fl_value_get_list_value(self->error, 0));'); }, ); @@ -1731,13 +1513,9 @@ class GObjectSourceGenerator 'const gchar* ${responseMethodPrefix}_get_error_message($responseClassName* self) {', '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), nullptr);', - ); + indent.writeln('g_return_val_if_fail($testResponseMacro(self), nullptr);'); indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); - indent.writeln( - 'return fl_value_get_string(fl_value_get_list_value(self->error, 1));', - ); + indent.writeln('return fl_value_get_string(fl_value_get_list_value(self->error, 1));'); }, ); @@ -1746,20 +1524,14 @@ class GObjectSourceGenerator 'FlValue* ${responseMethodPrefix}_get_error_details($responseClassName* self) {', '}', () { - indent.writeln( - 'g_return_val_if_fail($testResponseMacro(self), nullptr);', - ); + indent.writeln('g_return_val_if_fail($testResponseMacro(self), nullptr);'); indent.writeln('g_assert(${responseMethodPrefix}_is_error(self));'); indent.writeln('return fl_value_get_list_value(self->error, 2);'); }, ); if (!method.returnType.isVoid) { - final String primitiveType = _getType( - module, - method.returnType, - primitive: true, - ); + final String primitiveType = _getType(module, method.returnType, primitive: true); indent.newln(); final returnType = _isNullablePrimitiveType(method.returnType) @@ -1772,9 +1544,7 @@ class GObjectSourceGenerator indent.writeln( 'g_return_val_if_fail($testResponseMacro(self), ${_getDefaultValue(module, method.returnType)});', ); - indent.writeln( - 'g_assert(!${responseMethodPrefix}_is_error(self));', - ); + indent.writeln('g_assert(!${responseMethodPrefix}_is_error(self));'); if (method.returnType.isNullable) { indent.writeScoped( 'if (fl_value_get_type(self->return_value) == FL_VALUE_TYPE_NULL) {', @@ -1785,15 +1555,9 @@ class GObjectSourceGenerator ); } if (_isNumericListType(method.returnType)) { - indent.writeScoped( - 'if (return_value_length != nullptr) {', - '}', - () { - indent.writeln( - '*return_value_length = fl_value_get_length(self->return_value);', - ); - }, - ); + indent.writeScoped('if (return_value_length != nullptr) {', '}', () { + indent.writeln('*return_value_length = fl_value_get_length(self->return_value);'); + }); } if (_isNullablePrimitiveType(method.returnType)) { indent.writeln( @@ -1815,9 +1579,7 @@ class GObjectSourceGenerator '}', () { indent.writeln('GTask* task = G_TASK(user_data);'); - indent.writeln( - 'g_task_return_pointer(task, result, g_object_unref);', - ); + indent.writeln('g_task_return_pointer(task, result, g_object_unref);'); }, ); @@ -1835,53 +1597,35 @@ class GObjectSourceGenerator 'gpointer user_data', ]); indent.newln(); - indent.writeScoped( - "void ${methodPrefix}_$methodName(${asyncArgs.join(', ')}) {", - '}', - () { - indent.writeln('g_autoptr(FlValue) args = fl_value_new_list();'); - for (final Parameter param in method.parameters) { - final String name = _snakeCaseFromCamelCase(param.name); - final String value = _makeFlValue( - root, - module, - param.type, - name, - lengthVariableName: '${name}_length', - ); - indent.writeln('fl_value_append_take(args, $value);'); - } - final String channelName = makeChannelName( - api, - method, - dartPackageName, - ); - indent.writeln( - 'g_autofree gchar* channel_name = g_strdup_printf("$channelName%s", self->suffix);', - ); - indent.writeln( - 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();', - ); - indent.writeln( - 'FlBasicMessageChannel* channel = fl_basic_message_channel_new(self->messenger, channel_name, FL_MESSAGE_CODEC(codec));', - ); - indent.writeln( - 'GTask* task = g_task_new(self, cancellable, callback, user_data);', - ); - indent.writeln( - 'g_task_set_task_data(task, channel, g_object_unref);', - ); - indent.writeln( - 'fl_basic_message_channel_send(channel, args, cancellable, ${methodPrefix}_${methodName}_cb, task);', + indent.writeScoped("void ${methodPrefix}_$methodName(${asyncArgs.join(', ')}) {", '}', () { + indent.writeln('g_autoptr(FlValue) args = fl_value_new_list();'); + for (final Parameter param in method.parameters) { + final String name = _snakeCaseFromCamelCase(param.name); + final String value = _makeFlValue( + root, + module, + param.type, + name, + lengthVariableName: '${name}_length', ); - }, - ); + indent.writeln('fl_value_append_take(args, $value);'); + } + final String channelName = makeChannelName(api, method, dartPackageName); + indent.writeln( + 'g_autofree gchar* channel_name = g_strdup_printf("$channelName%s", self->suffix);', + ); + indent.writeln('g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();'); + indent.writeln( + 'FlBasicMessageChannel* channel = fl_basic_message_channel_new(self->messenger, channel_name, FL_MESSAGE_CODEC(codec));', + ); + indent.writeln('GTask* task = g_task_new(self, cancellable, callback, user_data);'); + indent.writeln('g_task_set_task_data(task, channel, g_object_unref);'); + indent.writeln( + 'fl_basic_message_channel_send(channel, args, cancellable, ${methodPrefix}_${methodName}_cb, task);', + ); + }); - final finishArgs = [ - '$className* self', - 'GAsyncResult* result', - 'GError** error', - ]; + final finishArgs = ['$className* self', 'GAsyncResult* result', 'GError** error']; indent.newln(); indent.writeScoped( "$responseClassName* ${methodPrefix}_${methodName}_finish(${finishArgs.join(', ')}) {", @@ -1923,9 +1667,7 @@ class GObjectSourceGenerator final String codecClassName = _getClassName(module, _codecBaseName); final String codecMethodPrefix = _getMethodPrefix(module, _codecBaseName); - final bool hasAsyncMethod = api.methods.any( - (Method method) => method.isAsynchronous, - ); + final bool hasAsyncMethod = api.methods.any((Method method) => method.isAsynchronous); if (hasAsyncMethod) { indent.newln(); _writeObjectStruct(indent, module, '${api.name}ResponseHandle', () { @@ -1955,9 +1697,7 @@ class GObjectSourceGenerator '}', () { _writeObjectNew(indent, module, '${api.name}ResponseHandle'); - indent.writeln( - 'self->channel = FL_BASIC_MESSAGE_CHANNEL(g_object_ref(channel));', - ); + indent.writeln('self->channel = FL_BASIC_MESSAGE_CHANNEL(g_object_ref(channel));'); indent.writeln( 'self->response_handle = FL_BASIC_MESSAGE_CHANNEL_RESPONSE_HANDLE(g_object_ref(response_handle));', ); @@ -1969,10 +1709,7 @@ class GObjectSourceGenerator for (final Method method in api.methods) { final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final String responseMethodPrefix = _getMethodPrefix( - module, - responseName, - ); + final String responseMethodPrefix = _getMethodPrefix(module, responseName); if (method.isAsynchronous) { indent.newln(); @@ -2025,9 +1762,7 @@ class GObjectSourceGenerator () { _writeObjectNew(indent, module, responseName); indent.writeln('self->value = fl_value_new_list();'); - indent.writeln( - 'fl_value_append_take(self->value, fl_value_new_string(code));', - ); + indent.writeln('fl_value_append_take(self->value, fl_value_new_string(code));'); indent.writeln( 'fl_value_append_take(self->value, fl_value_new_string(message != nullptr ? message : ""));', ); @@ -2104,15 +1839,9 @@ class GObjectSourceGenerator final Parameter param = method.parameters[i]; final String paramName = _snakeCaseFromCamelCase(param.name); final String paramType = _getType(module, param.type); - indent.writeln( - 'FlValue* value$i = fl_value_get_list_value(message_, $i);', - ); + indent.writeln('FlValue* value$i = fl_value_get_list_value(message_, $i);'); if (_isNullablePrimitiveType(param.type)) { - final String primitiveType = _getType( - module, - param.type, - primitive: true, - ); + final String primitiveType = _getType(module, param.type, primitive: true); indent.writeln('$paramType $paramName = nullptr;'); indent.writeln('$primitiveType ${paramName}_value;'); indent.writeScoped( @@ -2129,18 +1858,12 @@ class GObjectSourceGenerator }, ); } else { - final String paramValue = _fromFlValue( - module, - method.parameters[i].type, - 'value$i', - ); + final String paramValue = _fromFlValue(module, method.parameters[i].type, 'value$i'); indent.writeln('$paramType $paramName = $paramValue;'); } methodArgs.add(paramName); if (_isNumericListType(method.parameters[i].type)) { - indent.writeln( - 'size_t ${paramName}_length = fl_value_get_length(value$i);', - ); + indent.writeln('size_t ${paramName}_length = fl_value_get_length(value$i);'); methodArgs.add('${paramName}_length'); } } @@ -2151,9 +1874,7 @@ class GObjectSourceGenerator indent.writeln( 'g_autoptr(${className}ResponseHandle) handle = ${methodPrefix}_response_handle_new(channel, response_handle);', ); - indent.writeln( - "self->vtable->$methodName(${vfuncArgs.join(', ')});", - ); + indent.writeln("self->vtable->$methodName(${vfuncArgs.join(', ')});"); } else { final vfuncArgs = []; vfuncArgs.addAll(methodArgs); @@ -2197,16 +1918,10 @@ class GObjectSourceGenerator ); indent.newln(); - indent.writeln( - 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();', - ); + indent.writeln('g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();'); for (final Method method in api.methods) { final String methodName = _getMethodName(method.name); - final String channelName = makeChannelName( - api, - method, - dartPackageName, - ); + final String channelName = makeChannelName(api, method, dartPackageName); indent.writeln( 'g_autofree gchar* ${methodName}_channel_name = g_strdup_printf("$channelName%s", dot_suffix);', ); @@ -2230,16 +1945,10 @@ class GObjectSourceGenerator ); indent.newln(); - indent.writeln( - 'g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();', - ); + indent.writeln('g_autoptr($codecClassName) codec = ${codecMethodPrefix}_new();'); for (final Method method in api.methods) { final String methodName = _getMethodName(method.name); - final String channelName = makeChannelName( - api, - method, - dartPackageName, - ); + final String channelName = makeChannelName(api, method, dartPackageName); indent.writeln( 'g_autofree gchar* ${methodName}_channel_name = g_strdup_printf("$channelName%s", dot_suffix);', ); @@ -2253,17 +1962,12 @@ class GObjectSourceGenerator }, ); - for (final Method method in api.methods.where( - (Method method) => method.isAsynchronous, - )) { + for (final Method method in api.methods.where((Method method) => method.isAsynchronous)) { final String returnType = _getType(module, method.returnType); final String methodName = _getMethodName(method.name); final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final String responseMethodPrefix = _getMethodPrefix( - module, - responseName, - ); + final String responseMethodPrefix = _getMethodPrefix(module, responseName); indent.newln(); final respondArgs = [ @@ -2326,10 +2030,7 @@ class GObjectSourceGenerator } // Returns the module name to use. -String _getModule( - InternalGObjectOptions generatorOptions, - String dartPackageName, -) { +String _getModule(InternalGObjectOptions generatorOptions, String dartPackageName) { return generatorOptions.module ?? _camelCaseFromSnakeCase(dartPackageName); } @@ -2393,43 +2094,23 @@ void _writeObjectStruct( } // Writes the dispose method for a GObject. -void _writeDispose( - Indent indent, - String module, - String name, - void Function() func, -) { +void _writeDispose(Indent indent, String module, String name, void Function() func) { final String methodPrefix = _getMethodPrefix(module, name); - indent.writeScoped( - 'static void ${methodPrefix}_dispose(GObject* object) {', - '}', - () { - func(); - indent.writeln( - 'G_OBJECT_CLASS(${methodPrefix}_parent_class)->dispose(object);', - ); - }, - ); + indent.writeScoped('static void ${methodPrefix}_dispose(GObject* object) {', '}', () { + func(); + indent.writeln('G_OBJECT_CLASS(${methodPrefix}_parent_class)->dispose(object);'); + }); } // Writes the init function for a GObject. -void _writeInit( - Indent indent, - String module, - String name, - void Function() func, -) { +void _writeInit(Indent indent, String module, String name, void Function() func) { final String className = _getClassName(module, name); final String methodPrefix = _getMethodPrefix(module, name); - indent.writeScoped( - 'static void ${methodPrefix}_init($className* self) {', - '}', - () { - func(); - }, - ); + indent.writeScoped('static void ${methodPrefix}_init($className* self) {', '}', () { + func(); + }); } // Writes the class init function for a GObject. @@ -2443,18 +2124,12 @@ void _writeClassInit( final String className = _getClassName(module, name); final String methodPrefix = _getMethodPrefix(module, name); - indent.writeScoped( - 'static void ${methodPrefix}_class_init(${className}Class* klass) {', - '}', - () { - if (hasDispose) { - indent.writeln( - 'G_OBJECT_CLASS(klass)->dispose = ${methodPrefix}_dispose;', - ); - } - func(); - }, - ); + indent.writeScoped('static void ${methodPrefix}_class_init(${className}Class* klass) {', '}', () { + if (hasDispose) { + indent.writeln('G_OBJECT_CLASS(klass)->dispose = ${methodPrefix}_dispose;'); + } + func(); + }); } // Writes the constructor for a GObject. @@ -2469,12 +2144,7 @@ void _writeObjectNew(Indent indent, String module, String name) { } // Writes the cast used at the top of GObject methods. -void _writeCastSelf( - Indent indent, - String module, - String name, - String variableName, -) { +void _writeCastSelf(Indent indent, String module, String name, String variableName) { final String className = _getClassName(module, name); final String castMacro = _getClassCastMacro(module, name); indent.writeln('$className* self = $castMacro($variableName);'); @@ -2490,10 +2160,7 @@ String _snakeCaseFromCamelCase(String camelCase) { // Converts a string from snake_case to CamelCase String _camelCaseFromSnakeCase(String snakeCase) { - return snakeCase - .split('_') - .map((String v) => v[0].toUpperCase() + v.substring(1)) - .join(); + return snakeCase.split('_').map((String v) => v[0].toUpperCase() + v.substring(1)).join(); } // Returns the GObject class name for [name]. @@ -2634,9 +2301,7 @@ bool _isNullablePrimitiveType(TypeDeclaration type) { // Whether [type] is a type that needs to stay an FlValue* since it can't be // expressed as a more concrete type. bool _isFlValueWrappedType(TypeDeclaration type) { - return type.baseName == 'List' || - type.baseName == 'Map' || - type.baseName == 'Object'; + return type.baseName == 'List' || type.baseName == 'Map' || type.baseName == 'Object'; } // Returns code to clear a value stored in [variableName], or null if no function required. @@ -2655,11 +2320,7 @@ String? _getClearFunction(TypeDeclaration type, String variableName) { } // Returns code for the default value for [type]. -String _getDefaultValue( - String module, - TypeDeclaration type, { - bool primitive = false, -}) { +String _getDefaultValue(String module, TypeDeclaration type, {bool primitive = false}) { if (type.isClass || (type.isNullable && !primitive)) { return 'nullptr'; } else if (type.isEnum) { @@ -2715,11 +2376,7 @@ String _referenceValue( } } -String _getCustomTypeIdFromDeclaration( - Root root, - TypeDeclaration type, - String module, -) { +String _getCustomTypeIdFromDeclaration(Root root, TypeDeclaration type, String module) { return _getCustomTypeId( module, getEnumeratedTypes(root, excludeSealedClasses: true).firstWhere( @@ -2742,19 +2399,10 @@ String _makeFlValue( }) { final String value; if (type.isClass) { - final String customTypeId = _getCustomTypeIdFromDeclaration( - root, - type, - module, - ); - value = - 'fl_value_new_custom_object($customTypeId, G_OBJECT($variableName))'; + final String customTypeId = _getCustomTypeIdFromDeclaration(root, type, module); + value = 'fl_value_new_custom_object($customTypeId, G_OBJECT($variableName))'; } else if (type.isEnum) { - final String customTypeId = _getCustomTypeIdFromDeclaration( - root, - type, - module, - ); + final String customTypeId = _getCustomTypeIdFromDeclaration(root, type, module); value = 'fl_value_new_custom($customTypeId, fl_value_new_int(${type.isNullable ? '*$variableName' : variableName}), (GDestroyNotify)fl_value_unref)'; } else if (_isFlValueWrappedType(type)) { @@ -2832,27 +2480,22 @@ String _fromFlValue(String module, TypeDeclaration type, String variableName) { // Returns the name of a GObject class used to send responses to [methodName]. String _getResponseName(String name, String methodName) { - final String upperMethodName = - methodName[0].toUpperCase() + methodName.substring(1); + final String upperMethodName = methodName[0].toUpperCase() + methodName.substring(1); return '$name${upperMethodName}Response'; } void _writeHashHelpers(Indent indent) { - indent.writeScoped( - 'static guint G_GNUC_UNUSED flpigeon_hash_double(double v) {', - '}', - () { - indent.writeScoped('if (std::isnan(v)) {', '}', () { - indent.writeln('return static_cast(0x7FF80000);'); - }); - indent.writeScoped('if (v == 0.0) {', '}', () { - indent.writeln('v = 0.0;'); - }); - indent.writeln('union { double d; uint64_t u; } u;'); - indent.writeln('u.d = v;'); - indent.writeln('return static_cast(u.u ^ (u.u >> 32));'); - }, - ); + indent.writeScoped('static guint G_GNUC_UNUSED flpigeon_hash_double(double v) {', '}', () { + indent.writeScoped('if (std::isnan(v)) {', '}', () { + indent.writeln('return static_cast(0x7FF80000);'); + }); + indent.writeScoped('if (v == 0.0) {', '}', () { + indent.writeln('v = 0.0;'); + }); + indent.writeln('union { double d; uint64_t u; } u;'); + indent.writeln('u.d = v;'); + indent.writeln('return static_cast(u.u ^ (u.u >> 32));'); + }); indent.writeScoped( 'static gboolean G_GNUC_UNUSED flpigeon_equals_double(double a, double b) {', '}', @@ -2873,20 +2516,14 @@ void _writeDeepEquals(Indent indent) { indent.writeScoped('if (a == nullptr || b == nullptr) {', '}', () { indent.writeln('return FALSE;'); }); - indent.writeScoped( - 'if (fl_value_get_type(a) != fl_value_get_type(b)) {', - '}', - () { - indent.writeln('return FALSE;'); - }, - ); + indent.writeScoped('if (fl_value_get_type(a) != fl_value_get_type(b)) {', '}', () { + indent.writeln('return FALSE;'); + }); indent.writeScoped('switch (fl_value_get_type(a)) {', '}', () { indent.writeln('case FL_VALUE_TYPE_NULL:'); indent.writeln(' return TRUE;'); indent.writeln('case FL_VALUE_TYPE_BOOL:'); - indent.writeln( - ' return fl_value_get_bool(a) == fl_value_get_bool(b);', - ); + indent.writeln(' return fl_value_get_bool(a) == fl_value_get_bool(b);'); indent.writeln('case FL_VALUE_TYPE_INT:'); indent.writeln(' return fl_value_get_int(a) == fl_value_get_int(b);'); indent.writeln('case FL_VALUE_TYPE_FLOAT: {'); @@ -2895,27 +2532,19 @@ void _writeDeepEquals(Indent indent) { ); indent.writeln('}'); indent.writeln('case FL_VALUE_TYPE_STRING:'); - indent.writeln( - ' return g_strcmp0(fl_value_get_string(a), fl_value_get_string(b)) == 0;', - ); + indent.writeln(' return g_strcmp0(fl_value_get_string(a), fl_value_get_string(b)) == 0;'); indent.writeln('case FL_VALUE_TYPE_UINT8_LIST:'); - indent.writeln( - ' return fl_value_get_length(a) == fl_value_get_length(b) &&', - ); + indent.writeln(' return fl_value_get_length(a) == fl_value_get_length(b) &&'); indent.writeln( ' memcmp(fl_value_get_uint8_list(a), fl_value_get_uint8_list(b), fl_value_get_length(a)) == 0;', ); indent.writeln('case FL_VALUE_TYPE_INT32_LIST:'); - indent.writeln( - ' return fl_value_get_length(a) == fl_value_get_length(b) &&', - ); + indent.writeln(' return fl_value_get_length(a) == fl_value_get_length(b) &&'); indent.writeln( ' memcmp(fl_value_get_int32_list(a), fl_value_get_int32_list(b), fl_value_get_length(a) * sizeof(int32_t)) == 0;', ); indent.writeln('case FL_VALUE_TYPE_INT64_LIST:'); - indent.writeln( - ' return fl_value_get_length(a) == fl_value_get_length(b) &&', - ); + indent.writeln(' return fl_value_get_length(a) == fl_value_get_length(b) &&'); indent.writeln( ' memcmp(fl_value_get_int64_list(a), fl_value_get_int64_list(b), fl_value_get_length(a) * sizeof(int64_t)) == 0;', ); @@ -2927,9 +2556,7 @@ void _writeDeepEquals(Indent indent) { indent.writeln(' const double* a_data = fl_value_get_float_list(a);'); indent.writeln(' const double* b_data = fl_value_get_float_list(b);'); indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { - indent.writeln( - 'if (!flpigeon_equals_double(a_data[i], b_data[i])) {', - ); + indent.writeln('if (!flpigeon_equals_double(a_data[i], b_data[i])) {'); indent.writeln(' return FALSE;'); indent.writeln('}'); }); @@ -2960,25 +2587,19 @@ void _writeDeepEquals(Indent indent) { indent.writeln('gboolean found = FALSE;'); indent.writeScoped('for (size_t j = 0; j < len; j++) {', '}', () { indent.writeln('FlValue* b_key = fl_value_get_map_key(b, j);'); - indent.writeScoped( - 'if (flpigeon_deep_equals(key, b_key)) {', - '}', - () { - indent.writeln( - 'FlValue* b_val = fl_value_get_map_value(b, j);', - ); - indent.writeln('if (flpigeon_deep_equals(val, b_val)) {'); - indent.nest(1, () { - indent.writeln('found = TRUE;'); - indent.writeln('break;'); - }); - indent.writeln('} else {'); - indent.nest(1, () { - indent.writeln('return FALSE;'); - }); - indent.writeln('}'); - }, - ); + indent.writeScoped('if (flpigeon_deep_equals(key, b_key)) {', '}', () { + indent.writeln('FlValue* b_val = fl_value_get_map_value(b, j);'); + indent.writeln('if (flpigeon_deep_equals(val, b_val)) {'); + indent.nest(1, () { + indent.writeln('found = TRUE;'); + indent.writeln('break;'); + }); + indent.writeln('} else {'); + indent.nest(1, () { + indent.writeln('return FALSE;'); + }); + indent.writeln('}'); + }); }); indent.writeln('if (!found) {'); indent.writeln(' return FALSE;'); @@ -2995,104 +2616,82 @@ void _writeDeepEquals(Indent indent) { } void _writeDeepHash(Indent indent) { - indent.writeScoped( - 'static guint G_GNUC_UNUSED flpigeon_deep_hash(FlValue* value) {', - '}', - () { - indent.writeScoped('if (value == nullptr) {', '}', () { - indent.writeln('return 0;'); + indent.writeScoped('static guint G_GNUC_UNUSED flpigeon_deep_hash(FlValue* value) {', '}', () { + indent.writeScoped('if (value == nullptr) {', '}', () { + indent.writeln('return 0;'); + }); + indent.writeScoped('switch (fl_value_get_type(value)) {', '}', () { + indent.writeln('case FL_VALUE_TYPE_NULL:'); + indent.writeln(' return 0;'); + indent.writeln('case FL_VALUE_TYPE_BOOL:'); + indent.writeln(' return fl_value_get_bool(value) ? 1231 : 1237;'); + indent.writeln('case FL_VALUE_TYPE_INT: {'); + indent.writeln(' int64_t v = fl_value_get_int(value);'); + indent.writeln(' return static_cast(v ^ (v >> 32));'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_FLOAT:'); + indent.writeln(' return flpigeon_hash_double(fl_value_get_float(value));'); + indent.writeln('case FL_VALUE_TYPE_STRING:'); + indent.writeln(' return g_str_hash(fl_value_get_string(value));'); + indent.writeln('case FL_VALUE_TYPE_UINT8_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln(' const uint8_t* data = fl_value_get_uint8_list(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { + indent.writeln(' result = result * 31 + data[i];'); }); - indent.writeScoped('switch (fl_value_get_type(value)) {', '}', () { - indent.writeln('case FL_VALUE_TYPE_NULL:'); - indent.writeln(' return 0;'); - indent.writeln('case FL_VALUE_TYPE_BOOL:'); - indent.writeln(' return fl_value_get_bool(value) ? 1231 : 1237;'); - indent.writeln('case FL_VALUE_TYPE_INT: {'); - indent.writeln(' int64_t v = fl_value_get_int(value);'); - indent.writeln(' return static_cast(v ^ (v >> 32));'); - indent.writeln('}'); - indent.writeln('case FL_VALUE_TYPE_FLOAT:'); - indent.writeln( - ' return flpigeon_hash_double(fl_value_get_float(value));', - ); - indent.writeln('case FL_VALUE_TYPE_STRING:'); - indent.writeln(' return g_str_hash(fl_value_get_string(value));'); - indent.writeln('case FL_VALUE_TYPE_UINT8_LIST: {'); - indent.writeln(' guint result = 1;'); - indent.writeln(' size_t len = fl_value_get_length(value);'); - indent.writeln( - ' const uint8_t* data = fl_value_get_uint8_list(value);', - ); - indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { - indent.writeln(' result = result * 31 + data[i];'); - }); - indent.writeln(' return result;'); - indent.writeln('}'); - indent.writeln('case FL_VALUE_TYPE_INT32_LIST: {'); - indent.writeln(' guint result = 1;'); - indent.writeln(' size_t len = fl_value_get_length(value);'); - indent.writeln( - ' const int32_t* data = fl_value_get_int32_list(value);', - ); - indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { - indent.writeln( - ' result = result * 31 + static_cast(data[i]);', - ); - }); - indent.writeln(' return result;'); - indent.writeln('}'); - indent.writeln('case FL_VALUE_TYPE_INT64_LIST: {'); - indent.writeln(' guint result = 1;'); - indent.writeln(' size_t len = fl_value_get_length(value);'); - indent.writeln( - ' const int64_t* data = fl_value_get_int64_list(value);', - ); - indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { - indent.writeln( - ' result = result * 31 + static_cast(data[i] ^ (data[i] >> 32));', - ); - }); - indent.writeln(' return result;'); - indent.writeln('}'); - indent.writeln('case FL_VALUE_TYPE_FLOAT_LIST: {'); - indent.writeln(' guint result = 1;'); - indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_INT32_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln(' const int32_t* data = fl_value_get_int32_list(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { + indent.writeln(' result = result * 31 + static_cast(data[i]);'); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_INT64_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln(' const int64_t* data = fl_value_get_int64_list(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { + indent.writeln(' result = result * 31 + static_cast(data[i] ^ (data[i] >> 32));'); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_FLOAT_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln(' const double* data = fl_value_get_float_list(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { + indent.writeln('result = result * 31 + flpigeon_hash_double(data[i]);'); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { indent.writeln( - ' const double* data = fl_value_get_float_list(value);', + 'result = result * 31 + flpigeon_deep_hash(fl_value_get_list_value(value, i));', ); - indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { - indent.writeln( - 'result = result * 31 + flpigeon_hash_double(data[i]);', - ); - }); - indent.writeln(' return result;'); - indent.writeln('}'); - indent.writeln('case FL_VALUE_TYPE_LIST: {'); - indent.writeln(' guint result = 1;'); - indent.writeln(' size_t len = fl_value_get_length(value);'); - indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { - indent.writeln( - 'result = result * 31 + flpigeon_deep_hash(fl_value_get_list_value(value, i));', - ); - }); - indent.writeln(' return result;'); - indent.writeln('}'); - indent.writeln('case FL_VALUE_TYPE_MAP: {'); - indent.writeln(' guint result = 0;'); - indent.writeln(' size_t len = fl_value_get_length(value);'); - indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { - indent.writeln( - 'result += ((flpigeon_deep_hash(fl_value_get_map_key(value, i)) * 31) ^ flpigeon_deep_hash(fl_value_get_map_value(value, i)));', - ); - }); - indent.writeln(' return result;'); - indent.writeln('}'); - indent.writeln('default:'); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_MAP: {'); + indent.writeln(' guint result = 0;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { indent.writeln( - ' return static_cast(fl_value_get_type(value));', + 'result += ((flpigeon_deep_hash(fl_value_get_map_key(value, i)) * 31) ^ flpigeon_deep_hash(fl_value_get_map_value(value, i)));', ); }); - indent.writeln('return 0;'); - }, - ); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('default:'); + indent.writeln(' return static_cast(fl_value_get_type(value));'); + }); + indent.writeln('return 0;'); + }); } diff --git a/packages/pigeon/lib/src/kotlin/templates.dart b/packages/pigeon/lib/src/kotlin/templates.dart index f8afe99fe980..d8a7b9141d0b 100644 --- a/packages/pigeon/lib/src/kotlin/templates.dart +++ b/packages/pigeon/lib/src/kotlin/templates.dart @@ -266,5 +266,4 @@ class ${kotlinInstanceManagerClassName(options)}(private val finalizationListene '''; } -const String _finalizationListenerClassName = - '${proxyApiClassNamePrefix}FinalizationListener'; +const String _finalizationListenerClassName = '${proxyApiClassNamePrefix}FinalizationListener'; diff --git a/packages/pigeon/lib/src/pigeon_cl.dart b/packages/pigeon/lib/src/pigeon_cl.dart index 75504154bfcd..9548d968986c 100644 --- a/packages/pigeon/lib/src/pigeon_cl.dart +++ b/packages/pigeon/lib/src/pigeon_cl.dart @@ -9,10 +9,6 @@ import 'pigeon_lib.dart'; /// command line arguments and there is an optional [packageConfig] to /// accommodate users that want to integrate pigeon with other build systems. /// [sdkPath] for specifying an optional Dart SDK path. -Future runCommandLine( - List args, { - Uri? packageConfig, - String? sdkPath, -}) async { +Future runCommandLine(List args, {Uri? packageConfig, String? sdkPath}) async { return Pigeon.run(args, sdkPath: sdkPath); } diff --git a/packages/pigeon/lib/src/pigeon_lib.dart b/packages/pigeon/lib/src/pigeon_lib.dart index fd6b6c827b2b..f844a052566d 100644 --- a/packages/pigeon/lib/src/pigeon_lib.dart +++ b/packages/pigeon/lib/src/pigeon_lib.dart @@ -7,8 +7,7 @@ import 'dart:io'; import 'dart:mirrors'; -import 'package:analyzer/dart/analysis/analysis_context.dart' - show AnalysisContext; +import 'package:analyzer/dart/analysis/analysis_context.dart' show AnalysisContext; import 'package:analyzer/dart/analysis/analysis_context_collection.dart' show AnalysisContextCollection; import 'package:analyzer/dart/analysis/results.dart' show ParsedUnitResult; @@ -97,8 +96,7 @@ class ConfigurePigeon { class HostApi { /// Parametric constructor for [HostApi]. const HostApi({ - @Deprecated('Mock/fake the generated Dart API instead.') - this.dartHostTestHandler, + @Deprecated('Mock/fake the generated Dart API instead.') this.dartHostTestHandler, }); /// The name of an interface generated for tests. Implement this @@ -375,9 +373,7 @@ class PigeonOptions { gobjectHeaderOut: map['gobjectHeaderOut'] as String?, gobjectSourceOut: map['gobjectSourceOut'] as String?, gobjectOptions: map.containsKey('gobjectOptions') - ? GObjectOptions.fromMap( - map['gobjectOptions']! as Map, - ) + ? GObjectOptions.fromMap(map['gobjectOptions']! as Map) : null, dartOptions: map.containsKey('dartOptions') ? DartOptions.fromMap(map['dartOptions']! as Map) @@ -455,10 +451,7 @@ class Pigeon { /// [AnalysisContextCollection]. ParseResults parseFile(String inputPath, {String? sdkPath}) { final includedPaths = [path.absolute(path.normalize(inputPath))]; - final collection = AnalysisContextCollection( - includedPaths: includedPaths, - sdkPath: sdkPath, - ); + final collection = AnalysisContextCollection(includedPaths: includedPaths, sdkPath: sdkPath); final compilationErrors = []; final rootBuilder = RootBuilder(File(inputPath).readAsStringSync()); @@ -475,10 +468,7 @@ class Pigeon { Error( message: diagnostic.message, filename: diagnostic.source.fullName, - lineNumber: calculateLineNumber( - diagnostic.source.contents.data, - diagnostic.offset, - ), + lineNumber: calculateLineNumber(diagnostic.source.contents.data, diagnostic.offset), ), ); } @@ -489,11 +479,7 @@ class Pigeon { if (compilationErrors.isEmpty) { return rootBuilder.results(); } else { - return ParseResults( - root: Root.makeEmpty(), - errors: compilationErrors, - pigeonOptions: null, - ); + return ParseResults(root: Root.makeEmpty(), errors: compilationErrors, pigeonOptions: null); } } @@ -523,15 +509,9 @@ ${_argParser.usage}'''; 'Path to generated library for Dart tests, when using ' '@HostApi(dartHostTestHandler:).', ) - ..addOption( - 'objc_source_out', - help: 'Path to generated Objective-C source file (.m).', - ) + ..addOption('objc_source_out', help: 'Path to generated Objective-C source file (.m).') ..addOption('java_out', help: 'Path to generated Java file (.java).') - ..addOption( - 'java_package', - help: 'The package that generated Java code will be in.', - ) + ..addOption('java_package', help: 'The package that generated Java code will be in.') ..addFlag( 'java_use_generated_annotation', help: 'Adds the java.annotation.Generated annotation to the output.', @@ -565,10 +545,7 @@ ${_argParser.usage}'''; help: 'Path to generated C++ classes file (.cpp).', aliases: const ['experimental_cpp_source_out'], ) - ..addOption( - 'cpp_namespace', - help: 'The namespace that generated C++ code will be in.', - ) + ..addOption('cpp_namespace', help: 'The namespace that generated C++ code will be in.') ..addOption( 'gobject_header_out', help: 'Path to generated GObject header file (.h).', @@ -579,32 +556,17 @@ ${_argParser.usage}'''; help: 'Path to generated GObject classes file (.cc).', aliases: const ['experimental_gobject_source_out'], ) - ..addOption( - 'gobject_module', - help: 'The module that generated GObject code will be in.', - ) - ..addOption( - 'objc_header_out', - help: 'Path to generated Objective-C header file (.h).', - ) - ..addOption( - 'objc_prefix', - help: 'Prefix for generated Objective-C classes and protocols.', - ) + ..addOption('gobject_module', help: 'The module that generated GObject code will be in.') + ..addOption('objc_header_out', help: 'Path to generated Objective-C header file (.h).') + ..addOption('objc_prefix', help: 'Prefix for generated Objective-C classes and protocols.') ..addOption( 'copyright_header', - help: - 'Path to file with copyright header to be prepended to generated code.', - ) - ..addFlag( - 'one_language', - hide: true, - help: 'Does nothing, only here to avoid breaking changes', + help: 'Path to file with copyright header to be prepended to generated code.', ) + ..addFlag('one_language', hide: true, help: 'Does nothing, only here to avoid breaking changes') ..addOption( 'ast_out', - help: - 'Path to generated AST debugging info. (Warning: format subject to change)', + help: 'Path to generated AST debugging info. (Warning: format subject to change)', ) ..addFlag( 'debug_generators', @@ -616,10 +578,7 @@ ${_argParser.usage}'''; 'A base path to be prefixed to all outputs and copyright header path. Generally used for testing', hide: true, ) - ..addOption( - 'package_name', - help: 'The package that generated code will be in.', - ) + ..addOption('package_name', help: 'The package that generated code will be in.') ..addFlag( 'ignore_lints', help: 'Ignore all lint violations in generated Dart code.', @@ -644,24 +603,20 @@ ${_argParser.usage}'''; javaOut: results['java_out'] as String?, javaOptions: JavaOptions( package: results['java_package'] as String?, - useGeneratedAnnotation: - results['java_use_generated_annotation'] as bool?, + useGeneratedAnnotation: results['java_use_generated_annotation'] as bool?, ), swiftOut: results['swift_out'] as String?, kotlinOut: results['kotlin_out'] as String?, kotlinOptions: KotlinOptions( package: results['kotlin_package'] as String?, - useGeneratedAnnotation: - results['kotlin_use_generated_annotation'] as bool? ?? false, + useGeneratedAnnotation: results['kotlin_use_generated_annotation'] as bool? ?? false, ), cppHeaderOut: results['cpp_header_out'] as String?, cppSourceOut: results['cpp_source_out'] as String?, cppOptions: CppOptions(namespace: results['cpp_namespace'] as String?), gobjectHeaderOut: results['gobject_header_out'] as String?, gobjectSourceOut: results['gobject_source_out'] as String?, - gobjectOptions: GObjectOptions( - module: results['gobject_module'] as String?, - ), + gobjectOptions: GObjectOptions(module: results['gobject_module'] as String?), copyrightHeader: results['copyright_header'] as String?, astOut: results['ast_out'] as String?, debugGenerators: results['debug_generators'] as bool?, @@ -675,8 +630,7 @@ ${_argParser.usage}'''; /// Crawls through the reflection system looking for a configurePigeon method and /// executing it. static void _executeConfigurePigeon(PigeonOptions options) { - for (final LibraryMirror library - in currentMirrorSystem().libraries.values) { + for (final LibraryMirror library in currentMirrorSystem().libraries.values) { for (final DeclarationMirror declaration in library.declarations.values) { if (declaration is MethodMirror && MirrorSystem.getName(declaration.simpleName) == 'configurePigeon') { @@ -695,11 +649,7 @@ ${_argParser.usage}'''; /// command-line arguments. The optional parameter [adapters] allows you to /// customize the generators that pigeon will use. The optional parameter /// [sdkPath] allows you to specify the Dart SDK path. - static Future run( - List args, { - List? adapters, - String? sdkPath, - }) { + static Future run(List args, {List? adapters, String? sdkPath}) { final PigeonOptions options = Pigeon.parseArgs(args); return runWithOptions(options, adapters: adapters, sdkPath: sdkPath); } @@ -739,8 +689,7 @@ ${_argParser.usage}'''; return 0; } - parseResults = - parseResults ?? pigeon.parseFile(options.input!, sdkPath: sdkPath); + parseResults = parseResults ?? pigeon.parseFile(options.input!, sdkPath: sdkPath); final errors = []; errors.addAll(parseResults.errors); @@ -753,24 +702,15 @@ ${_argParser.usage}'''; } if (parseResults.pigeonOptions != null && mergeDefinitionFileOptions) { - options = PigeonOptions.fromMap( - mergeMaps(options.toMap(), parseResults.pigeonOptions!), - ); + options = PigeonOptions.fromMap(mergeMaps(options.toMap(), parseResults.pigeonOptions!)); } - final InternalPigeonOptions internalOptions = - InternalPigeonOptions.fromPigeonOptions(options); + final InternalPigeonOptions internalOptions = InternalPigeonOptions.fromPigeonOptions(options); for (final adapter in safeGeneratorAdapters) { - final IOSink? sink = adapter.shouldGenerate( - internalOptions, - FileType.source, - ); + final IOSink? sink = adapter.shouldGenerate(internalOptions, FileType.source); if (sink != null) { - final List adapterErrors = adapter.validate( - internalOptions, - parseResults.root, - ); + final List adapterErrors = adapter.validate(internalOptions, parseResults.root); errors.addAll(adapterErrors); await releaseSink(sink); } @@ -810,9 +750,7 @@ ${_argParser.usage}'''; for (final err in errors) { if (err.filename != null) { if (err.lineNumber != null) { - stderr.writeln( - 'Error: ${err.filename}:${err.lineNumber}: ${err.message}', - ); + stderr.writeln('Error: ${err.filename}:${err.lineNumber}: ${err.message}'); } else { stderr.writeln('Error: ${err.filename}: ${err.message}'); } @@ -846,11 +784,7 @@ class Error { /// A collection of an AST represented as a [Root] and [Error]'s. class ParseResults { /// Parametric constructor for [ParseResults]. - ParseResults({ - required this.root, - required this.errors, - required this.pigeonOptions, - }); + ParseResults({required this.root, required this.errors, required this.pigeonOptions}); /// The resulting AST. final Root root; diff --git a/packages/pigeon/lib/src/pigeon_lib_internal.dart b/packages/pigeon/lib/src/pigeon_lib_internal.dart index 617a901f37cc..dcb7aa5362ae 100644 --- a/packages/pigeon/lib/src/pigeon_lib_internal.dart +++ b/packages/pigeon/lib/src/pigeon_lib_internal.dart @@ -8,8 +8,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:analyzer/dart/ast/ast.dart' as dart_ast; -import 'package:analyzer/dart/ast/syntactic_entity.dart' - as dart_ast_syntactic_entity; +import 'package:analyzer/dart/ast/syntactic_entity.dart' as dart_ast_syntactic_entity; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart' as dart_ast_visitor; import 'package:collection/collection.dart' as collection; @@ -51,20 +50,14 @@ class InternalPigeonOptions { PigeonOptions options, Iterable? copyrightHeader, ) : input = options.input, - objcOptions = - (options.objcHeaderOut == null || options.objcSourceOut == null) + objcOptions = (options.objcHeaderOut == null || options.objcSourceOut == null) ? null : InternalObjcOptions.fromObjcOptions( options.objcOptions ?? const ObjcOptions(), objcHeaderOut: options.objcHeaderOut!, objcSourceOut: options.objcSourceOut!, fileSpecificClassNameComponent: - options.objcSourceOut - ?.split('/') - .lastOrNull - ?.split('.') - .firstOrNull ?? - '', + options.objcSourceOut?.split('/').lastOrNull?.split('.').firstOrNull ?? '', copyrightHeader: copyrightHeader, ), javaOptions = options.javaOut == null @@ -88,8 +81,7 @@ class InternalPigeonOptions { kotlinOut: options.kotlinOut!, copyrightHeader: copyrightHeader, ), - cppOptions = - (options.cppHeaderOut == null || options.cppSourceOut == null) + cppOptions = (options.cppHeaderOut == null || options.cppSourceOut == null) ? null : InternalCppOptions.fromCppOptions( options.cppOptions ?? const CppOptions(), @@ -97,8 +89,7 @@ class InternalPigeonOptions { cppSourceOut: options.cppSourceOut!, copyrightHeader: copyrightHeader, ), - gobjectOptions = - options.gobjectHeaderOut == null || options.gobjectSourceOut == null + gobjectOptions = options.gobjectHeaderOut == null || options.gobjectSourceOut == null ? null : InternalGObjectOptions.fromGObjectOptions( options.gobjectOptions ?? const GObjectOptions(), @@ -106,21 +97,16 @@ class InternalPigeonOptions { gobjectSourceOut: options.gobjectSourceOut!, copyrightHeader: copyrightHeader, ), - dartOptions = - (options.dartOut == null && - options.dartOptions?.sourceOutPath == null) + dartOptions = (options.dartOut == null && options.dartOptions?.sourceOutPath == null) ? null : InternalDartOptions.fromDartOptions( - options.dartOptions ?? - DartOptions(ignoreLints: options.ignoreLints), + options.dartOptions ?? DartOptions(ignoreLints: options.ignoreLints), dartOut: options.dartOut, testOut: options.dartTestOut, copyrightHeader: copyrightHeader, ), copyrightHeader = options.copyrightHeader != null - ? _lineReader( - path.posix.join(options.basePath ?? '', options.copyrightHeader), - ) + ? _lineReader(path.posix.join(options.basePath ?? '', options.copyrightHeader)) : null, astOut = options.astOut, debugGenerators = options.debugGenerators, @@ -130,15 +116,10 @@ class InternalPigeonOptions { /// Creates a instance of InternalPigeonOptions from PigeonOptions. static InternalPigeonOptions fromPigeonOptions(PigeonOptions options) { final Iterable? copyrightHeader = options.copyrightHeader != null - ? _lineReader( - path.posix.join(options.basePath ?? '', options.copyrightHeader), - ) + ? _lineReader(path.posix.join(options.basePath ?? '', options.copyrightHeader)) : null; - return InternalPigeonOptions._fromPigeonOptionsWithHeader( - options, - copyrightHeader, - ); + return InternalPigeonOptions._fromPigeonOptionsWithHeader(options, copyrightHeader); } /// Path to the file which will be processed. @@ -215,12 +196,7 @@ abstract class GeneratorAdapter { IOSink? shouldGenerate(InternalPigeonOptions options, FileType fileType); /// Write the generated code described in [root] to [sink] using the [options]. - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ); + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType); /// Generates errors that would only be appropriate for this [GeneratorAdapter]. /// @@ -242,9 +218,7 @@ void _errorOnSealedClass(List errors, String generator, Root root) { void _errorOnInheritedClass(List errors, String generator, Root root) { if (root.classes.any((Class element) => element.superClass != null)) { - errors.add( - Error(message: '$generator does not support inheritance in classes'), - ); + errors.add(Error(message: '$generator does not support inheritance in classes')); } } @@ -257,12 +231,7 @@ class AstGeneratorAdapter implements GeneratorAdapter { List get fileTypeList => const [FileType.na]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { generateAst(root, sink); } @@ -286,23 +255,13 @@ class DartGeneratorAdapter implements GeneratorAdapter { List get fileTypeList => const [FileType.na]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.dartOptions == null) { return; } const generator = DartGenerator(); - generator.generate( - options.dartOptions!, - root, - sink, - dartPackageName: options.dartPackageName, - ); + generator.generate(options.dartOptions!, root, sink, dartPackageName: options.dartPackageName); } @override @@ -322,12 +281,7 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { List get fileTypeList => const [FileType.na]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.dartOptions == null) { return; } @@ -335,8 +289,7 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { // The test code needs the actual package name of the Dart output, even if // the package name has been overridden for other uses. final String outputPackageName = - deducePackageName(options.dartOptions?.dartOut ?? '') ?? - options.dartPackageName; + deducePackageName(options.dartOptions?.dartOut ?? '') ?? options.dartPackageName; testGenerator.generateTest( options.dartOptions!, root, @@ -349,10 +302,7 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType _) { if (options.dartOptions?.testOut != null) { - return _openSink( - options.dartOptions?.testOut, - basePath: options.basePath ?? '', - ); + return _openSink(options.dartOptions?.testOut, basePath: options.basePath ?? ''); } return null; } @@ -370,18 +320,10 @@ class ObjcGeneratorAdapter implements GeneratorAdapter { static const String languageString = 'Objective-C'; @override - List get fileTypeList => const [ - FileType.header, - FileType.source, - ]; + List get fileTypeList => const [FileType.header, FileType.source]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.objcOptions == null) { return; } @@ -390,26 +332,15 @@ class ObjcGeneratorAdapter implements GeneratorAdapter { languageOptions: options.objcOptions!, ); const generator = ObjcGenerator(); - generator.generate( - outputFileOptions, - root, - sink, - dartPackageName: options.dartPackageName, - ); + generator.generate(outputFileOptions, root, sink, dartPackageName: options.dartPackageName); } @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType fileType) { if (fileType == FileType.source) { - return _openSink( - options.objcOptions?.objcSourceOut, - basePath: options.basePath ?? '', - ); + return _openSink(options.objcOptions?.objcSourceOut, basePath: options.basePath ?? ''); } else { - return _openSink( - options.objcOptions?.objcHeaderOut, - basePath: options.basePath ?? '', - ); + return _openSink(options.objcOptions?.objcHeaderOut, basePath: options.basePath ?? ''); } } @@ -435,22 +366,12 @@ class JavaGeneratorAdapter implements GeneratorAdapter { List get fileTypeList => const [FileType.na]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.javaOptions == null) { return; } const generator = JavaGenerator(); - generator.generate( - options.javaOptions!, - root, - sink, - dartPackageName: options.dartPackageName, - ); + generator.generate(options.javaOptions!, root, sink, dartPackageName: options.dartPackageName); } @override @@ -479,30 +400,17 @@ class SwiftGeneratorAdapter implements GeneratorAdapter { List get fileTypeList => const [FileType.na]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.swiftOptions == null) { return; } const generator = SwiftGenerator(); - generator.generate( - options.swiftOptions!, - root, - sink, - dartPackageName: options.dartPackageName, - ); + generator.generate(options.swiftOptions!, root, sink, dartPackageName: options.dartPackageName); } @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType _) => - _openSink( - options.swiftOptions?.swiftOut, - basePath: options.basePath ?? '', - ); + _openSink(options.swiftOptions?.swiftOut, basePath: options.basePath ?? ''); @override List validate(InternalPigeonOptions options, Root root) => []; @@ -517,18 +425,10 @@ class CppGeneratorAdapter implements GeneratorAdapter { static const String languageString = 'C++'; @override - List get fileTypeList => const [ - FileType.header, - FileType.source, - ]; + List get fileTypeList => const [FileType.header, FileType.source]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.cppOptions == null) { return; } @@ -537,26 +437,15 @@ class CppGeneratorAdapter implements GeneratorAdapter { languageOptions: options.cppOptions!, ); const generator = CppGenerator(); - generator.generate( - outputFileOptions, - root, - sink, - dartPackageName: options.dartPackageName, - ); + generator.generate(outputFileOptions, root, sink, dartPackageName: options.dartPackageName); } @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType fileType) { if (fileType == FileType.source) { - return _openSink( - options.cppOptions?.cppSourceOut, - basePath: options.basePath ?? '', - ); + return _openSink(options.cppOptions?.cppSourceOut, basePath: options.basePath ?? ''); } else { - return _openSink( - options.cppOptions?.cppHeaderOut, - basePath: options.basePath ?? '', - ); + return _openSink(options.cppOptions?.cppHeaderOut, basePath: options.basePath ?? ''); } } @@ -579,18 +468,10 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { static const String languageString = 'GObject'; @override - List get fileTypeList => const [ - FileType.header, - FileType.source, - ]; + List get fileTypeList => const [FileType.header, FileType.source]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.gobjectOptions == null) { return; } @@ -599,26 +480,15 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { languageOptions: options.gobjectOptions!, ); const generator = GObjectGenerator(); - generator.generate( - outputFileOptions, - root, - sink, - dartPackageName: options.dartPackageName, - ); + generator.generate(outputFileOptions, root, sink, dartPackageName: options.dartPackageName); } @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType fileType) { if (fileType == FileType.source) { - return _openSink( - options.gobjectOptions?.gobjectSourceOut, - basePath: options.basePath ?? '', - ); + return _openSink(options.gobjectOptions?.gobjectSourceOut, basePath: options.basePath ?? ''); } else { - return _openSink( - options.gobjectOptions?.gobjectHeaderOut, - basePath: options.basePath ?? '', - ); + return _openSink(options.gobjectOptions?.gobjectHeaderOut, basePath: options.basePath ?? ''); } } @@ -652,12 +522,7 @@ class KotlinGeneratorAdapter implements GeneratorAdapter { List get fileTypeList => const [FileType.na]; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) { + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) { if (options.kotlinOptions == null) { return; } @@ -672,29 +537,20 @@ class KotlinGeneratorAdapter implements GeneratorAdapter { @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType _) => - _openSink( - options.kotlinOptions?.kotlinOut, - basePath: options.basePath ?? '', - ); + _openSink(options.kotlinOptions?.kotlinOut, basePath: options.basePath ?? ''); @override List validate(InternalPigeonOptions options, Root root) => []; } -dart_ast.Annotation? _findMetadata( - dart_ast.NodeList metadata, - String query, -) { +dart_ast.Annotation? _findMetadata(dart_ast.NodeList metadata, String query) { final Iterable annotations = metadata.where( (dart_ast.Annotation element) => element.name.name == query, ); return annotations.isEmpty ? null : annotations.first; } -bool _hasMetadata( - dart_ast.NodeList metadata, - String query, -) { +bool _hasMetadata(dart_ast.NodeList metadata, String query) { return _findMetadata(metadata, query) != null; } @@ -705,9 +561,7 @@ extension _ObjectAs on Object { List _validateAst(Root root, String source) { final result = []; - final List customClasses = root.classes - .map((Class x) => x.name) - .toList(); + final List customClasses = root.classes.map((Class x) => x.name).toList(); final Iterable customEnums = root.enums.map((Enum x) => x.name); for (final Enum enumDefinition in root.enums) { final String? matchingPrefix = _findMatchingPrefixOrNull( @@ -750,9 +604,7 @@ List _validateAst(Root root, String source) { ), ); } - for (final NamedType field in getFieldsInSerializationOrder( - classDefinition, - )) { + for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { final String? matchingPrefix = _findMatchingPrefixOrNull( field.name, prefixes: disallowedPrefixes, @@ -781,8 +633,7 @@ List _validateAst(Root root, String source) { if (classDefinition.fields.isNotEmpty) { result.add( Error( - message: - 'Sealed class: "${classDefinition.name}" must not contain fields.', + message: 'Sealed class: "${classDefinition.name}" must not contain fields.', lineNumber: _calculateLineNumberNullable(source, field.offset), ), ); @@ -792,8 +643,7 @@ List _validateAst(Root root, String source) { if (!classDefinition.superClass!.isSealed) { result.add( Error( - message: - 'Child class: "${classDefinition.name}" must extend a sealed class.', + message: 'Child class: "${classDefinition.name}" must extend a sealed class.', lineNumber: _calculateLineNumberNullable(source, field.offset), ), ); @@ -811,19 +661,13 @@ List _validateAst(Root root, String source) { ); if (matchingPrefix != null) { result.add( - Error( - message: - 'API name must not begin with "$matchingPrefix" in API "${api.name}"', - ), + Error(message: 'API name must not begin with "$matchingPrefix" in API "${api.name}"'), ); } if (api is AstEventChannelApi) { if (containsEventChannelApi) { result.add( - Error( - message: - 'Event Channel methods must all be included in a single EventChannelApi', - ), + Error(message: 'Event Channel methods must all be included in a single EventChannelApi'), ); } containsEventChannelApi = true; @@ -906,21 +750,17 @@ List _validateAst(Root root, String source) { } } if (method.objcSelector.isNotEmpty) { - if (':'.allMatches(method.objcSelector).length != - method.parameters.length) { + if (':'.allMatches(method.objcSelector).length != method.parameters.length) { result.add( Error( - message: - 'Invalid selector, expected ${method.parameters.length} parameters.', + message: 'Invalid selector, expected ${method.parameters.length} parameters.', lineNumber: _calculateLineNumberNullable(source, method.offset), ), ); } } if (method.swiftFunction.isNotEmpty) { - final signatureRegex = RegExp( - '\\w+ *\\((\\w+:){${method.parameters.length}}\\)', - ); + final signatureRegex = RegExp('\\w+ *\\((\\w+:){${method.parameters.length}}\\)'); if (!signatureRegex.hasMatch(method.swiftFunction)) { result.add( Error( @@ -931,8 +771,7 @@ List _validateAst(Root root, String source) { ); } } - if (method.taskQueueType != TaskQueueType.serial && - method.location == ApiLocation.flutter) { + if (method.taskQueueType != TaskQueueType.serial && method.location == ApiLocation.flutter) { result.add( Error( message: 'Unsupported TaskQueue specification on ${method.name}', @@ -954,8 +793,7 @@ List _validateProxyApi( }) { final result = []; - bool isDataClass(NamedType type) => - customClasses.contains(type.type.baseName); + bool isDataClass(NamedType type) => customClasses.contains(type.type.baseName); bool isProxyApi(NamedType type) => proxyApis.any((AstProxyApi api) => api.name == type.type.baseName); Error unsupportedDataClassError(NamedType type) { @@ -984,8 +822,7 @@ List _validateProxyApi( } // Validate that the api does not inherit an unattached field from its super class. - if (directSuperClass != null && - directSuperClass.unattachedFields.isNotEmpty) { + if (directSuperClass != null && directSuperClass.unattachedFields.isNotEmpty) { result.add( Error( message: @@ -1006,8 +843,7 @@ List _validateProxyApi( if (!proxyApis.any((AstProxyApi api) => api.name == interfaceName)) { result.add( Error( - message: - 'Interface of ${api.name} is not annotated with a @ProxyApi: $interfaceName', + message: 'Interface of ${api.name} is not annotated with a @ProxyApi: $interfaceName', ), ); } @@ -1076,13 +912,8 @@ List _validateProxyApi( result.add(unsupportedDataClassError(parameter)); } - if (api.fields.any( - (ApiField field) => - field.name == parameter.name && !field.isAttached, - ) || - api.flutterMethods.any( - (Method method) => method.name == parameter.name, - )) { + if (api.fields.any((ApiField field) => field.name == parameter.name && !field.isAttached) || + api.flutterMethods.any((Method method) => method.name == parameter.name)) { result.add( Error( message: @@ -1110,28 +941,20 @@ List _validateProxyApi( Error( message: 'Parameter name must not begin with "$matchingPrefix" in constructor "${constructor.name} in API: "${api.name}"', - lineNumber: _calculateLineNumberNullable( - source, - parameter.offset, - ), + lineNumber: _calculateLineNumberNullable(source, parameter.offset), ), ); } } } if (constructor.swiftFunction.isNotEmpty) { - final signatureRegex = RegExp( - '\\w+ *\\((\\w+:){${constructor.parameters.length}}\\)', - ); + final signatureRegex = RegExp('\\w+ *\\((\\w+:){${constructor.parameters.length}}\\)'); if (!signatureRegex.hasMatch(constructor.swiftFunction)) { result.add( Error( message: 'Invalid constructor signature, expected ${constructor.parameters.length} parameters.', - lineNumber: _calculateLineNumberNullable( - source, - constructor.offset, - ), + lineNumber: _calculateLineNumberNullable(source, constructor.offset), ), ); } @@ -1161,9 +984,7 @@ List _validateProxyApi( } if (method.location == ApiLocation.flutter) { - if (!method.returnType.isVoid && - !method.returnType.isNullable && - !method.isRequired) { + if (!method.returnType.isVoid && !method.returnType.isNullable && !method.isRequired) { result.add( Error( message: @@ -1175,8 +996,7 @@ List _validateProxyApi( if (method.isStatic) { result.add( Error( - message: - 'Static callback methods are not supported: ${method.name}.', + message: 'Static callback methods are not supported: ${method.name}.', lineNumber: _calculateLineNumberNullable(source, method.offset), ), ); @@ -1210,8 +1030,7 @@ List _validateProxyApi( if (!isProxyApi(field)) { result.add( Error( - message: - 'Attached fields must be a ProxyApi: ${field.type.baseName}', + message: 'Attached fields must be a ProxyApi: ${field.type.baseName}', lineNumber: _calculateLineNumberNullable(source, field.offset), ), ); @@ -1219,8 +1038,7 @@ List _validateProxyApi( if (field.type.isNullable) { result.add( Error( - message: - 'Attached fields must not be nullable: ${field.type.baseName}?', + message: 'Attached fields must not be nullable: ${field.type.baseName}?', lineNumber: _calculateLineNumberNullable(source, field.offset), ), ); @@ -1231,10 +1049,7 @@ List _validateProxyApi( return result; } -String? _findMatchingPrefixOrNull( - String value, { - required List prefixes, -}) { +String? _findMatchingPrefixOrNull(String value, {required List prefixes}) { for (final prefix in prefixes) { if (value.startsWith(prefix)) { return prefix; @@ -1294,17 +1109,12 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { _storeCurrentApi(); _storeCurrentClass(); - final Map> referencedTypes = getReferencedTypes( - _apis, - _classes, - ); + final Map> referencedTypes = getReferencedTypes(_apis, _classes); final Set referencedTypeNames = referencedTypes.keys .map((TypeDeclaration e) => e.baseName) .toSet(); final nonReferencedTypes = List.from(_classes); - nonReferencedTypes.removeWhere( - (Class x) => referencedTypeNames.contains(x.name), - ); + nonReferencedTypes.removeWhere((Class x) => referencedTypeNames.contains(x.name)); for (final x in nonReferencedTypes) { x.isReferenced = false; } @@ -1340,12 +1150,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { final totalErrors = List.from(_errors); - for (final MapEntry> element - in referencedTypes.entries) { + for (final MapEntry> element in referencedTypes.entries) { if (!_classes.map((Class e) => e.name).contains(element.key.baseName) && - !referencedEnums - .map((Enum e) => e.name) - .contains(element.key.baseName) && + !referencedEnums.map((Enum e) => e.name).contains(element.key.baseName) && !_apis .whereType() .map((AstProxyApi e) => e.name) @@ -1359,17 +1166,12 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ? null : calculateLineNumber(source, element.value.first); totalErrors.add( - Error( - message: 'Unknown type: ${element.key.baseName}', - lineNumber: lineNumber, - ), + Error(message: 'Unknown type: ${element.key.baseName}', lineNumber: lineNumber), ); } } for (final Class classDefinition in _classes) { - classDefinition.fields = _attachAssociatedDefinitions( - classDefinition.fields, - ); + classDefinition.fields = _attachAssociatedDefinitions(classDefinition.fields); classDefinition.superClass = _attachSuperClass(classDefinition); } @@ -1380,9 +1182,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } if (api is AstProxyApi) { for (final Constructor constructor in api.constructors) { - constructor.parameters = _attachAssociatedDefinitions( - constructor.parameters, - ); + constructor.parameters = _attachAssociatedDefinitions(constructor.parameters); } api.fields = _attachAssociatedDefinitions(api.fields); @@ -1417,11 +1217,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { final Class? assocClass = _classes.firstWhereOrNull( (Class classDefinition) => classDefinition.name == type.baseName, ); - final AstProxyApi? assocProxyApi = _apis - .whereType() - .firstWhereOrNull( - (Api apiDefinition) => apiDefinition.name == type.baseName, - ); + final AstProxyApi? assocProxyApi = _apis.whereType().firstWhereOrNull( + (Api apiDefinition) => apiDefinition.name == type.baseName, + ); if (assocClass != null) { type = type.copyWithClass(assocClass); } else if (assocEnum != null) { @@ -1443,9 +1241,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { List _attachAssociatedDefinitions(Iterable types) { final result = []; for (final NamedType type in types) { - result.add( - type.copyWithType(_attachAssociatedDefinition(type.type)) as T, - ); + result.add(type.copyWithType(_attachAssociatedDefinition(type.type)) as T); } return result; } @@ -1467,12 +1263,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { Object _expressionToMap(dart_ast.Expression expression) { if (expression is dart_ast.MethodInvocation) { final result = {}; - for (final dart_ast.Expression argument - in expression.argumentList.arguments) { + for (final dart_ast.Expression argument in expression.argumentList.arguments) { if (argument is dart_ast.NamedExpression) { - result[argument.name.label.name] = _expressionToMap( - argument.expression, - ); + result[argument.name.label.name] = _expressionToMap(argument.expression); } else { _errors.add( Error( @@ -1524,8 +1317,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } else { _errors.add( Error( - message: - 'unrecognized expression type ${expression.runtimeType} $expression', + message: 'unrecognized expression type ${expression.runtimeType} $expression', lineNumber: calculateLineNumber(source, expression.offset), ), ); @@ -1559,8 +1351,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ); } final pigeonOptionsMap = - _expressionToMap(node.arguments!.arguments.first) - as Map; + _expressionToMap(node.arguments!.arguments.first) as Map; _pigeonOptions = pigeonOptionsMap; } node.visitChildren(this); @@ -1574,8 +1365,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (node.abstractKeyword != null) { if (node.metadata.length > 2 || - (node.metadata.length > 1 && - !_hasMetadata(node.metadata, 'ConfigurePigeon'))) { + (node.metadata.length > 1 && !_hasMetadata(node.metadata, 'ConfigurePigeon'))) { _errors.add( Error( message: @@ -1590,14 +1380,11 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ); String? dartHostTestHandler; if (hostApi.arguments != null) { - for (final dart_ast.Expression expression - in hostApi.arguments!.arguments) { + for (final dart_ast.Expression expression in hostApi.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { if (expression.name.label.name == 'dartHostTestHandler') { - final dart_ast.Expression dartHostTestHandlerExpression = - expression.expression; - if (dartHostTestHandlerExpression - is dart_ast.SimpleStringLiteral) { + final dart_ast.Expression dartHostTestHandlerExpression = expression.expression; + if (dartHostTestHandlerExpression is dart_ast.SimpleStringLiteral) { dartHostTestHandler = dartHostTestHandlerExpression.value; } } @@ -1609,17 +1396,13 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { name: node.namePart.typeName.lexeme, methods: [], dartHostTestHandler: dartHostTestHandler, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } else if (_hasMetadata(node.metadata, 'FlutterApi')) { _currentApi = AstFlutterApi( name: node.namePart.typeName.lexeme, methods: [], - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } else if (_hasMetadata(node.metadata, 'ProxyApi')) { final dart_ast.Annotation proxyApiAnnotation = node.metadata.firstWhere( @@ -1627,12 +1410,9 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ); final annotationMap = {}; - for (final dart_ast.Expression expression - in proxyApiAnnotation.arguments!.arguments) { + for (final dart_ast.Expression expression in proxyApiAnnotation.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { - annotationMap[expression.name.label.name] = _expressionToMap( - expression.expression, - ); + annotationMap[expression.name.label.name] = _expressionToMap(expression.expression); } } @@ -1647,10 +1427,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ), ); } else if (superClassName != null) { - superClass = TypeDeclaration( - baseName: superClassName, - isNullable: false, - ); + superClass = TypeDeclaration(baseName: superClassName, isNullable: false); } else if (node.extendsClause != null) { superClass = TypeDeclaration( baseName: node.extendsClause!.superclass.name.lexeme, @@ -1660,17 +1437,13 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { final interfaces = {}; if (node.implementsClause != null) { - for (final dart_ast.NamedType type - in node.implementsClause!.interfaces) { - interfaces.add( - TypeDeclaration(baseName: type.name.lexeme, isNullable: false), - ); + for (final dart_ast.NamedType type in node.implementsClause!.interfaces) { + interfaces.add(TypeDeclaration(baseName: type.name.lexeme, isNullable: false)); } } SwiftProxyApiOptions? swiftOptions; - final swiftOptionsMap = - annotationMap['swiftOptions'] as Map?; + final swiftOptionsMap = annotationMap['swiftOptions'] as Map?; if (swiftOptionsMap != null) { swiftOptions = SwiftProxyApiOptions( name: swiftOptionsMap['name'] as String?, @@ -1703,8 +1476,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { tryParseApiRequirement(swiftOptions?.minMacosApi); KotlinProxyApiOptions? kotlinOptions; - final kotlinOptionsMap = - annotationMap['kotlinOptions'] as Map?; + final kotlinOptionsMap = annotationMap['kotlinOptions'] as Map?; if (kotlinOptionsMap != null) { kotlinOptions = KotlinProxyApiOptions( fullClassName: kotlinOptionsMap['fullClassName'] as String?, @@ -1721,42 +1493,32 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { interfaces: interfaces, swiftOptions: swiftOptions, kotlinOptions: kotlinOptions, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } else if (_hasMetadata(node.metadata, 'EventChannelApi')) { final dart_ast.Annotation annotation = node.metadata.firstWhere( - (dart_ast.Annotation element) => - element.name.name == 'EventChannelApi', + (dart_ast.Annotation element) => element.name.name == 'EventChannelApi', ); final annotationMap = {}; - for (final dart_ast.Expression expression - in annotation.arguments!.arguments) { + for (final dart_ast.Expression expression in annotation.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { - annotationMap[expression.name.label.name] = _expressionToMap( - expression.expression, - ); + annotationMap[expression.name.label.name] = _expressionToMap(expression.expression); } } SwiftEventChannelOptions? swiftOptions; KotlinEventChannelOptions? kotlinOptions; - final swiftOptionsMap = - annotationMap['swiftOptions'] as Map?; + final swiftOptionsMap = annotationMap['swiftOptions'] as Map?; if (swiftOptionsMap != null) { swiftOptions = SwiftEventChannelOptions( - includeSharedClasses: - swiftOptionsMap['includeSharedClasses'] as bool? ?? true, + includeSharedClasses: swiftOptionsMap['includeSharedClasses'] as bool? ?? true, ); } - final kotlinOptionsMap = - annotationMap['kotlinOptions'] as Map?; + final kotlinOptionsMap = annotationMap['kotlinOptions'] as Map?; if (kotlinOptionsMap != null) { kotlinOptions = KotlinEventChannelOptions( - includeSharedClasses: - kotlinOptionsMap['includeSharedClasses'] as bool? ?? true, + includeSharedClasses: kotlinOptionsMap['includeSharedClasses'] as bool? ?? true, ); } _currentApi = AstEventChannelApi( @@ -1764,9 +1526,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { methods: [], swiftOptions: swiftOptions, kotlinOptions: kotlinOptions, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } } else { @@ -1778,9 +1538,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { node.extendsClause?.superclass.name.toString(), isSealed: node.sealedKeyword != null, isSwiftClass: _hasMetadata(node.metadata, 'SwiftClass'), - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); } @@ -1809,15 +1567,15 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { bool? isRequired, String? defaultValue, }) { - final dart_ast.NamedType? parameter = - _getFirstChildOfType(formalParameter); + final dart_ast.NamedType? parameter = _getFirstChildOfType(formalParameter); final dart_ast.SimpleFormalParameter? simpleFormalParameter = _getFirstChildOfType(formalParameter); if (parameter != null) { final String argTypeBaseName = _getNamedTypeQualifiedName(parameter); final isNullable = parameter.question != null; - final List argTypeArguments = - _typeAnnotationsToTypeArguments(parameter.typeArguments); + final List argTypeArguments = _typeAnnotationsToTypeArguments( + parameter.typeArguments, + ); return Parameter( type: TypeDeclaration( baseName: argTypeBaseName, @@ -1856,8 +1614,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } static T? _getFirstChildOfType(dart_ast.AstNode entity) { - for (final dart_ast_syntactic_entity.SyntacticEntity child - in entity.childEntities) { + for (final dart_ast_syntactic_entity.SyntacticEntity child in entity.childEntities) { if (child is T) { return child as T; } @@ -1886,17 +1643,16 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { final bool isAsynchronous = _hasMetadata(node.metadata, 'async'); final bool isStatic = _hasMetadata(node.metadata, 'static'); final String objcSelector = - _findMetadata(node.metadata, 'ObjCSelector')?.arguments?.arguments.first - .asNullable() - ?.value ?? + _findMetadata( + node.metadata, + 'ObjCSelector', + )?.arguments?.arguments.first.asNullable()?.value ?? ''; final String swiftFunction = - _findMetadata(node.metadata, 'SwiftFunction') - ?.arguments - ?.arguments - .first - .asNullable() - ?.value ?? + _findMetadata( + node.metadata, + 'SwiftFunction', + )?.arguments?.arguments.first.asNullable()?.value ?? ''; final dart_ast.ArgumentList? taskQueueArguments = _findMetadata( node.metadata, @@ -1908,8 +1664,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { taskQueueArguments, )?.expression.asNullable()?.name; final TaskQueueType taskQueueType = - _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? - TaskQueueType.serial; + _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? TaskQueueType.serial; if (_currentApi != null) { // Methods without named return types aren't supported. @@ -1923,13 +1678,11 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { // `node.declaredFragment!.element.returnType`. String erroneousDeclaration = node.name.lexeme; dart_ast.AstNode? enclosingDeclaration = node.parent; - while (enclosingDeclaration != null && - enclosingDeclaration is! dart_ast.ClassDeclaration) { + while (enclosingDeclaration != null && enclosingDeclaration is! dart_ast.ClassDeclaration) { enclosingDeclaration = enclosingDeclaration.parent; } if (enclosingDeclaration is dart_ast.ClassDeclaration) { - erroneousDeclaration = - '${enclosingDeclaration.namePart.typeName}.$erroneousDeclaration'; + erroneousDeclaration = '${enclosingDeclaration.namePart.typeName}.$erroneousDeclaration'; } _errors.add( Error( @@ -1945,9 +1698,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { name: node.name.lexeme, returnType: TypeDeclaration( baseName: _getNamedTypeQualifiedName(returnType), - typeArguments: _typeAnnotationsToTypeArguments( - returnType.typeArguments, - ), + typeArguments: _typeAnnotationsToTypeArguments(returnType.typeArguments), isNullable: returnType.question != null, ), parameters: arguments, @@ -1963,17 +1714,14 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { swiftFunction: swiftFunction, offset: node.offset, taskQueueType: taskQueueType, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ), ); } } else if (_currentClass != null) { _errors.add( Error( - message: - 'Methods aren\'t supported in Pigeon data classes ("${node.name.lexeme}").', + message: 'Methods aren\'t supported in Pigeon data classes ("${node.name.lexeme}").', lineNumber: calculateLineNumber(source, node.offset), ), ); @@ -1991,24 +1739,18 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { .map( (dart_ast.EnumConstantDeclaration e) => EnumMember( name: e.name.lexeme, - documentationComments: _documentationCommentsParser( - e.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(e.documentationComment?.tokens), ), ) .toList(), - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ), ); node.visitChildren(this); return null; } - List _typeAnnotationsToTypeArguments( - dart_ast.TypeArgumentList? typeArguments, - ) { + List _typeAnnotationsToTypeArguments(dart_ast.TypeArgumentList? typeArguments) { final result = []; if (typeArguments != null) { for (final Object x in typeArguments.childEntities) { @@ -2033,8 +1775,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (node.isStatic) { _errors.add( Error( - message: - 'Pigeon doesn\'t support static fields ("$node"), consider using enums.', + message: 'Pigeon doesn\'t support static fields ("$node"), consider using enums.', lineNumber: calculateLineNumber(source, node.offset), ), ); @@ -2061,9 +1802,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { name: name, offset: node.offset, defaultValue: _currentClassDefaultValues[name], - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ); _currentClass!.fields.add(field); } @@ -2097,12 +1836,10 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { .map(_formalParameterToPigeonParameter) .toList(); final String swiftFunction = - _findMetadata(node.metadata, 'SwiftFunction') - ?.arguments - ?.arguments - .first - .asNullable() - ?.value ?? + _findMetadata( + node.metadata, + 'SwiftFunction', + )?.arguments?.arguments.first.asNullable()?.value ?? ''; (_currentApi as AstProxyApi?)!.constructors.add( @@ -2111,9 +1848,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { parameters: arguments, swiftFunction: swiftFunction, offset: node.offset, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ), ); } else if (_currentApi != null) { @@ -2127,8 +1862,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (node.body.beginToken.lexeme != ';') { _errors.add( Error( - message: - 'Constructor bodies aren\'t supported in data classes ("$node").', + message: 'Constructor bodies aren\'t supported in data classes ("$node").', lineNumber: calculateLineNumber(source, node.offset), ), ); @@ -2141,13 +1875,10 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ), ); } else { - for (final dart_ast.FormalParameter param - in node.parameters.parameters) { + for (final dart_ast.FormalParameter param in node.parameters.parameters) { if (param is dart_ast.DefaultFormalParameter) { if (param.name != null && param.defaultValue != null) { - _currentClassDefaultValues[param.name!.toString()] = param - .defaultValue! - .toString(); + _currentClassDefaultValues[param.name!.toString()] = param.defaultValue!.toString(); } } } @@ -2165,22 +1896,17 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { return node.name.lexeme; } - void _addProxyApiField( - dart_ast.TypeAnnotation? type, - dart_ast.FieldDeclaration node, - ) { + void _addProxyApiField(dart_ast.TypeAnnotation? type, dart_ast.FieldDeclaration node) { final bool isStatic = _hasMetadata(node.metadata, 'static'); if (type is dart_ast.GenericFunctionType) { final List parameters = type.parameters.parameters .map(_formalParameterToPigeonParameter) .toList(); final String swiftFunction = - _findMetadata(node.metadata, 'SwiftFunction') - ?.arguments - ?.arguments - .first - .asNullable() - ?.value ?? + _findMetadata( + node.metadata, + 'SwiftFunction', + )?.arguments?.arguments.first.asNullable()?.value ?? ''; final dart_ast.ArgumentList? taskQueueArguments = _findMetadata( node.metadata, @@ -2192,8 +1918,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { taskQueueArguments, )?.expression.asNullable()?.name; final TaskQueueType taskQueueType = - _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? - TaskQueueType.serial; + _stringToEnum(TaskQueueType.values, taskQueueTypeName) ?? TaskQueueType.serial; // Methods without named return types aren't supported. final dart_ast.TypeAnnotation returnType = type.returnType!; @@ -2204,9 +1929,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { name: node.fields.variables[0].name.lexeme, returnType: TypeDeclaration( baseName: _getNamedTypeQualifiedName(returnType), - typeArguments: _typeAnnotationsToTypeArguments( - returnType.typeArguments, - ), + typeArguments: _typeAnnotationsToTypeArguments(returnType.typeArguments), isNullable: returnType.question != null, ), location: ApiLocation.flutter, @@ -2217,9 +1940,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { swiftFunction: swiftFunction, offset: node.offset, taskQueueType: taskQueueType, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ), ); } else if (type is dart_ast.NamedType) { @@ -2246,9 +1967,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { isAttached: _hasMetadata(node.metadata, 'attached') || isStatic, isStatic: isStatic, offset: node.offset, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, - ), + documentationComments: _documentationCommentsParser(node.documentationComment?.tokens), ), ); } diff --git a/packages/pigeon/pigeons/configure_pigeon_dart_out.dart b/packages/pigeon/pigeons/configure_pigeon_dart_out.dart index 05282780d62f..71a54f41833b 100644 --- a/packages/pigeon/pigeons/configure_pigeon_dart_out.dart +++ b/packages/pigeon/pigeons/configure_pigeon_dart_out.dart @@ -5,11 +5,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( - PigeonOptions( - dartOut: 'stdout', - javaOut: 'stdout', - dartOptions: DartOptions(ignoreLints: false), - ), + PigeonOptions(dartOut: 'stdout', javaOut: 'stdout', dartOptions: DartOptions(ignoreLints: false)), ) @HostApi() abstract class ConfigurePigeonApi { diff --git a/packages/pigeon/pigeons/core_tests.dart b/packages/pigeon/pigeons/core_tests.dart index f55c0bbfd519..572dac448ba9 100644 --- a/packages/pigeon/pigeons/core_tests.dart +++ b/packages/pigeon/pigeons/core_tests.dart @@ -377,9 +377,7 @@ abstract class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoClassMap:') @SwiftFunction('echo(classMap:)') - Map echoClassMap( - Map classMap, - ); + Map echoClassMap(Map classMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNonNullStringMap:') @@ -399,9 +397,7 @@ abstract class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNonNullClassMap:') @SwiftFunction('echoNonNull(classMap:)') - Map echoNonNullClassMap( - Map classMap, - ); + Map echoNonNullClassMap(Map classMap); /// Returns the passed class to test nested class serialization and deserialization. @ObjCSelector('echoClassWrapper:') @@ -442,9 +438,7 @@ abstract class HostIntegrationCoreApi { int getAllNullableTypesHash(AllNullableTypes value); /// Returns the platform-side hash code for the given object. - int getAllNullableTypesWithoutRecursionHash( - AllNullableTypesWithoutRecursion value, - ); + int getAllNullableTypesWithoutRecursionHash(AllNullableTypesWithoutRecursion value); /// Returns the passed object, to test serialization and deserialization. @ObjCSelector('echoAllNullableTypes:') @@ -481,9 +475,7 @@ abstract class HostIntegrationCoreApi { /// Returns passed in arguments of multiple types. @ObjCSelector('sendMultipleNullableTypesWithoutRecursionABool:anInt:aString:') - @SwiftFunction( - 'sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)', - ) + @SwiftFunction('sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)') AllNullableTypesWithoutRecursion sendMultipleNullableTypesWithoutRecursion( bool? aNullableBool, int? aNullableInt, @@ -533,9 +525,7 @@ abstract class HostIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableClassList:') @SwiftFunction('echoNullable(classList:)') - List? echoNullableClassList( - List? classList, - ); + List? echoNullableClassList(List? classList); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullEnumList:') @@ -545,9 +535,7 @@ abstract class HostIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullClassList:') @SwiftFunction('echoNullableNonNull(classList:)') - List? echoNullableNonNullClassList( - List? classList, - ); + List? echoNullableNonNullClassList(List? classList); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableMap:') @@ -557,9 +545,7 @@ abstract class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableStringMap:') @SwiftFunction('echoNullable(stringMap:)') - Map? echoNullableStringMap( - Map? stringMap, - ); + Map? echoNullableStringMap(Map? stringMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableIntMap:') @@ -574,16 +560,12 @@ abstract class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableClassMap:') @SwiftFunction('echoNullable(classMap:)') - Map? echoNullableClassMap( - Map? classMap, - ); + Map? echoNullableClassMap(Map? classMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullStringMap:') @SwiftFunction('echoNullableNonNull(stringMap:)') - Map? echoNullableNonNullStringMap( - Map? stringMap, - ); + Map? echoNullableNonNullStringMap(Map? stringMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullIntMap:') @@ -598,9 +580,7 @@ abstract class HostIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullClassMap:') @SwiftFunction('echoNullableNonNull(classMap:)') - Map? echoNullableNonNullClassMap( - Map? classMap, - ); + Map? echoNullableNonNullClassMap(Map? classMap); @ObjCSelector('echoNullableEnum:') @SwiftFunction('echoNullable(_:)') @@ -709,9 +689,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('echoAsyncClassMap:') @SwiftFunction('echoAsync(classMap:)') - Map echoAsyncClassMap( - Map classMap, - ); + Map echoAsyncClassMap(Map classMap); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async @@ -747,16 +725,13 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('echoAsyncNullableAllNullableTypes:') @SwiftFunction('echoAsync(_:)') - AllNullableTypes? echoAsyncNullableAllNullableTypes( - AllNullableTypes? everything, - ); + AllNullableTypes? echoAsyncNullableAllNullableTypes(AllNullableTypes? everything); /// Returns the passed object, to test serialization and deserialization. @async @ObjCSelector('echoAsyncNullableAllNullableTypesWithoutRecursion:') @SwiftFunction('echoAsync(_:)') - AllNullableTypesWithoutRecursion? - echoAsyncNullableAllNullableTypesWithoutRecursion( + AllNullableTypesWithoutRecursion? echoAsyncNullableAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ); @@ -812,9 +787,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('echoAsyncNullableClassList:') @SwiftFunction('echoAsyncNullable(classList:)') - List? echoAsyncNullableClassList( - List? classList, - ); + List? echoAsyncNullableClassList(List? classList); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @@ -826,9 +799,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('echoAsyncNullableStringMap:') @SwiftFunction('echoAsyncNullable(stringMap:)') - Map? echoAsyncNullableStringMap( - Map? stringMap, - ); + Map? echoAsyncNullableStringMap(Map? stringMap); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @@ -840,17 +811,13 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('echoAsyncNullableEnumMap:') @SwiftFunction('echoAsyncNullable(enumMap:)') - Map? echoAsyncNullableEnumMap( - Map? enumMap, - ); + Map? echoAsyncNullableEnumMap(Map? enumMap); /// Returns the passed map, to test asynchronous serialization and deserialization. @async @ObjCSelector('echoAsyncNullableClassMap:') @SwiftFunction('echoAsyncNullable(classMap:)') - Map? echoAsyncNullableClassMap( - Map? classMap, - ); + Map? echoAsyncNullableClassMap(Map? classMap); /// Returns the passed enum, to test asynchronous serialization and deserialization. @async @@ -894,9 +861,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoAllNullableTypes:') @SwiftFunction('callFlutterEcho(_:)') - AllNullableTypes? callFlutterEchoAllNullableTypes( - AllNullableTypes? everything, - ); + AllNullableTypes? callFlutterEchoAllNullableTypes(AllNullableTypes? everything); @async @ObjCSelector('callFlutterSendMultipleNullableTypesABool:anInt:aString:') @@ -910,20 +875,14 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoAllNullableTypesWithoutRecursion:') @SwiftFunction('callFlutterEcho(_:)') - AllNullableTypesWithoutRecursion? - callFlutterEchoAllNullableTypesWithoutRecursion( + AllNullableTypesWithoutRecursion? callFlutterEchoAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ); @async - @ObjCSelector( - 'callFlutterSendMultipleNullableTypesWithoutRecursionABool:anInt:aString:', - ) - @SwiftFunction( - 'callFlutterSendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)', - ) - AllNullableTypesWithoutRecursion - callFlutterSendMultipleNullableTypesWithoutRecursion( + @ObjCSelector('callFlutterSendMultipleNullableTypesWithoutRecursionABool:anInt:aString:') + @SwiftFunction('callFlutterSendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)') + AllNullableTypesWithoutRecursion callFlutterSendMultipleNullableTypesWithoutRecursion( bool? aNullableBool, int? aNullableInt, String? aNullableString, @@ -967,9 +926,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoClassList:') @SwiftFunction('callFlutterEcho(classList:)') - List callFlutterEchoClassList( - List classList, - ); + List callFlutterEchoClassList(List classList); @async @ObjCSelector('callFlutterEchoNonNullEnumList:') @@ -979,9 +936,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoNonNullClassList:') @SwiftFunction('callFlutterEchoNonNull(classList:)') - List callFlutterEchoNonNullClassList( - List classList, - ); + List callFlutterEchoNonNullClassList(List classList); @async @ObjCSelector('callFlutterEchoMap:') @@ -991,9 +946,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoStringMap:') @SwiftFunction('callFlutterEcho(stringMap:)') - Map callFlutterEchoStringMap( - Map stringMap, - ); + Map callFlutterEchoStringMap(Map stringMap); @async @ObjCSelector('callFlutterEchoIntMap:') @@ -1008,16 +961,12 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoClassMap:') @SwiftFunction('callFlutterEcho(classMap:)') - Map callFlutterEchoClassMap( - Map classMap, - ); + Map callFlutterEchoClassMap(Map classMap); @async @ObjCSelector('callFlutterEchoNonNullStringMap:') @SwiftFunction('callFlutterEchoNonNull(stringMap:)') - Map callFlutterEchoNonNullStringMap( - Map stringMap, - ); + Map callFlutterEchoNonNullStringMap(Map stringMap); @async @ObjCSelector('callFlutterEchoNonNullIntMap:') @@ -1027,16 +976,12 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoNonNullEnumMap:') @SwiftFunction('callFlutterEchoNonNull(enumMap:)') - Map callFlutterEchoNonNullEnumMap( - Map enumMap, - ); + Map callFlutterEchoNonNullEnumMap(Map enumMap); @async @ObjCSelector('callFlutterEchoNonNullClassMap:') @SwiftFunction('callFlutterEchoNonNull(classMap:)') - Map callFlutterEchoNonNullClassMap( - Map classMap, - ); + Map callFlutterEchoNonNullClassMap(Map classMap); @async @ObjCSelector('callFlutterEchoEnum:') @@ -1086,9 +1031,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoNullableClassList:') @SwiftFunction('callFlutterEchoNullable(classList:)') - List? callFlutterEchoNullableClassList( - List? classList, - ); + List? callFlutterEchoNullableClassList(List? classList); @async @ObjCSelector('callFlutterEchoNullableNonNullEnumList:') @@ -1110,9 +1053,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoNullableStringMap:') @SwiftFunction('callFlutterEchoNullable(stringMap:)') - Map? callFlutterEchoNullableStringMap( - Map? stringMap, - ); + Map? callFlutterEchoNullableStringMap(Map? stringMap); @async @ObjCSelector('callFlutterEchoNullableIntMap:') @@ -1122,9 +1063,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoNullableEnumMap:') @SwiftFunction('callFlutterEchoNullable(enumMap:)') - Map? callFlutterEchoNullableEnumMap( - Map? enumMap, - ); + Map? callFlutterEchoNullableEnumMap(Map? enumMap); @async @ObjCSelector('callFlutterEchoNullableClassMap:') @@ -1136,9 +1075,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoNullableNonNullStringMap:') @SwiftFunction('callFlutterEchoNullableNonNull(stringMap:)') - Map? callFlutterEchoNullableNonNullStringMap( - Map? stringMap, - ); + Map? callFlutterEchoNullableNonNullStringMap(Map? stringMap); @async @ObjCSelector('callFlutterEchoNullableNonNullIntMap:') @@ -1148,9 +1085,7 @@ abstract class HostIntegrationCoreApi { @async @ObjCSelector('callFlutterEchoNullableNonNullEnumMap:') @SwiftFunction('callFlutterEchoNullableNonNull(enumMap:)') - Map? callFlutterEchoNullableNonNullEnumMap( - Map? enumMap, - ); + Map? callFlutterEchoNullableNonNullEnumMap(Map? enumMap); @async @ObjCSelector('callFlutterEchoNullableNonNullClassMap:') @@ -1221,9 +1156,7 @@ abstract class FlutterIntegrationCoreApi { /// /// Tests multiple-arity FlutterApi handling. @ObjCSelector('sendMultipleNullableTypesWithoutRecursionABool:anInt:aString:') - @SwiftFunction( - 'sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)', - ) + @SwiftFunction('sendMultipleNullableTypesWithoutRecursion(aBool:anInt:aString:)') AllNullableTypesWithoutRecursion sendMultipleNullableTypesWithoutRecursion( bool? aNullableBool, int? aNullableInt, @@ -1305,9 +1238,7 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoClassMap:') @SwiftFunction('echo(classMap:)') - Map echoClassMap( - Map classMap, - ); + Map echoClassMap(Map classMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNonNullStringMap:') @@ -1327,9 +1258,7 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNonNullClassMap:') @SwiftFunction('echoNonNull(classMap:)') - Map echoNonNullClassMap( - Map classMap, - ); + Map echoNonNullClassMap(Map classMap); /// Returns the passed enum to test serialization and deserialization. @ObjCSelector('echoEnum:') @@ -1381,9 +1310,7 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableClassList:') @SwiftFunction('echoNullable(classList:)') - List? echoNullableClassList( - List? classList, - ); + List? echoNullableClassList(List? classList); /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullEnumList:') @@ -1393,9 +1320,7 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed list, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullClassList:') @SwiftFunction('echoNullableNonNull(classList:)') - List? echoNullableNonNullClassList( - List? classList, - ); + List? echoNullableNonNullClassList(List? classList); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableMap:') @@ -1405,9 +1330,7 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableStringMap:') @SwiftFunction('echoNullable(stringMap:)') - Map? echoNullableStringMap( - Map? stringMap, - ); + Map? echoNullableStringMap(Map? stringMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableIntMap:') @@ -1422,16 +1345,12 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableClassMap:') @SwiftFunction('echoNullable(classMap:)') - Map? echoNullableClassMap( - Map? classMap, - ); + Map? echoNullableClassMap(Map? classMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullStringMap:') @SwiftFunction('echoNullableNonNull(stringMap:)') - Map? echoNullableNonNullStringMap( - Map? stringMap, - ); + Map? echoNullableNonNullStringMap(Map? stringMap); /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullIntMap:') @@ -1446,9 +1365,7 @@ abstract class FlutterIntegrationCoreApi { /// Returns the passed map, to test serialization and deserialization. @ObjCSelector('echoNullableNonNullClassMap:') @SwiftFunction('echoNullableNonNull(classMap:)') - Map? echoNullableNonNullClassMap( - Map? classMap, - ); + Map? echoNullableNonNullClassMap(Map? classMap); /// Returns the passed enum to test serialization and deserialization. @ObjCSelector('echoNullableEnum:') diff --git a/packages/pigeon/pigeons/message.dart b/packages/pigeon/pigeons/message.dart index a261a9893f85..5a25c478447f 100644 --- a/packages/pigeon/pigeons/message.dart +++ b/packages/pigeon/pigeons/message.dart @@ -9,10 +9,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( - javaOptions: JavaOptions( - className: 'MessagePigeon', - package: 'dev.flutter.aaclarke.pigeon', - ), + javaOptions: JavaOptions(className: 'MessagePigeon', package: 'dev.flutter.aaclarke.pigeon'), objcOptions: ObjcOptions(prefix: 'AC'), ), ) diff --git a/packages/pigeon/pigeons/non_null_fields.dart b/packages/pigeon/pigeons/non_null_fields.dart index b73d7fdf6920..144032498afb 100644 --- a/packages/pigeon/pigeons/non_null_fields.dart +++ b/packages/pigeon/pigeons/non_null_fields.dart @@ -21,13 +21,7 @@ class ExtraData { enum ReplyType { success, error } class NonNullFieldSearchReply { - NonNullFieldSearchReply( - this.result, - this.error, - this.indices, - this.extraData, - this.type, - ); + NonNullFieldSearchReply(this.result, this.error, this.indices, this.extraData, this.type); String result; String error; List indices; diff --git a/packages/pigeon/pigeons/null_fields.dart b/packages/pigeon/pigeons/null_fields.dart index 6afe85c3afc8..b72f6e99759b 100644 --- a/packages/pigeon/pigeons/null_fields.dart +++ b/packages/pigeon/pigeons/null_fields.dart @@ -18,13 +18,7 @@ class NullFieldsSearchRequest { enum NullFieldsSearchReplyType { success, failure } class NullFieldsSearchReply { - NullFieldsSearchReply( - this.result, - this.error, - this.indices, - this.request, - this.type, - ); + NullFieldsSearchReply(this.result, this.error, this.indices, this.request, this.type); String? result; String? error; List? indices; diff --git a/packages/pigeon/pigeons/proxy_api_tests.dart b/packages/pigeon/pigeons/proxy_api_tests.dart index a3480d679d3f..f58c7bb22448 100644 --- a/packages/pigeon/pigeons/proxy_api_tests.dart +++ b/packages/pigeon/pigeons/proxy_api_tests.dart @@ -9,8 +9,7 @@ enum ProxyApiTestEnum { one, two, three } /// The core ProxyApi test class that each supported host language must /// implement in platform_tests integration tests. @ProxyApi() -abstract class ProxyApiTestClass extends ProxyApiSuperClass - implements ProxyApiInterface { +abstract class ProxyApiTestClass extends ProxyApiSuperClass implements ProxyApiInterface { ProxyApiTestClass( // ignore: avoid_unused_constructor_parameters bool boolParam, @@ -110,26 +109,21 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. - late List Function(List aList) - flutterEchoProxyApiList; + late List Function(List aList) flutterEchoProxyApiList; /// Returns the passed map, to test serialization and deserialization. - late Map Function(Map aMap) - flutterEchoMap; + late Map Function(Map aMap) flutterEchoMap; /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. - late Map Function( - Map aMap, - ) + late Map Function(Map aMap) flutterEchoProxyApiMap; /// Returns the passed enum to test serialization and deserialization. late ProxyApiTestEnum Function(ProxyApiTestEnum anEnum) flutterEchoEnum; /// Returns the passed ProxyApi to test serialization and deserialization. - late ProxyApiSuperClass Function(ProxyApiSuperClass aProxyApi) - flutterEchoProxyApi; + late ProxyApiSuperClass Function(ProxyApiSuperClass aProxyApi) flutterEchoProxyApi; // ========== Nullable argument/return type tests ========== @@ -152,16 +146,13 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass late List? Function(List? aList)? flutterEchoNullableList; /// Returns the passed map, to test serialization and deserialization. - late Map? Function(Map? aMap)? - flutterEchoNullableMap; + late Map? Function(Map? aMap)? flutterEchoNullableMap; /// Returns the passed enum to test serialization and deserialization. - late ProxyApiTestEnum? Function(ProxyApiTestEnum? anEnum)? - flutterEchoNullableEnum; + late ProxyApiTestEnum? Function(ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum; /// Returns the passed ProxyApi to test serialization and deserialization. - late ProxyApiSuperClass? Function(ProxyApiSuperClass? aProxyApi)? - flutterEchoNullableProxyApi; + late ProxyApiSuperClass? Function(ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi; // ========== Async tests ========== // These are minimal since async FlutterApi only changes Dart generation. @@ -222,9 +213,7 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed map with ProxyApis, to test serialization and /// deserialization. - Map echoProxyApiMap( - Map aMap, - ); + Map echoProxyApiMap(Map aMap); /// Returns the passed enum to test serialization and deserialization. ProxyApiTestEnum echoEnum(ProxyApiTestEnum anEnum); @@ -261,9 +250,7 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass ProxyApiTestEnum? echoNullableEnum(ProxyApiTestEnum? aNullableEnum); /// Returns the passed ProxyApi to test serialization and deserialization. - ProxyApiSuperClass? echoNullableProxyApi( - ProxyApiSuperClass? aNullableProxyApi, - ); + ProxyApiSuperClass? echoNullableProxyApi(ProxyApiSuperClass? aNullableProxyApi); // ========== Asynchronous method tests ========== @@ -398,9 +385,7 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass List callFlutterEchoList(List aList); @async - List callFlutterEchoProxyApiList( - List aList, - ); + List callFlutterEchoProxyApiList(List aList); @async Map callFlutterEchoMap(Map aMap); @@ -435,17 +420,13 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass List? callFlutterEchoNullableList(List? aList); @async - Map? callFlutterEchoNullableMap( - Map? aMap, - ); + Map? callFlutterEchoNullableMap(Map? aMap); @async ProxyApiTestEnum? callFlutterEchoNullableEnum(ProxyApiTestEnum? anEnum); @async - ProxyApiSuperClass? callFlutterEchoNullableProxyApi( - ProxyApiSuperClass? aProxyApi, - ); + ProxyApiSuperClass? callFlutterEchoNullableProxyApi(ProxyApiSuperClass? aProxyApi); @async void callFlutterNoopAsync(); @@ -456,9 +437,7 @@ abstract class ProxyApiTestClass extends ProxyApiSuperClass /// ProxyApi to serve as a super class to the core ProxyApi class. @ProxyApi( - kotlinOptions: KotlinProxyApiOptions( - fullClassName: 'com.example.test_plugin.ProxyApiSuperClass', - ), + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'com.example.test_plugin.ProxyApiSuperClass'), swiftOptions: SwiftProxyApiOptions(name: 'ProxyApiSuperClass'), ) abstract class ProxyApiSuperClass { @@ -475,10 +454,7 @@ abstract class ProxyApiInterface { @ProxyApi( kotlinOptions: KotlinProxyApiOptions(minAndroidApi: 25), - swiftOptions: SwiftProxyApiOptions( - minIosApi: '15.0.0', - minMacosApi: '10.0.0', - ), + swiftOptions: SwiftProxyApiOptions(minIosApi: '15.0.0', minMacosApi: '10.0.0'), ) abstract class ClassWithApiRequirement { ClassWithApiRequirement(); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart index 9ed43123a701..131041caab3d 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart @@ -52,9 +52,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(api.noop(), completes); }); - testWidgets('all datatypes serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('all datatypes serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.echoAllTypes(genericAllTypes); @@ -73,106 +71,89 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, recursiveAllNullableTypes); }); - testWidgets('all null datatypes serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('all null datatypes serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final allTypesNull = AllNullableTypes(); - final AllNullableTypes? echoNullFilledClass = await api - .echoAllNullableTypes(allTypesNull); + final AllNullableTypes? echoNullFilledClass = await api.echoAllNullableTypes(allTypesNull); expect(allTypesNull, echoNullFilledClass); }); - testWidgets( - 'Classes with list of null serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('Classes with list of null serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final listTypes = AllNullableTypes(list: ['String', null]); + final listTypes = AllNullableTypes(list: ['String', null]); - final AllNullableTypes? echoNullFilledClass = await api - .echoAllNullableTypes(listTypes); + final AllNullableTypes? echoNullFilledClass = await api.echoAllNullableTypes(listTypes); - expect(listTypes, echoNullFilledClass); - }, - ); + expect(listTypes, echoNullFilledClass); + }); - testWidgets( - 'Classes with map of null serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('Classes with map of null serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final listTypes = AllNullableTypes( - map: {'String': 'string', 'null': null}, - ); + final listTypes = AllNullableTypes(map: {'String': 'string', 'null': null}); - final AllNullableTypes? echoNullFilledClass = await api - .echoAllNullableTypes(listTypes); + final AllNullableTypes? echoNullFilledClass = await api.echoAllNullableTypes(listTypes); - expect(listTypes, echoNullFilledClass); - }, - ); + expect(listTypes, echoNullFilledClass); + }); - testWidgets( - 'all nullable datatypes without recursion serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('all nullable datatypes without recursion serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion? echoObject = await api - .echoAllNullableTypesWithoutRecursion( - genericAllNullableTypesWithoutRecursion, - ); + final AllNullableTypesWithoutRecursion? echoObject = await api + .echoAllNullableTypesWithoutRecursion(genericAllNullableTypesWithoutRecursion); - expect(echoObject, genericAllNullableTypesWithoutRecursion); - }, - ); + expect(echoObject, genericAllNullableTypesWithoutRecursion); + }); - testWidgets( - 'all null datatypes without recursion serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('all null datatypes without recursion serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final allTypesNull = AllNullableTypesWithoutRecursion(); + final allTypesNull = AllNullableTypesWithoutRecursion(); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api - .echoAllNullableTypesWithoutRecursion(allTypesNull); - expect(allTypesNull, echoNullFilledClass); - }, - ); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAllNullableTypesWithoutRecursion(allTypesNull); + expect(allTypesNull, echoNullFilledClass); + }); - testWidgets( - 'Classes without recursion with list of null serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('Classes without recursion with list of null serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final listTypes = AllNullableTypesWithoutRecursion( - list: ['String', null], - ); + final listTypes = AllNullableTypesWithoutRecursion(list: ['String', null]); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api - .echoAllNullableTypesWithoutRecursion(listTypes); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAllNullableTypesWithoutRecursion(listTypes); - expect(listTypes, echoNullFilledClass); - }, - ); + expect(listTypes, echoNullFilledClass); + }); - testWidgets( - 'Classes without recursion with map of null serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('Classes without recursion with map of null serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final listTypes = AllNullableTypesWithoutRecursion( - map: {'String': 'string', 'null': null}, - ); + final listTypes = AllNullableTypesWithoutRecursion( + map: {'String': 'string', 'null': null}, + ); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api - .echoAllNullableTypesWithoutRecursion(listTypes); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAllNullableTypesWithoutRecursion(listTypes); - expect(listTypes, echoNullFilledClass); - }, - ); + expect(listTypes, echoNullFilledClass); + }); testWidgets('errors are returned correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); @@ -182,9 +163,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('errors are returned from void methods correctly', ( - WidgetTester _, - ) async { + testWidgets('errors are returned from void methods correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); expect(() async { @@ -192,9 +171,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('flutter errors are returned correctly', ( - WidgetTester _, - ) async { + testWidgets('flutter errors are returned correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); expect( @@ -212,32 +189,23 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nested objects can be sent correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); - final String? receivedString = await api.extractNestedNullableString( - classWrapper, - ); + final String? receivedString = await api.extractNestedNullableString(classWrapper); expect(receivedString, classWrapper.allNullableTypes.aNullableString); }); - testWidgets('nested objects can be received correctly', ( - WidgetTester _, - ) async { + testWidgets('nested objects can be received correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentString = 'Some string'; - final AllClassesWrapper receivedObject = await api - .createNestedNullableString(sentString); + final AllClassesWrapper receivedObject = await api.createNestedNullableString(sentString); expect(receivedObject.allNullableTypes.aNullableString, sentString); }); - testWidgets('nested classes can serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nested classes can serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); - final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper( - classWrapper, - ); + final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper(classWrapper); expect(classWrapper, receivedClassWrapper); }); @@ -249,43 +217,42 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { classWrapper.allTypes = null; - final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper( - classWrapper, - ); + final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper(classWrapper); expect(classWrapper, receivedClassWrapper); }); - testWidgets( - 'Arguments of multiple types serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - const aNullableString = 'this is a String'; - const aNullableBool = false; - const int aNullableInt = regularInt; + testWidgets('Arguments of multiple types serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + const aNullableString = 'this is a String'; + const aNullableBool = false; + const int aNullableInt = regularInt; - final AllNullableTypes echoObject = await api.sendMultipleNullableTypes( - aNullableBool, - aNullableInt, - aNullableString, - ); - expect(echoObject.aNullableInt, aNullableInt); - expect(echoObject.aNullableBool, aNullableBool); - expect(echoObject.aNullableString, aNullableString); - }, - ); + final AllNullableTypes echoObject = await api.sendMultipleNullableTypes( + aNullableBool, + aNullableInt, + aNullableString, + ); + expect(echoObject.aNullableInt, aNullableInt); + expect(echoObject.aNullableBool, aNullableBool); + expect(echoObject.aNullableString, aNullableString); + }); - testWidgets( - 'Arguments of multiple null types serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('Arguments of multiple null types serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final AllNullableTypes echoNullFilledClass = await api - .sendMultipleNullableTypes(null, null, null); - expect(echoNullFilledClass.aNullableInt, null); - expect(echoNullFilledClass.aNullableBool, null); - expect(echoNullFilledClass.aNullableString, null); - }, - ); + final AllNullableTypes echoNullFilledClass = await api.sendMultipleNullableTypes( + null, + null, + null, + ); + expect(echoNullFilledClass.aNullableInt, null); + expect(echoNullFilledClass.aNullableBool, null); + expect(echoNullFilledClass.aNullableString, null); + }); testWidgets( 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', @@ -320,18 +287,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, ); - testWidgets('Int serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Int serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = regularInt; final int receivedInt = await api.echoInt(sentInt); expect(receivedInt, sentInt); }); - testWidgets('Int64 serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Int64 serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -339,9 +302,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Doubles serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Doubles serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentDouble = 2.0694; @@ -349,9 +310,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedDouble, sentDouble); }); - testWidgets('booleans serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('booleans serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); for (final sentBool in [true, false]) { @@ -360,30 +319,22 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('strings serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('strings serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentString = 'default'; final String receivedString = await api.echoString(sentString); expect(receivedString, sentString); }); - testWidgets('Uint8List serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Uint8List serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; final sentUint8List = Uint8List.fromList(data); - final Uint8List receivedUint8List = await api.echoUint8List( - sentUint8List, - ); + final Uint8List receivedUint8List = await api.echoUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); }); - testWidgets('generic Objects serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('generic Objects serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object receivedString = await api.echoObject(sentString); @@ -395,51 +346,37 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final List echoObject = await api.echoList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final List echoObject = await api.echoEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('class lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('class lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List echoObject = await api.echoClassList( - allNullableTypesList, - ); + final List echoObject = await api.echoClassList(allNullableTypesList); for (final (int index, AllNullableTypes? value) in echoObject.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets('NonNull enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List echoObject = await api.echoNonNullEnumList( - nonNullEnumList, - ); + final List echoObject = await api.echoNonNullEnumList(nonNullEnumList); expect(listEquals(echoObject, nonNullEnumList), true); }); - testWidgets('NonNull class lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull class lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final List echoObject = await api.echoNonNullClassList( @@ -450,97 +387,67 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.echoStringMap( - stringMap, - ); + final Map echoObject = await api.echoStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.echoClassMap( - allNullableTypesMap, - ); - for (final MapEntry entry - in echoObject.entries) { + final Map echoObject = await api.echoClassMap(allNullableTypesMap); + for (final MapEntry entry in echoObject.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('NonNull string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.echoNonNullStringMap( - nonNullStringMap, - ); + final Map echoObject = await api.echoNonNullStringMap(nonNullStringMap); expect(mapEquals(echoObject, nonNullStringMap), true); }); - testWidgets('NonNull int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.echoNonNullIntMap( - nonNullIntMap, - ); + final Map echoObject = await api.echoNonNullIntMap(nonNullIntMap); expect(mapEquals(echoObject, nonNullIntMap), true); }); - testWidgets('NonNull enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.echoNonNullEnumMap( - nonNullEnumMap, - ); + final Map echoObject = await api.echoNonNullEnumMap(nonNullEnumMap); expect(mapEquals(echoObject, nonNullEnumMap), true); }); - testWidgets('NonNull class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api - .echoNonNullClassMap(nonNullAllNullableTypesMap); + final Map echoObject = await api.echoNonNullClassMap( + nonNullAllNullableTypesMap, + ); for (final MapEntry entry in echoObject.entries) { expect(entry.value, nonNullAllNullableTypesMap[entry.key]); } }); - testWidgets('enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.two; @@ -548,9 +455,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedEnum, sentEnum); }); - testWidgets('enums serialize and deserialize correctly (again)', ( - WidgetTester _, - ) async { + testWidgets('enums serialize and deserialize correctly (again)', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; @@ -558,9 +463,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedEnum, sentEnum); }); - testWidgets('multi word enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('multi word enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; @@ -589,9 +492,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final api = HostIntegrationCoreApi(); const sentDouble = 3.15; - final double receivedDouble = await api.echoOptionalDefaultDouble( - sentDouble, - ); + final double receivedDouble = await api.echoOptionalDefaultDouble(sentDouble); expect(receivedDouble, sentDouble); }); @@ -607,15 +508,11 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final api = HostIntegrationCoreApi(); // This string corresponds with the default value of this method. const sentString = 'notDefault'; - final String receivedString = await api.echoNamedDefaultString( - aString: sentString, - ); + final String receivedString = await api.echoNamedDefaultString(aString: sentString); expect(receivedString, sentString); }); - testWidgets('Nullable Int serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Nullable Int serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = regularInt; @@ -623,9 +520,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Nullable Int64 serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Nullable Int64 serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -633,18 +528,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Null Ints serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Null Ints serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final int? receivedNullInt = await api.echoNullableInt(null); expect(receivedNullInt, null); }); - testWidgets('Nullable Doubles serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Nullable Doubles serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentDouble = 2.0694; @@ -652,18 +543,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedDouble, sentDouble); }); - testWidgets('Null Doubles serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Null Doubles serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final double? receivedNullDouble = await api.echoNullableDouble(null); expect(receivedNullDouble, null); }); - testWidgets('Nullable booleans serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Nullable booleans serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); for (final sentBool in [true, false]) { @@ -672,9 +559,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('Null booleans serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Null booleans serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const bool? sentBool = null; @@ -682,223 +567,179 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedBool, sentBool); }); - testWidgets('Nullable strings serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Nullable strings serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentString = "I'm a computer"; final String? receivedString = await api.echoNullableString(sentString); expect(receivedString, sentString); }); - testWidgets('Null strings serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Null strings serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final String? receivedNullString = await api.echoNullableString(null); expect(receivedNullString, null); }); - testWidgets('Nullable Uint8List serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Nullable Uint8List serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; final sentUint8List = Uint8List.fromList(data); - final Uint8List? receivedUint8List = await api.echoNullableUint8List( - sentUint8List, - ); + final Uint8List? receivedUint8List = await api.echoNullableUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); }); - testWidgets('Null Uint8List serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Null Uint8List serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Uint8List? receivedNullUint8List = await api.echoNullableUint8List( - null, - ); + final Uint8List? receivedNullUint8List = await api.echoNullableUint8List(null); expect(receivedNullUint8List, null); }); - testWidgets( - 'generic nullable Objects serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - const Object sentString = "I'm a computer"; - final Object? receivedString = await api.echoNullableObject(sentString); - expect(receivedString, sentString); - - // Echo a second type as well to ensure the handling is generic. - const Object sentInt = regularInt; - final Object? receivedInt = await api.echoNullableObject(sentInt); - expect(receivedInt, sentInt); - }, - ); - - testWidgets('Null generic Objects serialize and deserialize correctly', ( + testWidgets('generic nullable Objects serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + const Object sentString = "I'm a computer"; + final Object? receivedString = await api.echoNullableObject(sentString); + expect(receivedString, sentString); + + // Echo a second type as well to ensure the handling is generic. + const Object sentInt = regularInt; + final Object? receivedInt = await api.echoNullableObject(sentInt); + expect(receivedInt, sentInt); + }); + + testWidgets('Null generic Objects serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); final Object? receivedNullObject = await api.echoNullableObject(null); expect(receivedNullObject, null); }); - testWidgets('nullable lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoNullableList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('nullable enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api.echoNullableEnumList( - enumList, - ); + final List? echoObject = await api.echoNullableEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('nullable lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api - .echoNullableClassList(allNullableTypesList); + final List? echoObject = await api.echoNullableClassList( + allNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets( - 'nullable NonNull enum lists serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('nullable NonNull enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final List? echoObject = await api.echoNullableNonNullEnumList( - nonNullEnumList, - ); - expect(listEquals(echoObject, nonNullEnumList), true); - }, - ); + final List? echoObject = await api.echoNullableNonNullEnumList(nonNullEnumList); + expect(listEquals(echoObject, nonNullEnumList), true); + }); testWidgets('nullable NonNull lists serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api - .echoNullableClassList(nonNullAllNullableTypesList); + final List? echoObject = await api.echoNullableClassList( + nonNullAllNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, nonNullAllNullableTypesList[index]); } }); - testWidgets('nullable maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('nullable string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoNullableStringMap( - stringMap, - ); + final Map? echoObject = await api.echoNullableStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('nullable int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('nullable enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoNullableEnumMap( - enumMap, - ); + final Map? echoObject = await api.echoNullableEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('nullable class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoNullableClassMap(allNullableTypesMap); - for (final MapEntry entry - in echoObject!.entries) { + final Map? echoObject = await api.echoNullableClassMap( + allNullableTypesMap, + ); + for (final MapEntry entry in echoObject!.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets( - 'nullable NonNull string maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoNullableNonNullStringMap(nonNullStringMap); - expect(mapEquals(echoObject, nonNullStringMap), true); - }, - ); - - testWidgets( - 'nullable NonNull int maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoNullableNonNullIntMap( - nonNullIntMap, - ); - expect(mapEquals(echoObject, nonNullIntMap), true); - }, - ); + testWidgets('nullable NonNull string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final Map? echoObject = await api.echoNullableNonNullStringMap( + nonNullStringMap, + ); + expect(mapEquals(echoObject, nonNullStringMap), true); + }); - testWidgets( - 'nullable NonNull enum maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoNullableNonNullEnumMap(nonNullEnumMap); - expect(mapEquals(echoObject, nonNullEnumMap), true); - }, - ); + testWidgets('nullable NonNull int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final Map? echoObject = await api.echoNullableNonNullIntMap(nonNullIntMap); + expect(mapEquals(echoObject, nonNullIntMap), true); + }); - testWidgets( - 'nullable NonNull class maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoNullableNonNullClassMap(nonNullAllNullableTypesMap); - for (final MapEntry entry - in echoObject!.entries) { - expect(entry.value, nonNullAllNullableTypesMap[entry.key]); - } - }, - ); + testWidgets('nullable NonNull enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final Map? echoObject = await api.echoNullableNonNullEnumMap( + nonNullEnumMap, + ); + expect(mapEquals(echoObject, nonNullEnumMap), true); + }); - testWidgets('nullable enums serialize and deserialize correctly', ( + testWidgets('nullable NonNull class maps serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + final Map? echoObject = await api.echoNullableNonNullClassMap( + nonNullAllNullableTypesMap, + ); + for (final MapEntry entry in echoObject!.entries) { + expect(entry.value, nonNullAllNullableTypesMap[entry.key]); + } + }); + + testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); @@ -915,58 +756,45 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets( - 'multi word nullable enums serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - - const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; - final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); - expect(echoEnum, sentEnum); - }, - ); - - testWidgets('null lists serialize and deserialize correctly', ( + testWidgets('multi word nullable enums serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; + final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); + expect(echoEnum, sentEnum); + }); + + testWidgets('null lists serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + final List? echoObject = await api.echoNullableList(null); expect(listEquals(echoObject, null), true); }); - testWidgets('null maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoNullableStringMap( - null, - ); + final Map? echoObject = await api.echoNullableStringMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableIntMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; @@ -974,9 +802,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null enums serialize and deserialize correctly (again)', ( - WidgetTester _, - ) async { + testWidgets('null enums serialize and deserialize correctly (again)', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; @@ -984,9 +810,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null classes serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null classes serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final AllNullableTypes? echoObject = await api.echoAllNullableTypes(null); @@ -1012,9 +836,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('named nullable parameter', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentString = "I'm a computer"; - final String? receivedString = await api.echoNamedNullableString( - aNullableString: sentString, - ); + final String? receivedString = await api.echoNamedNullableString(aNullableString: sentString); expect(receivedString, sentString); }); @@ -1042,11 +864,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final int hashA = await api.getAllNullableTypesHash(a); final int hashB = await api.getAllNullableTypesHash(b); - expect( - hashA, - hashB, - reason: 'Hash codes for 0.0 and -0.0 should be equal', - ); + expect(hashA, hashB, reason: 'Hash codes for 0.0 and -0.0 should be equal'); }); testWidgets('NaN equality', (WidgetTester _) async { @@ -1069,9 +887,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(hashA, hashB, reason: 'Hash codes for two NaNs should be equal'); }); - testWidgets('Collection equality with signed zero and NaN', ( - WidgetTester _, - ) async { + testWidgets('Collection equality with signed zero and NaN', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final a = AllNullableTypes( @@ -1086,9 +902,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(await api.areAllNullableTypesEqual(a, b), isTrue); }); - testWidgets('Collection hashing with signed zero and NaN', ( - WidgetTester _, - ) async { + testWidgets('Collection hashing with signed zero and NaN', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final a = AllNullableTypes( @@ -1100,35 +914,21 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { stringMap: {'n': null, 'k': 'v'}, ); - expect( - await api.getAllNullableTypesHash(a), - await api.getAllNullableTypesHash(b), - ); + expect(await api.getAllNullableTypesHash(a), await api.getAllNullableTypesHash(b)); }); testWidgets('Collection hashing with null/NSNull', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final a = AllNullableTypes( - list: [null], - stringMap: {'k': null}, - ); - final b = AllNullableTypes( - list: [null], - stringMap: {'k': null}, - ); + final a = AllNullableTypes(list: [null], stringMap: {'k': null}); + final b = AllNullableTypes(list: [null], stringMap: {'k': null}); // Verify cross-platform equivalence via identical hash values. - expect( - await api.getAllNullableTypesHash(a), - await api.getAllNullableTypesHash(b), - ); + expect(await api.getAllNullableTypesHash(a), await api.getAllNullableTypesHash(b)); expect(await api.areAllNullableTypesEqual(a, b), isTrue); }); - testWidgets('Map equality with signed zero keys and values', ( - WidgetTester _, - ) async { + testWidgets('Map equality with signed zero keys and values', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final a = AllNullableTypes(map: {0.0: 'a', 'b': 0.0}); @@ -1137,23 +937,16 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(await api.areAllNullableTypesEqual(a, b), isTrue); }); - testWidgets('Map hashing with signed zero keys and values', ( - WidgetTester _, - ) async { + testWidgets('Map hashing with signed zero keys and values', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final a = AllNullableTypes(map: {0.0: 'a', 'b': 0.0}); final b = AllNullableTypes(map: {-0.0: 'a', 'b': -0.0}); - expect( - await api.getAllNullableTypesHash(a), - await api.getAllNullableTypesHash(b), - ); + expect(await api.getAllNullableTypesHash(a), await api.getAllNullableTypesHash(b)); }); - testWidgets('Map equality with null values and different keys', ( - WidgetTester _, - ) async { + testWidgets('Map equality with null values and different keys', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final a = AllNullableTypes(intMap: {1: null}); @@ -1165,19 +958,13 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Deeply nested equality', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final a = AllNullableTypes( - allNullableTypes: AllNullableTypes(aNullableDouble: 0.0), - ); - final b = AllNullableTypes( - allNullableTypes: AllNullableTypes(aNullableDouble: -0.0), - ); + final a = AllNullableTypes(allNullableTypes: AllNullableTypes(aNullableDouble: 0.0)); + final b = AllNullableTypes(allNullableTypes: AllNullableTypes(aNullableDouble: -0.0)); expect(await api.areAllNullableTypesEqual(a, b), isTrue); }); - testWidgets('Hashing inequality across types with same values', ( - WidgetTester _, - ) async { + testWidgets('Hashing inequality across types with same values', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final a = AllNullableTypes(aNullableInt: 42); final b = AllNullableTypesWithoutRecursion(aNullableInt: 42); @@ -1208,9 +995,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('async errors are returned from void methods correctly', ( - WidgetTester _, - ) async { + testWidgets('async errors are returned from void methods correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); expect(() async { @@ -1218,58 +1003,55 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets( - 'async flutter errors are returned from non void methods correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - - expect( - () => api.throwAsyncFlutterError(), - throwsA( - (dynamic e) => - e is PlatformException && - e.code == 'code' && - e.message == 'message' && - e.details == 'details', - ), - ); - }, - ); - - testWidgets('all datatypes async serialize and deserialize correctly', ( + testWidgets('async flutter errors are returned from non void methods correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + expect( + () => api.throwAsyncFlutterError(), + throwsA( + (dynamic e) => + e is PlatformException && + e.code == 'code' && + e.message == 'message' && + e.details == 'details', + ), + ); + }); + + testWidgets('all datatypes async serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + final AllTypes echoObject = await api.echoAsyncAllTypes(genericAllTypes); expect(echoObject, genericAllTypes); }); - testWidgets( - 'all nullable async datatypes serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('all nullable async datatypes serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final AllNullableTypes? echoObject = await api - .echoAsyncNullableAllNullableTypes(recursiveAllNullableTypes); + final AllNullableTypes? echoObject = await api.echoAsyncNullableAllNullableTypes( + recursiveAllNullableTypes, + ); - expect(echoObject, recursiveAllNullableTypes); - }, - ); + expect(echoObject, recursiveAllNullableTypes); + }); - testWidgets( - 'all null datatypes async serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('all null datatypes async serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final allTypesNull = AllNullableTypes(); + final allTypesNull = AllNullableTypes(); - final AllNullableTypes? echoNullFilledClass = await api - .echoAsyncNullableAllNullableTypes(allTypesNull); - expect(echoNullFilledClass, allTypesNull); - }, - ); + final AllNullableTypes? echoNullFilledClass = await api.echoAsyncNullableAllNullableTypes( + allTypesNull, + ); + expect(echoNullFilledClass, allTypesNull); + }); testWidgets( 'all nullable async datatypes without recursion serialize and deserialize correctly', @@ -1285,22 +1067,19 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, ); - testWidgets( - 'all null datatypes without recursion async serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('all null datatypes without recursion async serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final allTypesNull = AllNullableTypesWithoutRecursion(); + final allTypesNull = AllNullableTypesWithoutRecursion(); - final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api - .echoAsyncNullableAllNullableTypesWithoutRecursion(allTypesNull); - expect(echoNullFilledClass, allTypesNull); - }, - ); + final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api + .echoAsyncNullableAllNullableTypesWithoutRecursion(allTypesNull); + expect(echoNullFilledClass, allTypesNull); + }); - testWidgets('Int async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Int async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = regularInt; @@ -1308,9 +1087,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Int64 async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Int64 async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -1318,9 +1095,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('Doubles async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Doubles async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentDouble = 2.0694; @@ -1328,9 +1103,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedDouble, sentDouble); }); - testWidgets('booleans async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('booleans async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); for (final sentBool in [true, false]) { @@ -1339,9 +1112,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('strings async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('strings async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentObject = 'Hello, asynchronously!'; @@ -1350,15 +1121,11 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('Uint8List async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Uint8List async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; final sentUint8List = Uint8List.fromList(data); - final Uint8List receivedUint8List = await api.echoAsyncUint8List( - sentUint8List, - ); + final Uint8List receivedUint8List = await api.echoAsyncUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); }); @@ -1376,88 +1143,64 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final List echoObject = await api.echoAsyncList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final List echoObject = await api.echoAsyncEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('class lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('class lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List echoObject = await api.echoAsyncClassList( - allNullableTypesList, - ); + final List echoObject = await api.echoAsyncClassList(allNullableTypesList); for (final (int index, AllNullableTypes? value) in echoObject.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets('maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.echoAsyncStringMap( - stringMap, - ); + final Map echoObject = await api.echoAsyncStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.echoAsyncEnumMap( - enumMap, - ); + final Map echoObject = await api.echoAsyncEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api - .echoAsyncClassMap(allNullableTypesMap); - for (final MapEntry entry - in echoObject.entries) { + final Map echoObject = await api.echoAsyncClassMap( + allNullableTypesMap, + ); + for (final MapEntry entry in echoObject.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -1465,9 +1208,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('enums serialize and deserialize correctly (again)', ( - WidgetTester _, - ) async { + testWidgets('enums serialize and deserialize correctly (again)', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; @@ -1475,9 +1216,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('multi word enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('multi word enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; @@ -1485,9 +1224,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('nullable Int async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable Int async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = regularInt; @@ -1495,9 +1232,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(receivedInt, sentInt); }); - testWidgets('nullable Int64 async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable Int64 async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; @@ -1511,9 +1246,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final api = HostIntegrationCoreApi(); const sentDouble = 2.0694; - final double? receivedDouble = await api.echoAsyncNullableDouble( - sentDouble, - ); + final double? receivedDouble = await api.echoAsyncNullableDouble(sentDouble); expect(receivedDouble, sentDouble); }); @@ -1539,120 +1272,90 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets( - 'nullable Uint8List async serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; - final sentUint8List = Uint8List.fromList(data); - final Uint8List? receivedUint8List = await api - .echoAsyncNullableUint8List(sentUint8List); - expect(receivedUint8List, sentUint8List); - }, - ); - - testWidgets( - 'nullable generic Objects async serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - const Object sentString = "I'm a computer"; - final Object? receivedString = await api.echoAsyncNullableObject( - sentString, - ); - expect(receivedString, sentString); - - // Echo a second type as well to ensure the handling is generic. - const Object sentInt = regularInt; - final Object? receivedInt = await api.echoAsyncNullableObject(sentInt); - expect(receivedInt, sentInt); - }, - ); + testWidgets('nullable Uint8List async serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; + final sentUint8List = Uint8List.fromList(data); + final Uint8List? receivedUint8List = await api.echoAsyncNullableUint8List(sentUint8List); + expect(receivedUint8List, sentUint8List); + }); - testWidgets('nullable lists serialize and deserialize correctly', ( + testWidgets('nullable generic Objects async serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + const Object sentString = "I'm a computer"; + final Object? receivedString = await api.echoAsyncNullableObject(sentString); + expect(receivedString, sentString); + + // Echo a second type as well to ensure the handling is generic. + const Object sentInt = regularInt; + final Object? receivedInt = await api.echoAsyncNullableObject(sentInt); + expect(receivedInt, sentInt); + }); + + testWidgets('nullable lists serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoAsyncNullableList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('nullable enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api.echoAsyncNullableEnumList( - enumList, - ); + final List? echoObject = await api.echoAsyncNullableEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('nullable class lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable class lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api - .echoAsyncNullableClassList(allNullableTypesList); + final List? echoObject = await api.echoAsyncNullableClassList( + allNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets('nullable maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoAsyncNullableMap( - map, - ); + final Map? echoObject = await api.echoAsyncNullableMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('nullable string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoAsyncNullableStringMap(stringMap); + final Map? echoObject = await api.echoAsyncNullableStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('nullable int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoAsyncNullableIntMap( - intMap, - ); + final Map? echoObject = await api.echoAsyncNullableIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('nullable enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoAsyncNullableEnumMap(enumMap); + final Map? echoObject = await api.echoAsyncNullableEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('nullable class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoAsyncNullableClassMap(allNullableTypesMap); - for (final MapEntry entry - in echoObject!.entries) { + final Map? echoObject = await api.echoAsyncNullableClassMap( + allNullableTypesMap, + ); + for (final MapEntry entry in echoObject!.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('nullable enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -1666,15 +1369,11 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; - final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum( - sentEnum, - ); + final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); - testWidgets('nullable enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; @@ -1682,106 +1381,78 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null Ints async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null Ints async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final int? receivedInt = await api.echoAsyncNullableInt(null); expect(receivedInt, null); }); - testWidgets('null Doubles async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null Doubles async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final double? receivedDouble = await api.echoAsyncNullableDouble(null); expect(receivedDouble, null); }); - testWidgets('null booleans async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null booleans async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final bool? receivedBool = await api.echoAsyncNullableBool(null); expect(receivedBool, null); }); - testWidgets('null strings async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null strings async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final String? echoObject = await api.echoAsyncNullableString(null); expect(echoObject, null); }); - testWidgets('null Uint8List async serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null Uint8List async serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Uint8List? receivedUint8List = await api.echoAsyncNullableUint8List( - null, - ); + final Uint8List? receivedUint8List = await api.echoAsyncNullableUint8List(null); expect(receivedUint8List, null); }); - testWidgets( - 'null generic Objects async serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Object? receivedString = await api.echoAsyncNullableObject(null); - expect(receivedString, null); - }, - ); - - testWidgets('null lists serialize and deserialize correctly', ( + testWidgets('null generic Objects async serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + final Object? receivedString = await api.echoAsyncNullableObject(null); + expect(receivedString, null); + }); + + testWidgets('null lists serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoAsyncNullableList(null); expect(listEquals(echoObject, null), true); }); - testWidgets('null maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoAsyncNullableMap( - null, - ); + final Map? echoObject = await api.echoAsyncNullableMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .echoAsyncNullableStringMap(null); + final Map? echoObject = await api.echoAsyncNullableStringMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api.echoAsyncNullableIntMap( - null, - ); + final Map? echoObject = await api.echoAsyncNullableIntMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('null enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; @@ -1789,23 +1460,17 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('null enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; - final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum( - null, - ); + final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum(null); expect(echoEnum, sentEnum); }); }); group('Host API with suffix', () { - testWidgets('echo string succeeds with suffix with multiple instances', ( - _, - ) async { + testWidgets('echo string succeeds with suffix with multiple instances', (_) async { final apiWithSuffixOne = HostSmallApi(messageChannelSuffix: 'suffixOne'); final apiWithSuffixTwo = HostSmallApi(messageChannelSuffix: 'suffixTwo'); const sentString = "I'm a computer"; @@ -1815,17 +1480,11 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(sentString, echoStringTwo); }); - testWidgets('multiple instances will have different method channel names', ( - _, - ) async { + testWidgets('multiple instances will have different method channel names', (_) async { // The only way to get the channel name back is to throw an exception. // These APIs have no corresponding APIs on the host platforms. - final apiWithSuffixOne = HostSmallApi( - messageChannelSuffix: 'suffixWithNoHost', - ); - final apiWithSuffixTwo = HostSmallApi( - messageChannelSuffix: 'suffixWithoutHost', - ); + final apiWithSuffixOne = HostSmallApi(messageChannelSuffix: 'suffixWithNoHost'); + final apiWithSuffixTwo = HostSmallApi(messageChannelSuffix: 'suffixWithoutHost'); const sentString = "I'm a computer"; try { await apiWithSuffixOne.echo(sentString); @@ -1855,9 +1514,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(api.callFlutterNoop(), completes); }); - testWidgets('errors are returned from non void methods correctly', ( - WidgetTester _, - ) async { + testWidgets('errors are returned from non void methods correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); expect(() async { @@ -1865,9 +1522,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('errors are returned from void methods correctly', ( - WidgetTester _, - ) async { + testWidgets('errors are returned from void methods correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); expect(() async { @@ -1875,50 +1530,46 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }, throwsA(isA())); }); - testWidgets('all datatypes serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('all datatypes serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final AllTypes echoObject = await api.callFlutterEchoAllTypes( - genericAllTypes, - ); + final AllTypes echoObject = await api.callFlutterEchoAllTypes(genericAllTypes); expect(echoObject, genericAllTypes); }); - testWidgets( - 'Arguments of multiple types serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - const aNullableString = 'this is a String'; - const aNullableBool = false; - const int aNullableInt = regularInt; + testWidgets('Arguments of multiple types serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + const aNullableString = 'this is a String'; + const aNullableBool = false; + const int aNullableInt = regularInt; - final AllNullableTypes compositeObject = await api - .callFlutterSendMultipleNullableTypes( - aNullableBool, - aNullableInt, - aNullableString, - ); - expect(compositeObject.aNullableInt, aNullableInt); - expect(compositeObject.aNullableBool, aNullableBool); - expect(compositeObject.aNullableString, aNullableString); - }, - ); + final AllNullableTypes compositeObject = await api.callFlutterSendMultipleNullableTypes( + aNullableBool, + aNullableInt, + aNullableString, + ); + expect(compositeObject.aNullableInt, aNullableInt); + expect(compositeObject.aNullableBool, aNullableBool); + expect(compositeObject.aNullableString, aNullableString); + }); - testWidgets( - 'Arguments of multiple null types serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('Arguments of multiple null types serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final AllNullableTypes compositeObject = await api - .callFlutterSendMultipleNullableTypes(null, null, null); - expect(compositeObject.aNullableInt, null); - expect(compositeObject.aNullableBool, null); - expect(compositeObject.aNullableString, null); - }, - ); + final AllNullableTypes compositeObject = await api.callFlutterSendMultipleNullableTypes( + null, + null, + null, + ); + expect(compositeObject.aNullableInt, null); + expect(compositeObject.aNullableBool, null); + expect(compositeObject.aNullableString, null); + }); testWidgets( 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', @@ -1946,20 +1597,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final api = HostIntegrationCoreApi(); final AllNullableTypesWithoutRecursion compositeObject = await api - .callFlutterSendMultipleNullableTypesWithoutRecursion( - null, - null, - null, - ); + .callFlutterSendMultipleNullableTypesWithoutRecursion(null, null, null); expect(compositeObject.aNullableInt, null); expect(compositeObject.aNullableBool, null); expect(compositeObject.aNullableString, null); }, ); - testWidgets('booleans serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('booleans serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); for (final sentObject in [true, false]) { @@ -1968,9 +1613,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } }); - testWidgets('ints serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('ints serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentObject = regularInt; @@ -1978,9 +1621,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('doubles serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('doubles serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentObject = 2.0694; @@ -1988,9 +1629,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('strings serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('strings serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentObject = 'Hello Dart!'; @@ -1998,167 +1637,125 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('Uint8Lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('Uint8Lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; final sentObject = Uint8List.fromList(data); - final Uint8List echoObject = await api.callFlutterEchoUint8List( - sentObject, - ); + final Uint8List echoObject = await api.callFlutterEchoUint8List(sentObject); expect(echoObject, sentObject); }); - testWidgets('lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final List echoObject = await api.callFlutterEchoList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List echoObject = await api.callFlutterEchoEnumList( - enumList, - ); + final List echoObject = await api.callFlutterEchoEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('class lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('class lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List echoObject = await api - .callFlutterEchoClassList(allNullableTypesList); + final List echoObject = await api.callFlutterEchoClassList( + allNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject.indexed) { expect(value, allNullableTypesList[index]); } }); - - testWidgets('NonNull enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + + testWidgets('NonNull enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List echoObject = await api.callFlutterEchoNonNullEnumList( - nonNullEnumList, - ); + final List echoObject = await api.callFlutterEchoNonNullEnumList(nonNullEnumList); expect(listEquals(echoObject, nonNullEnumList), true); }); - testWidgets('NonNull class lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull class lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List echoObject = await api - .callFlutterEchoNonNullClassList(nonNullAllNullableTypesList); + final List echoObject = await api.callFlutterEchoNonNullClassList( + nonNullAllNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject.indexed) { expect(value, nonNullAllNullableTypesList[index]); } }); - testWidgets('maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.callFlutterEchoMap( - map, - ); + final Map echoObject = await api.callFlutterEchoMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api - .callFlutterEchoStringMap(stringMap); + final Map echoObject = await api.callFlutterEchoStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.callFlutterEchoIntMap( - intMap, - ); + final Map echoObject = await api.callFlutterEchoIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.callFlutterEchoEnumMap( - enumMap, - ); + final Map echoObject = await api.callFlutterEchoEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api - .callFlutterEchoClassMap(allNullableTypesMap); - for (final MapEntry entry - in echoObject.entries) { + final Map echoObject = await api.callFlutterEchoClassMap( + allNullableTypesMap, + ); + for (final MapEntry entry in echoObject.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets('NonNull string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api - .callFlutterEchoNonNullStringMap(nonNullStringMap); + final Map echoObject = await api.callFlutterEchoNonNullStringMap( + nonNullStringMap, + ); expect(mapEquals(echoObject, nonNullStringMap), true); }); - testWidgets('NonNull int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api.callFlutterEchoNonNullIntMap( - nonNullIntMap, - ); + final Map echoObject = await api.callFlutterEchoNonNullIntMap(nonNullIntMap); expect(mapEquals(echoObject, nonNullIntMap), true); }); - testWidgets('NonNull enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api - .callFlutterEchoNonNullEnumMap(nonNullEnumMap); + final Map echoObject = await api.callFlutterEchoNonNullEnumMap( + nonNullEnumMap, + ); expect(mapEquals(echoObject, nonNullEnumMap), true); }); - testWidgets('NonNull class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('NonNull class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map echoObject = await api - .callFlutterEchoNonNullClassMap(nonNullAllNullableTypesMap); + final Map echoObject = await api.callFlutterEchoNonNullClassMap( + nonNullAllNullableTypesMap, + ); for (final MapEntry entry in echoObject.entries) { expect(entry.value, nonNullAllNullableTypesMap[entry.key]); } }); - testWidgets('enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -2166,21 +1763,15 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('enums serialize and deserialize correctly (again)', ( - WidgetTester _, - ) async { + testWidgets('enums serialize and deserialize correctly (again)', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; - final AnotherEnum echoEnum = await api.callFlutterEchoAnotherEnum( - sentEnum, - ); + final AnotherEnum echoEnum = await api.callFlutterEchoAnotherEnum(sentEnum); expect(echoEnum, sentEnum); }); - testWidgets('multi word enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('multi word enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; @@ -2188,34 +1779,24 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoEnum, sentEnum); }); - testWidgets('nullable booleans serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable booleans serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); for (final sentObject in [true, false]) { - final bool? echoObject = await api.callFlutterEchoNullableBool( - sentObject, - ); + final bool? echoObject = await api.callFlutterEchoNullableBool(sentObject); expect(echoObject, sentObject); } }); - testWidgets('null booleans serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null booleans serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const bool? sentObject = null; - final bool? echoObject = await api.callFlutterEchoNullableBool( - sentObject, - ); + final bool? echoObject = await api.callFlutterEchoNullableBool(sentObject); expect(echoObject, sentObject); }); - testWidgets('nullable ints serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable ints serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentObject = regularInt; @@ -2223,9 +1804,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('nullable big ints serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable big ints serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const int sentObject = biggerThanBigInt; @@ -2233,265 +1812,206 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(echoObject, sentObject); }); - testWidgets('null ints serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null ints serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final int? echoObject = await api.callFlutterEchoNullableInt(null); expect(echoObject, null); }); - testWidgets('nullable doubles serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable doubles serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentObject = 2.0694; - final double? echoObject = await api.callFlutterEchoNullableDouble( - sentObject, - ); + final double? echoObject = await api.callFlutterEchoNullableDouble(sentObject); expect(echoObject, sentObject); }); - testWidgets('null doubles serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null doubles serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final double? echoObject = await api.callFlutterEchoNullableDouble(null); expect(echoObject, null); }); - testWidgets('nullable strings serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable strings serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const sentObject = "I'm a computer"; - final String? echoObject = await api.callFlutterEchoNullableString( - sentObject, - ); + final String? echoObject = await api.callFlutterEchoNullableString(sentObject); expect(echoObject, sentObject); }); - testWidgets('null strings serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null strings serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final String? echoObject = await api.callFlutterEchoNullableString(null); expect(echoObject, null); }); - testWidgets('nullable Uint8Lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable Uint8Lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; final sentObject = Uint8List.fromList(data); - final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List( - sentObject, - ); + final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List(sentObject); expect(echoObject, sentObject); }); - testWidgets('null Uint8Lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null Uint8Lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List( - null, - ); + final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List(null); expect(echoObject, null); }); - testWidgets('nullable lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api.callFlutterEchoNullableList( - list, - ); + final List? echoObject = await api.callFlutterEchoNullableList(list); expect(listEquals(echoObject, list), true); }); - testWidgets('nullable enum lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enum lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api - .callFlutterEchoNullableEnumList(enumList); + final List? echoObject = await api.callFlutterEchoNullableEnumList(enumList); expect(listEquals(echoObject, enumList), true); }); - testWidgets('nullable class lists serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable class lists serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api - .callFlutterEchoNullableClassList(allNullableTypesList); + final List? echoObject = await api.callFlutterEchoNullableClassList( + allNullableTypesList, + ); for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { expect(value, allNullableTypesList[index]); } }); - testWidgets( - 'nullable NonNull enum lists serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - - final List? echoObject = await api - .callFlutterEchoNullableNonNullEnumList(nonNullEnumList); - expect(listEquals(echoObject, nonNullEnumList), true); - }, - ); - - testWidgets( - 'nullable NonNull class lists serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); + testWidgets('nullable NonNull enum lists serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); - final List? echoObject = await api - .callFlutterEchoNullableNonNullClassList( - nonNullAllNullableTypesList, - ); - for (final (int index, AllNullableTypes? value) - in echoObject!.indexed) { - expect(value, nonNullAllNullableTypesList[index]); - } - }, - ); + final List? echoObject = await api.callFlutterEchoNullableNonNullEnumList( + nonNullEnumList, + ); + expect(listEquals(echoObject, nonNullEnumList), true); + }); - testWidgets('null lists serialize and deserialize correctly', ( + testWidgets('nullable NonNull class lists serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); - final List? echoObject = await api.callFlutterEchoNullableList( - null, + final List? echoObject = await api.callFlutterEchoNullableNonNullClassList( + nonNullAllNullableTypesList, ); + for (final (int index, AllNullableTypes? value) in echoObject!.indexed) { + expect(value, nonNullAllNullableTypesList[index]); + } + }); + + testWidgets('null lists serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + + final List? echoObject = await api.callFlutterEchoNullableList(null); expect(listEquals(echoObject, null), true); }); - testWidgets('nullable maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableMap(map); + final Map? echoObject = await api.callFlutterEchoNullableMap(map); expect(mapEquals(echoObject, map), true); }); - testWidgets('null maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('null maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableMap(null); + final Map? echoObject = await api.callFlutterEchoNullableMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('nullable string maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable string maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableStringMap(stringMap); + final Map? echoObject = await api.callFlutterEchoNullableStringMap( + stringMap, + ); expect(mapEquals(echoObject, stringMap), true); }); - testWidgets('nullable int maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable int maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableIntMap(intMap); + final Map? echoObject = await api.callFlutterEchoNullableIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); - testWidgets('nullable enum maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enum maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableEnumMap(enumMap); + final Map? echoObject = await api.callFlutterEchoNullableEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); - testWidgets('nullable class maps serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable class maps serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableClassMap(allNullableTypesMap); - for (final MapEntry entry - in echoObject!.entries) { + final Map? echoObject = await api.callFlutterEchoNullableClassMap( + allNullableTypesMap, + ); + for (final MapEntry entry in echoObject!.entries) { expect(entry.value, allNullableTypesMap[entry.key]); } }); - testWidgets( - 'nullable NonNull string maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableNonNullStringMap(nonNullStringMap); - expect(mapEquals(echoObject, nonNullStringMap), true); - }, - ); - - testWidgets( - 'nullable NonNull int maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableNonNullIntMap(nonNullIntMap); - expect(mapEquals(echoObject, nonNullIntMap), true); - }, - ); + testWidgets('nullable NonNull string maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final Map? echoObject = await api.callFlutterEchoNullableNonNullStringMap( + nonNullStringMap, + ); + expect(mapEquals(echoObject, nonNullStringMap), true); + }); - testWidgets( - 'nullable NonNull enum maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableNonNullEnumMap(nonNullEnumMap); - expect(mapEquals(echoObject, nonNullEnumMap), true); - }, - ); + testWidgets('nullable NonNull int maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final Map? echoObject = await api.callFlutterEchoNullableNonNullIntMap( + nonNullIntMap, + ); + expect(mapEquals(echoObject, nonNullIntMap), true); + }); - testWidgets( - 'nullable NonNull class maps serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableNonNullClassMap(nonNullAllNullableTypesMap); - for (final MapEntry entry - in echoObject!.entries) { - expect(entry.value, nonNullAllNullableTypesMap[entry.key]); - } - }, - ); + testWidgets('nullable NonNull enum maps serialize and deserialize correctly', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final Map? echoObject = await api.callFlutterEchoNullableNonNullEnumMap( + nonNullEnumMap, + ); + expect(mapEquals(echoObject, nonNullEnumMap), true); + }); - testWidgets('null maps serialize and deserialize correctly', ( + testWidgets('nullable NonNull class maps serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + final Map? echoObject = await api + .callFlutterEchoNullableNonNullClassMap(nonNullAllNullableTypesMap); + for (final MapEntry entry in echoObject!.entries) { + expect(entry.value, nonNullAllNullableTypesMap[entry.key]); + } + }); + + testWidgets('null maps serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); - final Map? echoObject = await api - .callFlutterEchoNullableIntMap(null); + final Map? echoObject = await api.callFlutterEchoNullableIntMap(null); expect(mapEquals(echoObject, null), true); }); - testWidgets('nullable enums serialize and deserialize correctly', ( - WidgetTester _, - ) async { + testWidgets('nullable enums serialize and deserialize correctly', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; @@ -2505,42 +2025,33 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; - final AnotherEnum? echoEnum = await api - .callFlutterEchoAnotherNullableEnum(sentEnum); + final AnotherEnum? echoEnum = await api.callFlutterEchoAnotherNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); - testWidgets( - 'multi word nullable enums serialize and deserialize correctly', - (WidgetTester _) async { - final api = HostIntegrationCoreApi(); - - const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; - final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum( - sentEnum, - ); - expect(echoEnum, sentEnum); - }, - ); - - testWidgets('null enums serialize and deserialize correctly', ( + testWidgets('multi word nullable enums serialize and deserialize correctly', ( WidgetTester _, ) async { final api = HostIntegrationCoreApi(); + const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; + final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); + expect(echoEnum, sentEnum); + }); + + testWidgets('null enums serialize and deserialize correctly', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + const AnEnum? sentEnum = null; final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); - testWidgets('null enums serialize and deserialize correctly (again)', ( - WidgetTester _, - ) async { + testWidgets('null enums serialize and deserialize correctly (again)', (WidgetTester _) async { final api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; - final AnotherEnum? echoEnum = await api - .callFlutterEchoAnotherNullableEnum(sentEnum); + final AnotherEnum? echoEnum = await api.callFlutterEchoAnotherNullableEnum(sentEnum); expect(echoEnum, sentEnum); }); }); @@ -2587,19 +2098,13 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('throwError', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - await expectLater( - () => api.throwError(), - throwsA(isA()), - ); + await expectLater(() => api.throwError(), throwsA(isA())); }); testWidgets('throwErrorFromVoid', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - await expectLater( - () => api.throwErrorFromVoid(), - throwsA(isA()), - ); + await expectLater(() => api.throwErrorFromVoid(), throwsA(isA())); }); testWidgets('throwFlutterError', (_) async { @@ -2685,9 +2190,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoProxyApiMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - final value = { - '42': _createGenericProxyApiTestClass(), - }; + final value = {'42': _createGenericProxyApiTestClass()}; expect(await api.echoProxyApiMap(value), value); }); @@ -2750,19 +2253,13 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoNullableMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); expect(await api.echoNullableMap(null), null); - expect( - await api.echoNullableMap({'value': 1}), - {'value': 1}, - ); + expect(await api.echoNullableMap({'value': 1}), {'value': 1}); }); testWidgets('echoNullableEnum', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); expect(await api.echoNullableEnum(null), null); - expect( - await api.echoNullableEnum(ProxyApiTestEnum.one), - ProxyApiTestEnum.one, - ); + expect(await api.echoNullableEnum(ProxyApiTestEnum.one), ProxyApiTestEnum.one); }); testWidgets('echoNullableProxyApi', (_) async { @@ -2844,19 +2341,13 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('throwAsyncError', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - await expectLater( - () => api.throwAsyncError(), - throwsA(isA()), - ); + await expectLater(() => api.throwAsyncError(), throwsA(isA())); }); testWidgets('throwAsyncErrorFromVoid', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - await expectLater( - () => api.throwAsyncErrorFromVoid(), - throwsA(isA()), - ); + await expectLater(() => api.throwAsyncErrorFromVoid(), throwsA(isA())); }); testWidgets('throwAsyncFlutterError', (_) async { @@ -2918,19 +2409,15 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoAsyncNullableMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); expect(await api.echoAsyncNullableMap(null), null); - expect( - await api.echoAsyncNullableMap({'banana': 1}), - {'banana': 1}, - ); + expect(await api.echoAsyncNullableMap({'banana': 1}), { + 'banana': 1, + }); }); testWidgets('echoAsyncNullableEnum', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); expect(await api.echoAsyncNullableEnum(null), null); - expect( - await api.echoAsyncNullableEnum(ProxyApiTestEnum.one), - ProxyApiTestEnum.one, - ); + expect(await api.echoAsyncNullableEnum(ProxyApiTestEnum.one), ProxyApiTestEnum.one); }); testWidgets('staticNoop', (_) async { @@ -3055,9 +2542,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoProxyApiList: (_, List aList) => aList, ); - final List value = [ - _createGenericProxyApiTestClass(), - ]; + final List value = [_createGenericProxyApiTestClass()]; expect(await api.callFlutterEchoProxyApiList(value), value); }); @@ -3072,13 +2557,10 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('callFlutterEchoProxyApiMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass( - flutterEchoProxyApiMap: (_, Map aMap) => - aMap, + flutterEchoProxyApiMap: (_, Map aMap) => aMap, ); - final value = { - 'a String': _createGenericProxyApiTestClass(), - }; + final value = {'a String': _createGenericProxyApiTestClass()}; expect(await api.callFlutterEchoProxyApiMap(value), value); }); @@ -3137,10 +2619,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoNullableUint8List: (_, Uint8List? aUint8List) => aUint8List, ); expect(await api.callFlutterEchoNullableUint8List(null), null); - expect( - await api.callFlutterEchoNullableUint8List(Uint8List(0)), - Uint8List(0), - ); + expect(await api.callFlutterEchoNullableUint8List(Uint8List(0)), Uint8List(0)); }); testWidgets('callFlutterEchoNullableList', (_) async { @@ -3156,10 +2635,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoNullableMap: (_, Map? aMap) => aMap, ); expect(await api.callFlutterEchoNullableMap(null), null); - expect( - await api.callFlutterEchoNullableMap({'str': 0}), - {'str': 0}, - ); + expect(await api.callFlutterEchoNullableMap({'str': 0}), { + 'str': 0, + }); }); testWidgets('callFlutterEchoNullableEnum', (_) async { @@ -3167,16 +2645,12 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoNullableEnum: (_, ProxyApiTestEnum? anEnum) => anEnum, ); expect(await api.callFlutterEchoNullableEnum(null), null); - expect( - await api.callFlutterEchoNullableEnum(ProxyApiTestEnum.two), - ProxyApiTestEnum.two, - ); + expect(await api.callFlutterEchoNullableEnum(ProxyApiTestEnum.two), ProxyApiTestEnum.two); }); testWidgets('callFlutterEchoNullableProxyApi', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass( - flutterEchoNullableProxyApi: (_, ProxyApiSuperClass? aProxyApi) => - aProxyApi, + flutterEchoNullableProxyApi: (_, ProxyApiSuperClass? aProxyApi) => aProxyApi, ); expect(await api.callFlutterEchoNullableProxyApi(null), null); @@ -3209,24 +2683,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { group('Flutter API with suffix', () { setUp(() { - FlutterSmallApi.setUp( - _SmallFlutterApi(), - messageChannelSuffix: 'suffixOne', - ); - FlutterSmallApi.setUp( - _SmallFlutterApi(), - messageChannelSuffix: 'suffixTwo', - ); + FlutterSmallApi.setUp(_SmallFlutterApi(), messageChannelSuffix: 'suffixOne'); + FlutterSmallApi.setUp(_SmallFlutterApi(), messageChannelSuffix: 'suffixTwo'); }); - testWidgets('echo string succeeds with suffix with multiple instances', ( - _, - ) async { + testWidgets('echo string succeeds with suffix with multiple instances', (_) async { final api = HostIntegrationCoreApi(); const sentObject = "I'm a computer"; - final String echoObject = await api.callFlutterSmallApiEchoString( - sentObject, - ); + final String echoObject = await api.callFlutterSmallApiEchoString(sentObject); expect(echoObject, sentObject); }); }); @@ -3260,92 +2724,77 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { /// Event channels - const eventChannelSupported = [ - TargetGenerator.kotlin, - TargetGenerator.swift, - ]; - - testWidgets( - 'event channel sends continuous ints', - (_) async { - final Stream events = streamInts(); - final List listEvents = await events.toList(); - for (final value in listEvents) { - expect(listEvents[value], value); - } - }, - skip: !eventChannelSupported.contains(targetGenerator), - ); - - testWidgets( - 'event channel handles extended sealed classes', - (_) async { - final completer = Completer(); - var count = 0; - final Stream events = streamEvents(); - events.listen((PlatformEvent event) { - switch (event) { - case IntEvent(): - expect(event.value, 1); - expect(count, 0); - count++; - case StringEvent(): - expect(event.value, 'string'); - expect(count, 1); - count++; - case BoolEvent(): - expect(event.value, false); - expect(count, 2); - count++; - case DoubleEvent(): - expect(event.value, 3.14); - expect(count, 3); - count++; - case ObjectsEvent(): - expect(event.value, true); - expect(count, 4); - count++; - case EnumEvent(): - expect(event.value, EventEnum.fortyTwo); - expect(count, 5); - count++; - case ClassEvent(): - expect(event.value.aNullableInt, 0); - expect(count, 6); - count++; - completer.complete(); - } - }); - await completer.future; - }, - skip: !eventChannelSupported.contains(targetGenerator), - ); + const eventChannelSupported = [TargetGenerator.kotlin, TargetGenerator.swift]; - testWidgets( - 'event channels handle multiple instances', - (_) async { - final completer1 = Completer(); - final completer2 = Completer(); - final Stream events1 = streamConsistentNumbers(instanceName: '1'); - final Stream events2 = streamConsistentNumbers(instanceName: '2'); - - events1 - .listen((int event) { - expect(event, 1); - }) - .onDone(() => completer1.complete()); - - events2 - .listen((int event) { - expect(event, 2); - }) - .onDone(() => completer2.complete()); - - await completer1.future; - await completer2.future; - }, - skip: !eventChannelSupported.contains(targetGenerator), - ); + testWidgets('event channel sends continuous ints', (_) async { + final Stream events = streamInts(); + final List listEvents = await events.toList(); + for (final value in listEvents) { + expect(listEvents[value], value); + } + }, skip: !eventChannelSupported.contains(targetGenerator)); + + testWidgets('event channel handles extended sealed classes', (_) async { + final completer = Completer(); + var count = 0; + final Stream events = streamEvents(); + events.listen((PlatformEvent event) { + switch (event) { + case IntEvent(): + expect(event.value, 1); + expect(count, 0); + count++; + case StringEvent(): + expect(event.value, 'string'); + expect(count, 1); + count++; + case BoolEvent(): + expect(event.value, false); + expect(count, 2); + count++; + case DoubleEvent(): + expect(event.value, 3.14); + expect(count, 3); + count++; + case ObjectsEvent(): + expect(event.value, true); + expect(count, 4); + count++; + case EnumEvent(): + expect(event.value, EventEnum.fortyTwo); + expect(count, 5); + count++; + case ClassEvent(): + expect(event.value.aNullableInt, 0); + expect(count, 6); + count++; + completer.complete(); + } + }); + await completer.future; + }, skip: !eventChannelSupported.contains(targetGenerator)); + + testWidgets('event channels handle multiple instances', (_) async { + final completer1 = Completer(); + final completer2 = Completer(); + final Stream events1 = streamConsistentNumbers(instanceName: '1'); + final Stream events2 = streamConsistentNumbers(instanceName: '2'); + + events1 + .listen((int event) { + expect(event, 1); + }) + .onDone(() => completer1.complete()); + + events2 + .listen((int event) { + expect(event, 2); + }) + .onDone(() => completer2.complete()); + + await completer1.future; + await completer2.future; + }, skip: !eventChannelSupported.contains(targetGenerator)); } class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { @@ -3435,9 +2884,7 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { List echoNonNullEnumList(List enumList) => enumList; @override - List echoNonNullClassList( - List classList, - ) { + List echoNonNullClassList(List classList) { return classList; } @@ -3445,8 +2892,7 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { Map echoMap(Map map) => map; @override - Map echoStringMap(Map stringMap) => - stringMap; + Map echoStringMap(Map stringMap) => stringMap; @override Map echoIntMap(Map intMap) => intMap; @@ -3455,27 +2901,21 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { Map echoEnumMap(Map enumMap) => enumMap; @override - Map echoClassMap( - Map classMap, - ) { + Map echoClassMap(Map classMap) { return classMap; } @override - Map echoNonNullStringMap(Map stringMap) => - stringMap; + Map echoNonNullStringMap(Map stringMap) => stringMap; @override Map echoNonNullIntMap(Map intMap) => intMap; @override - Map echoNonNullEnumMap(Map enumMap) => - enumMap; + Map echoNonNullEnumMap(Map enumMap) => enumMap; @override - Map echoNonNullClassMap( - Map classMap, - ) { + Map echoNonNullClassMap(Map classMap) { return classMap; } @@ -3501,9 +2941,7 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { List? echoNullableEnumList(List? enumList) => enumList; @override - List? echoNullableClassList( - List? classList, - ) { + List? echoNullableClassList(List? classList) { return classList; } @@ -3513,9 +2951,7 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { } @override - List? echoNullableNonNullClassList( - List? classList, - ) { + List? echoNullableNonNullClassList(List? classList) { return classList; } @@ -3523,9 +2959,7 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { Map? echoNullableMap(Map? map) => map; @override - Map? echoNullableStringMap( - Map? stringMap, - ) { + Map? echoNullableStringMap(Map? stringMap) { return stringMap; } @@ -3538,16 +2972,12 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { } @override - Map? echoNullableClassMap( - Map? classMap, - ) { + Map? echoNullableClassMap(Map? classMap) { return classMap; } @override - Map? echoNullableNonNullStringMap( - Map? stringMap, - ) { + Map? echoNullableNonNullStringMap(Map? stringMap) { return stringMap; } @@ -3557,16 +2987,12 @@ class _FlutterApiTestImplementation implements FlutterIntegrationCoreApi { } @override - Map? echoNullableNonNullEnumMap( - Map? enumMap, - ) { + Map? echoNullableNonNullEnumMap(Map? enumMap) { return enumMap; } @override - Map? echoNullableNonNullClassMap( - Map? classMap, - ) { + Map? echoNullableNonNullClassMap(Map? classMap) { return classMap; } @@ -3609,68 +3035,37 @@ ProxyApiTestClass _createGenericProxyApiTestClass({ void Function(ProxyApiTestClass instance)? flutterThrowErrorFromVoid, bool Function(ProxyApiTestClass instance, bool aBool)? flutterEchoBool, int Function(ProxyApiTestClass instance, int anInt)? flutterEchoInt, - double Function(ProxyApiTestClass instance, double aDouble)? - flutterEchoDouble, - String Function(ProxyApiTestClass instance, String aString)? - flutterEchoString, - Uint8List Function(ProxyApiTestClass instance, Uint8List aList)? - flutterEchoUint8List, - List Function(ProxyApiTestClass instance, List aList)? - flutterEchoList, - List Function( - ProxyApiTestClass instance, - List aList, - )? + double Function(ProxyApiTestClass instance, double aDouble)? flutterEchoDouble, + String Function(ProxyApiTestClass instance, String aString)? flutterEchoString, + Uint8List Function(ProxyApiTestClass instance, Uint8List aList)? flutterEchoUint8List, + List Function(ProxyApiTestClass instance, List aList)? flutterEchoList, + List Function(ProxyApiTestClass instance, List aList)? flutterEchoProxyApiList, - Map Function( - ProxyApiTestClass instance, - Map aMap, - )? + Map Function(ProxyApiTestClass instance, Map aMap)? flutterEchoMap, Map Function( ProxyApiTestClass instance, Map aMap, )? flutterEchoProxyApiMap, - ProxyApiTestEnum Function( - ProxyApiTestClass instance, - ProxyApiTestEnum anEnum, - )? - flutterEchoEnum, - ProxyApiSuperClass Function( - ProxyApiTestClass instance, - ProxyApiSuperClass aProxyApi, - )? + ProxyApiTestEnum Function(ProxyApiTestClass instance, ProxyApiTestEnum anEnum)? flutterEchoEnum, + ProxyApiSuperClass Function(ProxyApiTestClass instance, ProxyApiSuperClass aProxyApi)? flutterEchoProxyApi, - bool? Function(ProxyApiTestClass instance, bool? aBool)? - flutterEchoNullableBool, + bool? Function(ProxyApiTestClass instance, bool? aBool)? flutterEchoNullableBool, int? Function(ProxyApiTestClass instance, int? anInt)? flutterEchoNullableInt, - double? Function(ProxyApiTestClass instance, double? aDouble)? - flutterEchoNullableDouble, - String? Function(ProxyApiTestClass instance, String? aString)? - flutterEchoNullableString, - Uint8List? Function(ProxyApiTestClass instance, Uint8List? aList)? - flutterEchoNullableUint8List, + double? Function(ProxyApiTestClass instance, double? aDouble)? flutterEchoNullableDouble, + String? Function(ProxyApiTestClass instance, String? aString)? flutterEchoNullableString, + Uint8List? Function(ProxyApiTestClass instance, Uint8List? aList)? flutterEchoNullableUint8List, List? Function(ProxyApiTestClass instance, List? aList)? flutterEchoNullableList, - Map? Function( - ProxyApiTestClass instance, - Map? aMap, - )? + Map? Function(ProxyApiTestClass instance, Map? aMap)? flutterEchoNullableMap, - ProxyApiTestEnum? Function( - ProxyApiTestClass instance, - ProxyApiTestEnum? anEnum, - )? + ProxyApiTestEnum? Function(ProxyApiTestClass instance, ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum, - ProxyApiSuperClass? Function( - ProxyApiTestClass instance, - ProxyApiSuperClass? aProxyApi, - )? + ProxyApiSuperClass? Function(ProxyApiTestClass instance, ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass instance)? flutterNoopAsync, - Future Function(ProxyApiTestClass instance, String aString)? - flutterEchoAsyncString, + Future Function(ProxyApiTestClass instance, String aString)? flutterEchoAsyncString, }) { return ProxyApiTestClass( aBool: true, @@ -3694,15 +3089,13 @@ ProxyApiTestClass _createGenericProxyApiTestClass({ flutterNoop: flutterNoop, flutterThrowError: flutterThrowError, flutterThrowErrorFromVoid: flutterThrowErrorFromVoid, - flutterEchoBool: - flutterEchoBool ?? (ProxyApiTestClass instance, bool aBool) => true, + flutterEchoBool: flutterEchoBool ?? (ProxyApiTestClass instance, bool aBool) => true, flutterEchoInt: flutterEchoInt ?? (_, __) => 3, flutterEchoDouble: flutterEchoDouble ?? (_, __) => 1.0, flutterEchoString: flutterEchoString ?? (_, __) => '', flutterEchoUint8List: flutterEchoUint8List ?? (_, __) => Uint8List(0), flutterEchoList: flutterEchoList ?? (_, __) => [], - flutterEchoProxyApiList: - flutterEchoProxyApiList ?? (_, __) => [], + flutterEchoProxyApiList: flutterEchoProxyApiList ?? (_, __) => [], flutterEchoMap: flutterEchoMap ?? (_, __) => {}, flutterEchoEnum: flutterEchoEnum ?? (_, __) => ProxyApiTestEnum.one, flutterEchoProxyApi: flutterEchoProxyApi ?? (_, __) => ProxyApiSuperClass(), @@ -3717,7 +3110,6 @@ ProxyApiTestClass _createGenericProxyApiTestClass({ flutterEchoNullableProxyApi: flutterEchoNullableProxyApi, flutterNoopAsync: flutterNoopAsync, flutterEchoAsyncString: flutterEchoAsyncString ?? (_, __) async => '', - flutterEchoProxyApiMap: - flutterEchoProxyApiMap ?? (_, __) => {}, + flutterEchoProxyApiMap: flutterEchoProxyApiMap ?? (_, __) => {}, ); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart index d6e49a4b33b3..5cc6b0041cfd 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart @@ -44,13 +44,11 @@ class BackgroundApi2Host { /// Constructor for [BackgroundApi2Host]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - BackgroundApi2Host({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + BackgroundApi2Host({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -65,11 +63,9 @@ class BackgroundApi2Host { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [ - [x, y], - ], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + [x, y], + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart index 482368add83b..70c013eceb54 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -64,9 +60,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -309,10 +303,8 @@ class AllTypes { intMap: (result[23]! as Map).cast(), enumMap: (result[24]! as Map).cast(), objectMap: (result[25]! as Map).cast(), - listMap: (result[26]! as Map) - .cast>(), - mapMap: (result[27]! as Map) - .cast>(), + listMap: (result[26]! as Map).cast>(), + mapMap: (result[27]! as Map).cast>(), ); } @@ -523,20 +515,15 @@ class AllNullableTypes { objectList: result[19] as List?, listList: (result[20] as List?)?.cast?>(), mapList: (result[21] as List?)?.cast?>(), - recursiveClassList: (result[22] as List?) - ?.cast(), + recursiveClassList: (result[22] as List?)?.cast(), map: result[23] as Map?, - stringMap: (result[24] as Map?) - ?.cast(), + stringMap: (result[24] as Map?)?.cast(), intMap: (result[25] as Map?)?.cast(), enumMap: (result[26] as Map?)?.cast(), objectMap: result[27] as Map?, - listMap: (result[28] as Map?) - ?.cast?>(), - mapMap: (result[29] as Map?) - ?.cast?>(), - recursiveClassMap: (result[30] as Map?) - ?.cast(), + listMap: (result[28] as Map?)?.cast?>(), + mapMap: (result[29] as Map?)?.cast?>(), + recursiveClassMap: (result[30] as Map?)?.cast(), ); } @@ -740,23 +727,19 @@ class AllNullableTypesWithoutRecursion { listList: (result[19] as List?)?.cast?>(), mapList: (result[20] as List?)?.cast?>(), map: result[21] as Map?, - stringMap: (result[22] as Map?) - ?.cast(), + stringMap: (result[22] as Map?)?.cast(), intMap: (result[23] as Map?)?.cast(), enumMap: (result[24] as Map?)?.cast(), objectMap: result[25] as Map?, - listMap: (result[26] as Map?) - ?.cast?>(), - mapMap: (result[27] as Map?) - ?.cast?>(), + listMap: (result[26] as Map?)?.cast?>(), + mapMap: (result[27] as Map?)?.cast?>(), ); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! AllNullableTypesWithoutRecursion || - other.runtimeType != runtimeType) { + if (other is! AllNullableTypesWithoutRecursion || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -847,12 +830,10 @@ class AllClassesWrapper { result as List; return AllClassesWrapper( allNullableTypes: result[0]! as AllNullableTypes, - allNullableTypesWithoutRecursion: - result[1] as AllNullableTypesWithoutRecursion?, + allNullableTypesWithoutRecursion: result[1] as AllNullableTypesWithoutRecursion?, allTypes: result[2] as AllTypes?, classList: (result[3]! as List).cast(), - nullableClassList: (result[4] as List?) - ?.cast(), + nullableClassList: (result[4] as List?)?.cast(), classMap: (result[5]! as Map).cast(), nullableClassMap: (result[6] as Map?) ?.cast(), @@ -869,10 +850,7 @@ class AllClassesWrapper { return true; } return _deepEquals(allNullableTypes, other.allNullableTypes) && - _deepEquals( - allNullableTypesWithoutRecursion, - other.allNullableTypesWithoutRecursion, - ) && + _deepEquals(allNullableTypesWithoutRecursion, other.allNullableTypesWithoutRecursion) && _deepEquals(allTypes, other.allTypes) && _deepEquals(classList, other.classList) && _deepEquals(nullableClassList, other.nullableClassList) && @@ -990,13 +968,11 @@ class HostIntegrationCoreApi { /// Constructor for [HostIntegrationCoreApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - HostIntegrationCoreApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + HostIntegrationCoreApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -1016,11 +992,7 @@ class HostIntegrationCoreApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Returns the passed object, to test serialization and deserialization. @@ -1032,9 +1004,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1077,11 +1047,7 @@ class HostIntegrationCoreApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Returns a Flutter error, to test error handling. @@ -1113,9 +1079,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1135,9 +1099,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1157,9 +1119,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1179,9 +1139,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1201,9 +1159,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aUint8List]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1223,9 +1179,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anObject]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1245,9 +1199,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [list], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([list]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1267,9 +1219,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1281,9 +1231,7 @@ class HostIntegrationCoreApi { } /// Returns the passed list, to test serialization and deserialization. - Future> echoClassList( - List classList, - ) async { + Future> echoClassList(List classList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1291,9 +1239,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1313,9 +1259,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1327,9 +1271,7 @@ class HostIntegrationCoreApi { } /// Returns the passed list, to test serialization and deserialization. - Future> echoNonNullClassList( - List classList, - ) async { + Future> echoNonNullClassList(List classList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullClassList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1337,9 +1279,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1359,9 +1299,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [map], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([map]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1373,9 +1311,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test serialization and deserialization. - Future> echoStringMap( - Map stringMap, - ) async { + Future> echoStringMap(Map stringMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoStringMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1383,9 +1319,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1393,8 +1327,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test serialization and deserialization. @@ -1406,9 +1339,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1420,9 +1351,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test serialization and deserialization. - Future> echoEnumMap( - Map enumMap, - ) async { + Future> echoEnumMap(Map enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1430,9 +1359,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1440,14 +1367,11 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test serialization and deserialization. - Future> echoClassMap( - Map classMap, - ) async { + Future> echoClassMap(Map classMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1455,9 +1379,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1465,14 +1387,11 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test serialization and deserialization. - Future> echoNonNullStringMap( - Map stringMap, - ) async { + Future> echoNonNullStringMap(Map stringMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullStringMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1480,9 +1399,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1490,8 +1407,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test serialization and deserialization. @@ -1503,9 +1419,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1517,9 +1431,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test serialization and deserialization. - Future> echoNonNullEnumMap( - Map enumMap, - ) async { + Future> echoNonNullEnumMap(Map enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1527,9 +1439,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1537,8 +1447,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test serialization and deserialization. @@ -1552,9 +1461,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1562,8 +1469,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed class to test nested class serialization and deserialization. @@ -1575,9 +1481,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [wrapper], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([wrapper]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1597,9 +1501,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1619,9 +1521,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anotherEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anotherEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1641,9 +1541,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1663,9 +1561,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1685,9 +1581,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1699,10 +1593,7 @@ class HostIntegrationCoreApi { } /// Returns the result of platform-side equality check. - Future areAllNullableTypesEqual( - AllNullableTypes a, - AllNullableTypes b, - ) async { + Future areAllNullableTypesEqual(AllNullableTypes a, AllNullableTypes b) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.areAllNullableTypesEqual$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1710,9 +1601,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [a, b], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([a, b]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1732,9 +1621,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1756,9 +1643,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1770,9 +1655,7 @@ class HostIntegrationCoreApi { } /// Returns the passed object, to test serialization and deserialization. - Future echoAllNullableTypes( - AllNullableTypes? everything, - ) async { + Future echoAllNullableTypes(AllNullableTypes? everything) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllNullableTypes$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1780,9 +1663,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1794,8 +1675,7 @@ class HostIntegrationCoreApi { } /// Returns the passed object, to test serialization and deserialization. - Future - echoAllNullableTypesWithoutRecursion( + Future echoAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ) async { final pigeonVar_channelName = @@ -1805,9 +1685,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1828,9 +1706,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [wrapper], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([wrapper]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1843,9 +1719,7 @@ class HostIntegrationCoreApi { /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. - Future createNestedNullableString( - String? nullableString, - ) async { + Future createNestedNullableString(String? nullableString) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.createNestedNullableString$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -1853,9 +1727,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [nullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([nullableString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1879,9 +1751,11 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableBool, aNullableInt, aNullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + aNullableBool, + aNullableInt, + aNullableString, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1893,8 +1767,7 @@ class HostIntegrationCoreApi { } /// Returns passed in arguments of multiple types. - Future - sendMultipleNullableTypesWithoutRecursion( + Future sendMultipleNullableTypesWithoutRecursion( bool? aNullableBool, int? aNullableInt, String? aNullableString, @@ -1906,9 +1779,11 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableBool, aNullableInt, aNullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + aNullableBool, + aNullableInt, + aNullableString, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1928,9 +1803,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1950,9 +1823,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1972,9 +1843,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -1994,9 +1863,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2008,9 +1875,7 @@ class HostIntegrationCoreApi { } /// Returns the passed in Uint8List. - Future echoNullableUint8List( - Uint8List? aNullableUint8List, - ) async { + Future echoNullableUint8List(Uint8List? aNullableUint8List) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableUint8List$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2018,9 +1883,9 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + aNullableUint8List, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2040,9 +1905,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableObject]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2062,9 +1925,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2084,9 +1945,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2098,9 +1957,7 @@ class HostIntegrationCoreApi { } /// Returns the passed list, to test serialization and deserialization. - Future?> echoNullableClassList( - List? classList, - ) async { + Future?> echoNullableClassList(List? classList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableClassList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2108,9 +1965,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2122,9 +1977,7 @@ class HostIntegrationCoreApi { } /// Returns the passed list, to test serialization and deserialization. - Future?> echoNullableNonNullEnumList( - List? enumList, - ) async { + Future?> echoNullableNonNullEnumList(List? enumList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullEnumList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2132,9 +1985,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2156,9 +2007,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2170,9 +2019,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test serialization and deserialization. - Future?> echoNullableMap( - Map? map, - ) async { + Future?> echoNullableMap(Map? map) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2180,9 +2027,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [map], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([map]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2194,9 +2039,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test serialization and deserialization. - Future?> echoNullableStringMap( - Map? stringMap, - ) async { + Future?> echoNullableStringMap(Map? stringMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableStringMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2204,9 +2047,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2214,8 +2055,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. @@ -2227,9 +2067,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2241,9 +2079,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test serialization and deserialization. - Future?> echoNullableEnumMap( - Map? enumMap, - ) async { + Future?> echoNullableEnumMap(Map? enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2251,9 +2087,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2261,8 +2095,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. @@ -2276,9 +2109,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2286,14 +2117,11 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. - Future?> echoNullableNonNullStringMap( - Map? stringMap, - ) async { + Future?> echoNullableNonNullStringMap(Map? stringMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullStringMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2301,9 +2129,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2311,14 +2137,11 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. - Future?> echoNullableNonNullIntMap( - Map? intMap, - ) async { + Future?> echoNullableNonNullIntMap(Map? intMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullIntMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2326,9 +2149,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2340,9 +2161,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test serialization and deserialization. - Future?> echoNullableNonNullEnumMap( - Map? enumMap, - ) async { + Future?> echoNullableNonNullEnumMap(Map? enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2350,9 +2169,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2360,8 +2177,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. @@ -2375,9 +2191,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2385,8 +2199,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } Future echoNullableEnum(AnEnum? anEnum) async { @@ -2397,9 +2210,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2418,9 +2229,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anotherEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anotherEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2440,9 +2249,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2462,9 +2269,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aNullableString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2488,11 +2293,7 @@ class HostIntegrationCoreApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Returns passed in int asynchronously. @@ -2504,9 +2305,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2526,9 +2325,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2548,9 +2345,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2570,9 +2365,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2592,9 +2385,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aUint8List]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2614,9 +2405,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anObject]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2636,9 +2425,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [list], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([list]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2658,9 +2445,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2672,9 +2457,7 @@ class HostIntegrationCoreApi { } /// Returns the passed list, to test asynchronous serialization and deserialization. - Future> echoAsyncClassList( - List classList, - ) async { + Future> echoAsyncClassList(List classList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncClassList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2682,9 +2465,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2704,9 +2485,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [map], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([map]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2718,9 +2497,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test asynchronous serialization and deserialization. - Future> echoAsyncStringMap( - Map stringMap, - ) async { + Future> echoAsyncStringMap(Map stringMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncStringMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2728,9 +2505,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2738,8 +2513,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. @@ -2751,9 +2525,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2765,9 +2537,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test asynchronous serialization and deserialization. - Future> echoAsyncEnumMap( - Map enumMap, - ) async { + Future> echoAsyncEnumMap(Map enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2775,9 +2545,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2785,8 +2553,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. @@ -2800,9 +2567,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2810,8 +2575,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. @@ -2823,9 +2587,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2845,9 +2607,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anotherEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anotherEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2890,11 +2650,7 @@ class HostIntegrationCoreApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Responds with a Flutter error from an async function returning a value. @@ -2926,9 +2682,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2940,9 +2694,7 @@ class HostIntegrationCoreApi { } /// Returns the passed object, to test serialization and deserialization. - Future echoAsyncNullableAllNullableTypes( - AllNullableTypes? everything, - ) async { + Future echoAsyncNullableAllNullableTypes(AllNullableTypes? everything) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableAllNullableTypes$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -2950,9 +2702,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2964,8 +2714,7 @@ class HostIntegrationCoreApi { } /// Returns the passed object, to test serialization and deserialization. - Future - echoAsyncNullableAllNullableTypesWithoutRecursion( + Future echoAsyncNullableAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ) async { final pigeonVar_channelName = @@ -2975,9 +2724,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -2997,9 +2744,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3019,9 +2764,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3041,9 +2784,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3063,9 +2804,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3085,9 +2824,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aUint8List]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3107,9 +2844,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anObject]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3129,9 +2864,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [list], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([list]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3143,9 +2876,7 @@ class HostIntegrationCoreApi { } /// Returns the passed list, to test asynchronous serialization and deserialization. - Future?> echoAsyncNullableEnumList( - List? enumList, - ) async { + Future?> echoAsyncNullableEnumList(List? enumList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnumList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3153,9 +2884,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3177,9 +2906,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3191,9 +2918,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test asynchronous serialization and deserialization. - Future?> echoAsyncNullableMap( - Map? map, - ) async { + Future?> echoAsyncNullableMap(Map? map) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3201,9 +2926,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [map], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([map]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3225,9 +2948,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3235,14 +2956,11 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. - Future?> echoAsyncNullableIntMap( - Map? intMap, - ) async { + Future?> echoAsyncNullableIntMap(Map? intMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableIntMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3250,9 +2968,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3264,9 +2980,7 @@ class HostIntegrationCoreApi { } /// Returns the passed map, to test asynchronous serialization and deserialization. - Future?> echoAsyncNullableEnumMap( - Map? enumMap, - ) async { + Future?> echoAsyncNullableEnumMap(Map? enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3274,9 +2988,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3284,8 +2996,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. @@ -3299,9 +3010,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3309,8 +3018,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. @@ -3322,9 +3030,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3336,9 +3042,7 @@ class HostIntegrationCoreApi { } /// Returns the passed enum, to test asynchronous serialization and deserialization. - Future echoAnotherAsyncNullableEnum( - AnotherEnum? anotherEnum, - ) async { + Future echoAnotherAsyncNullableEnum(AnotherEnum? anotherEnum) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherAsyncNullableEnum$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3346,9 +3050,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anotherEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anotherEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3412,11 +3114,7 @@ class HostIntegrationCoreApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } Future callFlutterThrowError() async { @@ -3449,11 +3147,7 @@ class HostIntegrationCoreApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } Future callFlutterEchoAllTypes(AllTypes everything) async { @@ -3464,9 +3158,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3477,9 +3169,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue! as AllTypes; } - Future callFlutterEchoAllNullableTypes( - AllNullableTypes? everything, - ) async { + Future callFlutterEchoAllNullableTypes(AllNullableTypes? everything) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllNullableTypes$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3487,9 +3177,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3512,9 +3200,11 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableBool, aNullableInt, aNullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + aNullableBool, + aNullableInt, + aNullableString, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3525,8 +3215,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue! as AllNullableTypes; } - Future - callFlutterEchoAllNullableTypesWithoutRecursion( + Future callFlutterEchoAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ) async { final pigeonVar_channelName = @@ -3536,9 +3225,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [everything], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([everything]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3549,8 +3236,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue as AllNullableTypesWithoutRecursion?; } - Future - callFlutterSendMultipleNullableTypesWithoutRecursion( + Future callFlutterSendMultipleNullableTypesWithoutRecursion( bool? aNullableBool, int? aNullableInt, String? aNullableString, @@ -3562,9 +3248,11 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aNullableBool, aNullableInt, aNullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + aNullableBool, + aNullableInt, + aNullableString, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3583,9 +3271,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3604,9 +3290,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3625,9 +3309,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3646,9 +3328,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3667,9 +3347,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [list], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([list]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3688,9 +3366,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [list], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([list]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3709,9 +3385,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3732,9 +3406,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3745,9 +3417,7 @@ class HostIntegrationCoreApi { return (pigeonVar_replyValue! as List).cast(); } - Future> callFlutterEchoNonNullEnumList( - List enumList, - ) async { + Future> callFlutterEchoNonNullEnumList(List enumList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullEnumList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3755,9 +3425,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3778,9 +3446,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3791,9 +3457,7 @@ class HostIntegrationCoreApi { return (pigeonVar_replyValue! as List).cast(); } - Future> callFlutterEchoMap( - Map map, - ) async { + Future> callFlutterEchoMap(Map map) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3801,9 +3465,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [map], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([map]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3814,9 +3476,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue! as Map; } - Future> callFlutterEchoStringMap( - Map stringMap, - ) async { + Future> callFlutterEchoStringMap(Map stringMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoStringMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3824,9 +3484,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3834,8 +3492,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } Future> callFlutterEchoIntMap(Map intMap) async { @@ -3846,9 +3503,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3859,9 +3514,7 @@ class HostIntegrationCoreApi { return (pigeonVar_replyValue! as Map).cast(); } - Future> callFlutterEchoEnumMap( - Map enumMap, - ) async { + Future> callFlutterEchoEnumMap(Map enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3869,9 +3522,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3879,8 +3530,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } Future> callFlutterEchoClassMap( @@ -3893,9 +3543,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3903,13 +3551,10 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } - Future> callFlutterEchoNonNullStringMap( - Map stringMap, - ) async { + Future> callFlutterEchoNonNullStringMap(Map stringMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullStringMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3917,9 +3562,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3927,13 +3570,10 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } - Future> callFlutterEchoNonNullIntMap( - Map intMap, - ) async { + Future> callFlutterEchoNonNullIntMap(Map intMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullIntMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3941,9 +3581,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3954,9 +3592,7 @@ class HostIntegrationCoreApi { return (pigeonVar_replyValue! as Map).cast(); } - Future> callFlutterEchoNonNullEnumMap( - Map enumMap, - ) async { + Future> callFlutterEchoNonNullEnumMap(Map enumMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullEnumMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -3964,9 +3600,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3974,8 +3608,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } Future> callFlutterEchoNonNullClassMap( @@ -3988,9 +3621,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3998,8 +3629,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } Future callFlutterEchoEnum(AnEnum anEnum) async { @@ -4010,9 +3640,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4023,9 +3651,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue! as AnEnum; } - Future callFlutterEchoAnotherEnum( - AnotherEnum anotherEnum, - ) async { + Future callFlutterEchoAnotherEnum(AnotherEnum anotherEnum) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAnotherEnum$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4033,9 +3659,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anotherEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anotherEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4054,9 +3678,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4075,9 +3697,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4096,9 +3716,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4117,9 +3735,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4138,9 +3754,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [list], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([list]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4151,9 +3765,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue as Uint8List?; } - Future?> callFlutterEchoNullableList( - List? list, - ) async { + Future?> callFlutterEchoNullableList(List? list) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4161,9 +3773,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [list], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([list]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4174,9 +3784,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue as List?; } - Future?> callFlutterEchoNullableEnumList( - List? enumList, - ) async { + Future?> callFlutterEchoNullableEnumList(List? enumList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnumList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4184,9 +3792,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4207,9 +3813,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4220,9 +3824,7 @@ class HostIntegrationCoreApi { return (pigeonVar_replyValue as List?)?.cast(); } - Future?> callFlutterEchoNullableNonNullEnumList( - List? enumList, - ) async { + Future?> callFlutterEchoNullableNonNullEnumList(List? enumList) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullEnumList$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4230,9 +3832,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4253,9 +3853,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4266,9 +3864,7 @@ class HostIntegrationCoreApi { return (pigeonVar_replyValue as List?)?.cast(); } - Future?> callFlutterEchoNullableMap( - Map? map, - ) async { + Future?> callFlutterEchoNullableMap(Map? map) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4276,9 +3872,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [map], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([map]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4299,9 +3893,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4309,13 +3901,10 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } - Future?> callFlutterEchoNullableIntMap( - Map? intMap, - ) async { + Future?> callFlutterEchoNullableIntMap(Map? intMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableIntMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4323,9 +3912,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4346,9 +3933,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4356,8 +3941,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } Future?> callFlutterEchoNullableClassMap( @@ -4370,9 +3954,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4380,8 +3962,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } Future?> callFlutterEchoNullableNonNullStringMap( @@ -4394,9 +3975,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [stringMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([stringMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4404,13 +3983,10 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } - Future?> callFlutterEchoNullableNonNullIntMap( - Map? intMap, - ) async { + Future?> callFlutterEchoNullableNonNullIntMap(Map? intMap) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullIntMap$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4418,9 +3994,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [intMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([intMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4441,9 +4015,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [enumMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([enumMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4451,8 +4023,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } Future?> callFlutterEchoNullableNonNullClassMap( @@ -4465,9 +4036,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [classMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([classMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4475,8 +4044,7 @@ class HostIntegrationCoreApi { pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } Future callFlutterEchoNullableEnum(AnEnum? anEnum) async { @@ -4487,9 +4055,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4500,9 +4066,7 @@ class HostIntegrationCoreApi { return pigeonVar_replyValue as AnEnum?; } - Future callFlutterEchoAnotherNullableEnum( - AnotherEnum? anotherEnum, - ) async { + Future callFlutterEchoAnotherNullableEnum(AnotherEnum? anotherEnum) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAnotherNullableEnum$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -4510,9 +4074,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [anotherEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([anotherEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4531,9 +4093,7 @@ class HostIntegrationCoreApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4632,9 +4192,7 @@ abstract class FlutterIntegrationCoreApi { Map echoEnumMap(Map enumMap); /// Returns the passed map, to test serialization and deserialization. - Map echoClassMap( - Map classMap, - ); + Map echoClassMap(Map classMap); /// Returns the passed map, to test serialization and deserialization. Map echoNonNullStringMap(Map stringMap); @@ -4646,9 +4204,7 @@ abstract class FlutterIntegrationCoreApi { Map echoNonNullEnumMap(Map enumMap); /// Returns the passed map, to test serialization and deserialization. - Map echoNonNullClassMap( - Map classMap, - ); + Map echoNonNullClassMap(Map classMap); /// Returns the passed enum to test serialization and deserialization. AnEnum echoEnum(AnEnum anEnum); @@ -4678,25 +4234,19 @@ abstract class FlutterIntegrationCoreApi { List? echoNullableEnumList(List? enumList); /// Returns the passed list, to test serialization and deserialization. - List? echoNullableClassList( - List? classList, - ); + List? echoNullableClassList(List? classList); /// Returns the passed list, to test serialization and deserialization. List? echoNullableNonNullEnumList(List? enumList); /// Returns the passed list, to test serialization and deserialization. - List? echoNullableNonNullClassList( - List? classList, - ); + List? echoNullableNonNullClassList(List? classList); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableMap(Map? map); /// Returns the passed map, to test serialization and deserialization. - Map? echoNullableStringMap( - Map? stringMap, - ); + Map? echoNullableStringMap(Map? stringMap); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableIntMap(Map? intMap); @@ -4705,14 +4255,10 @@ abstract class FlutterIntegrationCoreApi { Map? echoNullableEnumMap(Map? enumMap); /// Returns the passed map, to test serialization and deserialization. - Map? echoNullableClassMap( - Map? classMap, - ); + Map? echoNullableClassMap(Map? classMap); /// Returns the passed map, to test serialization and deserialization. - Map? echoNullableNonNullStringMap( - Map? stringMap, - ); + Map? echoNullableNonNullStringMap(Map? stringMap); /// Returns the passed map, to test serialization and deserialization. Map? echoNullableNonNullIntMap(Map? intMap); @@ -4721,9 +4267,7 @@ abstract class FlutterIntegrationCoreApi { Map? echoNullableNonNullEnumMap(Map? enumMap); /// Returns the passed map, to test serialization and deserialization. - Map? echoNullableNonNullClassMap( - Map? classMap, - ); + Map? echoNullableNonNullClassMap(Map? classMap); /// Returns the passed enum to test serialization and deserialization. AnEnum? echoNullableEnum(AnEnum? anEnum); @@ -4743,9 +4287,7 @@ abstract class FlutterIntegrationCoreApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop$messageChannelSuffix', @@ -4853,9 +4395,7 @@ abstract class FlutterIntegrationCoreApi { final List args = message! as List; final AllNullableTypes? arg_everything = args[0] as AllNullableTypes?; try { - final AllNullableTypes? output = api.echoAllNullableTypes( - arg_everything, - ); + final AllNullableTypes? output = api.echoAllNullableTypes(arg_everything); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5118,8 +4658,7 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List arg_enumList = (args[0]! as List) - .cast(); + final List arg_enumList = (args[0]! as List).cast(); try { final List output = api.echoEnumList(arg_enumList); return wrapResponse(result: output); @@ -5144,12 +4683,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List arg_classList = - (args[0]! as List).cast(); + final List arg_classList = (args[0]! as List) + .cast(); try { - final List output = api.echoClassList( - arg_classList, - ); + final List output = api.echoClassList(arg_classList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5172,8 +4709,7 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List arg_enumList = (args[0]! as List) - .cast(); + final List arg_enumList = (args[0]! as List).cast(); try { final List output = api.echoNonNullEnumList(arg_enumList); return wrapResponse(result: output); @@ -5198,12 +4734,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List arg_classList = - (args[0]! as List).cast(); + final List arg_classList = (args[0]! as List) + .cast(); try { - final List output = api.echoNonNullClassList( - arg_classList, - ); + final List output = api.echoNonNullClassList(arg_classList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5226,8 +4760,7 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_map = - args[0]! as Map; + final Map arg_map = args[0]! as Map; try { final Map output = api.echoMap(arg_map); return wrapResponse(result: output); @@ -5252,12 +4785,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_stringMap = - (args[0]! as Map).cast(); + final Map arg_stringMap = (args[0]! as Map) + .cast(); try { - final Map output = api.echoStringMap( - arg_stringMap, - ); + final Map output = api.echoStringMap(arg_stringMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5280,8 +4811,7 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_intMap = (args[0]! as Map) - .cast(); + final Map arg_intMap = (args[0]! as Map).cast(); try { final Map output = api.echoIntMap(arg_intMap); return wrapResponse(result: output); @@ -5306,8 +4836,8 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_enumMap = - (args[0]! as Map).cast(); + final Map arg_enumMap = (args[0]! as Map) + .cast(); try { final Map output = api.echoEnumMap(arg_enumMap); return wrapResponse(result: output); @@ -5332,13 +4862,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_classMap = - (args[0]! as Map) - .cast(); + final Map arg_classMap = (args[0]! as Map) + .cast(); try { - final Map output = api.echoClassMap( - arg_classMap, - ); + final Map output = api.echoClassMap(arg_classMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5361,12 +4888,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_stringMap = - (args[0]! as Map).cast(); + final Map arg_stringMap = (args[0]! as Map) + .cast(); try { - final Map output = api.echoNonNullStringMap( - arg_stringMap, - ); + final Map output = api.echoNonNullStringMap(arg_stringMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5389,8 +4914,7 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_intMap = (args[0]! as Map) - .cast(); + final Map arg_intMap = (args[0]! as Map).cast(); try { final Map output = api.echoNonNullIntMap(arg_intMap); return wrapResponse(result: output); @@ -5415,12 +4939,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_enumMap = - (args[0]! as Map).cast(); + final Map arg_enumMap = (args[0]! as Map) + .cast(); try { - final Map output = api.echoNonNullEnumMap( - arg_enumMap, - ); + final Map output = api.echoNonNullEnumMap(arg_enumMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5443,12 +4965,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_classMap = - (args[0]! as Map).cast(); + final Map arg_classMap = (args[0]! as Map) + .cast(); try { - final Map output = api.echoNonNullClassMap( - arg_classMap, - ); + final Map output = api.echoNonNullClassMap(arg_classMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5671,12 +5191,9 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List? arg_enumList = (args[0] as List?) - ?.cast(); + final List? arg_enumList = (args[0] as List?)?.cast(); try { - final List? output = api.echoNullableEnumList( - arg_enumList, - ); + final List? output = api.echoNullableEnumList(arg_enumList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5699,12 +5216,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List? arg_classList = - (args[0] as List?)?.cast(); + final List? arg_classList = (args[0] as List?) + ?.cast(); try { - final List? output = api.echoNullableClassList( - arg_classList, - ); + final List? output = api.echoNullableClassList(arg_classList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5727,12 +5242,9 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List? arg_enumList = (args[0] as List?) - ?.cast(); + final List? arg_enumList = (args[0] as List?)?.cast(); try { - final List? output = api.echoNullableNonNullEnumList( - arg_enumList, - ); + final List? output = api.echoNullableNonNullEnumList(arg_enumList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5755,11 +5267,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List? arg_classList = - (args[0] as List?)?.cast(); + final List? arg_classList = (args[0] as List?) + ?.cast(); try { - final List? output = api - .echoNullableNonNullClassList(arg_classList); + final List? output = api.echoNullableNonNullClassList(arg_classList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5782,8 +5293,7 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_map = - args[0] as Map?; + final Map? arg_map = args[0] as Map?; try { final Map? output = api.echoNullableMap(arg_map); return wrapResponse(result: output); @@ -5808,12 +5318,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_stringMap = - (args[0] as Map?)?.cast(); + final Map? arg_stringMap = (args[0] as Map?) + ?.cast(); try { - final Map? output = api.echoNullableStringMap( - arg_stringMap, - ); + final Map? output = api.echoNullableStringMap(arg_stringMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5836,8 +5344,8 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_intMap = - (args[0] as Map?)?.cast(); + final Map? arg_intMap = (args[0] as Map?) + ?.cast(); try { final Map? output = api.echoNullableIntMap(arg_intMap); return wrapResponse(result: output); @@ -5862,12 +5370,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_enumMap = - (args[0] as Map?)?.cast(); + final Map? arg_enumMap = (args[0] as Map?) + ?.cast(); try { - final Map? output = api.echoNullableEnumMap( - arg_enumMap, - ); + final Map? output = api.echoNullableEnumMap(arg_enumMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5890,12 +5396,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_classMap = - (args[0] as Map?) - ?.cast(); + final Map? arg_classMap = (args[0] as Map?) + ?.cast(); try { - final Map? output = api - .echoNullableClassMap(arg_classMap); + final Map? output = api.echoNullableClassMap(arg_classMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5918,11 +5422,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_stringMap = - (args[0] as Map?)?.cast(); + final Map? arg_stringMap = (args[0] as Map?) + ?.cast(); try { - final Map? output = api - .echoNullableNonNullStringMap(arg_stringMap); + final Map? output = api.echoNullableNonNullStringMap(arg_stringMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5945,12 +5448,9 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_intMap = (args[0] as Map?) - ?.cast(); + final Map? arg_intMap = (args[0] as Map?)?.cast(); try { - final Map? output = api.echoNullableNonNullIntMap( - arg_intMap, - ); + final Map? output = api.echoNullableNonNullIntMap(arg_intMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5973,12 +5473,10 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_enumMap = - (args[0] as Map?)?.cast(); + final Map? arg_enumMap = (args[0] as Map?) + ?.cast(); try { - final Map? output = api.echoNullableNonNullEnumMap( - arg_enumMap, - ); + final Map? output = api.echoNullableNonNullEnumMap(arg_enumMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6001,12 +5499,12 @@ abstract class FlutterIntegrationCoreApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map? arg_classMap = - (args[0] as Map?) - ?.cast(); + final Map? arg_classMap = (args[0] as Map?) + ?.cast(); try { - final Map? output = api - .echoNullableNonNullClassMap(arg_classMap); + final Map? output = api.echoNullableNonNullClassMap( + arg_classMap, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6056,9 +5554,7 @@ abstract class FlutterIntegrationCoreApi { final List args = message! as List; final AnotherEnum? arg_anotherEnum = args[0] as AnotherEnum?; try { - final AnotherEnum? output = api.echoAnotherNullableEnum( - arg_anotherEnum, - ); + final AnotherEnum? output = api.echoAnotherNullableEnum(arg_anotherEnum); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6126,13 +5622,11 @@ class HostTrivialApi { /// Constructor for [HostTrivialApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - HostTrivialApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + HostTrivialApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -6150,11 +5644,7 @@ class HostTrivialApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } } @@ -6163,13 +5653,11 @@ class HostSmallApi { /// Constructor for [HostSmallApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - HostSmallApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + HostSmallApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -6184,9 +5672,7 @@ class HostSmallApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -6208,11 +5694,7 @@ class HostSmallApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } } @@ -6229,9 +5711,7 @@ abstract class FlutterSmallApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList$messageChannelSuffix', diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart index 202b98268626..9cf0c40d99ee 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -64,9 +60,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -204,13 +198,11 @@ class EnumApi2Host { /// Constructor for [EnumApi2Host]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - EnumApi2Host({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + EnumApi2Host({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -226,9 +218,7 @@ class EnumApi2Host { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [data], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([data]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -252,9 +242,7 @@ abstract class EnumApi2Flutter { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo$messageChannelSuffix', diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart index 4734c4b0cdb0..5f8750388f88 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart @@ -25,9 +25,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -243,19 +241,14 @@ class EventAllNullableTypes { objectList: result[19] as List?, listList: (result[20] as List?)?.cast?>(), mapList: (result[21] as List?)?.cast?>(), - recursiveClassList: (result[22] as List?) - ?.cast(), + recursiveClassList: (result[22] as List?)?.cast(), map: result[23] as Map?, - stringMap: (result[24] as Map?) - ?.cast(), + stringMap: (result[24] as Map?)?.cast(), intMap: (result[25] as Map?)?.cast(), - enumMap: (result[26] as Map?) - ?.cast(), + enumMap: (result[26] as Map?)?.cast(), objectMap: result[27] as Map?, - listMap: (result[28] as Map?) - ?.cast?>(), - mapMap: (result[29] as Map?) - ?.cast?>(), + listMap: (result[28] as Map?)?.cast?>(), + mapMap: (result[29] as Map?)?.cast?>(), recursiveClassMap: (result[30] as Map?) ?.cast(), ); @@ -628,9 +621,7 @@ class _PigeonCodec extends StandardMessageCodec { } } -const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( - _PigeonCodec(), -); +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec(_PigeonCodec()); Stream streamInts({String instanceName = ''}) { if (instanceName.isNotEmpty) { @@ -666,9 +657,7 @@ Stream streamConsistentNumbers({String instanceName = ''}) { 'dev.flutter.pigeon.pigeon_integration_tests.EventChannelMethods.streamConsistentNumbers$instanceName', pigeonMethodCodec, ); - return streamConsistentNumbersChannel.receiveBroadcastStream().map(( - dynamic event, - ) { + return streamConsistentNumbersChannel.receiveBroadcastStream().map((dynamic event) { return event as int; }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart index 3ef61fed39b0..1bc0680e378b 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart @@ -34,9 +34,7 @@ class _PigeonCodec extends StandardMessageCodec { } } -const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( - _PigeonCodec(), -); +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec(_PigeonCodec()); Stream streamIntsAgain({String instanceName = ''}) { if (instanceName.isNotEmpty) { diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart index 3fe4b498ee2d..549ef4a503ed 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart @@ -50,9 +50,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -153,10 +151,7 @@ class FlutterSearchReply { static FlutterSearchReply decode(Object result) { result as List; - return FlutterSearchReply( - result: result[0] as String?, - error: result[1] as String?, - ); + return FlutterSearchReply(result: result[0] as String?, error: result[1] as String?); } @override @@ -310,9 +305,7 @@ class Api { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [request], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([request]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -331,9 +324,7 @@ class Api { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [request], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([request]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -352,9 +343,7 @@ class Api { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [requests], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([requests]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -373,9 +362,7 @@ class Api { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart index 9013d5973196..f83c1f684d96 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -64,9 +60,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -312,13 +306,11 @@ class MessageApi { /// Constructor for [MessageApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MessageApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MessageApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -339,11 +331,7 @@ class MessageApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// This comment is to test method documentation comments. @@ -355,9 +343,7 @@ class MessageApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [request], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([request]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -374,13 +360,11 @@ class MessageNestedApi { /// Constructor for [MessageNestedApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MessageNestedApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MessageNestedApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -398,9 +382,7 @@ class MessageNestedApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [nested], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([nested]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -424,9 +406,7 @@ abstract class MessageFlutterSearchApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search$messageChannelSuffix', @@ -438,8 +418,7 @@ abstract class MessageFlutterSearchApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final MessageSearchRequest arg_request = - args[0]! as MessageSearchRequest; + final MessageSearchRequest arg_request = args[0]! as MessageSearchRequest; try { final MessageSearchReply output = api.search(arg_request); return wrapResponse(result: output); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart index 7b2ebf15d84e..cfabf89d7f40 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -77,13 +73,11 @@ class MultipleArityHostApi { /// Constructor for [MultipleArityHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - MultipleArityHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + MultipleArityHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -98,9 +92,7 @@ class MultipleArityHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [x, y], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([x, y]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -122,9 +114,7 @@ abstract class MultipleArityFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract$messageChannelSuffix', diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart index 476917a52f9f..2f4a0fd15662 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -64,9 +60,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -138,8 +132,7 @@ class NonNullFieldSearchRequest { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! NonNullFieldSearchRequest || - other.runtimeType != runtimeType) { + if (other is! NonNullFieldSearchRequest || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -170,10 +163,7 @@ class ExtraData { static ExtraData decode(Object result) { result as List; - return ExtraData( - detailA: result[0]! as String, - detailB: result[1]! as String, - ); + return ExtraData(detailA: result[0]! as String, detailB: result[1]! as String); } @override @@ -185,8 +175,7 @@ class ExtraData { if (identical(this, other)) { return true; } - return _deepEquals(detailA, other.detailA) && - _deepEquals(detailB, other.detailB); + return _deepEquals(detailA, other.detailA) && _deepEquals(detailB, other.detailB); } @override @@ -299,22 +288,18 @@ class NonNullFieldHostApi { /// Constructor for [NonNullFieldHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NonNullFieldHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + NonNullFieldHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); final String pigeonVar_messageChannelSuffix; - Future search( - NonNullFieldSearchRequest nested, - ) async { + Future search(NonNullFieldSearchRequest nested) async { final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldHostApi.search$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -322,9 +307,7 @@ class NonNullFieldHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [nested], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([nested]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -346,9 +329,7 @@ abstract class NonNullFieldFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search$messageChannelSuffix', @@ -360,8 +341,7 @@ abstract class NonNullFieldFlutterApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final NonNullFieldSearchRequest arg_request = - args[0]! as NonNullFieldSearchRequest; + final NonNullFieldSearchRequest arg_request = args[0]! as NonNullFieldSearchRequest; try { final NonNullFieldSearchReply output = api.search(arg_request); return wrapResponse(result: output); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart index e861dbaa62ed..38affeab9b9c 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -64,9 +60,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -134,10 +128,7 @@ class NullFieldsSearchRequest { static NullFieldsSearchRequest decode(Object result) { result as List; - return NullFieldsSearchRequest( - query: result[0] as String?, - identifier: result[1]! as int, - ); + return NullFieldsSearchRequest(query: result[0] as String?, identifier: result[1]! as int); } @override @@ -149,8 +140,7 @@ class NullFieldsSearchRequest { if (identical(this, other)) { return true; } - return _deepEquals(query, other.query) && - _deepEquals(identifier, other.identifier); + return _deepEquals(query, other.query) && _deepEquals(identifier, other.identifier); } @override @@ -159,13 +149,7 @@ class NullFieldsSearchRequest { } class NullFieldsSearchReply { - NullFieldsSearchReply({ - this.result, - this.error, - this.indices, - this.request, - this.type, - }); + NullFieldsSearchReply({this.result, this.error, this.indices, this.request, this.type}); String? result; @@ -258,13 +242,11 @@ class NullFieldsHostApi { /// Constructor for [NullFieldsHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullFieldsHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + NullFieldsHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -279,9 +261,7 @@ class NullFieldsHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [nested], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([nested]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -303,9 +283,7 @@ abstract class NullFieldsFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search$messageChannelSuffix', @@ -317,8 +295,7 @@ abstract class NullFieldsFlutterApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final NullFieldsSearchRequest arg_request = - args[0]! as NullFieldsSearchRequest; + final NullFieldsSearchRequest arg_request = args[0]! as NullFieldsSearchRequest; try { final NullFieldsSearchReply output = api.search(arg_request); return wrapResponse(result: output); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart index 2c9c03a02426..9aa24097d442 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -77,13 +73,11 @@ class NullableReturnHostApi { /// Constructor for [NullableReturnHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullableReturnHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + NullableReturnHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -120,9 +114,7 @@ abstract class NullableReturnFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit$messageChannelSuffix', @@ -153,13 +145,11 @@ class NullableArgHostApi { /// Constructor for [NullableArgHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullableArgHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + NullableArgHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -174,9 +164,7 @@ class NullableArgHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [x], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([x]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -198,9 +186,7 @@ abstract class NullableArgFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit$messageChannelSuffix', @@ -276,9 +262,7 @@ abstract class NullableCollectionReturnFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit$messageChannelSuffix', @@ -309,13 +293,11 @@ class NullableCollectionArgHostApi { /// Constructor for [NullableCollectionArgHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - NullableCollectionArgHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + NullableCollectionArgHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -330,9 +312,7 @@ class NullableCollectionArgHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [x], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([x]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -354,9 +334,7 @@ abstract class NullableCollectionArgFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit$messageChannelSuffix', @@ -368,8 +346,7 @@ abstract class NullableCollectionArgFlutterApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List? arg_x = (args[0] as List?) - ?.cast(); + final List? arg_x = (args[0] as List?)?.cast(); try { final List output = api.doit(arg_x); return wrapResponse(result: output); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart index b86058696a44..c90f8204eb9a 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart @@ -38,11 +38,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -77,13 +73,11 @@ class PrimitiveHostApi { /// Constructor for [PrimitiveHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - PrimitiveHostApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + PrimitiveHostApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -98,9 +92,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -119,9 +111,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -140,9 +130,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -161,9 +149,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -182,9 +168,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -203,9 +187,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -224,9 +206,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -245,9 +225,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -266,9 +244,7 @@ class PrimitiveHostApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [value], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([value]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -276,8 +252,7 @@ class PrimitiveHostApi { pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } } @@ -307,9 +282,7 @@ abstract class PrimitiveFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt$messageChannelSuffix', @@ -421,8 +394,7 @@ abstract class PrimitiveFlutterApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_value = - args[0]! as Map; + final Map arg_value = args[0]! as Map; try { final Map output = api.aMap(arg_value); return wrapResponse(result: output); @@ -497,8 +469,7 @@ abstract class PrimitiveFlutterApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final List arg_value = (args[0]! as List) - .cast(); + final List arg_value = (args[0]! as List).cast(); try { final List output = api.aBoolList(arg_value); return wrapResponse(result: output); @@ -523,8 +494,8 @@ abstract class PrimitiveFlutterApi { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final Map arg_value = - (args[0]! as Map).cast(); + final Map arg_value = (args[0]! as Map) + .cast(); try { final Map output = api.aStringIntMap(arg_value); return wrapResponse(result: output); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart index a25fca2e2880..9dd9bde1b354 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart @@ -40,11 +40,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -74,23 +70,13 @@ class PigeonOverrides { required Map aMap, required ProxyApiTestEnum anEnum, required ProxyApiSuperClass aProxyApi, - required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) - flutterEchoBool, - required int Function(ProxyApiTestClass pigeon_instance, int anInt) - flutterEchoInt, - required double Function(ProxyApiTestClass pigeon_instance, double aDouble) - flutterEchoDouble, - required String Function(ProxyApiTestClass pigeon_instance, String aString) - flutterEchoString, - required Uint8List Function( - ProxyApiTestClass pigeon_instance, - Uint8List aList, - ) + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoString, + required Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList) flutterEchoUint8List, - required List Function( - ProxyApiTestClass pigeon_instance, - List aList, - ) + required List Function(ProxyApiTestClass pigeon_instance, List aList) flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, @@ -107,20 +93,14 @@ class PigeonOverrides { Map aMap, ) flutterEchoProxyApiMap, - required ProxyApiTestEnum Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum anEnum, - ) + required ProxyApiTestEnum Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum) flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, ) flutterEchoProxyApi, - required Future Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) + required Future Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoAsyncString, required bool boolParam, required int intParam, @@ -144,35 +124,19 @@ class PigeonOverrides { void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? - flutterEchoNullableBool, - int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? - flutterEchoNullableInt, - double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? - flutterEchoNullableDouble, - String? Function(ProxyApiTestClass pigeon_instance, String? aString)? - flutterEchoNullableString, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? flutterEchoNullableString, Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? flutterEchoNullableUint8List, - List? Function( - ProxyApiTestClass pigeon_instance, - List? aList, - )? + List? Function(ProxyApiTestClass pigeon_instance, List? aList)? flutterEchoNullableList, - Map? Function( - ProxyApiTestClass pigeon_instance, - Map? aMap, - )? + Map? Function(ProxyApiTestClass pigeon_instance, Map? aMap)? flutterEchoNullableMap, - ProxyApiTestEnum? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum? anEnum, - )? + ProxyApiTestEnum? Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum, - ProxyApiSuperClass? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiSuperClass? aProxyApi, - )? + ProxyApiSuperClass? Function(ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, bool? nullableBoolParam, @@ -198,23 +162,13 @@ class PigeonOverrides { required Map aMap, required ProxyApiTestEnum anEnum, required ProxyApiSuperClass aProxyApi, - required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) - flutterEchoBool, - required int Function(ProxyApiTestClass pigeon_instance, int anInt) - flutterEchoInt, - required double Function(ProxyApiTestClass pigeon_instance, double aDouble) - flutterEchoDouble, - required String Function(ProxyApiTestClass pigeon_instance, String aString) - flutterEchoString, - required Uint8List Function( - ProxyApiTestClass pigeon_instance, - Uint8List aList, - ) + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoString, + required Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList) flutterEchoUint8List, - required List Function( - ProxyApiTestClass pigeon_instance, - List aList, - ) + required List Function(ProxyApiTestClass pigeon_instance, List aList) flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, @@ -231,20 +185,14 @@ class PigeonOverrides { Map aMap, ) flutterEchoProxyApiMap, - required ProxyApiTestEnum Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum anEnum, - ) + required ProxyApiTestEnum Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum) flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, ) flutterEchoProxyApi, - required Future Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) + required Future Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoAsyncString, bool? aNullableBool, int? aNullableInt, @@ -259,35 +207,19 @@ class PigeonOverrides { void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? - flutterEchoNullableBool, - int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? - flutterEchoNullableInt, - double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? - flutterEchoNullableDouble, - String? Function(ProxyApiTestClass pigeon_instance, String? aString)? - flutterEchoNullableString, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? flutterEchoNullableString, Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? flutterEchoNullableUint8List, - List? Function( - ProxyApiTestClass pigeon_instance, - List? aList, - )? + List? Function(ProxyApiTestClass pigeon_instance, List? aList)? flutterEchoNullableList, - Map? Function( - ProxyApiTestClass pigeon_instance, - Map? aMap, - )? + Map? Function(ProxyApiTestClass pigeon_instance, Map? aMap)? flutterEchoNullableMap, - ProxyApiTestEnum? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum? anEnum, - )? + ProxyApiTestEnum? Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum, - ProxyApiSuperClass? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiSuperClass? aProxyApi, - )? + ProxyApiSuperClass? Function(ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, })? @@ -335,8 +267,7 @@ abstract class PigeonInternalProxyApiBaseClass { PigeonInternalProxyApiBaseClass({ this.pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - }) : pigeon_instanceManager = - pigeon_instanceManager ?? PigeonInstanceManager.instance; + }) : pigeon_instanceManager = pigeon_instanceManager ?? PigeonInstanceManager.instance; /// Sends and receives binary data across the Flutter platform barrier. /// @@ -406,8 +337,8 @@ class PigeonInstanceManager { // by calling instanceManager.getIdentifier() inside of `==` while this was a // HashMap). final Expando _identifiers = Expando(); - final Map> - _weakInstances = >{}; + final Map> _weakInstances = + >{}; final Map _strongInstances = {}; late final Finalizer _finalizer; @@ -422,8 +353,7 @@ class PigeonInstanceManager { return PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); } WidgetsFlutterBinding.ensureInitialized(); - final _PigeonInternalInstanceManagerApi api = - _PigeonInternalInstanceManagerApi(); + final _PigeonInternalInstanceManagerApi api = _PigeonInternalInstanceManagerApi(); // Clears the native `PigeonInstanceManager` on the initial use of the Dart one. api.clear(); final PigeonInstanceManager instanceManager = PigeonInstanceManager( @@ -431,21 +361,11 @@ class PigeonInstanceManager { api.removeStrongReference(identifier); }, ); - _PigeonInternalInstanceManagerApi.setUpMessageHandlers( - instanceManager: instanceManager, - ); - ProxyApiTestClass.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ProxyApiSuperClass.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ProxyApiInterface.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); - ClassWithApiRequirement.pigeon_setUpMessageHandlers( - pigeon_instanceManager: instanceManager, - ); + _PigeonInternalInstanceManagerApi.setUpMessageHandlers(instanceManager: instanceManager); + ProxyApiTestClass.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ProxyApiSuperClass.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ProxyApiInterface.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + ClassWithApiRequirement.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); return instanceManager; } @@ -462,9 +382,7 @@ class PigeonInstanceManager { final int identifier = _nextUniqueIdentifier(); _identifiers[instance] = identifier; - _weakInstances[identifier] = WeakReference( - instance, - ); + _weakInstances[identifier] = WeakReference(instance); _finalizer.attach(instance, identifier, detach: instance); final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); @@ -525,21 +443,15 @@ class PigeonInstanceManager { /// /// This method also expects the host `InstanceManager` to have a strong /// reference to the instance the identifier is associated with. - T? getInstanceWithWeakReference( - int identifier, - ) { - final PigeonInternalProxyApiBaseClass? weakInstance = - _weakInstances[identifier]?.target; + T? getInstanceWithWeakReference(int identifier) { + final PigeonInternalProxyApiBaseClass? weakInstance = _weakInstances[identifier]?.target; if (weakInstance == null) { - final PigeonInternalProxyApiBaseClass? strongInstance = - _strongInstances[identifier]; + final PigeonInternalProxyApiBaseClass? strongInstance = _strongInstances[identifier]; if (strongInstance != null) { - final PigeonInternalProxyApiBaseClass copy = strongInstance - .pigeon_copy(); + final PigeonInternalProxyApiBaseClass copy = strongInstance.pigeon_copy(); _identifiers[copy] = identifier; - _weakInstances[identifier] = - WeakReference(copy); + _weakInstances[identifier] = WeakReference(copy); _finalizer.attach(copy, identifier, detach: copy); return copy as T; } @@ -561,10 +473,7 @@ class PigeonInstanceManager { /// /// Throws assertion error if the instance or its identifier has already been /// added. - void addHostCreatedInstance( - PigeonInternalProxyApiBaseClass instance, - int identifier, - ) { + void addHostCreatedInstance(PigeonInternalProxyApiBaseClass instance, int identifier) { assert(!containsIdentifier(identifier)); assert(getIdentifier(instance) == null); assert(identifier >= 0); @@ -575,8 +484,7 @@ class PigeonInstanceManager { /// Whether this manager contains the given [identifier]. bool containsIdentifier(int identifier) { - return _weakInstances.containsKey(identifier) || - _strongInstances.containsKey(identifier); + return _weakInstances.containsKey(identifier) || _strongInstances.containsKey(identifier); } int _nextUniqueIdentifier() { @@ -617,9 +525,7 @@ class _PigeonInternalInstanceManagerApi { final List args = message! as List; final int arg_identifier = args[0]! as int; try { - (instanceManager ?? PigeonInstanceManager.instance).remove( - arg_identifier, - ); + (instanceManager ?? PigeonInstanceManager.instance).remove(arg_identifier); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -641,16 +547,10 @@ class _PigeonInternalInstanceManagerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [identifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([identifier]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Clear the native `PigeonInstanceManager`. @@ -667,11 +567,7 @@ class _PigeonInternalInstanceManagerApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } } @@ -692,9 +588,7 @@ class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: - return instanceManager.getInstanceWithWeakReference( - readValue(buffer)! as int, - ); + return instanceManager.getInstanceWithWeakReference(readValue(buffer)! as int); default: return super.readValueOfType(type, buffer); } @@ -732,8 +626,7 @@ class _PigeonCodec extends StandardMessageCodec { /// The core ProxyApi test class that each supported host language must /// implement in platform_tests integration tests. -class ProxyApiTestClass extends ProxyApiSuperClass - implements ProxyApiInterface { +class ProxyApiTestClass extends ProxyApiSuperClass implements ProxyApiInterface { factory ProxyApiTestClass({ BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, @@ -759,23 +652,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) - flutterEchoBool, - required int Function(ProxyApiTestClass pigeon_instance, int anInt) - flutterEchoInt, - required double Function(ProxyApiTestClass pigeon_instance, double aDouble) - flutterEchoDouble, - required String Function(ProxyApiTestClass pigeon_instance, String aString) - flutterEchoString, - required Uint8List Function( - ProxyApiTestClass pigeon_instance, - Uint8List aList, - ) + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoString, + required Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList) flutterEchoUint8List, - required List Function( - ProxyApiTestClass pigeon_instance, - List aList, - ) + required List Function(ProxyApiTestClass pigeon_instance, List aList) flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, @@ -792,51 +675,29 @@ class ProxyApiTestClass extends ProxyApiSuperClass Map aMap, ) flutterEchoProxyApiMap, - required ProxyApiTestEnum Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum anEnum, - ) + required ProxyApiTestEnum Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum) flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, ) flutterEchoProxyApi, - bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? - flutterEchoNullableBool, - int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? - flutterEchoNullableInt, - double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? - flutterEchoNullableDouble, - String? Function(ProxyApiTestClass pigeon_instance, String? aString)? - flutterEchoNullableString, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? flutterEchoNullableString, Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? flutterEchoNullableUint8List, - List? Function( - ProxyApiTestClass pigeon_instance, - List? aList, - )? + List? Function(ProxyApiTestClass pigeon_instance, List? aList)? flutterEchoNullableList, - Map? Function( - ProxyApiTestClass pigeon_instance, - Map? aMap, - )? + Map? Function(ProxyApiTestClass pigeon_instance, Map? aMap)? flutterEchoNullableMap, - ProxyApiTestEnum? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum? anEnum, - )? + ProxyApiTestEnum? Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum, - ProxyApiSuperClass? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiSuperClass? aProxyApi, - )? + ProxyApiSuperClass? Function(ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, - required Future Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) + required Future Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoAsyncString, required bool boolParam, required int intParam, @@ -1058,10 +919,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass ProxyApiTestEnum? nullableEnumParam, ProxyApiSuperClass? nullableProxyApiParam, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_defaultConstructor'; @@ -1070,54 +929,49 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - aBool, - anInt, - aDouble, - aString, - aUint8List, - aList, - aMap, - anEnum, - aProxyApi, - aNullableBool, - aNullableInt, - aNullableDouble, - aNullableString, - aNullableUint8List, - aNullableList, - aNullableMap, - aNullableEnum, - aNullableProxyApi, - boolParam, - intParam, - doubleParam, - stringParam, - aUint8ListParam, - listParam, - mapParam, - enumParam, - proxyApiParam, - nullableBoolParam, - nullableIntParam, - nullableDoubleParam, - nullableStringParam, - nullableUint8ListParam, - nullableListParam, - nullableMapParam, - nullableEnumParam, - nullableProxyApiParam, - ]); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + aBool, + anInt, + aDouble, + aString, + aUint8List, + aList, + aMap, + anEnum, + aProxyApi, + aNullableBool, + aNullableInt, + aNullableDouble, + aNullableString, + aNullableUint8List, + aNullableList, + aNullableMap, + aNullableEnum, + aNullableProxyApi, + boolParam, + intParam, + doubleParam, + stringParam, + aUint8ListParam, + listParam, + mapParam, + enumParam, + proxyApiParam, + nullableBoolParam, + nullableIntParam, + nullableDoubleParam, + nullableStringParam, + nullableUint8ListParam, + nullableListParam, + nullableMapParam, + nullableEnumParam, + nullableProxyApiParam, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); }(); } @@ -1146,23 +1000,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) - flutterEchoBool, - required int Function(ProxyApiTestClass pigeon_instance, int anInt) - flutterEchoInt, - required double Function(ProxyApiTestClass pigeon_instance, double aDouble) - flutterEchoDouble, - required String Function(ProxyApiTestClass pigeon_instance, String aString) - flutterEchoString, - required Uint8List Function( - ProxyApiTestClass pigeon_instance, - Uint8List aList, - ) + required bool Function(ProxyApiTestClass pigeon_instance, bool aBool) flutterEchoBool, + required int Function(ProxyApiTestClass pigeon_instance, int anInt) flutterEchoInt, + required double Function(ProxyApiTestClass pigeon_instance, double aDouble) flutterEchoDouble, + required String Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoString, + required Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList) flutterEchoUint8List, - required List Function( - ProxyApiTestClass pigeon_instance, - List aList, - ) + required List Function(ProxyApiTestClass pigeon_instance, List aList) flutterEchoList, required List Function( ProxyApiTestClass pigeon_instance, @@ -1179,51 +1023,29 @@ class ProxyApiTestClass extends ProxyApiSuperClass Map aMap, ) flutterEchoProxyApiMap, - required ProxyApiTestEnum Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum anEnum, - ) + required ProxyApiTestEnum Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum) flutterEchoEnum, required ProxyApiSuperClass Function( ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi, ) flutterEchoProxyApi, - bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? - flutterEchoNullableBool, - int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? - flutterEchoNullableInt, - double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? - flutterEchoNullableDouble, - String? Function(ProxyApiTestClass pigeon_instance, String? aString)? - flutterEchoNullableString, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? flutterEchoNullableString, Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? flutterEchoNullableUint8List, - List? Function( - ProxyApiTestClass pigeon_instance, - List? aList, - )? + List? Function(ProxyApiTestClass pigeon_instance, List? aList)? flutterEchoNullableList, - Map? Function( - ProxyApiTestClass pigeon_instance, - Map? aMap, - )? + Map? Function(ProxyApiTestClass pigeon_instance, Map? aMap)? flutterEchoNullableMap, - ProxyApiTestEnum? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum? anEnum, - )? + ProxyApiTestEnum? Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum, - ProxyApiSuperClass? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiSuperClass? aProxyApi, - )? + ProxyApiSuperClass? Function(ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, - required Future Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) + required Future Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoAsyncString, }) { if (PigeonOverrides.proxyApiTestClass_namedConstructor != null) { @@ -1373,10 +1195,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass this.flutterNoopAsync, required this.flutterEchoAsyncString, }) : super.pigeon_detached() { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.namedConstructor'; @@ -1385,36 +1205,31 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel - .send([ - pigeonVar_instanceIdentifier, - aBool, - anInt, - aDouble, - aString, - aUint8List, - aList, - aMap, - anEnum, - aProxyApi, - aNullableBool, - aNullableInt, - aNullableDouble, - aNullableString, - aNullableUint8List, - aNullableList, - aNullableMap, - aNullableEnum, - aNullableProxyApi, - ]); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + aBool, + anInt, + aDouble, + aString, + aUint8List, + aList, + aMap, + anEnum, + aProxyApi, + aNullableBool, + aNullableInt, + aNullableDouble, + aNullableString, + aNullableUint8List, + aNullableList, + aNullableMap, + aNullableEnum, + aNullableProxyApi, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); }(); } @@ -1472,10 +1287,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass required this.flutterEchoAsyncString, }) : super.pigeon_detached(); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecProxyApiTestClass = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecProxyApiTestClass = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); final bool aBool; @@ -1575,8 +1388,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final void Function(ProxyApiTestClass pigeon_instance)? - flutterThrowErrorFromVoid; + final void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid; /// Returns the passed boolean, to test serialization and deserialization. /// @@ -1597,8 +1409,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final bool Function(ProxyApiTestClass pigeon_instance, bool aBool) - flutterEchoBool; + final bool Function(ProxyApiTestClass pigeon_instance, bool aBool) flutterEchoBool; /// Returns the passed int, to test serialization and deserialization. /// @@ -1619,8 +1430,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final int Function(ProxyApiTestClass pigeon_instance, int anInt) - flutterEchoInt; + final int Function(ProxyApiTestClass pigeon_instance, int anInt) flutterEchoInt; /// Returns the passed double, to test serialization and deserialization. /// @@ -1641,8 +1451,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final double Function(ProxyApiTestClass pigeon_instance, double aDouble) - flutterEchoDouble; + final double Function(ProxyApiTestClass pigeon_instance, double aDouble) flutterEchoDouble; /// Returns the passed string, to test serialization and deserialization. /// @@ -1663,8 +1472,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final String Function(ProxyApiTestClass pigeon_instance, String aString) - flutterEchoString; + final String Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoString; /// Returns the passed byte list, to test serialization and deserialization. /// @@ -1685,8 +1493,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList) - flutterEchoUint8List; + final Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList) flutterEchoUint8List; /// Returns the passed list, to test serialization and deserialization. /// @@ -1707,10 +1514,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final List Function( - ProxyApiTestClass pigeon_instance, - List aList, - ) + final List Function(ProxyApiTestClass pigeon_instance, List aList) flutterEchoList; /// Returns the passed list with ProxyApis, to test serialization and @@ -1809,10 +1613,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final ProxyApiTestEnum Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum anEnum, - ) + final ProxyApiTestEnum Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum) flutterEchoEnum; /// Returns the passed ProxyApi to test serialization and deserialization. @@ -1834,10 +1635,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final ProxyApiSuperClass Function( - ProxyApiTestClass pigeon_instance, - ProxyApiSuperClass aProxyApi, - ) + final ProxyApiSuperClass Function(ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi) flutterEchoProxyApi; /// Returns the passed boolean, to test serialization and deserialization. @@ -1859,8 +1657,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? - flutterEchoNullableBool; + final bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? flutterEchoNullableBool; /// Returns the passed int, to test serialization and deserialization. /// @@ -1881,8 +1678,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? - flutterEchoNullableInt; + final int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? flutterEchoNullableInt; /// Returns the passed double, to test serialization and deserialization. /// @@ -1947,10 +1743,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final Uint8List? Function( - ProxyApiTestClass pigeon_instance, - Uint8List? aList, - )? + final Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? flutterEchoNullableUint8List; /// Returns the passed list, to test serialization and deserialization. @@ -1972,10 +1765,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final List? Function( - ProxyApiTestClass pigeon_instance, - List? aList, - )? + final List? Function(ProxyApiTestClass pigeon_instance, List? aList)? flutterEchoNullableList; /// Returns the passed map, to test serialization and deserialization. @@ -2022,10 +1812,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final ProxyApiTestEnum? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum? anEnum, - )? + final ProxyApiTestEnum? Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum; /// Returns the passed ProxyApi to test serialization and deserialization. @@ -2073,8 +1860,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final Future Function(ProxyApiTestClass pigeon_instance)? - flutterNoopAsync; + final Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync; /// Returns the passed in generic Object asynchronously. /// @@ -2095,10 +1881,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to /// release the associated Native object manually. - final Future Function( - ProxyApiTestClass pigeon_instance, - String aString, - ) + final Future Function(ProxyApiTestClass pigeon_instance, String aString) flutterEchoAsyncString; @override @@ -2106,12 +1889,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass late final ProxyApiSuperClass attachedField = pigeonVar_attachedField(); - static final ProxyApiSuperClass _staticAttachedField = - pigeonVar_staticAttachedField(); + static final ProxyApiSuperClass _staticAttachedField = pigeonVar_staticAttachedField(); static ProxyApiSuperClass get staticAttachedField => - PigeonOverrides.proxyApiTestClass_staticAttachedField ?? - _staticAttachedField; + PigeonOverrides.proxyApiTestClass_staticAttachedField ?? _staticAttachedField; static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -2120,83 +1901,49 @@ class ProxyApiTestClass extends ProxyApiSuperClass void Function(ProxyApiTestClass pigeon_instance)? flutterNoop, Object? Function(ProxyApiTestClass pigeon_instance)? flutterThrowError, void Function(ProxyApiTestClass pigeon_instance)? flutterThrowErrorFromVoid, - bool Function(ProxyApiTestClass pigeon_instance, bool aBool)? - flutterEchoBool, + bool Function(ProxyApiTestClass pigeon_instance, bool aBool)? flutterEchoBool, int Function(ProxyApiTestClass pigeon_instance, int anInt)? flutterEchoInt, - double Function(ProxyApiTestClass pigeon_instance, double aDouble)? - flutterEchoDouble, - String Function(ProxyApiTestClass pigeon_instance, String aString)? - flutterEchoString, - Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList)? - flutterEchoUint8List, - List Function( - ProxyApiTestClass pigeon_instance, - List aList, - )? - flutterEchoList, + double Function(ProxyApiTestClass pigeon_instance, double aDouble)? flutterEchoDouble, + String Function(ProxyApiTestClass pigeon_instance, String aString)? flutterEchoString, + Uint8List Function(ProxyApiTestClass pigeon_instance, Uint8List aList)? flutterEchoUint8List, + List Function(ProxyApiTestClass pigeon_instance, List aList)? flutterEchoList, List Function( ProxyApiTestClass pigeon_instance, List aList, )? flutterEchoProxyApiList, - Map Function( - ProxyApiTestClass pigeon_instance, - Map aMap, - )? + Map Function(ProxyApiTestClass pigeon_instance, Map aMap)? flutterEchoMap, Map Function( ProxyApiTestClass pigeon_instance, Map aMap, )? flutterEchoProxyApiMap, - ProxyApiTestEnum Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum anEnum, - )? + ProxyApiTestEnum Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum anEnum)? flutterEchoEnum, - ProxyApiSuperClass Function( - ProxyApiTestClass pigeon_instance, - ProxyApiSuperClass aProxyApi, - )? + ProxyApiSuperClass Function(ProxyApiTestClass pigeon_instance, ProxyApiSuperClass aProxyApi)? flutterEchoProxyApi, - bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? - flutterEchoNullableBool, - int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? - flutterEchoNullableInt, - double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? - flutterEchoNullableDouble, - String? Function(ProxyApiTestClass pigeon_instance, String? aString)? - flutterEchoNullableString, + bool? Function(ProxyApiTestClass pigeon_instance, bool? aBool)? flutterEchoNullableBool, + int? Function(ProxyApiTestClass pigeon_instance, int? anInt)? flutterEchoNullableInt, + double? Function(ProxyApiTestClass pigeon_instance, double? aDouble)? flutterEchoNullableDouble, + String? Function(ProxyApiTestClass pigeon_instance, String? aString)? flutterEchoNullableString, Uint8List? Function(ProxyApiTestClass pigeon_instance, Uint8List? aList)? flutterEchoNullableUint8List, - List? Function( - ProxyApiTestClass pigeon_instance, - List? aList, - )? + List? Function(ProxyApiTestClass pigeon_instance, List? aList)? flutterEchoNullableList, - Map? Function( - ProxyApiTestClass pigeon_instance, - Map? aMap, - )? + Map? Function(ProxyApiTestClass pigeon_instance, Map? aMap)? flutterEchoNullableMap, - ProxyApiTestEnum? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiTestEnum? anEnum, - )? + ProxyApiTestEnum? Function(ProxyApiTestClass pigeon_instance, ProxyApiTestEnum? anEnum)? flutterEchoNullableEnum, - ProxyApiSuperClass? Function( - ProxyApiTestClass pigeon_instance, - ProxyApiSuperClass? aProxyApi, - )? + ProxyApiSuperClass? Function(ProxyApiTestClass pigeon_instance, ProxyApiSuperClass? aProxyApi)? flutterEchoNullableProxyApi, Future Function(ProxyApiTestClass pigeon_instance)? flutterNoopAsync, Future Function(ProxyApiTestClass pigeon_instance, String aString)? flutterEchoAsyncString, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -2209,12 +1956,9 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; try { - (flutterNoop ?? arg_pigeon_instance.flutterNoop)?.call( - arg_pigeon_instance, - ); + (flutterNoop ?? arg_pigeon_instance.flutterNoop)?.call(arg_pigeon_instance); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2238,12 +1982,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; try { - final Object? output = - (flutterThrowError ?? arg_pigeon_instance.flutterThrowError) - ?.call(arg_pigeon_instance); + final Object? output = (flutterThrowError ?? arg_pigeon_instance.flutterThrowError) + ?.call(arg_pigeon_instance); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2267,12 +2009,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; try { - (flutterThrowErrorFromVoid ?? - arg_pigeon_instance.flutterThrowErrorFromVoid) - ?.call(arg_pigeon_instance); + (flutterThrowErrorFromVoid ?? arg_pigeon_instance.flutterThrowErrorFromVoid)?.call( + arg_pigeon_instance, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2296,15 +2037,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final bool arg_aBool = args[1]! as bool; try { - final bool output = - (flutterEchoBool ?? arg_pigeon_instance.flutterEchoBool).call( - arg_pigeon_instance, - arg_aBool, - ); + final bool output = (flutterEchoBool ?? arg_pigeon_instance.flutterEchoBool).call( + arg_pigeon_instance, + arg_aBool, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2328,15 +2067,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final int arg_anInt = args[1]! as int; try { - final int output = - (flutterEchoInt ?? arg_pigeon_instance.flutterEchoInt).call( - arg_pigeon_instance, - arg_anInt, - ); + final int output = (flutterEchoInt ?? arg_pigeon_instance.flutterEchoInt).call( + arg_pigeon_instance, + arg_anInt, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2360,13 +2097,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final double arg_aDouble = args[1]! as double; try { - final double output = - (flutterEchoDouble ?? arg_pigeon_instance.flutterEchoDouble) - .call(arg_pigeon_instance, arg_aDouble); + final double output = (flutterEchoDouble ?? arg_pigeon_instance.flutterEchoDouble).call( + arg_pigeon_instance, + arg_aDouble, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2390,13 +2127,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final String arg_aString = args[1]! as String; try { - final String output = - (flutterEchoString ?? arg_pigeon_instance.flutterEchoString) - .call(arg_pigeon_instance, arg_aString); + final String output = (flutterEchoString ?? arg_pigeon_instance.flutterEchoString).call( + arg_pigeon_instance, + arg_aString, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2420,14 +2157,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final Uint8List arg_aList = args[1]! as Uint8List; try { final Uint8List output = - (flutterEchoUint8List ?? - arg_pigeon_instance.flutterEchoUint8List) - .call(arg_pigeon_instance, arg_aList); + (flutterEchoUint8List ?? arg_pigeon_instance.flutterEchoUint8List).call( + arg_pigeon_instance, + arg_aList, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2451,15 +2188,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final List arg_aList = args[1]! as List; try { - final List output = - (flutterEchoList ?? arg_pigeon_instance.flutterEchoList).call( - arg_pigeon_instance, - arg_aList, - ); + final List output = (flutterEchoList ?? arg_pigeon_instance.flutterEchoList) + .call(arg_pigeon_instance, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2483,15 +2216,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final List arg_aList = (args[1]! as List) .cast(); try { final List output = - (flutterEchoProxyApiList ?? - arg_pigeon_instance.flutterEchoProxyApiList) - .call(arg_pigeon_instance, arg_aList); + (flutterEchoProxyApiList ?? arg_pigeon_instance.flutterEchoProxyApiList).call( + arg_pigeon_instance, + arg_aList, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2515,10 +2248,9 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; - final Map arg_aMap = - (args[1]! as Map).cast(); + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; + final Map arg_aMap = (args[1]! as Map) + .cast(); try { final Map output = (flutterEchoMap ?? arg_pigeon_instance.flutterEchoMap).call( @@ -2548,16 +2280,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; - final Map arg_aMap = - (args[1]! as Map) - .cast(); + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; + final Map arg_aMap = (args[1]! as Map) + .cast(); try { final Map output = - (flutterEchoProxyApiMap ?? - arg_pigeon_instance.flutterEchoProxyApiMap) - .call(arg_pigeon_instance, arg_aMap); + (flutterEchoProxyApiMap ?? arg_pigeon_instance.flutterEchoProxyApiMap).call( + arg_pigeon_instance, + arg_aMap, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2581,15 +2312,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final ProxyApiTestEnum arg_anEnum = args[1]! as ProxyApiTestEnum; try { - final ProxyApiTestEnum output = - (flutterEchoEnum ?? arg_pigeon_instance.flutterEchoEnum).call( - arg_pigeon_instance, - arg_anEnum, - ); + final ProxyApiTestEnum output = (flutterEchoEnum ?? arg_pigeon_instance.flutterEchoEnum) + .call(arg_pigeon_instance, arg_anEnum); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2613,14 +2340,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; - final ProxyApiSuperClass arg_aProxyApi = - args[1]! as ProxyApiSuperClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; + final ProxyApiSuperClass arg_aProxyApi = args[1]! as ProxyApiSuperClass; try { final ProxyApiSuperClass output = - (flutterEchoProxyApi ?? arg_pigeon_instance.flutterEchoProxyApi) - .call(arg_pigeon_instance, arg_aProxyApi); + (flutterEchoProxyApi ?? arg_pigeon_instance.flutterEchoProxyApi).call( + arg_pigeon_instance, + arg_aProxyApi, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2644,14 +2371,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final bool? arg_aBool = args[1] as bool?; try { final bool? output = - (flutterEchoNullableBool ?? - arg_pigeon_instance.flutterEchoNullableBool) - ?.call(arg_pigeon_instance, arg_aBool); + (flutterEchoNullableBool ?? arg_pigeon_instance.flutterEchoNullableBool)?.call( + arg_pigeon_instance, + arg_aBool, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2675,14 +2402,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final int? arg_anInt = args[1] as int?; try { final int? output = - (flutterEchoNullableInt ?? - arg_pigeon_instance.flutterEchoNullableInt) - ?.call(arg_pigeon_instance, arg_anInt); + (flutterEchoNullableInt ?? arg_pigeon_instance.flutterEchoNullableInt)?.call( + arg_pigeon_instance, + arg_anInt, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2706,14 +2433,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final double? arg_aDouble = args[1] as double?; try { final double? output = - (flutterEchoNullableDouble ?? - arg_pigeon_instance.flutterEchoNullableDouble) - ?.call(arg_pigeon_instance, arg_aDouble); + (flutterEchoNullableDouble ?? arg_pigeon_instance.flutterEchoNullableDouble)?.call( + arg_pigeon_instance, + arg_aDouble, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2737,14 +2464,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final String? arg_aString = args[1] as String?; try { final String? output = - (flutterEchoNullableString ?? - arg_pigeon_instance.flutterEchoNullableString) - ?.call(arg_pigeon_instance, arg_aString); + (flutterEchoNullableString ?? arg_pigeon_instance.flutterEchoNullableString)?.call( + arg_pigeon_instance, + arg_aString, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2768,13 +2495,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final Uint8List? arg_aList = args[1] as Uint8List?; try { final Uint8List? output = - (flutterEchoNullableUint8List ?? - arg_pigeon_instance.flutterEchoNullableUint8List) + (flutterEchoNullableUint8List ?? arg_pigeon_instance.flutterEchoNullableUint8List) ?.call(arg_pigeon_instance, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -2799,14 +2524,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final List? arg_aList = args[1] as List?; try { final List? output = - (flutterEchoNullableList ?? - arg_pigeon_instance.flutterEchoNullableList) - ?.call(arg_pigeon_instance, arg_aList); + (flutterEchoNullableList ?? arg_pigeon_instance.flutterEchoNullableList)?.call( + arg_pigeon_instance, + arg_aList, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2830,15 +2555,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; - final Map? arg_aMap = - (args[1] as Map?)?.cast(); + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; + final Map? arg_aMap = (args[1] as Map?) + ?.cast(); try { final Map? output = - (flutterEchoNullableMap ?? - arg_pigeon_instance.flutterEchoNullableMap) - ?.call(arg_pigeon_instance, arg_aMap); + (flutterEchoNullableMap ?? arg_pigeon_instance.flutterEchoNullableMap)?.call( + arg_pigeon_instance, + arg_aMap, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2862,14 +2587,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final ProxyApiTestEnum? arg_anEnum = args[1] as ProxyApiTestEnum?; try { final ProxyApiTestEnum? output = - (flutterEchoNullableEnum ?? - arg_pigeon_instance.flutterEchoNullableEnum) - ?.call(arg_pigeon_instance, arg_anEnum); + (flutterEchoNullableEnum ?? arg_pigeon_instance.flutterEchoNullableEnum)?.call( + arg_pigeon_instance, + arg_anEnum, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2893,14 +2618,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; - final ProxyApiSuperClass? arg_aProxyApi = - args[1] as ProxyApiSuperClass?; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; + final ProxyApiSuperClass? arg_aProxyApi = args[1] as ProxyApiSuperClass?; try { final ProxyApiSuperClass? output = - (flutterEchoNullableProxyApi ?? - arg_pigeon_instance.flutterEchoNullableProxyApi) + (flutterEchoNullableProxyApi ?? arg_pigeon_instance.flutterEchoNullableProxyApi) ?.call(arg_pigeon_instance, arg_aProxyApi); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -2925,11 +2647,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; try { - await (flutterNoopAsync ?? arg_pigeon_instance.flutterNoopAsync) - ?.call(arg_pigeon_instance); + await (flutterNoopAsync ?? arg_pigeon_instance.flutterNoopAsync)?.call( + arg_pigeon_instance, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2953,14 +2675,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiTestClass arg_pigeon_instance = - args[0]! as ProxyApiTestClass; + final ProxyApiTestClass arg_pigeon_instance = args[0]! as ProxyApiTestClass; final String arg_aString = args[1]! as String; try { final String output = - await (flutterEchoAsyncString ?? - arg_pigeon_instance.flutterEchoAsyncString) - .call(arg_pigeon_instance, arg_aString); + await (flutterEchoAsyncString ?? arg_pigeon_instance.flutterEchoAsyncString).call( + arg_pigeon_instance, + arg_aString, + ); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2975,16 +2697,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass } ProxyApiSuperClass pigeonVar_attachedField() { - final ProxyApiSuperClass pigeonVar_instance = - ProxyApiSuperClass.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final ProxyApiSuperClass pigeonVar_instance = ProxyApiSuperClass.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.attachedField'; @@ -2993,29 +2714,27 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); }(); return pigeonVar_instance; } static ProxyApiSuperClass pigeonVar_staticAttachedField() { - final ProxyApiSuperClass pigeonVar_instance = - ProxyApiSuperClass.pigeon_detached(); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final ProxyApiSuperClass pigeonVar_instance = ProxyApiSuperClass.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + PigeonInstanceManager.instance, + ); final BinaryMessenger pigeonVar_binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger; - final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance - .addDartCreatedInstance(pigeonVar_instance); + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance.addDartCreatedInstance( + pigeonVar_instance, + ); () async { const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAttachedField'; @@ -3024,16 +2743,12 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); }(); return pigeonVar_instance; } @@ -3041,8 +2756,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. Future noop() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noop'; @@ -3051,22 +2765,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Returns an error, to test error handling. Future throwError() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwError'; @@ -3075,9 +2782,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3090,8 +2795,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns an error from a void function, to test error handling. Future throwErrorFromVoid() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwErrorFromVoid'; @@ -3100,22 +2804,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Returns a Flutter error, to test error handling. Future throwFlutterError() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwFlutterError'; @@ -3124,9 +2821,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3139,8 +2834,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns passed in int. Future echoInt(int anInt) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoInt'; @@ -3149,9 +2843,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3164,8 +2856,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns passed in double. Future echoDouble(double aDouble) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoDouble'; @@ -3174,9 +2865,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3189,8 +2878,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in boolean. Future echoBool(bool aBool) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoBool'; @@ -3199,9 +2887,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3214,8 +2900,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in string. Future echoString(String aString) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoString'; @@ -3224,9 +2909,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3239,8 +2922,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in Uint8List. Future echoUint8List(Uint8List aUint8List) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoUint8List'; @@ -3249,9 +2931,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aUint8List, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3264,8 +2947,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in generic Object. Future echoObject(Object anObject) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoObject'; @@ -3274,9 +2956,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anObject]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3289,8 +2969,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list, to test serialization and deserialization. Future> echoList(List aList) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoList'; @@ -3299,9 +2978,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3314,11 +2991,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list with ProxyApis, to test serialization and /// deserialization. - Future> echoProxyApiList( - List aList, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future> echoProxyApiList(List aList) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiList'; @@ -3327,9 +3001,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3342,8 +3014,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed map, to test serialization and deserialization. Future> echoMap(Map aMap) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoMap'; @@ -3352,9 +3023,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3362,8 +3031,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map with ProxyApis, to test serialization and @@ -3371,8 +3039,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass Future> echoProxyApiMap( Map aMap, ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiMap'; @@ -3381,9 +3048,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3391,14 +3056,12 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed enum to test serialization and deserialization. Future echoEnum(ProxyApiTestEnum anEnum) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoEnum'; @@ -3407,9 +3070,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3422,8 +3083,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed ProxyApi to test serialization and deserialization. Future echoProxyApi(ProxyApiSuperClass aProxyApi) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApi'; @@ -3432,9 +3092,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aProxyApi], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aProxyApi]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3447,8 +3105,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns passed in int. Future echoNullableInt(int? aNullableInt) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableInt'; @@ -3457,9 +3114,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableInt, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3472,8 +3130,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns passed in double. Future echoNullableDouble(double? aNullableDouble) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableDouble'; @@ -3482,9 +3139,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableDouble, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3497,8 +3155,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in boolean. Future echoNullableBool(bool? aNullableBool) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableBool'; @@ -3507,9 +3164,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableBool, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3522,8 +3180,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in string. Future echoNullableString(String? aNullableString) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableString'; @@ -3532,9 +3189,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableString, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3546,11 +3204,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } /// Returns the passed in Uint8List. - Future echoNullableUint8List( - Uint8List? aNullableUint8List, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future echoNullableUint8List(Uint8List? aNullableUint8List) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableUint8List'; @@ -3559,9 +3214,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableUint8List, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3574,8 +3230,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in generic Object. Future echoNullableObject(Object? aNullableObject) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableObject'; @@ -3584,9 +3239,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableObject, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3599,8 +3255,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableList(List? aNullableList) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableList'; @@ -3609,9 +3264,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableList, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3623,11 +3279,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } /// Returns the passed map, to test serialization and deserialization. - Future?> echoNullableMap( - Map? aNullableMap, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future?> echoNullableMap(Map? aNullableMap) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableMap'; @@ -3636,9 +3289,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableMap, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3646,15 +3300,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } - Future echoNullableEnum( - ProxyApiTestEnum? aNullableEnum, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future echoNullableEnum(ProxyApiTestEnum? aNullableEnum) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableEnum'; @@ -3663,9 +3313,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableEnum, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3677,11 +3328,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } /// Returns the passed ProxyApi to test serialization and deserialization. - Future echoNullableProxyApi( - ProxyApiSuperClass? aNullableProxyApi, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future echoNullableProxyApi(ProxyApiSuperClass? aNullableProxyApi) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableProxyApi'; @@ -3690,9 +3338,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aNullableProxyApi], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aNullableProxyApi, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3706,8 +3355,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. Future noopAsync() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noopAsync'; @@ -3716,22 +3364,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Returns passed in int asynchronously. Future echoAsyncInt(int anInt) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncInt'; @@ -3740,9 +3381,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3755,8 +3394,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns passed in double asynchronously. Future echoAsyncDouble(double aDouble) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncDouble'; @@ -3765,9 +3403,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3780,8 +3416,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in boolean asynchronously. Future echoAsyncBool(bool aBool) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncBool'; @@ -3790,9 +3425,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3805,8 +3438,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed string asynchronously. Future echoAsyncString(String aString) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncString'; @@ -3815,9 +3447,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3830,8 +3460,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in Uint8List asynchronously. Future echoAsyncUint8List(Uint8List aUint8List) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncUint8List'; @@ -3840,9 +3469,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aUint8List, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3855,8 +3485,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in generic Object asynchronously. Future echoAsyncObject(Object anObject) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncObject'; @@ -3865,9 +3494,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anObject]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3880,8 +3507,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list, to test asynchronous serialization and deserialization. Future> echoAsyncList(List aList) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncList'; @@ -3890,9 +3516,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3905,8 +3529,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncMap(Map aMap) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncMap'; @@ -3915,9 +3538,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3925,14 +3546,12 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. Future echoAsyncEnum(ProxyApiTestEnum anEnum) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncEnum'; @@ -3941,9 +3560,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3956,8 +3573,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Responds with an error from an async function returning a value. Future throwAsyncError() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncError'; @@ -3966,9 +3582,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -3981,8 +3595,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Responds with an error from an async void function. Future throwAsyncErrorFromVoid() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncErrorFromVoid'; @@ -3991,22 +3604,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Responds with a Flutter error from an async function returning a value. Future throwAsyncFlutterError() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncFlutterError'; @@ -4015,9 +3621,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4030,8 +3634,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns passed in int asynchronously. Future echoAsyncNullableInt(int? anInt) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableInt'; @@ -4040,9 +3643,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4055,8 +3656,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns passed in double asynchronously. Future echoAsyncNullableDouble(double? aDouble) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableDouble'; @@ -4065,9 +3665,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4080,8 +3678,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in boolean asynchronously. Future echoAsyncNullableBool(bool? aBool) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableBool'; @@ -4090,9 +3687,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4105,8 +3700,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed string asynchronously. Future echoAsyncNullableString(String? aString) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableString'; @@ -4115,9 +3709,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4130,8 +3722,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in Uint8List asynchronously. Future echoAsyncNullableUint8List(Uint8List? aUint8List) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableUint8List'; @@ -4140,9 +3731,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aUint8List, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4155,8 +3747,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed in generic Object asynchronously. Future echoAsyncNullableObject(Object? anObject) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableObject'; @@ -4165,9 +3756,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anObject], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anObject]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4180,8 +3769,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass /// Returns the passed list, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableList(List? aList) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableList'; @@ -4190,9 +3778,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4204,11 +3790,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass } /// Returns the passed map, to test asynchronous serialization and deserialization. - Future?> echoAsyncNullableMap( - Map? aMap, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future?> echoAsyncNullableMap(Map? aMap) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableMap'; @@ -4217,9 +3800,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4227,16 +3808,12 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. - Future echoAsyncNullableEnum( - ProxyApiTestEnum? anEnum, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future echoAsyncNullableEnum(ProxyApiTestEnum? anEnum) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableEnum'; @@ -4245,9 +3822,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4265,10 +3840,9 @@ class ProxyApiTestClass extends ProxyApiSuperClass if (PigeonOverrides.proxyApiTestClass_staticNoop != null) { return PigeonOverrides.proxyApiTestClass_staticNoop!(); } - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticNoop'; @@ -4280,11 +3854,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } static Future echoStaticString( @@ -4295,10 +3865,9 @@ class ProxyApiTestClass extends ProxyApiSuperClass if (PigeonOverrides.proxyApiTestClass_echoStaticString != null) { return PigeonOverrides.proxyApiTestClass_echoStaticString!(aString); } - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoStaticString'; @@ -4307,9 +3876,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4327,10 +3894,9 @@ class ProxyApiTestClass extends ProxyApiSuperClass if (PigeonOverrides.proxyApiTestClass_staticAsyncNoop != null) { return PigeonOverrides.proxyApiTestClass_staticAsyncNoop!(); } - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAsyncNoop'; @@ -4342,16 +3908,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } Future callFlutterNoop() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoop'; @@ -4360,21 +3921,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } Future callFlutterThrowError() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowError'; @@ -4383,9 +3937,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4397,8 +3949,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterThrowErrorFromVoid() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowErrorFromVoid'; @@ -4407,21 +3958,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } Future callFlutterEchoBool(bool aBool) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoBool'; @@ -4430,9 +3974,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4444,8 +3986,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoInt(int anInt) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoInt'; @@ -4454,9 +3995,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4468,8 +4007,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoDouble(double aDouble) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoDouble'; @@ -4478,9 +4016,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4492,8 +4028,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoString(String aString) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoString'; @@ -4502,9 +4037,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4516,8 +4049,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoUint8List(Uint8List aUint8List) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoUint8List'; @@ -4526,9 +4058,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aUint8List, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4540,8 +4073,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future> callFlutterEchoList(List aList) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoList'; @@ -4550,9 +4082,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4566,8 +4096,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass Future> callFlutterEchoProxyApiList( List aList, ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiList'; @@ -4576,9 +4105,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4589,11 +4116,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass return (pigeonVar_replyValue! as List).cast(); } - Future> callFlutterEchoMap( - Map aMap, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future> callFlutterEchoMap(Map aMap) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoMap'; @@ -4602,9 +4126,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4612,15 +4134,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } Future> callFlutterEchoProxyApiMap( Map aMap, ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiMap'; @@ -4629,9 +4149,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4639,13 +4157,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: false, ); - return (pigeonVar_replyValue! as Map) - .cast(); + return (pigeonVar_replyValue! as Map).cast(); } Future callFlutterEchoEnum(ProxyApiTestEnum anEnum) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoEnum'; @@ -4654,9 +4170,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4667,11 +4181,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass return pigeonVar_replyValue! as ProxyApiTestEnum; } - Future callFlutterEchoProxyApi( - ProxyApiSuperClass aProxyApi, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future callFlutterEchoProxyApi(ProxyApiSuperClass aProxyApi) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApi'; @@ -4680,9 +4191,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aProxyApi], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aProxyApi]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4694,8 +4203,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoNullableBool(bool? aBool) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableBool'; @@ -4704,9 +4212,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aBool], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aBool]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4718,8 +4224,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoNullableInt(int? anInt) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableInt'; @@ -4728,9 +4233,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anInt], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anInt]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4742,8 +4245,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoNullableDouble(double? aDouble) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableDouble'; @@ -4752,9 +4254,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aDouble], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aDouble]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4766,8 +4266,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterEchoNullableString(String? aString) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableString'; @@ -4776,9 +4275,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4789,11 +4286,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass return pigeonVar_replyValue as String?; } - Future callFlutterEchoNullableUint8List( - Uint8List? aUint8List, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future callFlutterEchoNullableUint8List(Uint8List? aUint8List) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableUint8List'; @@ -4802,9 +4296,10 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aUint8List], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + this, + aUint8List, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4815,11 +4310,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass return pigeonVar_replyValue as Uint8List?; } - Future?> callFlutterEchoNullableList( - List? aList, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future?> callFlutterEchoNullableList(List? aList) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableList'; @@ -4828,9 +4320,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4841,11 +4331,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass return pigeonVar_replyValue as List?; } - Future?> callFlutterEchoNullableMap( - Map? aMap, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future?> callFlutterEchoNullableMap(Map? aMap) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableMap'; @@ -4854,9 +4341,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aMap], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aMap]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4864,15 +4349,11 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channelName, isNullValid: true, ); - return (pigeonVar_replyValue as Map?) - ?.cast(); + return (pigeonVar_replyValue as Map?)?.cast(); } - Future callFlutterEchoNullableEnum( - ProxyApiTestEnum? anEnum, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future callFlutterEchoNullableEnum(ProxyApiTestEnum? anEnum) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableEnum'; @@ -4881,9 +4362,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, anEnum], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, anEnum]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4894,11 +4373,8 @@ class ProxyApiTestClass extends ProxyApiSuperClass return pigeonVar_replyValue as ProxyApiTestEnum?; } - Future callFlutterEchoNullableProxyApi( - ProxyApiSuperClass? aProxyApi, - ) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + Future callFlutterEchoNullableProxyApi(ProxyApiSuperClass? aProxyApi) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableProxyApi'; @@ -4907,9 +4383,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aProxyApi], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aProxyApi]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -4921,8 +4395,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } Future callFlutterNoopAsync() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoopAsync'; @@ -4931,21 +4404,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } Future callFlutterEchoAsyncString(String aString) async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiTestClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoAsyncString'; @@ -4954,9 +4420,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this, aString], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this, aString]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -5036,14 +4500,9 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { } @protected - ProxyApiSuperClass.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiSuperClass; + ProxyApiSuperClass.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiSuperClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_defaultConstructor'; @@ -5052,17 +4511,13 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); }(); } @@ -5071,15 +4526,10 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { /// This should only be used by subclasses created by this library or to /// create copies for an [PigeonInstanceManager]. @protected - ProxyApiSuperClass.pigeon_detached({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }); + ProxyApiSuperClass.pigeon_detached({super.pigeon_binaryMessenger, super.pigeon_instanceManager}); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecProxyApiSuperClass = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecProxyApiSuperClass = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5087,10 +4537,9 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ProxyApiSuperClass Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5105,15 +4554,14 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { final List args = message! as List; final int arg_pigeon_instanceIdentifier = args[0]! as int; try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ProxyApiSuperClass.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ProxyApiSuperClass.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5128,8 +4576,7 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { } Future aSuperMethod() async { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _pigeonVar_codecProxyApiSuperClass; + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiSuperClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.aSuperMethod'; @@ -5138,16 +4585,10 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } @override @@ -5200,10 +4641,9 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { ProxyApiInterface Function()? pigeon_newInstance, void Function(ProxyApiInterface pigeon_instance)? anInterfaceMethod, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5218,15 +4658,14 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { final List args = message! as List; final int arg_pigeon_instanceIdentifier = args[0]! as int; try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ProxyApiInterface.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ProxyApiInterface.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5250,12 +4689,9 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { } else { pigeonVar_channel.setMessageHandler((Object? message) async { final List args = message! as List; - final ProxyApiInterface arg_pigeon_instance = - args[0]! as ProxyApiInterface; + final ProxyApiInterface arg_pigeon_instance = args[0]! as ProxyApiInterface; try { - (anInterfaceMethod ?? arg_pigeon_instance.anInterfaceMethod)?.call( - arg_pigeon_instance, - ); + (anInterfaceMethod ?? arg_pigeon_instance.anInterfaceMethod)?.call(arg_pigeon_instance); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5294,12 +4730,8 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { } @protected - ClassWithApiRequirement.pigeon_new({ - super.pigeon_binaryMessenger, - super.pigeon_instanceManager, - }) { - final int pigeonVar_instanceIdentifier = pigeon_instanceManager - .addDartCreatedInstance(this); + ClassWithApiRequirement.pigeon_new({super.pigeon_binaryMessenger, super.pigeon_instanceManager}) { + final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecClassWithApiRequirement; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; @@ -5310,17 +4742,13 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + ]); () async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); }(); } @@ -5334,10 +4762,8 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { super.pigeon_instanceManager, }); - late final _PigeonInternalProxyApiBaseCodec - _pigeonVar_codecClassWithApiRequirement = _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager, - ); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecClassWithApiRequirement = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, @@ -5345,10 +4771,9 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { PigeonInstanceManager? pigeon_instanceManager, ClassWithApiRequirement Function()? pigeon_newInstance, }) { - final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = - _PigeonInternalProxyApiBaseCodec( - pigeon_instanceManager ?? PigeonInstanceManager.instance, - ); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance, + ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { final pigeonVar_channel = BasicMessageChannel( @@ -5363,15 +4788,14 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { final List args = message! as List; final int arg_pigeon_instanceIdentifier = args[0]! as int; try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - ClassWithApiRequirement.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier, - ); + (pigeon_instanceManager ?? PigeonInstanceManager.instance).addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ClassWithApiRequirement.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5396,16 +4820,10 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([this]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } @override diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart index 2f24d9bb2e44..dd0312a3d753 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/test_types.dart @@ -39,12 +39,7 @@ final List> nonNullListList = >[ nonNullEnumList, ]; -final Map nonNullMap = { - 'a': 1, - 'b': 2.0, - 'c': 'three', - 'd': false, -}; +final Map nonNullMap = {'a': 1, 'b': 2.0, 'c': 'three', 'd': false}; final Map nonNullStringMap = { 'a': '1', @@ -55,12 +50,7 @@ final Map nonNullStringMap = { final Map nonNullIntMap = {0: 0, 1: 1, 2: 3, 4: -1}; -final Map nonNullDoubleMap = { - 0.0: 0, - 1.1: 2.0, - 3: 0.3, - -.4: -0.2, -}; +final Map nonNullDoubleMap = {0.0: 0, 1.1: 2.0, 3: 0.3, -.4: -0.2}; final Map nonNullBoolMap = {0: true, 1: false, 2: true}; @@ -100,13 +90,7 @@ final List> nonNullMapList = >[ final List list = ['Thing 1', 2, true, 3.14, null]; -final List stringList = [ - 'Thing 1', - '2', - 'true', - '3.14', - null, -]; +final List stringList = ['Thing 1', '2', 'true', '3.14', null]; final List intList = [1, 2, 3, 4, null]; @@ -160,12 +144,7 @@ final Map doubleMap = { 1111111111111111.11111111111111111111111111111111111111111111: null, }; -final Map boolMap = { - 0: true, - 1: false, - 2: true, - 3: null, -}; +final Map boolMap = {0: true, 1: false, 2: true, 3: null}; final Map enumMap = { AnEnum.one: AnEnum.one, @@ -236,15 +215,14 @@ final AllNullableTypesWithoutRecursion genericAllNullableTypesWithoutRecursion = mapMap: mapMap, ); -final List -allNullableTypesWithoutRecursionClassList = [ - genericAllNullableTypesWithoutRecursion, - AllNullableTypesWithoutRecursion(), - null, -]; +final List allNullableTypesWithoutRecursionClassList = + [ + genericAllNullableTypesWithoutRecursion, + AllNullableTypesWithoutRecursion(), + null, + ]; -final Map -allNullableTypesWithoutRecursionClassMap = +final Map allNullableTypesWithoutRecursionClassMap = { 0: genericAllNullableTypesWithoutRecursion, 1: AllNullableTypesWithoutRecursion(), @@ -285,10 +263,7 @@ final AllTypes genericAllTypes = AllTypes( final List allTypesClassList = [genericAllTypes, null]; -final Map allTypesClassMap = { - 0: genericAllTypes, - 1: null, -}; +final Map allTypesClassMap = {0: genericAllTypes, 1: null}; final AllNullableTypes genericAllNullableTypes = AllNullableTypes( aNullableBool: true, @@ -325,8 +300,10 @@ final List nonNullAllNullableTypesList = [ AllNullableTypes(), ]; -final Map nonNullAllNullableTypesMap = - {0: genericAllNullableTypes, 1: AllNullableTypes()}; +final Map nonNullAllNullableTypesMap = { + 0: genericAllNullableTypes, + 1: AllNullableTypes(), +}; final List allNullableTypesList = [ genericAllNullableTypes, @@ -334,12 +311,11 @@ final List allNullableTypesList = [ null, ]; -final Map allNullableTypesMap = - { - 0: genericAllNullableTypes, - 1: AllNullableTypes(), - 2: null, - }; +final Map allNullableTypesMap = { + 0: genericAllNullableTypes, + 1: AllNullableTypes(), + 2: null, +}; final AllNullableTypes recursiveAllNullableTypes = AllNullableTypes( aNullableBool: true, diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/equality_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/equality_test.dart index 2fb8d597a3fa..b69641fd0e52 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/equality_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/equality_test.dart @@ -14,17 +14,13 @@ void main() { final all1 = AllNullableTypes( aNullableDouble: double.nan, doubleList: list, - recursiveClassList: [ - AllNullableTypes(aNullableDouble: double.nan), - ], + recursiveClassList: [AllNullableTypes(aNullableDouble: double.nan)], map: map, ); final all2 = AllNullableTypes( aNullableDouble: double.nan, doubleList: list, - recursiveClassList: [ - AllNullableTypes(aNullableDouble: double.nan), - ], + recursiveClassList: [AllNullableTypes(aNullableDouble: double.nan)], map: map, ); @@ -81,21 +77,9 @@ void main() { final matchingMap = {...correctMap}; final differentKeyMap = {'a': 1, 'b': 2, 'd': 'three'}; final differentValueMap = {'a': 1, 'b': 2, 'c': 'five'}; - final correctListInMap = { - 'a': 1, - 'b': 2, - 'c': correctList, - }; - final matchingListInMap = { - 'a': 1, - 'b': 2, - 'c': matchingList, - }; - final differentListInMap = { - 'a': 1, - 'b': 2, - 'c': differentList, - }; + final correctListInMap = {'a': 1, 'b': 2, 'c': correctList}; + final matchingListInMap = {'a': 1, 'b': 2, 'c': matchingList}; + final differentListInMap = {'a': 1, 'b': 2, 'c': differentList}; final correctMapInList = ['a', 2, correctMap]; final matchingMapInList = ['a', 2, matchingMap]; final differentKeyMapInList = ['a', 2, differentKeyMap]; @@ -103,9 +87,7 @@ void main() { test('equality method correctly checks deep equality', () { final AllNullableTypes generic = genericAllNullableTypes; - final AllNullableTypes identical = AllNullableTypes.decode( - generic.encode(), - ); + final AllNullableTypes identical = AllNullableTypes.decode(generic.encode()); expect(identical, generic); }); @@ -115,50 +97,35 @@ void main() { expect(allNull == generic, false); }); - test( - 'equality method correctly identifies non-matching lists in classes', - () { - final withList = AllNullableTypes(list: correctList); - final withDifferentList = AllNullableTypes(list: differentList); - expect(withList == withDifferentList, false); - }, - ); + test('equality method correctly identifies non-matching lists in classes', () { + final withList = AllNullableTypes(list: correctList); + final withDifferentList = AllNullableTypes(list: differentList); + expect(withList == withDifferentList, false); + }); - test( - 'equality method correctly identifies matching -but unique- lists in classes', - () { - final withList = AllNullableTypes(list: correctList); - final withDifferentList = AllNullableTypes(list: matchingList); - expect(withList, withDifferentList); - }, - ); + test('equality method correctly identifies matching -but unique- lists in classes', () { + final withList = AllNullableTypes(list: correctList); + final withDifferentList = AllNullableTypes(list: matchingList); + expect(withList, withDifferentList); + }); - test( - 'equality method correctly identifies non-matching keys in maps in classes', - () { - final withMap = AllNullableTypes(map: correctMap); - final withDifferentMap = AllNullableTypes(map: differentKeyMap); - expect(withMap == withDifferentMap, false); - }, - ); + test('equality method correctly identifies non-matching keys in maps in classes', () { + final withMap = AllNullableTypes(map: correctMap); + final withDifferentMap = AllNullableTypes(map: differentKeyMap); + expect(withMap == withDifferentMap, false); + }); - test( - 'equality method correctly identifies non-matching values in maps in classes', - () { - final withMap = AllNullableTypes(map: correctMap); - final withDifferentMap = AllNullableTypes(map: differentValueMap); - expect(withMap == withDifferentMap, false); - }, - ); + test('equality method correctly identifies non-matching values in maps in classes', () { + final withMap = AllNullableTypes(map: correctMap); + final withDifferentMap = AllNullableTypes(map: differentValueMap); + expect(withMap == withDifferentMap, false); + }); - test( - 'equality method correctly identifies matching -but unique- maps in classes', - () { - final withMap = AllNullableTypes(map: correctMap); - final withDifferentMap = AllNullableTypes(map: matchingMap); - expect(withMap, withDifferentMap); - }, - ); + test('equality method correctly identifies matching -but unique- maps in classes', () { + final withMap = AllNullableTypes(map: correctMap); + final withDifferentMap = AllNullableTypes(map: matchingMap); + expect(withMap, withDifferentMap); + }); test('signed zero equality', () { final v1 = AllNullableTypes(aNullableDouble: 0.0); final v2 = AllNullableTypes(aNullableDouble: -0.0); @@ -184,16 +151,11 @@ void main() { expect(v1.hashCode, v2.hashCode); }); - test( - 'equality method correctly identifies non-matching lists nested in maps in classes', - () { - final withListInMap = AllNullableTypes(map: correctListInMap); - final withDifferentListInMap = AllNullableTypes( - map: differentListInMap, - ); - expect(withListInMap == withDifferentListInMap, false); - }, - ); + test('equality method correctly identifies non-matching lists nested in maps in classes', () { + final withListInMap = AllNullableTypes(map: correctListInMap); + final withDifferentListInMap = AllNullableTypes(map: differentListInMap); + expect(withListInMap == withDifferentListInMap, false); + }); test( 'equality method correctly identifies matching -but unique- lists nested in maps in classes', @@ -208,9 +170,7 @@ void main() { 'equality method correctly identifies non-matching keys in maps nested in lists in classes', () { final withMapInList = AllNullableTypes(list: correctMapInList); - final withDifferentMapInList = AllNullableTypes( - list: differentKeyMapInList, - ); + final withDifferentMapInList = AllNullableTypes(list: differentKeyMapInList); expect(withMapInList == withDifferentMapInList, false); }, ); @@ -219,9 +179,7 @@ void main() { 'equality method correctly identifies non-matching values in maps nested in lists in classes', () { final withMapInList = AllNullableTypes(list: correctMapInList); - final withDifferentMapInList = AllNullableTypes( - list: differentValueMapInList, - ); + final withDifferentMapInList = AllNullableTypes(list: differentValueMapInList); expect(withMapInList == withDifferentMapInList, false); }, ); @@ -230,9 +188,7 @@ void main() { 'equality method correctly identifies matching -but unique- maps nested in lists in classes', () { final withMapInList = AllNullableTypes(list: correctMapInList); - final withDifferentMapInList = AllNullableTypes( - list: matchingMapInList, - ); + final withDifferentMapInList = AllNullableTypes(list: matchingMapInList); expect(withMapInList, withDifferentMapInList); }, ); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart index e8046afc4545..86aefc4a0f29 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart @@ -45,9 +45,7 @@ void main() { final api = MessageNestedApi(); final mock = MockNested(); TestNestedApi.setUp(mock); - final MessageSearchReply reply = await api.search( - MessageNested()..request = null, - ); + final MessageSearchReply reply = await api.search(MessageNested()..request = null); expect(mock.didCall, true); expect(reply.result, null); }); @@ -56,9 +54,7 @@ void main() { final api = MessageApi(); final mock = Mock(); TestHostApi.setUp(mock); - final MessageSearchReply reply = await api.search( - MessageSearchRequest()..query = 'foo', - ); + final MessageSearchReply reply = await api.search(MessageSearchRequest()..query = 'foo'); expect(mock.log, ['search']); expect(reply.result, 'foo'); }); @@ -82,12 +78,10 @@ void main() { isEmpty, ); expect( - () async => - await const BasicMessageChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search', - StandardMessageCodec(), - ).send([null]) - as List?, + () async => await const BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search', + StandardMessageCodec(), + ).send([null]) as List?, throwsA(isA()), ); expect(mock.log, ['initialize']); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart index ed38f8f53e45..fe6eb21e1937 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart @@ -11,34 +11,24 @@ import 'package:shared_test_plugin_code/src/generated/proxy_api_tests.gen.dart'; void main() { group('InstanceManager', () { test('addHostCreatedInstance', () { - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.getIdentifier(object), 0); - expect( - instanceManager.getInstanceWithWeakReference(0), - isA(), - ); + expect(instanceManager.getInstanceWithWeakReference(0), isA()); }); test('addHostCreatedInstance prevents already used objects and ids', () { - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); - expect( - () => instanceManager.addHostCreatedInstance(object, 0), - throwsAssertionError, - ); + expect(() => instanceManager.addHostCreatedInstance(object, 0), throwsAssertionError); expect( () => instanceManager.addHostCreatedInstance( @@ -50,9 +40,7 @@ void main() { }); test('addFlutterCreatedInstance', () { - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final object = CopyableObject(pigeon_instanceManager: instanceManager); @@ -76,33 +64,24 @@ void main() { instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.removeWeakReference(object), 0); - expect( - instanceManager.getInstanceWithWeakReference(0), - isA(), - ); + expect(instanceManager.getInstanceWithWeakReference(0), isA()); expect(weakInstanceId, 0); }); test('removeWeakReference removes only weak reference', () { - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); expect(instanceManager.removeWeakReference(object), 0); - final CopyableObject copy = instanceManager.getInstanceWithWeakReference( - 0, - )!; + final CopyableObject copy = instanceManager.getInstanceWithWeakReference(0)!; expect(identical(object, copy), isFalse); }); test('remove', () { - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final object = CopyableObject(pigeon_instanceManager: instanceManager); @@ -113,9 +92,7 @@ void main() { }); test('remove throws AssertionError if weak reference still exists', () { - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final object = CopyableObject(pigeon_instanceManager: instanceManager); @@ -124,104 +101,83 @@ void main() { }); test('getInstance can add a new weak reference', () { - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final instanceManager = PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); instanceManager.removeWeakReference(object); - final CopyableObject newWeakCopy = instanceManager - .getInstanceWithWeakReference(0)!; + final CopyableObject newWeakCopy = instanceManager.getInstanceWithWeakReference(0)!; expect(identical(object, newWeakCopy), isFalse); }); - test( - 'addDartCreatedInstance should add finalizer to original object', - () async { - var weakReferencedRemovedCalled = false; - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) { - weakReferencedRemovedCalled = true; - }, - ); - - CopyableObject? object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + test('addDartCreatedInstance should add finalizer to original object', () async { + var weakReferencedRemovedCalled = false; + final instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) { + weakReferencedRemovedCalled = true; + }, + ); - instanceManager.addDartCreatedInstance(object); + CopyableObject? object = CopyableObject(pigeon_instanceManager: instanceManager); - object = null; - await forceGC(fullGcCycles: 2); + instanceManager.addDartCreatedInstance(object); - expect(weakReferencedRemovedCalled, isTrue); - }, - ); + object = null; + await forceGC(fullGcCycles: 2); - test( - 'addHostCreatedInstance should not add finalizer to original object', - () async { - var weakReferencedRemovedCalled = false; - final instanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) { - weakReferencedRemovedCalled = true; - }, - ); + expect(weakReferencedRemovedCalled, isTrue); + }); - CopyableObject? object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + test('addHostCreatedInstance should not add finalizer to original object', () async { + var weakReferencedRemovedCalled = false; + final instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) { + weakReferencedRemovedCalled = true; + }, + ); - instanceManager.addHostCreatedInstance(object, 0); + CopyableObject? object = CopyableObject(pigeon_instanceManager: instanceManager); - object = null; - await forceGC(fullGcCycles: 2); + instanceManager.addHostCreatedInstance(object, 0); - expect(weakReferencedRemovedCalled, isFalse); - }, - ); + object = null; + await forceGC(fullGcCycles: 2); - testWidgets( - 'instantiating default InstanceManager does not make a message call', - (WidgetTester tester) async { - var messageCallMade = false; - TestDefaultBinaryMessengerBinding - .instance - .defaultBinaryMessenger - .allMessagesHandler = (_, __, ___) { - messageCallMade = true; - return null; - }; - - // Initialize default InstanceManager - // ignore: unnecessary_statements - PigeonInstanceManager.instance; + expect(weakReferencedRemovedCalled, isFalse); + }); - expect(messageCallMade, isFalse); - }, - ); + testWidgets('instantiating default InstanceManager does not make a message call', ( + WidgetTester tester, + ) async { + var messageCallMade = false; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.allMessagesHandler = + (_, __, ___) { + messageCallMade = true; + return null; + }; + + // Initialize default InstanceManager + // ignore: unnecessary_statements + PigeonInstanceManager.instance; + + expect(messageCallMade, isFalse); + }); testWidgets( 'default InstanceManager does not make message call when weak reference is removed', (WidgetTester tester) async { var messageCallMade = false; - TestDefaultBinaryMessengerBinding - .instance - .defaultBinaryMessenger - .allMessagesHandler = (_, __, ___) { - messageCallMade = true; - return null; - }; - - final PigeonInstanceManager instanceManager = - PigeonInstanceManager.instance; - - final int identifier = instanceManager.addDartCreatedInstance( - CopyableObject(), - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.allMessagesHandler = + (_, __, ___) { + messageCallMade = true; + return null; + }; + + final PigeonInstanceManager instanceManager = PigeonInstanceManager.instance; + + final int identifier = instanceManager.addDartCreatedInstance(CopyableObject()); instanceManager.onWeakReferenceRemoved(identifier); expect(messageCallMade, isFalse); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart index 2209c6936a45..d6a1b94a0a50 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart @@ -20,14 +20,13 @@ void main() { any, ), ).thenAnswer((Invocation realInvocation) async { - final Object input = MultipleArityHostApi.pigeonChannelCodec - .decodeMessage(realInvocation.positionalArguments[1] as ByteData?)!; + final Object input = MultipleArityHostApi.pigeonChannelCodec.decodeMessage( + realInvocation.positionalArguments[1] as ByteData?, + )!; final args = input as List; final int x = (args[0] as int?)!; final int y = (args[1] as int?)!; - return MultipleArityHostApi.pigeonChannelCodec.encodeMessage([ - x - y, - ]); + return MultipleArityHostApi.pigeonChannelCodec.encodeMessage([x - y]); }); final api = MultipleArityHostApi(binaryMessenger: mockMessenger); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart index 09033590b636..b9d0441ce813 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart @@ -41,17 +41,13 @@ void main() { }); test('test request decode with values', () { - final NullFieldsSearchRequest request = NullFieldsSearchRequest.decode( - ['query', 1], - ); + final NullFieldsSearchRequest request = NullFieldsSearchRequest.decode(['query', 1]); expect(request.query, 'query'); }); test('test request decode with null', () { - final NullFieldsSearchRequest request = NullFieldsSearchRequest.decode( - [null, 1], - ); + final NullFieldsSearchRequest request = NullFieldsSearchRequest.decode([null, 1]); expect(request.query, isNull); }); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart index e50136696b62..8524311ff587 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart @@ -22,8 +22,7 @@ import 'test_util.dart'; NullableCollectionReturnFlutterApi, ]) void main() { - final TestWidgetsFlutterBinding binding = - TestWidgetsFlutterBinding.ensureInitialized(); + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); test('with values filled', () { final reply = FlutterSearchReply() @@ -53,10 +52,7 @@ void main() { completer.complete(Api.pigeonChannelCodec.encodeMessage([reply])); final Future sendResult = completer.future; when( - mockMessenger.send( - 'dev.flutter.pigeon.pigeon_integration_tests.Api.search', - any, - ), + mockMessenger.send('dev.flutter.pigeon.pigeon_integration_tests.Api.search', any), ).thenAnswer((Invocation realInvocation) => sendResult); final api = Api(binaryMessenger: mockMessenger); final FlutterSearchReply readReply = await api.search(request); @@ -66,8 +62,7 @@ void main() { test('send/receive list classes', () async { final request = FlutterSearchRequest()..query = 'hey'; - final requests = FlutterSearchRequests() - ..requests = [request]; + final requests = FlutterSearchRequests()..requests = [request]; final BinaryMessenger mockMessenger = MockBinaryMessenger(); echoOneArgument( mockMessenger, @@ -95,25 +90,17 @@ void main() { test('return null to nonnull', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); const channel = 'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt'; - when(mockMessenger.send(channel, any)).thenAnswer(( - Invocation realInvocation, - ) async { + when(mockMessenger.send(channel, any)).thenAnswer((Invocation realInvocation) async { return Api.pigeonChannelCodec.encodeMessage([null]); }); final api = Api(binaryMessenger: mockMessenger); - expect( - () async => api.anInt(1), - throwsA(const TypeMatcher()), - ); + expect(() async => api.anInt(1), throwsA(const TypeMatcher())); }); test('send null parameter', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const channel = - 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit'; - when(mockMessenger.send(channel, any)).thenAnswer(( - Invocation realInvocation, - ) async { + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit'; + when(mockMessenger.send(channel, any)).thenAnswer((Invocation realInvocation) async { return Api.pigeonChannelCodec.encodeMessage([123]); }); final api = NullableArgHostApi(binaryMessenger: mockMessenger); @@ -122,11 +109,8 @@ void main() { test('send null collection parameter', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const channel = - 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit'; - when(mockMessenger.send(channel, any)).thenAnswer(( - Invocation realInvocation, - ) async { + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit'; + when(mockMessenger.send(channel, any)).thenAnswer((Invocation realInvocation) async { return Api.pigeonChannelCodec.encodeMessage([ ['123'], ]); @@ -147,9 +131,7 @@ void main() { NullableArgFlutterApi.pigeonChannelCodec.encodeMessage([null]), (ByteData? data) { resultCompleter.complete( - (NullableArgFlutterApi.pigeonChannelCodec.decodeMessage(data)! - as List) - .first! + (NullableArgFlutterApi.pigeonChannelCodec.decodeMessage(data)! as List).first! as int, ); }, @@ -170,14 +152,10 @@ void main() { final resultCompleter = Completer>(); binding.defaultBinaryMessenger.handlePlatformMessage( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit', - NullableCollectionArgFlutterApi.pigeonChannelCodec.encodeMessage( - [null], - ), + NullableCollectionArgFlutterApi.pigeonChannelCodec.encodeMessage([null]), (ByteData? data) { resultCompleter.complete( - ((NullableCollectionArgFlutterApi.pigeonChannelCodec.decodeMessage( - data, - )! + ((NullableCollectionArgFlutterApi.pigeonChannelCodec.decodeMessage(data)! as List) .first! as List) @@ -194,14 +172,9 @@ void main() { test('receive null return', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const channel = - 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit'; - when(mockMessenger.send(channel, any)).thenAnswer(( - Invocation realInvocation, - ) async { - return NullableReturnHostApi.pigeonChannelCodec.encodeMessage([ - null, - ]); + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit'; + when(mockMessenger.send(channel, any)).thenAnswer((Invocation realInvocation) async { + return NullableReturnHostApi.pigeonChannelCodec.encodeMessage([null]); }); final api = NullableReturnHostApi(binaryMessenger: mockMessenger); expect(await api.doit(), null); @@ -211,12 +184,8 @@ void main() { final BinaryMessenger mockMessenger = MockBinaryMessenger(); const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnHostApi.doit'; - when(mockMessenger.send(channel, any)).thenAnswer(( - Invocation realInvocation, - ) async { - return NullableCollectionReturnHostApi.pigeonChannelCodec.encodeMessage( - [null], - ); + when(mockMessenger.send(channel, any)).thenAnswer((Invocation realInvocation) async { + return NullableCollectionReturnHostApi.pigeonChannelCodec.encodeMessage([null]); }); final api = NullableCollectionReturnHostApi(binaryMessenger: mockMessenger); expect(await api.doit(), null); @@ -255,9 +224,7 @@ void main() { unawaited( binding.defaultBinaryMessenger.handlePlatformMessage( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit', - NullableCollectionReturnFlutterApi.pigeonChannelCodec.encodeMessage( - [], - ), + NullableCollectionReturnFlutterApi.pigeonChannelCodec.encodeMessage([]), (ByteData? data) { resultCompleter.complete(null); }, diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.mocks.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.mocks.dart index ce80f9ddf9c7..faa9d267e482 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.mocks.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.mocks.dart @@ -11,8 +11,7 @@ import 'dart:ui' as _i5; import 'package:flutter/services.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:shared_test_plugin_code/src/generated/nullable_returns.gen.dart' - as _i6; +import 'package:shared_test_plugin_code/src/generated/nullable_returns.gen.dart' as _i6; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -83,8 +82,7 @@ class MockBinaryMessenger extends _i1.Mock implements _i2.BinaryMessenger { /// A class which mocks [NullableArgFlutterApi]. /// /// See the documentation for Mockito's code generation for more information. -class MockNullableArgFlutterApi extends _i1.Mock - implements _i6.NullableArgFlutterApi { +class MockNullableArgFlutterApi extends _i1.Mock implements _i6.NullableArgFlutterApi { MockNullableArgFlutterApi() { _i1.throwOnMissingStub(this); } @@ -102,8 +100,7 @@ class MockNullableArgFlutterApi extends _i1.Mock /// A class which mocks [NullableReturnFlutterApi]. /// /// See the documentation for Mockito's code generation for more information. -class MockNullableReturnFlutterApi extends _i1.Mock - implements _i6.NullableReturnFlutterApi { +class MockNullableReturnFlutterApi extends _i1.Mock implements _i6.NullableReturnFlutterApi { MockNullableReturnFlutterApi() { _i1.throwOnMissingStub(this); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart index dbfc6cd78a85..72c54ecee3f0 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart @@ -66,9 +66,7 @@ void main() { PrimitiveHostApi.pigeonChannelCodec, ); final api = PrimitiveHostApi(binaryMessenger: mockMessenger); - final Map result = await api.aStringIntMap({ - 'hello': 1, - }); + final Map result = await api.aStringIntMap({'hello': 1}); expect(result['hello'], 1); }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.mocks.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.mocks.dart index 28578ce52081..c3b0a80a6091 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.mocks.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.mocks.dart @@ -11,8 +11,7 @@ import 'dart:ui' as _i5; import 'package:flutter/services.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; -import 'package:shared_test_plugin_code/src/generated/primitive.gen.dart' - as _i6; +import 'package:shared_test_plugin_code/src/generated/primitive.gen.dart' as _i6; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -83,8 +82,7 @@ class MockBinaryMessenger extends _i1.Mock implements _i2.BinaryMessenger { /// A class which mocks [PrimitiveFlutterApi]. /// /// See the documentation for Mockito's code generation for more information. -class MockPrimitiveFlutterApi extends _i1.Mock - implements _i6.PrimitiveFlutterApi { +class MockPrimitiveFlutterApi extends _i1.Mock implements _i6.PrimitiveFlutterApi { MockPrimitiveFlutterApi() { _i1.throwOnMissingStub(this); } @@ -122,8 +120,7 @@ class MockPrimitiveFlutterApi extends _i1.Mock returnValue: 0.0, ) as double); @override - Map aMap(Map? value) => - (super.noSuchMethod( + Map aMap(Map? value) => (super.noSuchMethod( Invocation.method( #aMap, [value], @@ -155,8 +152,7 @@ class MockPrimitiveFlutterApi extends _i1.Mock returnValue: [], ) as List); @override - Map aStringIntMap(Map? value) => - (super.noSuchMethod( + Map aStringIntMap(Map? value) => (super.noSuchMethod( Invocation.method( #aStringIntMap, [value], diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart index f7d5ac0a20ea..c1b34638c29d 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart @@ -36,16 +36,14 @@ void main() { }); test('pigeon_reset sets constructor overrides to null', () { - PigeonOverrides.proxyApiSuperClass_new = () => - ProxyApiSuperClass.pigeon_detached(); + PigeonOverrides.proxyApiSuperClass_new = () => ProxyApiSuperClass.pigeon_detached(); PigeonOverrides.pigeon_reset(); expect(PigeonOverrides.proxyApiSuperClass_new, isNull); }); test('pigeon_reset sets attached field overrides to null', () { - PigeonOverrides.proxyApiTestClass_staticAttachedField = - ProxyApiSuperClass.pigeon_detached(); + PigeonOverrides.proxyApiTestClass_staticAttachedField = ProxyApiSuperClass.pigeon_detached(); PigeonOverrides.pigeon_reset(); expect(PigeonOverrides.proxyApiTestClass_staticAttachedField, isNull); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart index 443efc77823d..73f416f82e9d 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart @@ -77,9 +77,7 @@ abstract class TestHostApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize$messageChannelSuffix', @@ -87,27 +85,26 @@ abstract class TestHostApi { binaryMessenger: binaryMessenger, ); if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, null); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler( + pigeonVar_channel, + null, + ); } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, ( - Object? message, - ) async { - try { - api.initialize(); - return wrapResponse(empty: true); - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException( - code: 'error', - message: e.toString(), - ), - ); - } - }); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler( + pigeonVar_channel, + (Object? message) async { + try { + api.initialize(); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); + } + }, + ); } } { @@ -117,30 +114,28 @@ abstract class TestHostApi { binaryMessenger: binaryMessenger, ); if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, null); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler( + pigeonVar_channel, + null, + ); } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, ( - Object? message, - ) async { - final List args = message! as List; - final MessageSearchRequest arg_request = - args[0]! as MessageSearchRequest; - try { - final MessageSearchReply output = api.search(arg_request); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException( - code: 'error', - message: e.toString(), - ), - ); - } - }); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler( + pigeonVar_channel, + (Object? message) async { + final List args = message! as List; + final MessageSearchRequest arg_request = args[0]! as MessageSearchRequest; + try { + final MessageSearchReply output = api.search(arg_request); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); + } + }, + ); } } } @@ -162,9 +157,7 @@ abstract class TestNestedApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search$messageChannelSuffix', @@ -172,29 +165,28 @@ abstract class TestNestedApi { binaryMessenger: binaryMessenger, ); if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, null); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler( + pigeonVar_channel, + null, + ); } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(pigeonVar_channel, ( - Object? message, - ) async { - final List args = message! as List; - final MessageNested arg_nested = args[0]! as MessageNested; - try { - final MessageSearchReply output = api.search(arg_nested); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException( - code: 'error', - message: e.toString(), - ), - ); - } - }); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler( + pigeonVar_channel, + (Object? message) async { + final List args = message! as List; + final MessageNested arg_nested = args[0]! as MessageNested; + try { + final MessageSearchReply output = api.search(arg_nested); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString()), + ); + } + }, + ); } } } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart index accc779e392e..8baff8e32e29 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart @@ -5,17 +5,9 @@ import 'package:flutter/services.dart'; import 'package:mockito/mockito.dart'; -void echoOneArgument( - BinaryMessenger mockMessenger, - String channel, - MessageCodec codec, -) { - when(mockMessenger.send(channel, any)).thenAnswer(( - Invocation realInvocation, - ) async { - final Object input = codec.decodeMessage( - realInvocation.positionalArguments[1] as ByteData?, - )!; +void echoOneArgument(BinaryMessenger mockMessenger, String channel, MessageCodec codec) { + when(mockMessenger.send(channel, any)).thenAnswer((Invocation realInvocation) async { + final Object input = codec.decodeMessage(realInvocation.positionalArguments[1] as ByteData?)!; final args = input as List; return codec.encodeMessage([args[0]!]); }); diff --git a/packages/pigeon/test/ast_generator_test.dart b/packages/pigeon/test/ast_generator_test.dart index 98a74f8a25de..632eb1c799f8 100644 --- a/packages/pigeon/test/ast_generator_test.dart +++ b/packages/pigeon/test/ast_generator_test.dart @@ -17,11 +17,7 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); generateAst(root, sink); final code = sink.toString(); diff --git a/packages/pigeon/test/cpp_generator_test.dart b/packages/pigeon/test/cpp_generator_test.dart index 0c77bed2b1de..aec1b205c3d9 100644 --- a/packages/pigeon/test/cpp_generator_test.dart +++ b/packages/pigeon/test/cpp_generator_test.dart @@ -87,12 +87,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Input')); expect(code, contains('class Output')); @@ -110,12 +105,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('Input::Input()')); expect(code, contains('Output::Output')); @@ -208,12 +198,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // Method name and argument names should be adjusted. expect(code, contains(' DoSomething(const Input& some_input)')); @@ -240,12 +225,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('encodable_some_input')); expect(code, contains('Output::output_field()')); @@ -264,17 +244,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'someInput', ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -293,12 +267,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( @@ -308,9 +277,7 @@ void main() { contains(' public:'), contains(' const std::string& code() const { return code_; }'), contains(' const std::string& message() const { return message_; }'), - contains( - ' const ::flutter::EncodableValue& details() const { return details_; }', - ), + contains(' const ::flutter::EncodableValue& details() const { return details_; }'), contains(' private:'), contains(' std::string code_;'), contains(' std::string message_;'), @@ -331,17 +298,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'someInput', ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -361,12 +322,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( @@ -445,12 +401,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); @@ -466,12 +417,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); @@ -489,17 +435,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: true), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -518,12 +458,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -550,12 +485,7 @@ void main() { cppSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -588,17 +518,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: true), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -618,12 +542,7 @@ void main() { cppSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('namespace foo {')); expect(code, contains('} // namespace foo')); @@ -640,12 +559,7 @@ void main() { cppSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('namespace foo {')); expect(code, contains('} // namespace foo')); @@ -725,21 +639,13 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // There should be a default constructor. expect(code, contains('Nested();')); // There should be a convenience constructor. - expect( - code, - contains(RegExp(r'explicit Nested\(\s*const bool\* nested_value\s*\)')), - ); + expect(code, contains(RegExp(r'explicit Nested\(\s*const bool\* nested_value\s*\)'))); // Getters should return const pointers. expect(code, contains('const bool* nullable_bool()')); @@ -750,25 +656,13 @@ void main() { expect(code, contains('void set_nullable_bool(const bool* value_arg)')); expect(code, contains('void set_nullable_int(const int64_t* value_arg)')); // Strings should be string_view rather than string as an argument. - expect( - code, - contains('void set_nullable_string(const std::string_view* value_arg)'), - ); - expect( - code, - contains('void set_nullable_nested(const Nested* value_arg)'), - ); + expect(code, contains('void set_nullable_string(const std::string_view* value_arg)')); + expect(code, contains('void set_nullable_nested(const Nested* value_arg)')); // Setters should have non-null-style variants. expect(code, contains('void set_nullable_bool(bool value_arg)')); expect(code, contains('void set_nullable_int(int64_t value_arg)')); - expect( - code, - contains('void set_nullable_string(std::string_view value_arg)'), - ); - expect( - code, - contains('void set_nullable_nested(const Nested& value_arg)'), - ); + expect(code, contains('void set_nullable_string(std::string_view value_arg)')); + expect(code, contains('void set_nullable_nested(const Nested& value_arg)')); // Most instance variables should be std::optionals. expect(code, contains('std::optional nullable_bool_')); expect(code, contains('std::optional nullable_int_')); @@ -787,12 +681,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // There should be a default constructor. @@ -810,18 +699,9 @@ void main() { ); // Getters extract optionals. - expect( - code, - contains('return nullable_bool_ ? &(*nullable_bool_) : nullptr;'), - ); - expect( - code, - contains('return nullable_int_ ? &(*nullable_int_) : nullptr;'), - ); - expect( - code, - contains('return nullable_string_ ? &(*nullable_string_) : nullptr;'), - ); + expect(code, contains('return nullable_bool_ ? &(*nullable_bool_) : nullptr;')); + expect(code, contains('return nullable_int_ ? &(*nullable_int_) : nullptr;')); + expect(code, contains('return nullable_string_ ? &(*nullable_string_) : nullptr;')); expect(code, contains('return nullable_nested_.get();')); // Setters convert to optionals. expect( @@ -847,9 +727,7 @@ void main() { ); expect( code, - contains( - 'nullable_nested_ = value_arg ? std::make_unique(*value_arg) : nullptr;', - ), + contains('nullable_nested_ = value_arg ? std::make_unique(*value_arg) : nullptr;'), ); // Serialization handles optionals. expect( @@ -861,9 +739,7 @@ void main() { ); expect( code, - contains( - 'nullable_nested_ ? CustomEncodableValue(*nullable_nested_) : EncodableValue())', - ), + contains('nullable_nested_ ? CustomEncodableValue(*nullable_nested_) : EncodableValue())'), ); // Serialization should use push_back, not initializer lists, to avoid @@ -926,10 +802,7 @@ void main() { name: 'nonNullableInt', ), NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'nonNullableString', ), NamedType( @@ -956,21 +829,13 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // There should not be a default constructor. expect(code, isNot(contains('Nested();'))); // There should be a convenience constructor. - expect( - code, - contains(RegExp(r'explicit Nested\(\s*bool nested_value\s*\)')), - ); + expect(code, contains(RegExp(r'explicit Nested\(\s*bool nested_value\s*\)'))); // POD getters should return copies references. expect(code, contains('bool non_nullable_bool()')); @@ -982,15 +847,9 @@ void main() { expect(code, contains('void set_non_nullable_bool(bool value_arg)')); expect(code, contains('void set_non_nullable_int(int64_t value_arg)')); // Strings should be string_view as an argument. - expect( - code, - contains('void set_non_nullable_string(std::string_view value_arg)'), - ); + expect(code, contains('void set_non_nullable_string(std::string_view value_arg)')); // Other non-POD setters should take const references. - expect( - code, - contains('void set_non_nullable_nested(const Nested& value_arg)'), - ); + expect(code, contains('void set_non_nullable_nested(const Nested& value_arg)')); // Instance variables should be plain types. expect(code, contains('bool non_nullable_bool_;')); expect(code, contains('int64_t non_nullable_int_;')); @@ -1009,12 +868,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // There should not be a default constructor. @@ -1041,10 +895,7 @@ void main() { expect(code, contains('non_nullable_int_ = value_arg;')); expect(code, contains('non_nullable_string_ = value_arg;')); // Unless it's a custom class. - expect( - code, - contains('non_nullable_nested_ = std::make_unique(value_arg);'), - ); + expect(code, contains('non_nullable_nested_ = std::make_unique(value_arg);')); // Serialization uses the value directly. expect(code, contains('EncodableValue(non_nullable_bool_)')); expect(code, contains('CustomEncodableValue(*non_nullable_nested_)')); @@ -1052,10 +903,7 @@ void main() { // Serialization should use push_back, not initializer lists, to avoid // copies. expect(code, contains('list.reserve(4)')); - expect( - code, - contains('list.push_back(CustomEncodableValue(*non_nullable_nested_))'), - ); + expect(code, contains('list.push_back(CustomEncodableValue(*non_nullable_nested_))')); } }); @@ -1069,28 +917,19 @@ void main() { name: 'returnNullableBool', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'bool', isNullable: true), ), Method( name: 'returnNullableInt', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), ), Method( name: 'returnNullableString', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: true), ), Method( name: 'returnNullableList', @@ -1154,43 +993,17 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); + expect(code, contains('ErrorOr> ReturnNullableBool()')); + expect(code, contains('ErrorOr> ReturnNullableInt()')); + expect(code, contains('ErrorOr> ReturnNullableString()')); expect( code, - contains('ErrorOr> ReturnNullableBool()'), - ); - expect( - code, - contains('ErrorOr> ReturnNullableInt()'), - ); - expect( - code, - contains('ErrorOr> ReturnNullableString()'), - ); - expect( - code, - contains( - 'ErrorOr> ReturnNullableList()', - ), - ); - expect( - code, - contains( - 'ErrorOr> ReturnNullableMap()', - ), - ); - expect( - code, - contains( - 'ErrorOr> ReturnNullableDataClass()', - ), + contains('ErrorOr> ReturnNullableList()'), ); + expect(code, contains('ErrorOr> ReturnNullableMap()')); + expect(code, contains('ErrorOr> ReturnNullableDataClass()')); } }); @@ -1204,28 +1017,19 @@ void main() { name: 'returnBool', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'bool', isNullable: false), ), Method( name: 'returnInt', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), Method( name: 'returnString', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), ), Method( name: 'returnList', @@ -1289,12 +1093,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('ErrorOr ReturnBool()')); expect(code, contains('ErrorOr ReturnInt()')); @@ -1317,24 +1116,15 @@ void main() { parameters: [ Parameter( name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'bool', isNullable: true), ), Parameter( name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), Parameter( name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: true), ), Parameter( name: 'aList', @@ -1367,10 +1157,7 @@ void main() { ), Parameter( name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Object', isNullable: true), ), ], returnType: const TypeDeclaration.voidDeclaration(), @@ -1402,12 +1189,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1436,52 +1218,29 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // Most types should just use get_if, since the parameter is a pointer, // and get_if will automatically handle null values (since a null // EncodableValue will not match the queried type, so get_if will return // nullptr). + expect(code, contains('const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);')); expect( code, - contains( - 'const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);', - ), - ); - expect( - code, - contains( - 'const auto* a_string_arg = std::get_if(&encodable_a_string_arg);', - ), - ); - expect( - code, - contains( - 'const auto* a_list_arg = std::get_if(&encodable_a_list_arg);', - ), + contains('const auto* a_string_arg = std::get_if(&encodable_a_string_arg);'), ); expect( code, - contains( - 'const auto* a_map_arg = std::get_if(&encodable_a_map_arg);', - ), + contains('const auto* a_list_arg = std::get_if(&encodable_a_list_arg);'), ); expect( code, - contains( - 'const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);', - ), + contains('const auto* a_map_arg = std::get_if(&encodable_a_map_arg);'), ); + expect(code, contains('const auto* a_bool_arg = std::get_if(&encodable_a_bool_arg);')); expect( code, - contains( - 'const auto* an_int_arg = std::get_if(&encodable_an_int_arg);', - ), + contains('const auto* an_int_arg = std::get_if(&encodable_an_int_arg);'), ); // Custom class types require an extra layer of extraction. expect( @@ -1492,12 +1251,7 @@ void main() { ); // "Object" requires no extraction at all since it has to use // EncodableValue directly. - expect( - code, - contains( - 'const auto* a_generic_object_arg = &encodable_a_generic_object_arg;', - ), - ); + expect(code, contains('const auto* a_generic_object_arg = &encodable_a_generic_object_arg;')); } }); @@ -1513,24 +1267,15 @@ void main() { parameters: [ Parameter( name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'bool', isNullable: false), ), Parameter( name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), Parameter( name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), ), Parameter( name: 'aList', @@ -1563,10 +1308,7 @@ void main() { ), Parameter( name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Object', isNullable: false), ), ], returnType: const TypeDeclaration.voidDeclaration(), @@ -1598,12 +1340,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1632,47 +1369,26 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // Most types should extract references. Since the type is non-nullable, // there's only one possible type. + expect(code, contains('const auto& a_bool_arg = std::get(encodable_a_bool_arg);')); expect( code, - contains( - 'const auto& a_bool_arg = std::get(encodable_a_bool_arg);', - ), + contains('const auto& a_string_arg = std::get(encodable_a_string_arg);'), ); expect( code, - contains( - 'const auto& a_string_arg = std::get(encodable_a_string_arg);', - ), - ); - expect( - code, - contains( - 'const auto& a_list_arg = std::get(encodable_a_list_arg);', - ), + contains('const auto& a_list_arg = std::get(encodable_a_list_arg);'), ); expect( code, - contains( - 'const auto& a_map_arg = std::get(encodable_a_map_arg);', - ), + contains('const auto& a_map_arg = std::get(encodable_a_map_arg);'), ); // Ints use a copy since there are two possible reference types, but // the parameter always needs an int64_t. - expect( - code, - contains( - 'const int64_t an_int_arg = encodable_an_int_arg.LongValue();', - ), - ); + expect(code, contains('const int64_t an_int_arg = encodable_an_int_arg.LongValue();')); // Custom class types require an extra layer of extraction. expect( code, @@ -1682,12 +1398,7 @@ void main() { ); // "Object" requires no extraction at all since it has to use // EncodableValue directly. - expect( - code, - contains( - 'const auto& a_generic_object_arg = encodable_a_generic_object_arg;', - ), - ); + expect(code, contains('const auto& a_generic_object_arg = encodable_a_generic_object_arg;')); } }); @@ -1703,24 +1414,15 @@ void main() { parameters: [ Parameter( name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'bool', isNullable: true), ), Parameter( name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), Parameter( name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: true), ), Parameter( name: 'aList', @@ -1753,16 +1455,10 @@ void main() { ), Parameter( name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Object', isNullable: true), ), ], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'bool', isNullable: true), ), ], ), @@ -1791,12 +1487,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // Nullable arguments should all be pointers. This will make them somewhat // awkward for some uses (literals, values that could be inlined) but @@ -1844,43 +1535,19 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // All types pass nulls values when the pointer is null. // Standard types are wrapped an EncodableValues. - expect( - code, - contains('a_bool_arg ? EncodableValue(*a_bool_arg) : EncodableValue()'), - ); - expect( - code, - contains('an_int_arg ? EncodableValue(*an_int_arg) : EncodableValue()'), - ); - expect( - code, - contains( - 'a_string_arg ? EncodableValue(*a_string_arg) : EncodableValue()', - ), - ); - expect( - code, - contains('a_list_arg ? EncodableValue(*a_list_arg) : EncodableValue()'), - ); - expect( - code, - contains('a_map_arg ? EncodableValue(*a_map_arg) : EncodableValue()'), - ); + expect(code, contains('a_bool_arg ? EncodableValue(*a_bool_arg) : EncodableValue()')); + expect(code, contains('an_int_arg ? EncodableValue(*an_int_arg) : EncodableValue()')); + expect(code, contains('a_string_arg ? EncodableValue(*a_string_arg) : EncodableValue()')); + expect(code, contains('a_list_arg ? EncodableValue(*a_list_arg) : EncodableValue()')); + expect(code, contains('a_map_arg ? EncodableValue(*a_map_arg) : EncodableValue()')); // Class types use ToEncodableList. expect( code, - contains( - 'an_object_arg ? CustomEncodableValue(*an_object_arg) : EncodableValue()', - ), + contains('an_object_arg ? CustomEncodableValue(*an_object_arg) : EncodableValue()'), ); } }); @@ -1897,24 +1564,15 @@ void main() { parameters: [ Parameter( name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'bool', isNullable: false), ), Parameter( name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), Parameter( name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), ), Parameter( name: 'aList', @@ -1947,16 +1605,10 @@ void main() { ), Parameter( name: 'aGenericObject', - type: const TypeDeclaration( - baseName: 'Object', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Object', isNullable: false), ), ], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'bool', isNullable: false), ), ], ), @@ -1985,12 +1637,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -2032,12 +1679,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // Standard types are wrapped in EncodableValues. expect(code, contains('EncodableValue(a_bool_arg)')); @@ -2062,10 +1704,7 @@ void main() { parameters: [ Parameter( name: 'anArg', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], returnType: const TypeDeclaration.voidDeclaration(), @@ -2087,19 +1726,11 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // A bare 'auto' here would create a copy, not a reference, which is // inefficient. - expect( - code, - contains('const auto& args = std::get(message);'), - ); + expect(code, contains('const auto& args = std::get(message);')); expect(code, contains('const auto& encodable_an_arg_arg = args.at(0);')); }); @@ -2139,11 +1770,7 @@ void main() { ], ); final List errors = validateCpp( - const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), + const InternalCppOptions(cppHeaderOut: '', cppSourceOut: '', headerIncludePath: ''), root, ); expect(errors.length, 1); @@ -2177,10 +1804,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -2210,15 +1834,9 @@ void main() { enums: [ Enum( name: 'enum', - documentationComments: [ - comments[count++], - unspacedComments[unspacedCount++], - ], + documentationComments: [comments[count++], unspacedComments[unspacedCount++]], members: [ - EnumMember( - name: 'one', - documentationComments: [comments[count++]], - ), + EnumMember(name: 'one', documentationComments: [comments[count++]]), EnumMember(name: 'two'), ], ), @@ -2234,12 +1852,7 @@ void main() { cppSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); for (final comment in comments) { expect(code, contains('//$comment')); @@ -2308,12 +1921,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(' : public ::flutter::StandardCodecSerializer')); }); @@ -2330,24 +1938,15 @@ void main() { parameters: [ Parameter( name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'bool', isNullable: false), ), Parameter( name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), Parameter( name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), ), Parameter( name: 'aList', @@ -2407,12 +2006,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('reply(wrap'))); expect(code, contains('reply(EncodableValue(')); @@ -2436,17 +2030,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: '', ), ], - returnType: const TypeDeclaration( - baseName: 'double', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'double', isNullable: false), isAsynchronous: true, ), ], @@ -2466,17 +2054,11 @@ void main() { location: ApiLocation.flutter, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: '', ), ], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'bool', isNullable: false), isAsynchronous: true, ), ], @@ -2495,12 +2077,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // Nothing should be captured by reference for async handlers, since their // lifetime is unknown (and expected to be longer than the stack's). @@ -2525,10 +2102,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -2549,18 +2123,11 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - '"Unable to establish connection on channel: \'" + channel_name + "\'."', - ), + contains('"Unable to establish connection on channel: \'" + channel_name + "\'."'), ); expect(code, contains('on_error(CreateConnectionError(channel_name));')); }); @@ -2578,10 +2145,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -2601,18 +2165,11 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - 'BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec());', - ), + contains('BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec());'), ); expect(code, contains('channel.Send')); }); @@ -2644,12 +2201,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('bool operator==(const Foo& other) const;')); } @@ -2664,12 +2216,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('bool Foo::operator==(const Foo& other) const {')); } @@ -2692,11 +2239,7 @@ void main() { name: 'Foo', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Nested', - isNullable: true, - associatedClass: nested, - ), + type: TypeDeclaration(baseName: 'Nested', isNullable: true, associatedClass: nested), name: 'nested', ), ], @@ -2715,12 +2258,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('bool Foo::operator==(const Foo& other) const {')); }); @@ -2752,12 +2290,7 @@ void main() { cppSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('size_t Hash() const;')); } @@ -2772,12 +2305,7 @@ void main() { cppSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('size_t Input::Hash() const {')); } diff --git a/packages/pigeon/test/dart/proxy_api_test.dart b/packages/pigeon/test/dart/proxy_api_test.dart index 96ca1ce6b093..337e3ba0f25e 100644 --- a/packages/pigeon/test/dart/proxy_api_test.dart +++ b/packages/pigeon/test/dart/proxy_api_test.dart @@ -20,10 +20,7 @@ void main() { name: 'name', parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], @@ -41,34 +38,22 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), ), Method( name: 'doSomethingElse', location: ApiLocation.flutter, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), isRequired: false, ), ], @@ -97,10 +82,7 @@ void main() { // Codec and class expect(code, contains('class _PigeonInternalProxyApiBaseCodec')); - expect( - code, - contains(r'class Api extends PigeonInternalProxyApiBaseClass'), - ); + expect(code, contains(r'class Api extends PigeonInternalProxyApiBaseClass')); // Constructors expect( @@ -127,9 +109,7 @@ void main() { expect(code, contains(r'static void pigeon_setUpMessageHandlers({')); expect( collapsedCode, - contains( - 'final String Function( Api pigeon_instance, Input input, )? doSomethingElse;', - ), + contains('final String Function( Api pigeon_instance, Input input, )? doSomethingElse;'), ); // Copy method @@ -162,10 +142,7 @@ void main() { expect(code, contains(r'class _PigeonInternalInstanceManagerApi')); - expect( - code, - contains('Future removeStrongReference(int identifier)'), - ); + expect(code, contains('Future removeStrongReference(int identifier)')); expect( code, contains( @@ -174,17 +151,13 @@ void main() { ); expect( collapsedCode, - contains( - '(instanceManager ?? PigeonInstanceManager.instance) .remove(arg_identifier);', - ), + contains('(instanceManager ?? PigeonInstanceManager.instance) .remove(arg_identifier);'), ); expect(code, contains('Future clear()')); expect( code, - contains( - 'dev.flutter.pigeon.$DEFAULT_PACKAGE_NAME.PigeonInternalInstanceManager.clear', - ), + contains('dev.flutter.pigeon.$DEFAULT_PACKAGE_NAME.PigeonInternalInstanceManager.clear'), ); }); @@ -212,10 +185,7 @@ void main() { ); final code = sink.toString(); - expect( - code, - contains(r'abstract class PigeonInternalProxyApiBaseClass'), - ); + expect(code, contains(r'abstract class PigeonInternalProxyApiBaseClass')); }); test('InstanceManager field', () { @@ -312,11 +282,7 @@ void main() { fields: [], methods: [], interfaces: { - TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: api2, - ), + TypeDeclaration(baseName: 'Api2', isNullable: false, associatedProxyApi: api2), }, ), api2, @@ -335,9 +301,7 @@ void main() { final code = sink.toString(); expect( code, - contains( - r'class Api extends PigeonInternalProxyApiBaseClass implements Api2', - ), + contains(r'class Api extends PigeonInternalProxyApiBaseClass implements Api2'), ); }); @@ -362,16 +326,8 @@ void main() { fields: [], methods: [], interfaces: { - TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: api2, - ), - TypeDeclaration( - baseName: 'Api3', - isNullable: false, - associatedProxyApi: api2, - ), + TypeDeclaration(baseName: 'Api2', isNullable: false, associatedProxyApi: api2), + TypeDeclaration(baseName: 'Api3', isNullable: false, associatedProxyApi: api2), }, ), api2, @@ -391,9 +347,7 @@ void main() { final code = sink.toString(); expect( code, - contains( - r'class Api extends PigeonInternalProxyApiBaseClass implements Api2, Api3', - ), + contains(r'class Api extends PigeonInternalProxyApiBaseClass implements Api2, Api3'), ); }); @@ -426,11 +380,7 @@ void main() { fields: [], methods: [], interfaces: { - TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: api2, - ), + TypeDeclaration(baseName: 'Api2', isNullable: false, associatedProxyApi: api2), }, ), api2, @@ -450,9 +400,7 @@ void main() { final String collapsedCode = _collapseNewlineAndIndentation(code); expect( code, - contains( - r'class Api extends PigeonInternalProxyApiBaseClass implements Api2', - ), + contains(r'class Api extends PigeonInternalProxyApiBaseClass implements Api2'), ); expect( collapsedCode, @@ -472,9 +420,7 @@ void main() { apis: [ AstProxyApi( name: 'Api', - constructors: [ - Constructor(name: '', parameters: []), - ], + constructors: [Constructor(name: '', parameters: [])], fields: [], methods: [], ), @@ -541,10 +487,7 @@ void main() { name: 'name', parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -556,17 +499,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -578,10 +515,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -659,15 +593,10 @@ void main() { apis: [ AstProxyApi( name: 'Api', - constructors: [ - Constructor(name: 'name', parameters: []), - ], + constructors: [Constructor(name: 'name', parameters: [])], fields: [ ApiField( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), ApiField( @@ -679,17 +608,11 @@ void main() { name: 'enumType', ), ApiField( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), ApiField( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), ApiField( @@ -701,10 +624,7 @@ void main() { name: 'nullableEnumType', ), ApiField( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -859,16 +779,8 @@ void main() { ); final code = sink.toString(); expect(code, contains('class Api')); - expect( - code, - contains( - r'static Api2 get aField => PigeonOverrides.api_aField ?? _aField;', - ), - ); - expect( - code, - contains(r'static final Api2 _aField = pigeonVar_aField();'), - ); + expect(code, contains(r'static Api2 get aField => PigeonOverrides.api_aField ?? _aField;')); + expect(code, contains(r'static final Api2 _aField = pigeonVar_aField();')); expect(code, contains(r'static Api2 pigeonVar_aField()')); }); }); @@ -891,10 +803,7 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -906,17 +815,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -928,10 +831,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -1042,10 +942,7 @@ void main() { isRequired: false, parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -1057,17 +954,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -1079,10 +970,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -1123,27 +1011,12 @@ void main() { r'doSomething', ), ); - expect( - code, - contains(r'final Api arg_pigeon_instance = args[0]! as Api;'), - ); + expect(code, contains(r'final Api arg_pigeon_instance = args[0]! as Api;')); expect(code, contains(r'final int arg_validType = args[1]! as int;')); - expect( - code, - contains(r'final AnEnum arg_enumType = args[2]! as AnEnum;'), - ); - expect( - code, - contains(r'final Api2 arg_proxyApiType = args[3]! as Api2;'), - ); - expect( - code, - contains(r'final int? arg_nullableValidType = args[4] as int?;'), - ); - expect( - code, - contains(r'final AnEnum? arg_nullableEnumType = args[5] as AnEnum?;'), - ); + expect(code, contains(r'final AnEnum arg_enumType = args[2]! as AnEnum;')); + expect(code, contains(r'final Api2 arg_proxyApiType = args[3]! as Api2;')); + expect(code, contains(r'final int? arg_nullableValidType = args[4] as int?;')); + expect(code, contains(r'final AnEnum? arg_nullableEnumType = args[5] as AnEnum?;')); expect( collapsedCode, contains( diff --git a/packages/pigeon/test/dart_generator_test.dart b/packages/pigeon/test/dart_generator_test.dart index f3774fc75c92..d6e0553341a4 100644 --- a/packages/pigeon/test/dart_generator_test.dart +++ b/packages/pigeon/test/dart_generator_test.dart @@ -42,11 +42,7 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const generator = DartGenerator(); generator.generate( @@ -158,23 +154,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -193,12 +180,7 @@ void main() { final code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('Future add(int x, int y)')); - expect( - code, - contains( - 'pigeonVar_sendFuture = pigeonVar_channel.send([x, y])', - ), - ); + expect(code, contains('pigeonVar_sendFuture = pigeonVar_channel.send([x, y])')); expect(code, contains('await pigeonVar_sendFuture')); }); @@ -214,23 +196,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -249,10 +222,7 @@ void main() { final code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('int add(int x, int y)')); - expect( - code, - contains('final List args = message! as List'), - ); + expect(code, contains('final List args = message! as List')); expect(code, contains('final int arg_x = args[0]! as int')); expect(code, contains('final int arg_y = args[1]! as int')); expect(code, contains('final int output = api.add(arg_x, arg_y)')); @@ -308,10 +278,7 @@ void main() { name: 'Input', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'input', ), ], @@ -589,11 +556,7 @@ void main() { name: 'EnumClass', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Enum', - isNullable: true, - associatedEnum: emptyEnum, - ), + type: TypeDeclaration(baseName: 'Enum', isNullable: true, associatedEnum: emptyEnum), name: 'enum1', ), ], @@ -620,10 +583,7 @@ void main() { final code = sink.toString(); expect(code, contains('return value == null ? null : Enum.values[value];')); expect(code, contains('writeValue(buffer, value.index);')); - expect( - code, - contains('final EnumClass arg_enumClass = args[0]! as EnumClass;'), - ); + expect(code, contains('final EnumClass arg_enumClass = args[0]! as EnumClass;')); expect(code, contains('EnumClass doSomething(EnumClass enumClass);')); }); @@ -673,10 +633,7 @@ void main() { final code = sink.toString(); expect(code, contains('enum Foo {')); expect(code, contains('Future bar(Foo? foo) async')); - expect( - code, - contains('pigeonVar_sendFuture = pigeonVar_channel.send([foo])'), - ); + expect(code, contains('pigeonVar_sendFuture = pigeonVar_channel.send([foo])')); expect(code, contains('await pigeonVar_sendFuture')); }); @@ -713,11 +670,7 @@ void main() { name: 'EnumClass', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Enum', - isNullable: false, - associatedEnum: emptyEnum, - ), + type: TypeDeclaration(baseName: 'Enum', isNullable: false, associatedEnum: emptyEnum), name: 'enum1', ), ], @@ -788,10 +741,7 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final code = sink.toString(); - expect( - code, - matches('pigeonVar_sendFuture = pigeonVar_channel.send[(]null[)]'), - ); + expect(code, matches('pigeonVar_sendFuture = pigeonVar_channel.send[(]null[)]')); }); test('mock Dart handler', () { @@ -879,11 +829,7 @@ void main() { const testGenerator = DartGenerator(); testGenerator.generateTest( - const InternalDartOptions( - dartOut: "fo'o.dart", - testOut: 'test.dart', - ignoreLints: false, - ), + const InternalDartOptions(dartOut: "fo'o.dart", testOut: 'test.dart', ignoreLints: false), root, testCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -960,10 +906,7 @@ void main() { final code = sink.toString(); expect(code, contains('abstract class Api')); expect(code, contains('Future doSomething(Input input);')); - expect( - code, - contains('final Output output = await api.doSomething(arg_input);'), - ); + expect(code, contains('final Output output = await api.doSomething(arg_input);')); }); test('gen one async Flutter Api with void return', () { @@ -1146,10 +1089,7 @@ void main() { const generator = DartGenerator(); generator.generate( - InternalDartOptions( - copyrightHeader: makeIterable('hello world'), - ignoreLints: false, - ), + InternalDartOptions(copyrightHeader: makeIterable('hello world'), ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -1166,19 +1106,13 @@ void main() { type: const TypeDeclaration( baseName: 'List', isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true), - ], + typeArguments: [TypeDeclaration(baseName: 'int', isNullable: true)], ), name: 'field1', ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const generator = DartGenerator(); generator.generate( @@ -1209,11 +1143,7 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const generator = DartGenerator(); generator.generate( @@ -1343,10 +1273,7 @@ void main() { ); final code = sink.toString(); expect(code, contains('Future> doit(')); - expect( - code, - contains('return (pigeonVar_replyValue! as List).cast();'), - ); + expect(code, contains('return (pigeonVar_replyValue! as List).cast();')); }); test('flutter generics argument non void return', () { @@ -1394,12 +1321,7 @@ void main() { ); final code = sink.toString(); expect(code, contains('List doit(')); - expect( - code, - contains( - 'final List arg_foo = (args[0]! as List).cast()', - ), - ); + expect(code, contains('final List arg_foo = (args[0]! as List).cast()')); expect(code, contains('final List output = api.doit(arg_foo)')); }); @@ -1412,10 +1334,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -1471,12 +1390,7 @@ void main() { ); final code = sink.toString(); expect(code, contains('Future?> doit()')); - expect( - code, - contains( - 'return (pigeonVar_replyValue as List?)?.cast();', - ), - ); + expect(code, contains('return (pigeonVar_replyValue as List?)?.cast();')); }); test('return nullable async host', () { @@ -1488,10 +1402,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], isAsynchronous: true, ), @@ -1523,10 +1434,7 @@ void main() { Method( name: 'doit', location: ApiLocation.flutter, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -1557,10 +1465,7 @@ void main() { Method( name: 'doit', location: ApiLocation.flutter, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], isAsynchronous: true, ), @@ -1592,10 +1497,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), parameters: [], ), ], @@ -1614,10 +1516,7 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final code = sink.toString(); - expect( - code, - contains('Host platform returned null value for non-null return value.'), - ); + expect(code, contains('Host platform returned null value for non-null return value.')); }); test('nullable argument host', () { @@ -1633,10 +1532,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1671,10 +1567,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1709,10 +1602,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), isNamed: true, isPositional: false, ), @@ -1764,10 +1654,7 @@ name: foobar dartOutputPackageName: outputPackageName, ); final code = sink.toString(); - expect( - code, - contains("import 'package:$outputPackageName/foo/bar.dart';"), - ); + expect(code, contains("import 'package:$outputPackageName/foo/bar.dart';")); } finally { tempDir.deleteSync(recursive: true); } @@ -1801,10 +1688,7 @@ name: foobar parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1834,15 +1718,9 @@ name: foobar enums: [ Enum( name: 'enum', - documentationComments: [ - comments[count++], - unspacedComments[unspacedCount++], - ], + documentationComments: [comments[count++], unspacedComments[unspacedCount++]], members: [ - EnumMember( - name: 'one', - documentationComments: [comments[count++]], - ), + EnumMember(name: 'one', documentationComments: [comments[count++]]), EnumMember(name: 'two'), ], ), @@ -1966,11 +1844,7 @@ name: foobar const testGenerator = DartGenerator(); testGenerator.generateTest( - const InternalDartOptions( - dartOut: 'code.dart', - testOut: 'test.dart', - ignoreLints: false, - ), + const InternalDartOptions(dartOut: 'code.dart', testOut: 'test.dart', ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -1979,10 +1853,7 @@ name: foobar final testCode = sink.toString(); expect(testCode, contains('final Enum arg_anEnum = args[0]! as Enum;')); - expect( - testCode, - contains('return value == null ? null : Enum.values[value];'), - ); + expect(testCode, contains('return value == null ? null : Enum.values[value];')); expect(testCode, contains('writeValue(buffer, value.index);')); }); @@ -1996,10 +1867,7 @@ name: foobar name: 'method', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'Output', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'Output', isNullable: false), ), ], ), @@ -2017,12 +1885,7 @@ name: foobar dartPackageName: DEFAULT_PACKAGE_NAME, ); final code = sink.toString(); - expect( - code, - contains( - '\'Unable to establish connection on channel: "\$channelName".\'', - ), - ); + expect(code, contains('\'Unable to establish connection on channel: "\$channelName".\'')); }); test('generate wrapResponse if is generating tests', () { @@ -2066,10 +1929,7 @@ name: foobar Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -2102,11 +1962,7 @@ name: foobar ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const generator = DartGenerator(); generator.generate( @@ -2134,11 +1990,7 @@ name: foobar ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const generator = DartGenerator(); generator.generate( diff --git a/packages/pigeon/test/functional_test.dart b/packages/pigeon/test/functional_test.dart index 48110f1487fe..458b15de6fd7 100644 --- a/packages/pigeon/test/functional_test.dart +++ b/packages/pigeon/test/functional_test.dart @@ -36,11 +36,7 @@ void main() { }); test('map2', () { - final List result = map2( - [3, 5, 7], - [1, 2, 3], - (int x, int y) => x * y, - ).toList(); + final List result = map2([3, 5, 7], [1, 2, 3], (int x, int y) => x * y).toList(); expect(result[0], 3); expect(result[1], 10); expect(result[2], 21); @@ -66,12 +62,7 @@ void main() { test('map3 unequal', () { expect( - () => map3( - [], - [1, 2, 3], - [], - (int x, int y, int z) => x * y * z, - ).toList(), + () => map3([], [1, 2, 3], [], (int x, int y, int z) => x * y * z).toList(), throwsArgumentError, ); }); diff --git a/packages/pigeon/test/generator_tools_test.dart b/packages/pigeon/test/generator_tools_test.dart index 183865f1e3f3..2c47589a4b4a 100644 --- a/packages/pigeon/test/generator_tools_test.dart +++ b/packages/pigeon/test/generator_tools_test.dart @@ -129,11 +129,7 @@ void main() { fields: [ NamedType( name: 'bar', - type: TypeDeclaration( - baseName: 'Bar', - isNullable: true, - associatedClass: emptyClass, - ), + type: TypeDeclaration(baseName: 'Bar', isNullable: true, associatedClass: emptyClass), ), ], ), @@ -151,14 +147,8 @@ void main() { ); final List classes = getEnumeratedTypes(root).toList(); expect(classes.length, 2); - expect( - classes.where((EnumeratedType element) => element.name == 'Foo').length, - 1, - ); - expect( - classes.where((EnumeratedType element) => element.name == 'Bar').length, - 1, - ); + expect(classes.where((EnumeratedType element) => element.name == 'Foo').length, 1); + expect(classes.where((EnumeratedType element) => element.name == 'Bar').length, 1); }); test('getEnumeratedTypes: Object', () { @@ -202,10 +192,7 @@ void main() { ); final List classes = getEnumeratedTypes(root).toList(); expect(classes.length, 1); - expect( - classes.where((EnumeratedType element) => element.name == 'Foo').length, - 1, - ); + expect(classes.where((EnumeratedType element) => element.name == 'Foo').length, 1); }); test('getEnumeratedTypes:ue entries', () { @@ -267,16 +254,11 @@ void main() { ); final List classes = getEnumeratedTypes(root).toList(); expect(classes.length, 1); - expect( - classes.where((EnumeratedType element) => element.name == 'Foo').length, - 1, - ); + expect(classes.where((EnumeratedType element) => element.name == 'Foo').length, 1); }); test('deduces package name successfully', () { - final String? dartPackageName = deducePackageName( - './pigeons/core_tests.dart', - ); + final String? dartPackageName = deducePackageName('./pigeons/core_tests.dart'); expect(dartPackageName, 'pigeon'); }); @@ -313,10 +295,7 @@ void main() { expect( api.allSuperClasses().toList(), - containsAllInOrder([ - superClassApi, - superClassOfSuperClassApi, - ]), + containsAllInOrder([superClassApi, superClassOfSuperClassApi]), ); }); @@ -370,16 +349,8 @@ void main() { constructors: [], fields: [], interfaces: { - TypeDeclaration( - baseName: 'Api2', - isNullable: false, - associatedProxyApi: interfaceApi, - ), - TypeDeclaration( - baseName: 'Api3', - isNullable: false, - associatedProxyApi: interfaceApi2, - ), + TypeDeclaration(baseName: 'Api2', isNullable: false, associatedProxyApi: interfaceApi), + TypeDeclaration(baseName: 'Api3', isNullable: false, associatedProxyApi: interfaceApi2), }, ); @@ -394,53 +365,38 @@ void main() { ); }); - test( - 'recursiveFindAllInterfacesApis throws error if api recursively implements itself', - () { - final a = AstProxyApi( - name: 'A', - methods: [], - constructors: [], - fields: [], - ); - final b = AstProxyApi( - name: 'B', - methods: [], - constructors: [], - fields: [], - ); - final c = AstProxyApi( - name: 'C', - methods: [], - constructors: [], - fields: [], - ); + test('recursiveFindAllInterfacesApis throws error if api recursively implements itself', () { + final a = AstProxyApi( + name: 'A', + methods: [], + constructors: [], + fields: [], + ); + final b = AstProxyApi( + name: 'B', + methods: [], + constructors: [], + fields: [], + ); + final c = AstProxyApi( + name: 'C', + methods: [], + constructors: [], + fields: [], + ); - a.interfaces = { - TypeDeclaration( - baseName: 'B', - isNullable: false, - associatedProxyApi: b, - ), - }; - b.interfaces = { - TypeDeclaration( - baseName: 'C', - isNullable: false, - associatedProxyApi: c, - ), - }; - c.interfaces = { - TypeDeclaration( - baseName: 'A', - isNullable: false, - associatedProxyApi: a, - ), - }; + a.interfaces = { + TypeDeclaration(baseName: 'B', isNullable: false, associatedProxyApi: b), + }; + b.interfaces = { + TypeDeclaration(baseName: 'C', isNullable: false, associatedProxyApi: c), + }; + c.interfaces = { + TypeDeclaration(baseName: 'A', isNullable: false, associatedProxyApi: a), + }; - expect(() => a.apisOfInterfaces(), throwsArgumentError); - }, - ); + expect(() => a.apisOfInterfaces(), throwsArgumentError); + }); test('findHighestApiRequirement', () { final typeWithoutMinApi = TypeDeclaration( @@ -476,24 +432,19 @@ void main() { ), ); - final ({TypeDeclaration type, int version})? result = - findHighestApiRequirement( - [ - typeWithoutMinApi, - typeWithMinApi, - typeWithHighestMinApi, - ], - onGetApiRequirement: (TypeDeclaration type) { - if (type == typeWithMinApi) { - return 1; - } else if (type == typeWithHighestMinApi) { - return 2; - } + final ({TypeDeclaration type, int version})? result = findHighestApiRequirement( + [typeWithoutMinApi, typeWithMinApi, typeWithHighestMinApi], + onGetApiRequirement: (TypeDeclaration type) { + if (type == typeWithMinApi) { + return 1; + } else if (type == typeWithHighestMinApi) { + return 2; + } - return null; - }, - onCompare: (int one, int two) => one.compareTo(two), - ); + return null; + }, + onCompare: (int one, int two) => one.compareTo(two), + ); expect(result?.type, typeWithHighestMinApi); expect(result?.version, 2); diff --git a/packages/pigeon/test/gobject_generator_test.dart b/packages/pigeon/test/gobject_generator_test.dart index 8f44885a4617..ebf6bda6a04b 100644 --- a/packages/pigeon/test/gobject_generator_test.dart +++ b/packages/pigeon/test/gobject_generator_test.dart @@ -70,12 +70,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -101,29 +96,11 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains( - 'static void test_package_input_init(TestPackageInput* self) {', - ), - ); - expect( - code, - contains( - 'static void test_package_output_init(TestPackageOutput* self) {', - ), - ); - expect( - code, - contains('static void test_package_api_init(TestPackageApi* self) {'), - ); + expect(code, contains('static void test_package_input_init(TestPackageInput* self) {')); + expect(code, contains('static void test_package_output_init(TestPackageOutput* self) {')); + expect(code, contains('static void test_package_api_init(TestPackageApi* self) {')); // See https://github.com/flutter/flutter/issues/153083. If a private type // is ever needed, this should be updated to ensure that any type declared // in the implementation file has a corresponding _IS_ call in the file. @@ -191,12 +168,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -206,15 +178,11 @@ void main() { ); expect( code, - contains( - 'gboolean test_package_input_get_input_field(TestPackageInput* object);', - ), + contains('gboolean test_package_input_get_input_field(TestPackageInput* object);'), ); expect( code, - contains( - 'gboolean test_package_output_get_output_field(TestPackageOutput* object);', - ), + contains('gboolean test_package_output_get_output_field(TestPackageOutput* object);'), ); } { @@ -228,24 +196,15 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - 'gboolean test_package_input_get_input_field(TestPackageInput* self) {', - ), + contains('gboolean test_package_input_get_input_field(TestPackageInput* self) {'), ); expect( code, - contains( - 'gboolean test_package_output_get_output_field(TestPackageOutput* self) {', - ), + contains('gboolean test_package_output_get_output_field(TestPackageOutput* self) {'), ); } }); @@ -310,12 +269,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); @@ -331,12 +285,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); @@ -354,17 +303,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: true), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -383,12 +326,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -408,12 +346,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -496,20 +429,10 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains( - 'TestPackageNested* test_package_nested_new(gboolean nested_value);', - ), - ); + expect(code, contains('TestPackageNested* test_package_nested_new(gboolean nested_value);')); } { final sink = StringBuffer(); @@ -522,20 +445,10 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains( - 'TestPackageNested* test_package_nested_new(gboolean nested_value) {', - ), - ); + expect(code, contains('TestPackageNested* test_package_nested_new(gboolean nested_value) {')); } }); @@ -558,28 +471,19 @@ void main() { name: 'returnBool', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'bool', isNullable: false), ), Method( name: 'returnInt', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), Method( name: 'returnString', location: ApiLocation.host, parameters: [], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), ), Method( name: 'returnList', @@ -633,42 +537,27 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - ' TestPackageApiReturnBoolResponse* (*return_bool)(gpointer user_data);', - ), + contains(' TestPackageApiReturnBoolResponse* (*return_bool)(gpointer user_data);'), ); expect( code, - contains( - ' TestPackageApiReturnIntResponse* (*return_int)(gpointer user_data);', - ), + contains(' TestPackageApiReturnIntResponse* (*return_int)(gpointer user_data);'), ); expect( code, - contains( - ' TestPackageApiReturnStringResponse* (*return_string)(gpointer user_data);', - ), + contains(' TestPackageApiReturnStringResponse* (*return_string)(gpointer user_data);'), ); expect( code, - contains( - ' TestPackageApiReturnListResponse* (*return_list)(gpointer user_data);', - ), + contains(' TestPackageApiReturnListResponse* (*return_list)(gpointer user_data);'), ); expect( code, - contains( - ' TestPackageApiReturnMapResponse* (*return_map)(gpointer user_data);', - ), + contains(' TestPackageApiReturnMapResponse* (*return_map)(gpointer user_data);'), ); expect( code, @@ -701,24 +590,15 @@ void main() { parameters: [ Parameter( name: 'aBool', - type: const TypeDeclaration( - baseName: 'bool', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'bool', isNullable: false), ), Parameter( name: 'anInt', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), Parameter( name: 'aString', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), ), Parameter( name: 'aList', @@ -739,10 +619,7 @@ void main() { type: TypeDeclaration( baseName: 'Map', typeArguments: [ - const TypeDeclaration( - baseName: 'String', - isNullable: true, - ), + const TypeDeclaration(baseName: 'String', isNullable: true), TypeDeclaration( baseName: 'Object', isNullable: true, @@ -788,12 +665,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -813,12 +685,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -857,10 +724,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -890,15 +754,9 @@ void main() { enums: [ Enum( name: 'enum', - documentationComments: [ - comments[count++], - unspacedComments[unspacedCount++], - ], + documentationComments: [comments[count++], unspacedComments[unspacedCount++]], members: [ - EnumMember( - name: 'one', - documentationComments: [comments[count++]], - ), + EnumMember(name: 'one', documentationComments: [comments[count++]]), EnumMember(name: 'two'), ], ), @@ -914,12 +772,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); for (final comment in comments) { expect(code, contains(' *$comment')); @@ -994,18 +847,10 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('extern const int test_packageenum_type_id;')); - expect( - code, - contains('extern const int test_package_parameter_object_type_id;'), - ); + expect(code, contains('extern const int test_package_parameter_object_type_id;')); expect(code, contains('extern const int test_package_object_type_id;')); } { @@ -1019,19 +864,11 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('const int test_packageenum_type_id = 129;')); - expect( - code, - contains('const int test_package_parameter_object_type_id = 130;'), - ); + expect(code, contains('const int test_package_parameter_object_type_id = 130;')); expect(code, contains('const int test_package_object_type_id = 131;')); } }); @@ -1054,11 +891,7 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [inputClass], - enums: [], - ); + final root = Root(apis: [], classes: [inputClass], enums: []); { final sink = StringBuffer(); const generator = GObjectGenerator(); @@ -1070,12 +903,7 @@ void main() { gobjectSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('gboolean test_package_input_equals(')); expect(code, contains('guint test_package_input_hash(')); diff --git a/packages/pigeon/test/java_generator_test.dart b/packages/pigeon/test/java_generator_test.dart index a5f0708abf58..3fb422410190 100644 --- a/packages/pigeon/test/java_generator_test.dart +++ b/packages/pigeon/test/java_generator_test.dart @@ -36,20 +36,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public class Messages')); expect(code, contains('public static final class Foobar')); @@ -71,12 +62,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public enum Foobar')); expect(code, contains(' ONE(0),')); @@ -97,11 +83,7 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const javaOptions = InternalJavaOptions( className: 'Messages', @@ -109,12 +91,7 @@ void main() { javaOut: '', ); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('package com.google.foobar;')); }); @@ -173,27 +150,18 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public interface Api')); expect(code, matches('Output.*doSomething.*Input')); expect(code, contains('channel.setMessageHandler(null)')); expect( code, - contains( - 'protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer)', - ), + contains('protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer)'), ); expect( code, - contains( - 'protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value)', - ), + contains('protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value)'), ); expect( code, @@ -230,31 +198,19 @@ void main() { name: 'aString', ), NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Uint8List', isNullable: true), name: 'aUint8List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int32List', isNullable: true), name: 'aInt32List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int64List', isNullable: true), name: 'aInt64List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Float64List', isNullable: true), name: 'aFloat64List', ), ], @@ -266,12 +222,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('private @Nullable Boolean aBool;')); expect(code, contains('private @Nullable Long aInt;')); @@ -336,12 +287,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public static class Api')); expect(code, matches('doSomething.*Input.*Output')); @@ -387,12 +333,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(matches('=.*doSomething'))); expect(code, contains('doSomething(')); @@ -438,18 +379,11 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - 'public void doSomething(@NonNull Input arg0Arg, @NonNull VoidResult result)', - ), + contains('public void doSomething(@NonNull Input arg0Arg, @NonNull VoidResult result)'), ); expect(code, contains('result.success();')); }); @@ -489,12 +423,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('Output doSomething()')); expect(code, contains('api.doSomething()')); @@ -535,17 +464,9 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('public void doSomething(@NonNull Result result)'), - ); + expect(code, contains('public void doSomething(@NonNull Result result)')); expect(code, contains(RegExp(r'channel.send\(\s*null'))); }); @@ -568,12 +489,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public static final class Foobar')); expect(code, contains('private @Nullable List field1;')); @@ -598,12 +514,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public static final class Foobar')); expect(code, contains('private @Nullable Map field1;')); @@ -614,11 +525,7 @@ void main() { name: 'Outer', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Nested', - associatedClass: emptyClass, - isNullable: true, - ), + type: TypeDeclaration(baseName: 'Nested', associatedClass: emptyClass, isNullable: true), name: 'nested', ), ], @@ -640,12 +547,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public class Messages')); expect(code, contains('public static final class Outer')); @@ -708,22 +610,12 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public interface Api')); expect(code, contains('public interface Result {')); expect(code, contains('void error(@NonNull Throwable error);')); - expect( - code, - contains( - 'void doSomething(@NonNull Input arg, @NonNull Result result);', - ), - ); + expect(code, contains('void doSomething(@NonNull Input arg, @NonNull Result result);')); expect(code, contains('api.doSomething(argArg, resultCallback);')); expect(code, contains('channel.setMessageHandler(null)')); }); @@ -782,12 +674,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public static class Api')); expect(code, matches('doSomething.*Input.*Output')); @@ -806,29 +693,16 @@ void main() { name: 'EnumClass', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), + type: TypeDeclaration(baseName: 'Enum1', associatedEnum: emptyEnum, isNullable: true), name: 'enum1', ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [anEnum], - ); + final root = Root(apis: [], classes: [classDefinition], enums: [anEnum]); final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public enum Enum1')); expect(code, contains(' ONE(0),')); @@ -880,26 +754,14 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public enum Foo')); expect( code, - contains( - 'return value == null ? null : Foo.values()[((Long) value).intValue()];', - ), - ); - expect( - code, - contains( - 'writeValue(stream, value == null ? null : ((Foo) value).index);', - ), + contains('return value == null ? null : Foo.values()[((Long) value).intValue()];'), ); + expect(code, contains('writeValue(stream, value == null ? null : ((Foo) value).index);')); expect(code, contains('Foo fooArg = (Foo) args.get(0);')); }); @@ -916,12 +778,7 @@ void main() { javaOut: '', ); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, startsWith('// hello world')); }); @@ -934,28 +791,17 @@ void main() { type: const TypeDeclaration( baseName: 'List', isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true), - ], + typeArguments: [TypeDeclaration(baseName: 'int', isNullable: true)], ), name: 'field1', ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains('List field1;')); @@ -978,20 +824,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains('Map field1;')); @@ -1029,12 +866,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doit(@NonNull List arg')); }); @@ -1071,12 +903,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doit(@NonNull List arg')); }); @@ -1108,12 +935,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('List doit(')); expect(code, contains('List output =')); @@ -1146,17 +968,9 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('public void doit(@NonNull Result> result)'), - ); + expect(code, contains('public void doit(@NonNull Result> result)')); expect(code, contains('List output = (List) listReply.get(0)')); }); @@ -1169,10 +983,7 @@ void main() { Method( name: 'doit', location: ApiLocation.flutter, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), parameters: [], isAsynchronous: true, ), @@ -1185,12 +996,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public void doit(@NonNull Result result)')); expect(code, contains('Long output = (Long) listReply.get(0);')); @@ -1208,23 +1014,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -1235,19 +1032,11 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Messages')); expect(code, contains('Long add(@NonNull Long x, @NonNull Long y)')); - expect( - code, - contains('ArrayList args = (ArrayList) message;'), - ); + expect(code, contains('ArrayList args = (ArrayList) message;')); expect(code, contains('Long xArg = (Long) args.get(0)')); expect(code, contains('Long yArg = (Long) args.get(1)')); expect(code, contains('Long output = api.add(xArg, yArg)')); @@ -1265,10 +1054,7 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'Object', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Object'), ), ], returnType: const TypeDeclaration.voidDeclaration(), @@ -1282,12 +1068,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Api', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('Object xArg = args.get(0)')); }); @@ -1304,23 +1085,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -1331,12 +1103,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Messages')); expect(code, contains('BasicMessageChannel channel')); @@ -1369,16 +1136,10 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -1389,12 +1150,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1415,10 +1171,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -1430,12 +1183,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(RegExp(r'@Nullable\s*Long doit\(\);'))); }); @@ -1449,10 +1197,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), isAsynchronous: true, parameters: [], ), @@ -1465,12 +1210,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); // Java doesn't accept nullability annotations in type arguments. expect(code, contains('Result')); @@ -1489,10 +1229,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1505,12 +1242,7 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(' void doit(@Nullable Long foo);')); }); @@ -1528,10 +1260,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1544,19 +1273,9 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains( - 'public void doit(@Nullable Long fooArg, @NonNull VoidResult result) {', - ), - ); + expect(code, contains('public void doit(@Nullable Long fooArg, @NonNull VoidResult result) {')); }); test('background platform channel', () { @@ -1572,10 +1291,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], taskQueueType: TaskQueueType.serialBackgroundThread, @@ -1589,18 +1305,11 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - 'BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();', - ), + contains('BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();'), ); expect( code, @@ -1617,16 +1326,11 @@ void main() { late Root root; late StringBuffer sink; late JavaGenerator generator; - const generatedAnnotation = - '@javax.annotation.Generated("$defaultPluginPackageName")'; + const generatedAnnotation = '@javax.annotation.Generated("$defaultPluginPackageName")'; setUp(() { classDefinition = Class(name: 'Foobar', fields: []); - root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + root = Root(apis: [], classes: [classDefinition], enums: []); sink = StringBuffer(); generator = const JavaGenerator(); }); @@ -1637,27 +1341,14 @@ void main() { useGeneratedAnnotation: true, javaOut: '', ); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(generatedAnnotation)); }); test('without generated annotation', () { - const javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains(generatedAnnotation))); }); @@ -1691,10 +1382,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1724,15 +1412,9 @@ void main() { enums: [ Enum( name: 'enum', - documentationComments: [ - comments[count++], - unspacedComments[unspacedCount++], - ], + documentationComments: [comments[count++], unspacedComments[unspacedCount++]], members: [ - EnumMember( - name: 'one', - documentationComments: [comments[count++]], - ), + EnumMember(name: 'one', documentationComments: [comments[count++]]), EnumMember(name: 'two'), ], ), @@ -1741,20 +1423,12 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); for (final comment in comments) { // This regex finds the comment only between the open and close comment block expect( - RegExp( - r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', - dotAll: true, - ).hasMatch(code), + RegExp(r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', dotAll: true).hasMatch(code), true, ); } @@ -1815,33 +1489,18 @@ void main() { final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(' extends StandardMessageCodec')); }); test('creates api error class for custom errors', () { final Api api = AstHostApi(name: 'Api', methods: []); - final root = Root( - apis: [api], - classes: [], - enums: [], - containsHostApi: true, - ); + final root = Root(apis: [api], classes: [], enums: [], containsHostApi: true); final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class FlutterError')); }); @@ -1859,10 +1518,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1876,12 +1532,7 @@ void main() { final sink = StringBuffer(); const generator = JavaGenerator(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('createConnectionError(channelName)')); expect( @@ -1902,20 +1553,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); const generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('public boolean equals(Object o) {')); expect(code, contains('public int hashCode() {')); diff --git a/packages/pigeon/test/kotlin/proxy_api_test.dart b/packages/pigeon/test/kotlin/proxy_api_test.dart index e942a2c9bd06..6b02f1ad95ff 100644 --- a/packages/pigeon/test/kotlin/proxy_api_test.dart +++ b/packages/pigeon/test/kotlin/proxy_api_test.dart @@ -15,18 +15,13 @@ void main() { apis: [ AstProxyApi( name: 'Api', - kotlinOptions: const KotlinProxyApiOptions( - fullClassName: 'my.library.Api', - ), + kotlinOptions: const KotlinProxyApiOptions(fullClassName: 'my.library.Api'), constructors: [ Constructor( name: 'name', parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], @@ -44,17 +39,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), ), Method( name: 'doSomethingElse', @@ -62,17 +51,11 @@ void main() { isRequired: false, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), ), ], ), @@ -83,10 +66,7 @@ void main() { final sink = StringBuffer(); const generator = KotlinGenerator(); generator.generate( - const InternalKotlinOptions( - fileSpecificClassNameComponent: 'MyFile', - kotlinOut: '', - ), + const InternalKotlinOptions(fileSpecificClassNameComponent: 'MyFile', kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -123,10 +103,7 @@ void main() { ); // Constructors - expect( - collapsedCode, - contains(r'abstract fun name(someField: Long, input: Input)'), - ); + expect(collapsedCode, contains(r'abstract fun name(someField: Long, input: Input)')); expect( collapsedCode, contains( @@ -135,25 +112,15 @@ void main() { ); // Field - expect( - code, - contains( - 'abstract fun someField(pigeon_instance: my.library.Api): Long', - ), - ); + expect(code, contains('abstract fun someField(pigeon_instance: my.library.Api): Long')); // Dart -> Host method - expect( - collapsedCode, - contains('api.doSomething(pigeon_instanceArg, inputArg)'), - ); + expect(collapsedCode, contains('api.doSomething(pigeon_instanceArg, inputArg)')); // Host -> Dart method expect( code, - contains( - r'fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiApi?)', - ), + contains(r'fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiApi?)'), ); expect( code, @@ -199,10 +166,7 @@ void main() { ); final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains('fun pigeon_getPigeonApiApi2(): PigeonApiApi2'), - ); + expect(collapsedCode, contains('fun pigeon_getPigeonApiApi2(): PigeonApiApi2')); }); test('implements', () { @@ -220,11 +184,7 @@ void main() { fields: [], methods: [], interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ), + TypeDeclaration(baseName: api2.name, isNullable: false, associatedProxyApi: api2), }, ), api2, @@ -265,16 +225,8 @@ void main() { fields: [], methods: [], interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ), - TypeDeclaration( - baseName: api3.name, - isNullable: false, - associatedProxyApi: api3, - ), + TypeDeclaration(baseName: api2.name, isNullable: false, associatedProxyApi: api2), + TypeDeclaration(baseName: api3.name, isNullable: false, associatedProxyApi: api3), }, ), api2, @@ -303,9 +255,7 @@ void main() { apis: [ AstProxyApi( name: 'Api', - constructors: [ - Constructor(name: '', parameters: []), - ], + constructors: [Constructor(name: '', parameters: [])], fields: [], methods: [], ), @@ -329,10 +279,7 @@ void main() { 'abstract class PigeonApiApi(open val pigeonRegistrar: PigeonProxyApiRegistrar) ', ), ); - expect( - collapsedCode, - contains('abstract fun pigeon_defaultConstructor(): Api'), - ); + expect(collapsedCode, contains('abstract fun pigeon_defaultConstructor(): Api')); expect( collapsedCode, contains( @@ -361,10 +308,7 @@ void main() { name: 'name', parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -376,17 +320,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -398,10 +336,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -477,10 +412,7 @@ void main() { final sink = StringBuffer(); const generator = KotlinGenerator(); generator.generate( - const InternalKotlinOptions( - errorClassName: 'TestError', - kotlinOut: '', - ), + const InternalKotlinOptions(errorClassName: 'TestError', kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -496,48 +428,39 @@ void main() { ); }); - test( - 'host platform constructor calls new instance error for required callbacks', - () { - final root = Root( - apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [ - Method( - name: 'aCallbackMethod', - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [], - location: ApiLocation.flutter, - ), - ], - ), - ], - classes: [], - enums: [], - ); - final sink = StringBuffer(); - const generator = KotlinGenerator(); - generator.generate( - const InternalKotlinOptions( - errorClassName: 'TestError', - kotlinOut: '', + test('host platform constructor calls new instance error for required callbacks', () { + final root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [ + Method( + name: 'aCallbackMethod', + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [], + location: ApiLocation.flutter, + ), + ], ), - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final code = sink.toString(); - final String collapsedCode = _collapseNewlineAndIndentation(code); + ], + classes: [], + enums: [], + ); + final sink = StringBuffer(); + const generator = KotlinGenerator(); + generator.generate( + const InternalKotlinOptions(errorClassName: 'TestError', kotlinOut: ''), + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains(r'Result.failure( TestError("new-instance-error"'), - ); - }, - ); + expect(collapsedCode, contains(r'Result.failure( TestError("new-instance-error"')); + }); }); group('Fields', () { @@ -550,15 +473,10 @@ void main() { apis: [ AstProxyApi( name: 'Api', - constructors: [ - Constructor(name: 'name', parameters: []), - ], + constructors: [Constructor(name: 'name', parameters: [])], fields: [ ApiField( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), ApiField( @@ -570,17 +488,11 @@ void main() { name: 'enumType', ), ApiField( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), ApiField( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), ApiField( @@ -592,10 +504,7 @@ void main() { name: 'nullableEnumType', ), ApiField( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -645,36 +554,12 @@ void main() { 'nullableEnumTypeArg, nullableProxyApiTypeArg))', ), ); - expect( - code, - contains(r'abstract fun validType(pigeon_instance: Api): Long'), - ); - expect( - code, - contains(r'abstract fun enumType(pigeon_instance: Api): AnEnum'), - ); - expect( - code, - contains(r'abstract fun proxyApiType(pigeon_instance: Api): Api2'), - ); - expect( - code, - contains( - r'abstract fun nullableValidType(pigeon_instance: Api): Long?', - ), - ); - expect( - code, - contains( - r'abstract fun nullableEnumType(pigeon_instance: Api): AnEnum?', - ), - ); - expect( - code, - contains( - r'abstract fun nullableProxyApiType(pigeon_instance: Api): Api2?', - ), - ); + expect(code, contains(r'abstract fun validType(pigeon_instance: Api): Long')); + expect(code, contains(r'abstract fun enumType(pigeon_instance: Api): AnEnum')); + expect(code, contains(r'abstract fun proxyApiType(pigeon_instance: Api): Api2')); + expect(code, contains(r'abstract fun nullableValidType(pigeon_instance: Api): Long?')); + expect(code, contains(r'abstract fun nullableEnumType(pigeon_instance: Api): AnEnum?')); + expect(code, contains(r'abstract fun nullableProxyApiType(pigeon_instance: Api): Api2?')); }); test('attached field', () { @@ -716,10 +601,7 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final code = sink.toString(); - expect( - code, - contains(r'abstract fun aField(pigeon_instance: Api): Api2'), - ); + expect(code, contains(r'abstract fun aField(pigeon_instance: Api): Api2')); expect( code, contains( @@ -796,10 +678,7 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -811,17 +690,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -833,10 +706,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -936,10 +806,7 @@ void main() { location: ApiLocation.flutter, parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -951,17 +818,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -973,10 +834,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -1019,57 +877,41 @@ void main() { }); group('InstanceManager', () { - test( - 'InstanceManager passes runnable field and not a new runnable instance', - () { - final root = Root( - apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [], - ), - ], - classes: [], - enums: [], - ); - final sink = StringBuffer(); - const generator = KotlinGenerator(); - generator.generate( - const InternalKotlinOptions(kotlinOut: ''), - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final code = sink.toString(); - final String collapsedCode = _collapseNewlineAndIndentation(code); - - expect( - code, - contains( - 'handler.removeCallbacks(releaseAllFinalizedInstancesRunnable)', - ), - ); - expect( - code, - contains( - 'handler.postDelayed(releaseAllFinalizedInstancesRunnable', + test('InstanceManager passes runnable field and not a new runnable instance', () { + final root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [], ), - ); + ], + classes: [], + enums: [], + ); + final sink = StringBuffer(); + const generator = KotlinGenerator(); + generator.generate( + const InternalKotlinOptions(kotlinOut: ''), + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains( - 'private val releaseAllFinalizedInstancesRunnable = Runnable { this.releaseAllFinalizedInstances() }', - ), - ); - expect( - 'this.releaseAllFinalizedInstances()'.allMatches(code).length, - 1, - ); - }, - ); + expect(code, contains('handler.removeCallbacks(releaseAllFinalizedInstancesRunnable)')); + expect(code, contains('handler.postDelayed(releaseAllFinalizedInstancesRunnable')); + + expect( + collapsedCode, + contains( + 'private val releaseAllFinalizedInstancesRunnable = Runnable { this.releaseAllFinalizedInstances() }', + ), + ); + expect('this.releaseAllFinalizedInstances()'.allMatches(code).length, 1); + }); test('InstanceManager.getInstance specifies nonnull type', () { final root = Root( @@ -1095,10 +937,7 @@ void main() { final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains('fun getInstance(identifier: Long): T?'), - ); + expect(collapsedCode, contains('fun getInstance(identifier: Long): T?')); }); }); }); diff --git a/packages/pigeon/test/kotlin_generator_test.dart b/packages/pigeon/test/kotlin_generator_test.dart index fe9600e81bc1..726f6e69dc03 100644 --- a/packages/pigeon/test/kotlin_generator_test.dart +++ b/packages/pigeon/test/kotlin_generator_test.dart @@ -34,20 +34,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('data class Foobar (')); expect(code, contains('val field1: Long? = null')); @@ -68,12 +59,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('enum class Foobar(val raw: Int) {')); expect(code, contains('ONE(0)')); @@ -89,18 +75,11 @@ void main() { fields: [ NamedType( name: 'field1', - type: TypeDeclaration( - baseName: 'Foo', - isNullable: false, - associatedEnum: emptyEnum, - ), + type: TypeDeclaration(baseName: 'Foo', isNullable: false, associatedEnum: emptyEnum), ), NamedType( name: 'field2', - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), ), ], ), @@ -118,12 +97,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('enum class Foo(val raw: Int) {')); expect(code, contains('data class Bar (')); @@ -174,12 +148,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('enum class Foo(val raw: Int) {')); expect(code, contains('Foo.ofRaw(it.toInt())')); @@ -238,12 +207,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('interface Api')); expect(code, contains('fun doSomething(input: Input): Output')); @@ -292,45 +256,27 @@ void main() { name: 'aInt', ), NamedType( - type: const TypeDeclaration( - baseName: 'double', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'double', isNullable: false), name: 'aDouble', ), NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'aString', ), NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Uint8List', isNullable: true), name: 'aUint8List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Int32List', isNullable: false), name: 'aInt32List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Int64List', isNullable: false), name: 'aInt64List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Float64List', isNullable: false), name: 'aFloat64List', ), NamedType( @@ -350,31 +296,19 @@ void main() { name: 'aNullableString', ), NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Uint8List', isNullable: true), name: 'aNullableUint8List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int32List', isNullable: true), name: 'aNullableInt32List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int64List', isNullable: true), name: 'aNullableInt64List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Float64List', isNullable: true), name: 'aNullableFloat64List', ), ], @@ -387,12 +321,7 @@ void main() { const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('val aBool: Boolean')); expect(code, contains('val aInt: Long')); @@ -465,12 +394,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -521,12 +445,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(matches('.*doSomething(.*) ->'))); expect(code, matches('doSomething(.*)')); @@ -572,12 +491,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('callback: (Result) -> Unit')); expect(code, contains('callback(Result.success(Unit))')); @@ -620,12 +534,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun doSomething(): Output')); expect(code, contains('listOf(api.doSomething())')); @@ -668,17 +577,9 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('fun doSomething(callback: (Result) -> Unit)'), - ); + expect(code, contains('fun doSomething(callback: (Result) -> Unit)')); expect(code, contains('channel.send(null)')); }); @@ -701,12 +602,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: List? = null')); @@ -731,12 +627,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: Map? = null')); @@ -747,11 +638,7 @@ void main() { name: 'Outer', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Nested', - associatedClass: emptyClass, - isNullable: true, - ), + type: TypeDeclaration(baseName: 'Nested', associatedClass: emptyClass, isNullable: true), name: 'nested', ), ], @@ -773,12 +660,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('data class Outer')); expect(code, contains('data class Nested')); @@ -842,12 +724,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('interface Api')); expect(code, contains('api.doSomething(argArg) {')); @@ -908,12 +785,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Api')); expect(code, matches('fun doSomething.*Input.*callback.*Output.*Unit')); @@ -940,20 +812,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [anEnum], - ); + final root = Root(apis: [], classes: [classDefinition], enums: [anEnum]); final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('enum class SampleEnum(val raw: Int)')); expect(code, contains('SAMPLE_VERSION(0)')); @@ -972,12 +835,7 @@ void main() { kotlinOut: '', ); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, startsWith('// hello world')); }); @@ -999,12 +857,7 @@ void main() { kotlinOut: '', useGeneratedAnnotation: true, ); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(kotlinGeneratedAnnotation)); }); @@ -1014,12 +867,7 @@ void main() { copyrightHeader: makeIterable('hello world'), kotlinOut: '', ); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains(kotlinGeneratedAnnotation))); }); @@ -1033,28 +881,17 @@ void main() { type: const TypeDeclaration( baseName: 'List', isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true), - ], + typeArguments: [TypeDeclaration(baseName: 'int', isNullable: true)], ), name: 'field1', ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: List')); @@ -1077,20 +914,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: Map')); @@ -1128,12 +956,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun doit(arg: List')); }); @@ -1170,12 +993,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun doit(argArg: List')); }); @@ -1207,12 +1025,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun doit(): List')); expect(code, contains('listOf(api.doit())')); @@ -1246,12 +1059,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun doit(callback: (Result>) -> Unit)')); expect(code, contains('val output = it[0] as List')); @@ -1270,23 +1078,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -1297,12 +1096,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun add(x: Long, y: Long): Long')); expect(code, contains('val args = message as List')); @@ -1322,23 +1116,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), Parameter( name: 'y', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -1349,21 +1134,11 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('val channel = BasicMessageChannel')); expect(code, contains('callback(Result.success(output))')); - expect( - code, - contains( - 'fun add(xArg: Long, yArg: Long, callback: (Result) -> Unit)', - ), - ); + expect(code, contains('fun add(xArg: Long, yArg: Long, callback: (Result) -> Unit)')); expect(code, contains('channel.send(listOf(xArg, yArg)) {')); }); @@ -1376,10 +1151,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -1391,12 +1163,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun doit(): Long?')); }); @@ -1410,10 +1177,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), isAsynchronous: true, parameters: [], ), @@ -1426,12 +1190,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('fun doit(callback: (Result) -> Unit')); }); @@ -1449,10 +1208,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1465,12 +1221,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('val fooArg = args[0]')); }); @@ -1488,10 +1239,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1504,17 +1252,9 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('fun doit(fooArg: Long?, callback: (Result) -> Unit)'), - ); + expect(code, contains('fun doit(fooArg: Long?, callback: (Result) -> Unit)')); }); test('nonnull fields', () { @@ -1546,10 +1286,7 @@ void main() { name: 'Input', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'input', ), ], @@ -1560,12 +1297,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('val input: String\n')); }); @@ -1598,10 +1330,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1631,15 +1360,9 @@ void main() { enums: [ Enum( name: 'enum', - documentationComments: [ - comments[count++], - unspacedComments[unspacedCount++], - ], + documentationComments: [comments[count++], unspacedComments[unspacedCount++]], members: [ - EnumMember( - name: 'one', - documentationComments: [comments[count++]], - ), + EnumMember(name: 'one', documentationComments: [comments[count++]]), EnumMember(name: 'two'), ], ), @@ -1648,20 +1371,12 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); for (final comment in comments) { // This regex finds the comment only between the open and close comment block expect( - RegExp( - r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', - dotAll: true, - ).hasMatch(code), + RegExp(r'(?<=\/\*\*.*?)' + comment + r'(?=.*?\*\/)', dotAll: true).hasMatch(code), true, ); } @@ -1722,12 +1437,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(' : StandardMessageCodec() ')); }); @@ -1740,24 +1450,11 @@ void main() { parameters: [], ); final api = AstHostApi(name: 'SomeApi', methods: [method]); - final root = Root( - apis: [api], - classes: [], - enums: [], - containsHostApi: true, - ); + final root = Root(apis: [api], classes: [], enums: [], containsHostApi: true); final sink = StringBuffer(); - const kotlinOptions = InternalKotlinOptions( - errorClassName: 'SomeError', - kotlinOut: '', - ); + const kotlinOptions = InternalKotlinOptions(errorClassName: 'SomeError', kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class SomeError')); expect(code, contains('if (exception is SomeError)')); @@ -1779,10 +1476,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1796,12 +1490,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1811,9 +1500,7 @@ void main() { ); expect( code, - contains( - 'callback(Result.failure(PigeonUtils.createConnectionError(channelName)))', - ), + contains('callback(Result.failure(PigeonUtils.createConnectionError(channelName)))'), ); }); @@ -1830,10 +1517,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1846,12 +1530,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('FlutterError')); }); @@ -1869,10 +1548,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1885,12 +1561,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('FlutterError')); }); @@ -1908,10 +1579,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1923,17 +1591,9 @@ void main() { ); final sink = StringBuffer(); const errorClassName = 'FooError'; - const kotlinOptions = InternalKotlinOptions( - errorClassName: errorClassName, - kotlinOut: '', - ); + const kotlinOptions = InternalKotlinOptions(errorClassName: errorClassName, kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(errorClassName)); expect(code, isNot(contains('FlutterError'))); @@ -1952,10 +1612,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1967,17 +1624,9 @@ void main() { ); final sink = StringBuffer(); const errorClassName = 'FooError'; - const kotlinOptions = InternalKotlinOptions( - errorClassName: errorClassName, - kotlinOut: '', - ); + const kotlinOptions = InternalKotlinOptions(errorClassName: errorClassName, kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(errorClassName)); expect(code, isNot(contains('FlutterError'))); @@ -1996,10 +1645,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -2012,12 +1658,7 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(': RuntimeException()')); }); @@ -2035,10 +1676,7 @@ void main() { parameters: [ Parameter( name: 'bar', - type: const TypeDeclaration( - baseName: 'Bar', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Bar', isNullable: false), ), ], ), @@ -2074,17 +1712,9 @@ void main() { final sink = StringBuffer(); const errorClassName = 'FooError'; - const kotlinOptions = InternalKotlinOptions( - errorClassName: errorClassName, - kotlinOut: '', - ); + const kotlinOptions = InternalKotlinOptions(errorClassName: errorClassName, kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); @@ -2120,20 +1750,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('override fun equals(other: Any?): Boolean {')); expect(code, contains('override fun hashCode(): Int {')); @@ -2153,20 +1774,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); const generator = KotlinGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('override fun equals(other: Any?): Boolean {')); expect(code, contains('override fun hashCode(): Int {')); diff --git a/packages/pigeon/test/objc_generator_test.dart b/packages/pigeon/test/objc_generator_test.dart index fb18833f77bc..19e916230681 100644 --- a/packages/pigeon/test/objc_generator_test.dart +++ b/packages/pigeon/test/objc_generator_test.dart @@ -52,12 +52,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, matches('@property.*NSString.*field1')); @@ -89,12 +84,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('#import "foo.h"')); expect(code, contains('@implementation Foobar')); @@ -124,12 +114,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('typedef NS_ENUM(NSUInteger, Enum1) {')); expect(code, contains(' Enum1One = 0,')); @@ -161,12 +146,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('typedef NS_ENUM(NSUInteger, PREFIXEnum1) {')); expect(code, contains(' PREFIXEnum1One = 0,')); @@ -185,11 +165,7 @@ void main() { name: 'field1', ), NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), + type: TypeDeclaration(baseName: 'Enum1', associatedEnum: emptyEnum, isNullable: true), name: 'enum1', ), ], @@ -215,12 +191,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('#import "foo.h"')); expect(code, contains('@implementation Foobar')); @@ -280,12 +251,7 @@ void main() { fileType: FileType.header, languageOptions: options, ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('typedef NS_ENUM(NSUInteger, ACFoo)')); expect(code, contains(':(ACFoo)foo error:')); @@ -296,12 +262,7 @@ void main() { fileType: FileType.source, languageOptions: options, ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -371,11 +332,7 @@ void main() { name: 'field1', ), NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), + type: TypeDeclaration(baseName: 'Enum1', associatedEnum: emptyEnum, isNullable: true), name: 'enum1', ), ], @@ -401,17 +358,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('@property(nonatomic, strong, nullable) Enum1Box * enum1;'), - ); + expect(code, contains('@property(nonatomic, strong, nullable) Enum1Box * enum1;')); }); test('gen one api header', () { @@ -474,12 +423,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Input')); expect(code, contains('@interface Output')); @@ -549,23 +493,13 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('#import "foo.h"')); expect(code, contains('@implementation Input')); expect(code, contains('@implementation Output')); expect(code, contains('SetUpApi(')); - expect( - code, - contains( - 'NSCAssert([api respondsToSelector:@selector(doSomething:error:)', - ), - ); + expect(code, contains('NSCAssert([api respondsToSelector:@selector(doSomething:error:)')); }); test('all the simple datatypes header', () { @@ -592,31 +526,19 @@ void main() { name: 'aString', ), NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Uint8List', isNullable: true), name: 'aUint8List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int32List', isNullable: true), name: 'aInt32List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int64List', isNullable: true), name: 'aInt64List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Float64List', isNullable: true), name: 'aFloat64List', ), ], @@ -635,12 +557,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, contains('@class FlutterStandardTypedData;')); @@ -648,22 +565,10 @@ void main() { expect(code, matches('@property.*strong.*NSNumber.*aInt')); expect(code, matches('@property.*strong.*NSNumber.*aDouble')); expect(code, matches('@property.*copy.*NSString.*aString')); - expect( - code, - matches('@property.*strong.*FlutterStandardTypedData.*aUint8List'), - ); - expect( - code, - matches('@property.*strong.*FlutterStandardTypedData.*aInt32List'), - ); - expect( - code, - matches('@property.*strong.*FlutterStandardTypedData.*Int64List'), - ); - expect( - code, - matches('@property.*strong.*FlutterStandardTypedData.*Float64List'), - ); + expect(code, matches('@property.*strong.*FlutterStandardTypedData.*aUint8List')); + expect(code, matches('@property.*strong.*FlutterStandardTypedData.*aInt32List')); + expect(code, matches('@property.*strong.*FlutterStandardTypedData.*Int64List')); + expect(code, matches('@property.*strong.*FlutterStandardTypedData.*Float64List')); }); test('bool source', () { @@ -693,18 +598,10 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@implementation Foobar')); - expect( - code, - contains('pigeonResult.aBool = GetNullableObjectAtIndex(list, 0);'), - ); + expect(code, contains('pigeonResult.aBool = GetNullableObjectAtIndex(list, 0);')); }); test('nested class header', () { @@ -746,17 +643,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('@property(nonatomic, strong, nullable) Input * nested;'), - ); + expect(code, contains('@property(nonatomic, strong, nullable) Input * nested;')); }); test('nested class source', () { @@ -798,17 +687,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('pigeonResult.nested = GetNullableObjectAtIndex(list, 0);'), - ); + expect(code, contains('pigeonResult.nested = GetNullableObjectAtIndex(list, 0);')); }); test('prefix class header', () { @@ -838,12 +719,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface ABCFoobar')); }); @@ -875,12 +751,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@implementation ABCFoobar')); }); @@ -950,12 +821,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches('property.*ABCInput')); expect(code, matches('ABCNested.*doSomething.*ABCInput')); @@ -1027,12 +893,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('ABCInput fromList')); expect(code, matches(r'ABCInput.*=.*args.*0.*\;')); @@ -1099,20 +960,10 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Api : NSObject')); - expect( - code, - contains( - 'initWithBinaryMessenger:(id)binaryMessenger;', - ), - ); + expect(code, contains('initWithBinaryMessenger:(id)binaryMessenger;')); expect(code, matches('void.*doSomething.*Input.*Output')); }); @@ -1176,12 +1027,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@implementation Api')); expect(code, matches('void.*doSomething.*Input.*Output.*{')); @@ -1235,12 +1081,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('(void)doSomething:')); }); @@ -1293,12 +1134,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(matches('=.*doSomething'))); expect(code, matches('[.*doSomething:.*]')); @@ -1353,12 +1189,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('completion:(void (^)(FlutterError *_Nullable))')); }); @@ -1411,12 +1242,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('completion:(void (^)(FlutterError *_Nullable))')); expect(code, contains('completion(nil)')); @@ -1465,12 +1291,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches('ABCOutput.*doSomethingWithError:[(]FlutterError')); }); @@ -1518,12 +1339,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches('output.*=.*api doSomethingWithError:&error')); }); @@ -1571,12 +1387,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1629,12 +1440,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1671,12 +1477,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, matches('@property.*NSArray.*field1')); @@ -1708,12 +1509,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, matches('@property.*NSDictionary.*field1')); @@ -1752,20 +1548,10 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Foobar')); - expect( - code, - contains( - '@property(nonatomic, copy, nullable) NSDictionary *', - ), - ); + expect(code, contains('@property(nonatomic, copy, nullable) NSDictionary *')); }); test('gen map argument with object', () { @@ -1808,12 +1594,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('(NSDictionary *)foo')); }); @@ -1876,12 +1657,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1953,12 +1729,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -2012,12 +1783,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -2057,18 +1823,11 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - '(void)doSomethingWithCompletion:(void (^)(FlutterError *_Nullable))completion', - ), + contains('(void)doSomethingWithCompletion:(void (^)(FlutterError *_Nullable))completion'), ); }); @@ -2134,12 +1893,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -2207,18 +1961,11 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - '[api doSomethingFoo:arg_foo completion:^(FlutterError *_Nullable error) {', - ), + contains('[api doSomethingFoo:arg_foo completion:^(FlutterError *_Nullable error) {'), ); }); @@ -2252,19 +1999,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains( - '[api doSomethingWithCompletion:^(FlutterError *_Nullable error) {', - ), - ); + expect(code, contains('[api doSomethingWithCompletion:^(FlutterError *_Nullable error) {')); }); test('async output(void) HostApi source', () { @@ -2311,12 +2048,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -2344,12 +2076,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, startsWith('// hello world')); }); @@ -2368,12 +2095,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, startsWith('// hello world')); }); @@ -2392,12 +2114,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@import')); expect(code, isNot(contains('#import <'))); @@ -2411,19 +2128,13 @@ void main() { type: const TypeDeclaration( baseName: 'List', isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true), - ], + typeArguments: [TypeDeclaration(baseName: 'int', isNullable: true)], ), name: 'field1', ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const generator = ObjcGenerator(); final generatorOptions = OutputFileOptions( @@ -2435,12 +2146,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('NSArray * field1')); }); @@ -2486,12 +2192,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doitArg:(NSArray *)arg')); } @@ -2507,19 +2208,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains( - 'NSArray *arg_arg = GetNullableObjectAtIndex(args, 0)', - ), - ); + expect(code, contains('NSArray *arg_arg = GetNullableObjectAtIndex(args, 0)')); } }); @@ -2564,12 +2255,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doitArg:(NSArray *)arg')); } @@ -2585,12 +2271,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doitArg:(NSArray *)arg')); } @@ -2643,12 +2324,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doitArg:(NSArray *> *)arg')); } @@ -2690,17 +2366,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('- (nullable NSArray *)doitWithError:'), - ); + expect(code, contains('- (nullable NSArray *)doitWithError:')); } { final sink = StringBuffer(); @@ -2714,12 +2382,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('NSArray *output =')); } @@ -2761,17 +2424,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('doitWithCompletion:(void (^)(NSArray *'), - ); + expect(code, contains('doitWithCompletion:(void (^)(NSArray *')); } { final sink = StringBuffer(); @@ -2785,17 +2440,9 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('doitWithCompletion:(void (^)(NSArray *'), - ); + expect(code, contains('doitWithCompletion:(void (^)(NSArray *')); } }); @@ -2811,23 +2458,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -2847,12 +2485,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -2873,30 +2506,12 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('NSArray *args = message;')); - expect( - code, - contains( - 'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];', - ), - ); - expect( - code, - contains( - 'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];', - ), - ); - expect( - code, - contains('NSNumber *output = [api addX:arg_x y:arg_y error:&error]'), - ); + expect(code, contains('NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];')); + expect(code, contains('NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];')); + expect(code, contains('NSNumber *output = [api addX:arg_x y:arg_y error:&error]')); } }); @@ -2912,23 +2527,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), isAsynchronous: true, ), ], @@ -2949,12 +2555,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -2975,26 +2576,11 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('NSArray *args = message;')); - expect( - code, - contains( - 'NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];', - ), - ); - expect( - code, - contains( - 'NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];', - ), - ); + expect(code, contains('NSInteger arg_x = [GetNullableObjectAtIndex(args, 0) integerValue];')); + expect(code, contains('NSInteger arg_y = [GetNullableObjectAtIndex(args, 1) integerValue];')); expect(code, contains('[api addX:arg_x y:arg_y completion:')); } }); @@ -3011,23 +2597,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -3047,12 +2624,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -3073,12 +2645,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -3086,10 +2653,7 @@ void main() { '- (void)addX:(NSInteger)arg_x y:(NSInteger)arg_y completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion {', ), ); - expect( - code, - contains('[channel sendMessage:@[@(arg_x), @(arg_y)] reply:'), - ); + expect(code, contains('[channel sendMessage:@[@(arg_x), @(arg_y)] reply:')); } }); @@ -3105,24 +2669,15 @@ void main() { objcSelector: 'divideValue:by:', parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'x', ), Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'y', ), ], - returnType: const TypeDeclaration( - baseName: 'double', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'double', isNullable: false), ), ], ), @@ -3135,24 +2690,15 @@ void main() { objcSelector: 'divideValue:by:', parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'x', ), Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'y', ), ], - returnType: const TypeDeclaration( - baseName: 'double', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'double', isNullable: false), ), ], ), @@ -3176,12 +2722,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - divideRoot, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches('divideValue:.*by:.*error.*;')); } @@ -3197,12 +2738,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - divideRoot, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches('divideValue:.*by:.*error.*;')); } @@ -3222,12 +2758,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - divideRoot, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches('divideValue:.*by:.*completion.*;')); } @@ -3243,12 +2774,7 @@ void main() { objcSourceOut: '', ), ); - generator.generate( - generatorOptions, - divideRoot, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches('divideValue:.*by:.*completion.*{')); } @@ -3262,10 +2788,7 @@ void main() { name: 'Foobar', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'field1', ), ], @@ -3283,12 +2806,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, contains('@property(nonatomic, copy) NSString * field1')); @@ -3303,10 +2821,7 @@ void main() { Method( name: 'doit', location: ApiLocation.flutter, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -3325,18 +2840,11 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - matches( - r'doitWithCompletion.*void.*NSNumber \*_Nullable.*FlutterError.*completion;', - ), + matches(r'doitWithCompletion.*void.*NSNumber \*_Nullable.*FlutterError.*completion;'), ); }); @@ -3349,10 +2857,7 @@ void main() { Method( name: 'doit', location: ApiLocation.flutter, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -3371,12 +2876,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches(r'doitWithCompletion.*NSNumber \*_Nullable')); }); @@ -3390,10 +2890,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -3412,12 +2909,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, matches(r'nullable NSNumber.*doitWithError')); }); @@ -3435,10 +2927,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -3459,12 +2948,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doitFoo:(nullable NSNumber *)foo')); } @@ -3479,17 +2963,9 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('NSNumber *arg_foo = GetNullableObjectAtIndex(args, 0);'), - ); + expect(code, contains('NSNumber *arg_foo = GetNullableObjectAtIndex(args, 0);')); } }); @@ -3506,10 +2982,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -3530,12 +3003,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('doitFoo:(nullable NSNumber *)foo')); } @@ -3550,12 +3018,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('- (void)doitFoo:(nullable NSNumber *)arg_foo')); } @@ -3570,10 +3033,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], taskQueueType: TaskQueueType.serialBackgroundThread, ), @@ -3593,12 +3053,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -3637,10 +3092,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -3670,15 +3122,9 @@ void main() { enums: [ Enum( name: 'enum', - documentationComments: [ - comments[count++], - unspacedComments[unspacedCount++], - ], + documentationComments: [comments[count++], unspacedComments[unspacedCount++]], members: [ - EnumMember( - name: 'one', - documentationComments: [comments[count++]], - ), + EnumMember(name: 'one', documentationComments: [comments[count++]]), EnumMember(name: 'two'), ], ), @@ -3694,12 +3140,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); for (final comment in comments) { expect(code, contains('///$comment')); @@ -3768,12 +3209,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(' : FlutterStandardReader')); }); @@ -3791,10 +3227,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -3815,12 +3248,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -3872,12 +3300,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); @@ -3924,12 +3347,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); @@ -3943,11 +3361,7 @@ void main() { EnumMember(name: 'two'), ], ); - final enumType = TypeDeclaration( - baseName: 'Enum1', - isNullable: false, - associatedEnum: enum1, - ); + final enumType = TypeDeclaration(baseName: 'Enum1', isNullable: false, associatedEnum: enum1); final root = Root( apis: [ AstHostApi( @@ -3977,12 +3391,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); @@ -3996,11 +3405,7 @@ void main() { EnumMember(name: 'two'), ], ); - final enumType = TypeDeclaration( - baseName: 'Enum1', - isNullable: false, - associatedEnum: enum1, - ); + final enumType = TypeDeclaration(baseName: 'Enum1', isNullable: false, associatedEnum: enum1); final root = Root( apis: [ AstHostApi( @@ -4030,12 +3435,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); @@ -4069,12 +3469,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); } { final sink = StringBuffer(); @@ -4088,12 +3483,7 @@ void main() { headerIncludePath: '', ), ); - generator.generate( - generatorOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('- (BOOL)isEqual:(id)object {')); expect(code, contains('- (NSUInteger)hash {')); diff --git a/packages/pigeon/test/pigeon_lib_test.dart b/packages/pigeon/test/pigeon_lib_test.dart index 7b2d3b78a1c7..e318fe5d8f7f 100644 --- a/packages/pigeon/test/pigeon_lib_test.dart +++ b/packages/pigeon/test/pigeon_lib_test.dart @@ -22,12 +22,7 @@ class _ValidatorGeneratorAdapter implements GeneratorAdapter { final IOSink? sink; @override - void generate( - StringSink sink, - InternalPigeonOptions options, - Root root, - FileType fileType, - ) {} + void generate(StringSink sink, InternalPigeonOptions options, Root root, FileType fileType) {} @override IOSink? shouldGenerate(InternalPigeonOptions options, FileType _) => sink; @@ -66,120 +61,77 @@ void main() { } test('parse args - input', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--input', - 'foo.dart', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--input', 'foo.dart']); expect(opts.input, equals('foo.dart')); }); test('parse args - dart_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--dart_out', - 'foo.dart', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--dart_out', 'foo.dart']); expect(opts.dartOut, equals('foo.dart')); }); test('parse args - java_package', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--java_package', - 'com.google.foo', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--java_package', 'com.google.foo']); expect(opts.javaOptions?.package, equals('com.google.foo')); }); test('parse args - input', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--java_out', - 'foo.java', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--java_out', 'foo.java']); expect(opts.javaOut, equals('foo.java')); }); test('parse args - objc_header_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--objc_header_out', - 'foo.h', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--objc_header_out', 'foo.h']); expect(opts.objcHeaderOut, equals('foo.h')); }); test('parse args - objc_source_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--objc_source_out', - 'foo.m', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--objc_source_out', 'foo.m']); expect(opts.objcSourceOut, equals('foo.m')); }); test('parse args - swift_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--swift_out', - 'Foo.swift', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--swift_out', 'Foo.swift']); expect(opts.swiftOut, equals('Foo.swift')); }); test('parse args - kotlin_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--kotlin_out', - 'Foo.kt', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--kotlin_out', 'Foo.kt']); expect(opts.kotlinOut, equals('Foo.kt')); }); test('parse args - kotlin_package', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--kotlin_package', - 'com.google.foo', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--kotlin_package', 'com.google.foo']); expect(opts.kotlinOptions?.package, equals('com.google.foo')); }); test('parse args - kotlin_use_generated_annotation', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--kotlin_use_generated_annotation', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--kotlin_use_generated_annotation']); expect(opts.kotlinOptions!.useGeneratedAnnotation, isTrue); }); test('parse args - cpp_header_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--cpp_header_out', - 'foo.h', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--cpp_header_out', 'foo.h']); expect(opts.cppHeaderOut, equals('foo.h')); }); test('parse args - java_use_generated_annotation', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--java_use_generated_annotation', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--java_use_generated_annotation']); expect(opts.javaOptions!.useGeneratedAnnotation, isTrue); }); test('parse args - cpp_source_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--cpp_source_out', - 'foo.cpp', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--cpp_source_out', 'foo.cpp']); expect(opts.cppSourceOut, equals('foo.cpp')); }); test('parse args - ast_out', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--ast_out', - 'stdout', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--ast_out', 'stdout']); expect(opts.astOut, equals('stdout')); }); test('parse args - base_path', () { - final PigeonOptions opts = Pigeon.parseArgs([ - '--base_path', - './foo/', - ]); + final PigeonOptions opts = Pigeon.parseArgs(['--base_path', './foo/']); expect(opts.basePath, equals('./foo/')); }); @@ -211,10 +163,7 @@ abstract class Api1 { expect(root.apis[0].methods, hasLength(1)); expect(root.apis[0].methods[0].name, equals('doit')); expect(root.apis[0].methods[0].parameters[0].name, equals('input')); - expect( - root.apis[0].methods[0].parameters[0].type.baseName, - equals('Input1'), - ); + expect(root.apis[0].methods[0].parameters[0].type.baseName, equals('Input1')); expect(root.apis[0].methods[0].returnType.baseName, equals('Output1')); Class? input; @@ -369,9 +318,7 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors, isEmpty); expect(results.root.classes, hasLength(2)); - final Class nested = results.root.classes.firstWhere( - (Class x) => x.name == 'Nested', - ); + final Class nested = results.root.classes.firstWhere((Class x) => x.name == 'Nested'); expect(nested.fields, hasLength(1)); expect(nested.fields[0].type.baseName, equals('Input1')); expect(nested.fields[0].type.isNullable, isTrue); @@ -434,10 +381,7 @@ abstract class VoidArgApi { expect(results.root.apis, hasLength(1)); expect(results.root.apis[0].methods, hasLength(1)); expect(results.root.apis[0].name, equals('VoidArgApi')); - expect( - results.root.apis[0].methods[0].returnType.baseName, - equals('Output1'), - ); + expect(results.root.apis[0].methods[0].returnType.baseName, equals('Output1')); expect(results.root.apis[0].methods[0].parameters.isEmpty, isTrue); }); @@ -479,27 +423,19 @@ abstract class NestorApi { final ParseResults results = parseSource(code); expect(results.errors, isEmpty); expect(results.root.apis, hasLength(1)); - final List classNames = results.root.classes - .map((Class x) => x.name) - .toList(); + final List classNames = results.root.classes.map((Class x) => x.name).toList(); expect(classNames, hasLength(2)); expect(classNames, containsAll(['Nestor', 'OnlyVisibleFromNesting'])); }); test('copyright flag', () { - final PigeonOptions results = Pigeon.parseArgs([ - '--copyright_header', - 'foobar.txt', - ]); + final PigeonOptions results = Pigeon.parseArgs(['--copyright_header', 'foobar.txt']); expect(results.copyrightHeader, 'foobar.txt'); }); test('Dart generator copyright flag', () { final root = Root(apis: [], classes: [], enums: []); - const options = PigeonOptions( - copyrightHeader: './copyright_header.txt', - dartOut: '', - ); + const options = PigeonOptions(copyrightHeader: './copyright_header.txt', dartOut: ''); const dartGeneratorAdapter = DartGeneratorAdapter(); final buffer = StringBuffer(); dartGeneratorAdapter.generate( @@ -513,10 +449,7 @@ abstract class NestorApi { test('Java generator copyright flag', () { final root = Root(apis: [], classes: [], enums: []); - const options = PigeonOptions( - javaOut: 'Foo.java', - copyrightHeader: './copyright_header.txt', - ); + const options = PigeonOptions(javaOut: 'Foo.java', copyrightHeader: './copyright_header.txt'); const javaGeneratorAdapter = JavaGeneratorAdapter(); final buffer = StringBuffer(); javaGeneratorAdapter.generate( @@ -566,10 +499,7 @@ abstract class NestorApi { test('Swift generator copyright flag', () { final root = Root(apis: [], classes: [], enums: []); - const options = PigeonOptions( - swiftOut: 'Foo.swift', - copyrightHeader: './copyright_header.txt', - ); + const options = PigeonOptions(swiftOut: 'Foo.swift', copyrightHeader: './copyright_header.txt'); const swiftGeneratorAdapter = SwiftGeneratorAdapter(); final buffer = StringBuffer(); swiftGeneratorAdapter.generate( @@ -664,9 +594,7 @@ abstract class NotificationsHostApi { final ParseResults results = parseSource(code); expect(results.errors, isEmpty); expect(results.root.classes, hasLength(2)); - final Class foo = results.root.classes.firstWhere( - (Class aClass) => aClass.name == 'Foo', - ); + final Class foo = results.root.classes.firstWhere((Class aClass) => aClass.name == 'Foo'); expect(foo.fields, hasLength(1)); expect(foo.fields[0].type.baseName, 'Bar'); }); @@ -967,20 +895,8 @@ abstract class Api { '''; final ParseResults parseResult = parseSource(code); expect(parseResult.root.apis[0].methods[0].returnType.baseName, 'List'); - expect( - parseResult.root.apis[0].methods[0].returnType.typeArguments[0].baseName, - 'double', - ); - expect( - parseResult - .root - .apis[0] - .methods[0] - .returnType - .typeArguments[0] - .isNullable, - isTrue, - ); + expect(parseResult.root.apis[0].methods[0].returnType.typeArguments[0].baseName, 'double'); + expect(parseResult.root.apis[0].methods[0].returnType.typeArguments[0].isNullable, isTrue); }); test('argument generics', () { @@ -991,30 +907,13 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); + expect(parseResult.root.apis[0].methods[0].parameters[1].type.baseName, 'List'); expect( - parseResult.root.apis[0].methods[0].parameters[1].type.baseName, - 'List', - ); - expect( - parseResult - .root - .apis[0] - .methods[0] - .parameters[1] - .type - .typeArguments[0] - .baseName, + parseResult.root.apis[0].methods[0].parameters[1].type.typeArguments[0].baseName, 'double', ); expect( - parseResult - .root - .apis[0] - .methods[0] - .parameters[1] - .type - .typeArguments[0] - .isNullable, + parseResult.root.apis[0].methods[0].parameters[1].type.typeArguments[0].isNullable, isTrue, ); }); @@ -1065,10 +964,7 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); - expect( - results.errors[0].message, - contains('Parameters must specify their type'), - ); + expect(results.errors[0].message, contains('Parameters must specify their type')); }); test('custom objc selector', () { @@ -1083,10 +979,7 @@ abstract class Api { expect(results.errors, isEmpty); expect(results.root.apis, hasLength(1)); expect(results.root.apis[0].methods, hasLength(1)); - expect( - results.root.apis[0].methods[0].objcSelector, - equals('subtractValue:by:'), - ); + expect(results.root.apis[0].methods[0].objcSelector, equals('subtractValue:by:')); }); test('custom objc invalid selector', () { @@ -1100,10 +993,7 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); - expect( - results.errors[0].message, - contains('Invalid selector, expected 2 parameters'), - ); + expect(results.errors[0].message, contains('Invalid selector, expected 2 parameters')); }); test('custom objc no parameters', () { @@ -1133,10 +1023,7 @@ abstract class Api { expect(results.errors, isEmpty); expect(results.root.apis, hasLength(1)); expect(results.root.apis[0].methods, hasLength(1)); - expect( - results.root.apis[0].methods[0].swiftFunction, - equals('subtractValue(_:by:)'), - ); + expect(results.root.apis[0].methods[0].swiftFunction, equals('subtractValue(_:by:)')); }); test('custom swift invalid function signature', () { @@ -1242,14 +1129,8 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors, isEmpty); expect(results.root.classes, hasLength(2)); - expect( - results.root.classes.where((Class element) => element.name == 'Foo'), - hasLength(1), - ); - expect( - results.root.classes.where((Class element) => element.name == 'Bar'), - hasLength(1), - ); + expect(results.root.classes.where((Class element) => element.name == 'Foo'), hasLength(1)); + expect(results.root.classes.where((Class element) => element.name == 'Bar'), hasLength(1)); }); test('undeclared class in argument type argument', () { @@ -1428,10 +1309,7 @@ abstract class Api { '''; final ParseResults results = parseSource(code); expect(results.errors, isEmpty); - expect( - results.root.apis[0].methods[0].parameters[0].type.isNullable, - isTrue, - ); + expect(results.root.apis[0].methods[0].parameters[0].type.isNullable, isTrue); }); test('task queue specified', () { @@ -1461,10 +1339,7 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors, isEmpty); - expect( - results.root.apis[0].methods[0].taskQueueType, - equals(TaskQueueType.serial), - ); + expect(results.root.apis[0].methods[0].taskQueueType, equals(TaskQueueType.serial)); }); test('unsupported task queue on FlutterApi', () { @@ -1478,10 +1353,7 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors, hasLength(1)); - expect( - results.errors[0].message, - contains('Unsupported TaskQueue specification'), - ); + expect(results.errors[0].message, contains('Unsupported TaskQueue specification')); }); test('generator validation', () async { @@ -1539,10 +1411,7 @@ abstract class Api { final ParseResults results = parseSource(code); expect(results.errors, hasLength(1)); - expect( - results.errors[0].message, - contains('FlutterApi method parameters must be positional'), - ); + expect(results.errors[0].message, contains('FlutterApi method parameters must be positional')); }); test('unsupported optional parameters on FlutterApi', () { @@ -1604,10 +1473,7 @@ abstract class MyClass { '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, hasLength(1)); - expect( - parseResult.errors.single.message, - contains('ProxyApis do not support data classes'), - ); + expect(parseResult.errors.single.message, contains('ProxyApis do not support data classes')); }); test('super class must be proxy api', () { @@ -1668,10 +1534,8 @@ abstract class MyOtherClass { ); }); - test( - 'api is not used as an attached field while having an unattached field', - () { - const code = ''' + test('api is not used as an attached field while having an unattached field', () { + const code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1683,21 +1547,18 @@ abstract class MyOtherClass { late int aField; } '''; - final ParseResults parseResult = parseSource(code); - expect(parseResult.errors, isNotEmpty); - expect( - parseResult.errors[0].message, - contains( - 'ProxyApis with unattached fields can not be used as attached fields: anAttachedField', - ), - ); - }, - ); + final ParseResults parseResult = parseSource(code); + expect(parseResult.errors, isNotEmpty); + expect( + parseResult.errors[0].message, + contains( + 'ProxyApis with unattached fields can not be used as attached fields: anAttachedField', + ), + ); + }); - test( - 'api is not used as an attached field while having a required Flutter method', - () { - const code = ''' + test('api is not used as an attached field while having a required Flutter method', () { + const code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1709,16 +1570,15 @@ abstract class MyOtherClass { late void Function() aCallbackMethod; } '''; - final ParseResults parseResult = parseSource(code); - expect(parseResult.errors, isNotEmpty); - expect( - parseResult.errors[0].message, - contains( - 'ProxyApis with required callback methods can not be used as attached fields: anAttachedField', - ), - ); - }, - ); + final ParseResults parseResult = parseSource(code); + expect(parseResult.errors, isNotEmpty); + expect( + parseResult.errors[0].message, + contains( + 'ProxyApis with required callback methods can not be used as attached fields: anAttachedField', + ), + ); + }); test('interfaces can only have callback methods', () { const code = ''' @@ -1751,10 +1611,7 @@ abstract class MyClass { '''; final ParseResults parseResult = parseSource(code); expect(parseResult.errors, isNotEmpty); - expect( - parseResult.errors[0].message, - contains('Attached fields must be a ProxyApi: int'), - ); + expect(parseResult.errors[0].message, contains('Attached fields must be a ProxyApi: int')); }); test('attached fields must not be nullable', () { diff --git a/packages/pigeon/test/swift/proxy_api_test.dart b/packages/pigeon/test/swift/proxy_api_test.dart index ccf1df2f97e1..bd8c2333442e 100644 --- a/packages/pigeon/test/swift/proxy_api_test.dart +++ b/packages/pigeon/test/swift/proxy_api_test.dart @@ -15,19 +15,13 @@ void main() { apis: [ AstProxyApi( name: 'Api', - swiftOptions: const SwiftProxyApiOptions( - name: 'MyLibraryApi', - import: 'MyLibrary', - ), + swiftOptions: const SwiftProxyApiOptions(name: 'MyLibraryApi', import: 'MyLibrary'), constructors: [ Constructor( name: 'name', parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], @@ -45,17 +39,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), ), Method( name: 'doSomethingElse', @@ -63,17 +51,11 @@ void main() { isRequired: false, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'Input', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'Input', isNullable: false), name: 'input', ), ], - returnType: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'String', isNullable: false), ), ], ), @@ -84,10 +66,7 @@ void main() { final sink = StringBuffer(); const generator = SwiftGenerator(); generator.generate( - const InternalSwiftOptions( - fileSpecificClassNameComponent: 'MyFile', - swiftOut: '', - ), + const InternalSwiftOptions(fileSpecificClassNameComponent: 'MyFile', swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, @@ -106,9 +85,7 @@ void main() { expect(code, contains(r'protocol MyFilePigeonProxyApiDelegate')); expect( collapsedCode, - contains( - r'func pigeonApiApi(_ registrar: MyFilePigeonProxyApiRegistrar) -> PigeonApiApi', - ), + contains(r'func pigeonApiApi(_ registrar: MyFilePigeonProxyApiRegistrar) -> PigeonApiApi'), ); // API registrar @@ -178,10 +155,7 @@ void main() { apis: [ AstProxyApi( name: 'Api', - swiftOptions: const SwiftProxyApiOptions( - import: 'MyImport', - supportsIos: false, - ), + swiftOptions: const SwiftProxyApiOptions(import: 'MyImport', supportsIos: false), constructors: [], fields: [], methods: [], @@ -208,10 +182,7 @@ void main() { apis: [ AstProxyApi( name: 'Api', - swiftOptions: const SwiftProxyApiOptions( - import: 'MyImport', - supportsMacos: false, - ), + swiftOptions: const SwiftProxyApiOptions(import: 'MyImport', supportsMacos: false), constructors: [], fields: [], methods: [], @@ -261,10 +232,7 @@ void main() { ); final code = sink.toString(); - expect( - code, - contains('#if !os(iOS) || !os(macOS)\nimport MyImport\n#endif'), - ); + expect(code, contains('#if !os(iOS) || !os(macOS)\nimport MyImport\n#endif')); }); test('do not add check if at least one class is supported', () { @@ -272,10 +240,7 @@ void main() { apis: [ AstProxyApi( name: 'Api', - swiftOptions: const SwiftProxyApiOptions( - import: 'MyImport', - supportsIos: false, - ), + swiftOptions: const SwiftProxyApiOptions(import: 'MyImport', supportsIos: false), constructors: [], fields: [], methods: [], @@ -358,11 +323,7 @@ void main() { fields: [], methods: [], interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ), + TypeDeclaration(baseName: api2.name, isNullable: false, associatedProxyApi: api2), }, ), api2, @@ -403,16 +364,8 @@ void main() { fields: [], methods: [], interfaces: { - TypeDeclaration( - baseName: api2.name, - isNullable: false, - associatedProxyApi: api2, - ), - TypeDeclaration( - baseName: api3.name, - isNullable: false, - associatedProxyApi: api3, - ), + TypeDeclaration(baseName: api2.name, isNullable: false, associatedProxyApi: api2), + TypeDeclaration(baseName: api3.name, isNullable: false, associatedProxyApi: api3), }, ), api2, @@ -441,9 +394,7 @@ void main() { apis: [ AstProxyApi( name: 'Api', - constructors: [ - Constructor(name: '', parameters: []), - ], + constructors: [Constructor(name: '', parameters: [])], fields: [], methods: [], ), @@ -464,9 +415,7 @@ void main() { expect(code, contains('class PigeonApiApi: PigeonApiProtocolApi ')); expect( collapsedCode, - contains( - 'func pigeonDefaultConstructor(pigeonApi: PigeonApiApi) throws -> Api', - ), + contains('func pigeonDefaultConstructor(pigeonApi: PigeonApiApi) throws -> Api'), ); expect( collapsedCode, @@ -476,9 +425,7 @@ void main() { ); expect( collapsedCode, - contains( - r'api.pigeonRegistrar.instanceManager.addDartCreatedInstance(', - ), + contains(r'api.pigeonRegistrar.instanceManager.addDartCreatedInstance('), ); }); @@ -488,10 +435,7 @@ void main() { AstProxyApi( name: 'Api', constructors: [ - Constructor( - name: 'myConstructorName', - parameters: [], - ), + Constructor(name: 'myConstructorName', parameters: []), ], fields: [], methods: [], @@ -512,9 +456,7 @@ void main() { final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, - contains( - 'func myConstructorName(pigeonApi: PigeonApiApi) throws -> Api', - ), + contains('func myConstructorName(pigeonApi: PigeonApiApi) throws -> Api'), ); expect( collapsedCode, @@ -538,10 +480,7 @@ void main() { name: 'name', parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -553,17 +492,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -575,10 +508,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -625,50 +555,42 @@ void main() { ); }); - test( - 'host platform constructor calls new instance error for required callbacks', - () { - final root = Root( - apis: [ - AstProxyApi( - name: 'Api', - constructors: [], - fields: [], - methods: [ - Method( - name: 'aCallbackMethod', - returnType: const TypeDeclaration.voidDeclaration(), - parameters: [], - location: ApiLocation.flutter, - ), - ], - ), - ], - classes: [], - enums: [], - ); - final sink = StringBuffer(); - const generator = SwiftGenerator(); - generator.generate( - const InternalSwiftOptions( - errorClassName: 'TestError', - swiftOut: '', + test('host platform constructor calls new instance error for required callbacks', () { + final root = Root( + apis: [ + AstProxyApi( + name: 'Api', + constructors: [], + fields: [], + methods: [ + Method( + name: 'aCallbackMethod', + returnType: const TypeDeclaration.voidDeclaration(), + parameters: [], + location: ApiLocation.flutter, + ), + ], ), - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final code = sink.toString(); - final String collapsedCode = _collapseNewlineAndIndentation(code); + ], + classes: [], + enums: [], + ); + final sink = StringBuffer(); + const generator = SwiftGenerator(); + generator.generate( + const InternalSwiftOptions(errorClassName: 'TestError', swiftOut: ''), + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains( - r'completion( .failure( TestError( code: "new-instance-error"', - ), - ); - }, - ); + expect( + collapsedCode, + contains(r'completion( .failure( TestError( code: "new-instance-error"'), + ); + }); }); group('Fields', () { @@ -681,15 +603,10 @@ void main() { apis: [ AstProxyApi( name: 'Api', - constructors: [ - Constructor(name: 'name', parameters: []), - ], + constructors: [Constructor(name: 'name', parameters: [])], fields: [ ApiField( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), ApiField( @@ -701,17 +618,11 @@ void main() { name: 'enumType', ), ApiField( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), ApiField( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), ApiField( @@ -723,10 +634,7 @@ void main() { name: 'nullableEnumType', ), ApiField( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -777,15 +685,11 @@ void main() { ); expect( code, - contains( - r'func validType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Int64', - ), + contains(r'func validType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Int64'), ); expect( code, - contains( - r'func enumType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> AnEnum', - ), + contains(r'func enumType(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> AnEnum'), ); expect( code, @@ -854,9 +758,7 @@ void main() { final code = sink.toString(); expect( code, - contains( - r'func aField(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Api2', - ), + contains(r'func aField(pigeonApi: PigeonApiApi, pigeonInstance: Api) throws -> Api2'), ); expect( code, @@ -906,10 +808,7 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); final code = sink.toString(); - expect( - code, - contains(r'func aField(pigeonApi: PigeonApiApi) throws -> Api2'), - ); + expect(code, contains(r'func aField(pigeonApi: PigeonApiApi) throws -> Api2')); expect( code, contains( @@ -937,10 +836,7 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -952,17 +848,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -974,10 +864,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], @@ -1055,14 +942,8 @@ void main() { ); final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); - expect( - collapsedCode, - contains('func doSomething(pigeonApi: PigeonApiApi) throws'), - ); - expect( - collapsedCode, - contains(r'try api.pigeonDelegate.doSomething(pigeonApi: api)'), - ); + expect(collapsedCode, contains('func doSomething(pigeonApi: PigeonApiApi) throws')); + expect(collapsedCode, contains(r'try api.pigeonDelegate.doSomething(pigeonApi: api)')); }); }); @@ -1084,10 +965,7 @@ void main() { location: ApiLocation.flutter, parameters: [ Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), name: 'validType', ), Parameter( @@ -1099,17 +977,11 @@ void main() { name: 'enumType', ), Parameter( - type: const TypeDeclaration( - isNullable: false, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'Api2'), name: 'proxyApiType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'int'), name: 'nullableValidType', ), Parameter( @@ -1121,10 +993,7 @@ void main() { name: 'nullableEnumType', ), Parameter( - type: const TypeDeclaration( - isNullable: true, - baseName: 'Api2', - ), + type: const TypeDeclaration(isNullable: true, baseName: 'Api2'), name: 'nullableProxyApiType', ), ], diff --git a/packages/pigeon/test/swift_generator_test.dart b/packages/pigeon/test/swift_generator_test.dart index fa567e2b02c8..8b665eeea8da 100644 --- a/packages/pigeon/test/swift_generator_test.dart +++ b/packages/pigeon/test/swift_generator_test.dart @@ -34,27 +34,15 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: Int64? = nil')); - expect( - code, - contains('static func fromList(_ pigeonVar_list: [Any?]) -> Foobar?'), - ); + expect(code, contains('static func fromList(_ pigeonVar_list: [Any?]) -> Foobar?')); expect(code, contains('func toList() -> [Any?]')); expect(code, isNot(contains('if ('))); }); @@ -71,12 +59,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('enum Foobar: Int')); expect(code, contains(' case one = 0')); @@ -122,20 +105,10 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('enum Foo: Int')); - expect( - code, - contains( - 'let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)', - ), - ); + expect(code, contains('let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)')); expect(code, contains('return Foo(rawValue: enumResultAsInt)')); expect(code, contains('let fooArg = args[0] as! Foo')); expect(code, isNot(contains('if ('))); @@ -194,12 +167,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('protocol Api')); expect(code, matches('func doSomething.*Input.*Output')); @@ -231,31 +199,19 @@ void main() { name: 'aString', ), NamedType( - type: const TypeDeclaration( - baseName: 'Uint8List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Uint8List', isNullable: true), name: 'aUint8List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int32List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int32List', isNullable: true), name: 'aInt32List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Int64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Int64List', isNullable: true), name: 'aInt64List', ), NamedType( - type: const TypeDeclaration( - baseName: 'Float64List', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'Float64List', isNullable: true), name: 'aFloat64List', ), ], @@ -267,12 +223,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('var aBool: Bool? = nil')); expect(code, contains('var aInt: Int64? = nil')); @@ -290,21 +241,13 @@ void main() { const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class PigeonError: Error')); expect(code, contains('let code: String')); expect(code, contains('let message: String?')); expect(code, contains('let details: Sendable?')); - expect( - code, - contains('init(code: String, message: String?, details: Sendable?)'), - ); + expect(code, contains('init(code: String, message: String?, details: Sendable?)')); }); test('gen one flutter api', () { @@ -360,19 +303,12 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Api')); expect( code, - contains( - 'init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "")', - ), + contains('init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "")'), ); expect(code, matches('func doSomething.*Input.*Output')); expect(code, isNot(contains('if ('))); @@ -419,12 +355,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, isNot(matches('.*doSomething(.*) ->'))); expect(code, matches('doSomething(.*)')); @@ -471,17 +402,9 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('completion: @escaping (Result) -> Void'), - ); + expect(code, contains('completion: @escaping (Result) -> Void')); expect(code, contains('completion(.success(()))')); expect(code, isNot(contains('if ('))); }); @@ -521,12 +444,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func doSomething() throws -> Output')); expect(code, contains('let result = try api.doSomething()')); @@ -569,18 +487,11 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - 'func doSomething(completion: @escaping (Result) -> Void)', - ), + contains('func doSomething(completion: @escaping (Result) -> Void)'), ); expect(code, contains('channel.sendMessage(nil')); expect(code, isNot(contains('if ('))); @@ -605,12 +516,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [Any?]? = nil')); @@ -636,12 +542,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [AnyHashable?: Any?]? = nil')); @@ -653,11 +554,7 @@ void main() { name: 'Outer', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Nested', - associatedClass: emptyClass, - isNullable: true, - ), + type: TypeDeclaration(baseName: 'Nested', associatedClass: emptyClass, isNullable: true), name: 'nested', ), ], @@ -679,24 +576,13 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('struct Outer')); expect(code, contains('struct Nested')); expect(code, contains('var nested: Nested? = nil')); - expect( - code, - contains('static func fromList(_ pigeonVar_list: [Any?]) -> Outer?'), - ); - expect( - code, - contains('let nested: Nested? = nilOrValue(pigeonVar_list[0])'), - ); + expect(code, contains('static func fromList(_ pigeonVar_list: [Any?]) -> Outer?')); + expect(code, contains('let nested: Nested? = nilOrValue(pigeonVar_list[0])')); expect(code, contains('func toList() -> [Any?]')); expect(code, isNot(contains('if ('))); // Single-element list serializations should not have a trailing comma. @@ -757,12 +643,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('protocol Api')); expect(code, contains('api.doSomething(arg: argArg) { result in')); @@ -824,12 +705,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('class Api')); expect(code, matches('func doSomething.*Input.*completion.*Output.*Void')); @@ -848,29 +724,16 @@ void main() { name: 'EnumClass', fields: [ NamedType( - type: TypeDeclaration( - baseName: 'Enum1', - associatedEnum: emptyEnum, - isNullable: true, - ), + type: TypeDeclaration(baseName: 'Enum1', associatedEnum: emptyEnum, isNullable: true), name: 'enum1', ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [anEnum], - ); + final root = Root(apis: [], classes: [classDefinition], enums: [anEnum]); final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('enum Enum1: Int')); expect(code, contains('case one = 0')); @@ -886,12 +749,7 @@ void main() { copyrightHeader: ['hello world', ''], ); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, startsWith('// hello world')); // There should be no trailing whitespace on generated comments. @@ -906,28 +764,17 @@ void main() { type: const TypeDeclaration( baseName: 'List', isNullable: true, - typeArguments: [ - TypeDeclaration(baseName: 'int', isNullable: true), - ], + typeArguments: [TypeDeclaration(baseName: 'int', isNullable: true)], ), name: 'field1', ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [Int64?]')); @@ -950,20 +797,11 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [String?: String?]')); @@ -1001,12 +839,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func doit(arg: [Int64?]')); }); @@ -1043,12 +876,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func doit(arg argArg: [Int64?]')); }); @@ -1080,12 +908,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func doit() throws -> [Int64?]')); expect(code, contains('let result = try api.doit()')); @@ -1119,18 +942,11 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - 'func doit(completion: @escaping (Result<[Int64?], PigeonError>) -> Void)', - ), + contains('func doit(completion: @escaping (Result<[Int64?], PigeonError>) -> Void)'), ); expect(code, contains('let result = listResponse[0] as! [Int64?]')); expect(code, contains('completion(.success(result))')); @@ -1148,23 +964,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), Parameter( name: 'y', - type: const TypeDeclaration( - isNullable: false, - baseName: 'int', - ), + type: const TypeDeclaration(isNullable: false, baseName: 'int'), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -1175,12 +982,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func add(x: Int64, y: Int64) throws -> Int64')); expect(code, contains('let args = message as! [Any?]')); @@ -1202,23 +1004,14 @@ void main() { parameters: [ Parameter( name: 'x', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), Parameter( name: 'y', - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: false), ), ], ), @@ -1229,12 +1022,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('let channel = FlutterBasicMessageChannel')); expect(code, contains('let result = listResponse[0] as! Int64')); @@ -1245,10 +1033,7 @@ void main() { 'func add(x xArg: Int64, y yArg: Int64, completion: @escaping (Result) -> Void)', ), ); - expect( - code, - contains('channel.sendMessage([xArg, yArg] as [Any?]) { response in'), - ); + expect(code, contains('channel.sendMessage([xArg, yArg] as [Any?]) { response in')); }); test('return nullable host', () { @@ -1260,10 +1045,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), parameters: [], ), ], @@ -1275,12 +1057,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func doit() throws -> Int64?')); }); @@ -1294,10 +1071,7 @@ void main() { Method( name: 'doit', location: ApiLocation.host, - returnType: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + returnType: const TypeDeclaration(baseName: 'int', isNullable: true), isAsynchronous: true, parameters: [], ), @@ -1310,19 +1084,9 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains( - 'func doit(completion: @escaping (Result) -> Void', - ), - ); + expect(code, contains('func doit(completion: @escaping (Result) -> Void')); }); test('nullable argument host', () { @@ -1338,10 +1102,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1354,12 +1115,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('let fooArg: Int64? = nilOrValue(args[0])')); }); @@ -1377,10 +1133,7 @@ void main() { parameters: [ Parameter( name: 'foo', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1393,12 +1146,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, @@ -1437,10 +1185,7 @@ void main() { name: 'Input', fields: [ NamedType( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'input', ), ], @@ -1451,12 +1196,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('var input: String\n')); }); @@ -1489,10 +1229,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1522,15 +1259,9 @@ void main() { enums: [ Enum( name: 'enum', - documentationComments: [ - comments[count++], - unspacedComments[unspacedCount++], - ], + documentationComments: [comments[count++], unspacedComments[unspacedCount++]], members: [ - EnumMember( - name: 'one', - documentationComments: [comments[count++]], - ), + EnumMember(name: 'one', documentationComments: [comments[count++]]), EnumMember(name: 'two'), ], ), @@ -1539,12 +1270,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); for (final comment in comments) { expect(code, contains('///$comment')); @@ -1606,12 +1332,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains(': FlutterStandardReader ')); }); @@ -1627,17 +1348,11 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'int', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: false), name: 'value', ), Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'key', ), ], @@ -1653,12 +1368,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func setValue(_ value: Int64, for key: String)')); }); @@ -1674,10 +1384,7 @@ void main() { location: ApiLocation.host, parameters: [ Parameter( - type: const TypeDeclaration( - baseName: 'String', - isNullable: false, - ), + type: const TypeDeclaration(baseName: 'String', isNullable: false), name: 'key', ), ], @@ -1693,12 +1400,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func removeValue(key: String)')); }); @@ -1725,12 +1427,7 @@ void main() { final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect(code, contains('func removeAll()')); }); @@ -1748,10 +1445,7 @@ void main() { parameters: [ Parameter( name: 'field', - type: const TypeDeclaration( - baseName: 'int', - isNullable: true, - ), + type: const TypeDeclaration(baseName: 'int', isNullable: true), ), ], ), @@ -1765,18 +1459,11 @@ void main() { final sink = StringBuffer(); const kotlinOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - kotlinOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); expect( code, - contains( - 'completion(.failure(createConnectionError(withChannelName: channelName)))', - ), + contains('completion(.failure(createConnectionError(withChannelName: channelName)))'), ); expect( code, @@ -1796,25 +1483,13 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('static func == (lhs: Foobar, rhs: Foobar) -> Bool {'), - ); + expect(code, contains('static func == (lhs: Foobar, rhs: Foobar) -> Bool {')); expect(code, contains('func hash(into hasher: inout Hasher) {')); }); @@ -1832,25 +1507,13 @@ void main() { ), ], ); - final root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); + final root = Root(apis: [], classes: [classDefinition], enums: []); final sink = StringBuffer(); const swiftOptions = InternalSwiftOptions(swiftOut: ''); const generator = SwiftGenerator(); - generator.generate( - swiftOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); + generator.generate(swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME); final code = sink.toString(); - expect( - code, - contains('static func == (lhs: Foobar, rhs: Foobar) -> Bool {'), - ); + expect(code, contains('static func == (lhs: Foobar, rhs: Foobar) -> Bool {')); expect(code, contains('func hash(into hasher: inout Hasher) {')); }); } diff --git a/packages/pigeon/test/version_test.dart b/packages/pigeon/test/version_test.dart index 53cb80b35e67..88b5daebc208 100644 --- a/packages/pigeon/test/version_test.dart +++ b/packages/pigeon/test/version_test.dart @@ -17,8 +17,7 @@ void main() { expect( pigeonVersion, match?.group(1)?.trim(), - reason: - 'Update lib/src/generator_tools.dart pigeonVersion to the value in the pubspec', + reason: 'Update lib/src/generator_tools.dart pigeonVersion to the value in the pubspec', ); }); } diff --git a/packages/pigeon/tool/generate.dart b/packages/pigeon/tool/generate.dart index ed9e2bde1117..efddb0c2e8da 100644 --- a/packages/pigeon/tool/generate.dart +++ b/packages/pigeon/tool/generate.dart @@ -37,28 +37,17 @@ Future main(List args) async { defaultsTo: true, hide: true, ) - ..addFlag( - _noFormatFlag, - abbr: 'n', - help: 'Do not autoformat after generation.', - ) - ..addFlag( - _helpFlag, - negatable: false, - abbr: 'h', - help: 'Print this reference.', - ) + ..addFlag(_noFormatFlag, abbr: 'n', help: 'Do not autoformat after generation.') + ..addFlag(_helpFlag, negatable: false, abbr: 'h', help: 'Print this reference.') ..addFlag( _overflowFiller, abbr: 'o', - help: - 'Injects 120 Enums into the pigeon ast, used for testing overflow utilities.', + help: 'Injects 120 Enums into the pigeon ast, used for testing overflow utilities.', hide: true, ) ..addMultiOption( _files, - help: - 'Select specific groups of files to generate; $_test or $_example. Defaults to both.', + help: 'Select specific groups of files to generate; $_test or $_example. Defaults to both.', allowed: _fileGroups, ); @@ -106,9 +95,7 @@ ${parser.usage}'''); if (!argResults.wasParsed(_noFormatFlag)) { print('Formatting generated output...'); - final int formatExitCode = await formatAllFiles( - repositoryRoot: p.dirname(p.dirname(baseDir)), - ); + final int formatExitCode = await formatAllFiles(repositoryRoot: p.dirname(p.dirname(baseDir))); if (formatExitCode != 0) { print('Formatting failed; see above for errors.'); exit(formatExitCode); diff --git a/packages/pigeon/tool/run_tests.dart b/packages/pigeon/tool/run_tests.dart index 6f84cdc234b6..9319febd9f53 100644 --- a/packages/pigeon/tool/run_tests.dart +++ b/packages/pigeon/tool/run_tests.dart @@ -39,8 +39,7 @@ Future _validateGeneratedTestFiles() async { await _validateGeneratedFiles( (String baseDir) => generateTestPigeons(baseDir: baseDir), generationMessage: 'Generating test output', - incorrectFilesMessage: - 'The following files are not updated, or not formatted correctly:', + incorrectFilesMessage: 'The following files are not updated, or not formatted correctly:', ); } @@ -119,8 +118,7 @@ Future _validateGeneratedFiles( .flattened .toSet(); final Iterable filteredFiles = modifiedFiles.where( - (String path) => - extensions.contains(p.extension(path).replaceFirst('.', '')), + (String path) => extensions.contains(p.extension(path).replaceFirst('.', '')), ); if (filteredFiles.isEmpty) { diff --git a/packages/pigeon/tool/shared/flutter_utils.dart b/packages/pigeon/tool/shared/flutter_utils.dart index c6e3ed9f5347..07226eb841ee 100644 --- a/packages/pigeon/tool/shared/flutter_utils.dart +++ b/packages/pigeon/tool/shared/flutter_utils.dart @@ -24,11 +24,10 @@ Future getDeviceForPlatform(String platform) async { // can be removed once that is fixed. output = output.substring(output.indexOf('[')); - final List> devices = - (jsonDecode(output) as List).cast>(); + final List> devices = (jsonDecode(output) as List) + .cast>(); for (final deviceInfo in devices) { - final String targetPlatform = - (deviceInfo['targetPlatform'] as String?) ?? ''; + final String targetPlatform = (deviceInfo['targetPlatform'] as String?) ?? ''; if (targetPlatform.startsWith(platform)) { final deviceId = deviceInfo['id'] as String?; if (deviceId != null) { diff --git a/packages/pigeon/tool/shared/process_utils.dart b/packages/pigeon/tool/shared/process_utils.dart index e795f00b5d0c..098b6f0fc630 100644 --- a/packages/pigeon/tool/shared/process_utils.dart +++ b/packages/pigeon/tool/shared/process_utils.dart @@ -16,9 +16,7 @@ Future runProcess( command, arguments, workingDirectory: workingDirectory, - mode: streamOutput - ? ProcessStartMode.inheritStdio - : ProcessStartMode.normal, + mode: streamOutput ? ProcessStartMode.inheritStdio : ProcessStartMode.normal, ); if (streamOutput) { diff --git a/packages/pigeon/tool/shared/test_runner.dart b/packages/pigeon/tool/shared/test_runner.dart index 810e4746cb17..8a8b7a76206f 100644 --- a/packages/pigeon/tool/shared/test_runner.dart +++ b/packages/pigeon/tool/shared/test_runner.dart @@ -38,10 +38,7 @@ Future runTests( // https://github.com/flutter/flutter/issues/152916 await _runTests( testsToRun - .where( - (String test) => - test.contains('integration') && !test.contains('linux'), - ) + .where((String test) => test.contains('integration') && !test.contains('linux')) .toList(), ciMode: ciMode, ); @@ -78,9 +75,7 @@ Future _runGenerate( Future _runFormat(String baseDir, {required bool ciMode}) async { _printHeading('Formatting generated output', ciMode: ciMode); - final int formatExitCode = await formatAllFiles( - repositoryRoot: p.dirname(p.dirname(baseDir)), - ); + final int formatExitCode = await formatAllFiles(repositoryRoot: p.dirname(p.dirname(baseDir))); if (formatExitCode != 0) { print('Formatting failed; see above for errors.'); exit(formatExitCode); diff --git a/packages/pigeon/tool/shared/test_suites.dart b/packages/pigeon/tool/shared/test_suites.dart index f5f1a9991bdf..1d2ddf0e0ffb 100644 --- a/packages/pigeon/tool/shared/test_suites.dart +++ b/packages/pigeon/tool/shared/test_suites.dart @@ -17,8 +17,7 @@ import 'process_utils.dart'; const int _noDeviceAvailableExitCode = 100; const String _testPluginName = 'test_plugin'; -const String _alternateLanguageTestPluginName = - 'alternate_language_test_plugin'; +const String _alternateLanguageTestPluginName = 'alternate_language_test_plugin'; const String _testPluginRelativePath = 'platform_tests/$_testPluginName'; const String _alternateLanguageTestPluginRelativePath = 'platform_tests/$_alternateLanguageTestPluginName'; @@ -146,10 +145,7 @@ Future _runAndroidJavaUnitTests({bool ciMode = false}) async { } Future _runAndroidJavaIntegrationTests({bool ciMode = false}) async { - return _runMobileIntegrationTests( - 'Android', - _alternateLanguageTestPluginRelativePath, - ); + return _runMobileIntegrationTests('Android', _alternateLanguageTestPluginRelativePath); } Future _runAndroidJavaLint({bool ciMode = false}) async { @@ -164,10 +160,7 @@ Future _runAndroidKotlinUnitTests({bool ciMode = false}) async { } Future _runAndroidKotlinLint({bool ciMode = false}) async { - return _runAndroidLint( - testPluginName: _testPluginName, - testPluginPath: _testPluginRelativePath, - ); + return _runAndroidLint(testPluginName: _testPluginName, testPluginPath: _testPluginRelativePath); } Future _runAndroidUnitTests(String testPluginPath) async { @@ -209,10 +202,7 @@ Future _runAndroidKotlinIntegrationTests({bool ciMode = false}) async { return _runMobileIntegrationTests('Android', _testPluginRelativePath); } -Future _runMobileIntegrationTests( - String platform, - String testPluginPath, -) async { +Future _runMobileIntegrationTests(String platform, String testPluginPath) async { final String? device = await getDeviceForPlatform(platform.toLowerCase()); if (device == null) { print( @@ -255,11 +245,7 @@ Future _analyzeFlutterUnitTests(String flutterUnitTestsPath) async { return generateTestCode; } - final int analyzeCode = await runFlutterCommand( - flutterUnitTestsPath, - 'analyze', - [], - ); + final int analyzeCode = await runFlutterCommand(flutterUnitTestsPath, 'analyze', []); if (analyzeCode != 0) { return analyzeCode; } @@ -277,11 +263,7 @@ Future _runFlutterUnitTests({bool ciMode = false}) async { return analyzeCode; } - final int testCode = await runFlutterCommand( - flutterUnitTestsPath, - 'test', - [], - ); + final int testCode = await runFlutterCommand(flutterUnitTestsPath, 'test', []); if (testCode != 0) { return testCode; } @@ -370,11 +352,7 @@ Future _runIOSPluginUnitTests(String testPluginPath) async { ).whenComplete(() => _deleteSimulator(deviceName)); } -Future _createSimulator( - String deviceName, - String deviceType, - String deviceRuntime, -) async { +Future _createSimulator(String deviceName, String deviceType, String deviceRuntime) async { // Delete any existing simulators with the same name until it fails. It will // fail once there are no simulators with the name. Having more than one may // cause issues when builds target the device. @@ -391,11 +369,7 @@ Future _createSimulator( } Future _deleteSimulator(String deviceName) async { - return runProcess('xcrun', [ - 'simctl', - 'delete', - deviceName, - ], streamOutput: false); + return runProcess('xcrun', ['simctl', 'delete', deviceName], streamOutput: false); } Future _runIOSSwiftIntegrationTests({bool ciMode = false}) async { @@ -465,8 +439,7 @@ Future _runWindowsUnitTests({bool ciMode = false}) async { // https://github.com/flutter/flutter/issues/129807, and just construct the // version of the path with the current architecture. const buildDirBase = '$examplePath/build/windows'; - const buildRelativeBinaryPath = - 'plugins/test_plugin/Debug/test_plugin_test.exe'; + const buildRelativeBinaryPath = 'plugins/test_plugin/Debug/test_plugin_test.exe'; const arm64Path = '$buildDirBase/arm64/$buildRelativeBinaryPath'; const x64Path = '$buildDirBase/x64/$buildRelativeBinaryPath'; if (File(arm64Path).existsSync()) { diff --git a/packages/pigeon/tool/test.dart b/packages/pigeon/tool/test.dart index 926205cefe60..b4be8bb61453 100644 --- a/packages/pigeon/tool/test.dart +++ b/packages/pigeon/tool/test.dart @@ -28,43 +28,23 @@ const String _overflow = 'overflow'; Future main(List args) async { final parser = ArgParser() ..addMultiOption(_testFlag, abbr: 't', help: 'Only run specified tests.') - ..addFlag( - _noGen, - abbr: 'g', - help: 'Skips the generation step.', - negatable: false, - ) - ..addFlag( - _format, - abbr: 'f', - help: 'Formats generated test files before running tests.', - ) + ..addFlag(_noGen, abbr: 'g', help: 'Skips the generation step.', negatable: false) + ..addFlag(_format, abbr: 'f', help: 'Formats generated test files before running tests.') ..addFlag( _overflow, help: 'Generates overflow files for integration tests, runs tests with and without overflow files.', abbr: 'o', ) - ..addFlag( - _listFlag, - negatable: false, - abbr: 'l', - help: 'List available tests.', - ) - ..addFlag( - 'help', - negatable: false, - abbr: 'h', - help: 'Print this reference.', - ); + ..addFlag(_listFlag, negatable: false, abbr: 'l', help: 'List available tests.') + ..addFlag('help', negatable: false, abbr: 'h', help: 'Print this reference.'); final ArgResults argResults = parser.parse(args); var testsToRun = []; if (argResults.wasParsed(_listFlag)) { print('available tests:'); - final int columnWidth = - testSuites.keys.map((String key) => key.length).reduce(max) + 4; + final int columnWidth = testSuites.keys.map((String key) => key.length).reduce(max) + 4; for (final MapEntry info in testSuites.entries) { print('${info.key.padRight(columnWidth)}- ${info.value.description}'); @@ -84,11 +64,7 @@ ${parser.usage}'''); // If no tests are provided, run everything that is supported on the current // platform. if (testsToRun.isEmpty) { - const dartTests = [ - dartUnitTests, - flutterUnitTests, - commandLineTests, - ]; + const dartTests = [dartUnitTests, flutterUnitTests, commandLineTests]; const androidTests = [ androidJavaUnitTests, androidKotlinUnitTests, @@ -112,12 +88,7 @@ ${parser.usage}'''); const windowsTests = [windowsUnitTests, windowsIntegrationTests]; if (Platform.isMacOS) { - testsToRun = [ - ...dartTests, - ...androidTests, - ...iOSTests, - ...macOSTests, - ]; + testsToRun = [...dartTests, ...androidTests, ...iOSTests, ...macOSTests]; } else if (Platform.isWindows) { testsToRun = [...dartTests, ...windowsTests]; } else if (Platform.isLinux) { diff --git a/packages/plugin_platform_interface/lib/plugin_platform_interface.dart b/packages/plugin_platform_interface/lib/plugin_platform_interface.dart index 2a40957e252a..4d2bf3480e62 100644 --- a/packages/plugin_platform_interface/lib/plugin_platform_interface.dart +++ b/packages/plugin_platform_interface/lib/plugin_platform_interface.dart @@ -98,14 +98,11 @@ abstract class PlatformInterface { } return; } - if (preventConstObject && - identical(_instanceTokens[instance], const Object())) { + if (preventConstObject && identical(_instanceTokens[instance], const Object())) { throw AssertionError('`const Object()` cannot be used as the token.'); } if (!identical(token, _instanceTokens[instance])) { - throw AssertionError( - 'Platform interfaces must not be implemented with `implements`', - ); + throw AssertionError('Platform interfaces must not be implemented with `implements`'); } } } diff --git a/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart b/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart index 3b4d97338216..2dcd6e422a31 100644 --- a/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart +++ b/packages/plugin_platform_interface/test/plugin_platform_interface_test.dart @@ -36,13 +36,12 @@ abstract class SamplePluginPlatform extends PlatformInterface { class SamplePluginDefault extends SamplePluginPlatform { // A default real implementation of the platform interface would go here. } + // #enddocregion Example -class ImplementsSamplePluginPlatform extends Mock - implements SamplePluginPlatform {} +class ImplementsSamplePluginPlatform extends Mock implements SamplePluginPlatform {} -class ImplementsSamplePluginPlatformUsingNoSuchMethod - implements SamplePluginPlatform { +class ImplementsSamplePluginPlatformUsingNoSuchMethod implements SamplePluginPlatform { @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } @@ -51,6 +50,7 @@ class ImplementsSamplePluginPlatformUsingNoSuchMethod class SamplePluginPlatformMock extends Mock with MockPlatformInterfaceMixin implements SamplePluginPlatform {} + // #enddocregion Mock class SamplePluginPlatformFake extends Fake @@ -84,11 +84,9 @@ class VerifyTokenPluginPlatform extends PlatformInterface { } } -class ImplementsVerifyTokenPluginPlatform extends Mock - implements VerifyTokenPluginPlatform {} +class ImplementsVerifyTokenPluginPlatform extends Mock implements VerifyTokenPluginPlatform {} -class ImplementsVerifyTokenPluginPlatformUsingMockPlatformInterfaceMixin - extends Mock +class ImplementsVerifyTokenPluginPlatformUsingMockPlatformInterfaceMixin extends Mock with MockPlatformInterfaceMixin implements VerifyTokenPluginPlatform {} @@ -115,8 +113,7 @@ class ImplementsConstVerifyTokenPluginPlatform extends PlatformInterface // conflicts with instance methods in subclasses. class StaticMethodsOnlyPlatformInterfaceTest implements PlatformInterface {} -class StaticMethodsOnlyMockPlatformInterfaceMixinTest - implements MockPlatformInterfaceMixin {} +class StaticMethodsOnlyMockPlatformInterfaceMixinTest implements MockPlatformInterfaceMixin {} void main() { group('`verify`', () { @@ -128,8 +125,7 @@ void main() { test('prevents implmentation with `implements` and `noSuchMethod`', () { expect(() { - SamplePluginPlatform.instance = - ImplementsSamplePluginPlatformUsingNoSuchMethod(); + SamplePluginPlatform.instance = ImplementsSamplePluginPlatformUsingNoSuchMethod(); }, throwsA(isA())); }); @@ -158,8 +154,7 @@ void main() { group('`verifyToken`', () { test('prevents implementation with `implements`', () { expect(() { - VerifyTokenPluginPlatform.instance = - ImplementsVerifyTokenPluginPlatform(); + VerifyTokenPluginPlatform.instance = ImplementsVerifyTokenPluginPlatform(); }, throwsA(isA())); }); @@ -174,8 +169,7 @@ void main() { }); test('does not prevent `const Object()` token', () { - ConstVerifyTokenPluginPlatform.instance = - ImplementsConstVerifyTokenPluginPlatform(); + ConstVerifyTokenPluginPlatform.instance = ImplementsConstVerifyTokenPluginPlatform(); }); }); } diff --git a/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart b/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart index 9fd8e1e83cd6..56e200fee40a 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart +++ b/packages/pointer_interceptor/pointer_interceptor/example/lib/main.dart @@ -22,10 +22,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Stopping Clicks with some DOM', - home: MyHomePage(), - ); + return const MaterialApp(title: 'Stopping Clicks with some DOM', home: MyHomePage()); } } @@ -97,9 +94,7 @@ class _MyHomePageState extends State { intercepting: false, child: ElevatedButton( key: const Key('wrapped-transparent-button'), - child: const Text( - 'Never calls onPressed transparent', - ), + child: const Text('Never calls onPressed transparent'), onPressed: () { _clickedOn('wrapped-transparent-button'); }, diff --git a/packages/pointer_interceptor/pointer_interceptor/example/lib/native_widget.dart b/packages/pointer_interceptor/pointer_interceptor/example/lib/native_widget.dart index 877d3e10798a..dd2fb2991df0 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/lib/native_widget.dart +++ b/packages/pointer_interceptor/pointer_interceptor/example/lib/native_widget.dart @@ -2,5 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -export 'platforms/native_widget_ios.dart' - if (dart.library.html) 'platforms/native_widget_web.dart'; +export 'platforms/native_widget_ios.dart' if (dart.library.html) 'platforms/native_widget_web.dart'; diff --git a/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart b/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart index 712320a6765f..10df412b6f24 100644 --- a/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart +++ b/packages/pointer_interceptor/pointer_interceptor/lib/src/pointer_interceptor.dart @@ -33,10 +33,6 @@ class PointerInterceptor extends StatelessWidget { if (!intercepting) { return child; } - return PointerInterceptorPlatform.instance.buildWidget( - child: child, - debug: debug, - key: key, - ); + return PointerInterceptorPlatform.instance.buildWidget(child: child, debug: debug, key: key); } } diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart b/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart index f41d224e7835..370cf4cfb7ac 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart @@ -38,8 +38,7 @@ class PointerInterceptorIOSExample extends StatefulWidget { } } -class _PointerInterceptorIOSExampleState - extends State { +class _PointerInterceptorIOSExampleState extends State { bool _buttonTapped = false; @override @@ -53,9 +52,7 @@ class _PointerInterceptorIOSExampleState PointerInterceptorPlatform.instance.buildWidget( child: TextButton( style: TextButton.styleFrom(foregroundColor: Colors.red), - child: _buttonTapped - ? const Text('Tapped') - : const Text('Initial'), + child: _buttonTapped ? const Text('Tapped') : const Text('Initial'), onPressed: () { setState(() { _buttonTapped = !_buttonTapped; diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart b/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart index 7c4b9d998704..1ea28c17aed8 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_ios/test/pointer_interceptor_ios_test.dart @@ -41,9 +41,7 @@ class TestAppState extends State { void main() { testWidgets('Button remains clickable and is added to ' - 'hierarchy after being wrapped in pointer interceptor', ( - WidgetTester tester, - ) async { + 'hierarchy after being wrapped in pointer interceptor', (WidgetTester tester) async { await tester.pumpWidget(const TestApp()); await tester.tap(find.text('Test Button')); await tester.pump(); diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart b/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart index a0e2ef8435f4..8e3b0d0cdef1 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/lib/src/pointer_interceptor_platform.dart @@ -20,9 +20,7 @@ abstract class PointerInterceptorPlatform extends PlatformInterface { static set instance(PointerInterceptorPlatform? instance) { if (instance == null) { - throw AssertionError( - 'Platform interfaces can only be set to a non-null instance', - ); + throw AssertionError('Platform interfaces can only be set to a non-null instance'); } PlatformInterface.verify(instance, _token); diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart index 4caa0bd235e4..eb8e5cdd73e7 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart @@ -9,22 +9,16 @@ import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platf void main() { TestWidgetsFlutterBinding.ensureInitialized(); - test( - 'Default implementation of PointerInterceptorPlatform should throw unimplemented error', - () { - final PointerInterceptorPlatform unimplementedPointerInterceptorPlatform = - UnimplementedPointerInterceptorPlatform(); + test('Default implementation of PointerInterceptorPlatform should throw unimplemented error', () { + final PointerInterceptorPlatform unimplementedPointerInterceptorPlatform = + UnimplementedPointerInterceptorPlatform(); - final testChild = Container(); - expect( - () => unimplementedPointerInterceptorPlatform.buildWidget( - child: testChild, - ), - throwsUnimplementedError, - ); - }, - ); + final testChild = Container(); + expect( + () => unimplementedPointerInterceptorPlatform.buildWidget(child: testChild), + throwsUnimplementedError, + ); + }); } -class UnimplementedPointerInterceptorPlatform - extends PointerInterceptorPlatform {} +class UnimplementedPointerInterceptorPlatform extends PointerInterceptorPlatform {} diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart b/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart index c2b5be5877a1..6a5847c8a9f8 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart @@ -11,12 +11,8 @@ import 'package:integration_test/integration_test.dart'; import 'package:pointer_interceptor_web_example/main.dart' as app; import 'package:web/web.dart' as web; -final Finder nonClickableButtonFinder = find.byKey( - const Key('transparent-button'), -); -final Finder clickableWrappedButtonFinder = find.byKey( - const Key('wrapped-transparent-button'), -); +final Finder nonClickableButtonFinder = find.byKey(const Key('transparent-button')); +final Finder clickableWrappedButtonFinder = find.byKey(const Key('wrapped-transparent-button')); final Finder clickableButtonFinder = find.byKey(const Key('clickable-button')); final Finder backgroundFinder = find.byKey(const Key('background-widget')); @@ -24,78 +20,55 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('Without semantics', () { - testWidgets( - 'on wrapped elements, the browser does not hit the background-html-view', - (WidgetTester tester) async { - await _fullyRenderApp(tester); + testWidgets('on wrapped elements, the browser does not hit the background-html-view', ( + WidgetTester tester, + ) async { + await _fullyRenderApp(tester); - final web.Element element = _getHtmlElementAtCenter( - clickableButtonFinder, - tester, - ); + final web.Element element = _getHtmlElementAtCenter(clickableButtonFinder, tester); - expect(element.id, isNot('background-html-view')); - }, - semanticsEnabled: false, - ); + expect(element.id, isNot('background-html-view')); + }, semanticsEnabled: false); testWidgets( 'on wrapped elements with intercepting set to false, the browser hits the background-html-view', (WidgetTester tester) async { await _fullyRenderApp(tester); - final web.Element element = _getHtmlElementAtCenter( - clickableWrappedButtonFinder, - tester, - ); + final web.Element element = _getHtmlElementAtCenter(clickableWrappedButtonFinder, tester); expect(element.id, 'background-html-view'); }, semanticsEnabled: false, ); - testWidgets( - 'on unwrapped elements, the browser hits the background-html-view', - (WidgetTester tester) async { - await _fullyRenderApp(tester); + testWidgets('on unwrapped elements, the browser hits the background-html-view', ( + WidgetTester tester, + ) async { + await _fullyRenderApp(tester); - final web.Element element = _getHtmlElementAtCenter( - nonClickableButtonFinder, - tester, - ); + final web.Element element = _getHtmlElementAtCenter(nonClickableButtonFinder, tester); - expect(element.id, 'background-html-view'); - }, - semanticsEnabled: false, - ); + expect(element.id, 'background-html-view'); + }, semanticsEnabled: false); testWidgets('on background directly', (WidgetTester tester) async { await _fullyRenderApp(tester); - final web.Element element = _getHtmlElementAt( - tester.getTopLeft(backgroundFinder), - ); + final web.Element element = _getHtmlElementAt(tester.getTopLeft(backgroundFinder)); expect(element.id, 'background-html-view'); }, semanticsEnabled: false); // Regression test for https://github.com/flutter/flutter/issues/157920 - testWidgets('prevents default action of mousedown events', ( - WidgetTester tester, - ) async { + testWidgets('prevents default action of mousedown events', (WidgetTester tester) async { await _fullyRenderApp(tester); - final web.Element element = _getHtmlElementAtCenter( - clickableButtonFinder, - tester, - ); + final web.Element element = _getHtmlElementAtCenter(clickableButtonFinder, tester); expect(element.tagName.toLowerCase(), 'div'); for (var i = 0; i <= 4; i++) { - final event = web.MouseEvent( - 'mousedown', - web.MouseEventInit(button: i, cancelable: true), - ); + final event = web.MouseEvent('mousedown', web.MouseEventInit(button: i, cancelable: true)); element.dispatchEvent(event); expect(event.target, element); expect(event.defaultPrevented, isTrue); @@ -129,9 +102,7 @@ web.Element _getHtmlElementAt(Offset point) { // Probe at the shadow so the browser reports semantics nodes in addition to // platform view elements. If probed from `html.document` the browser hides // the contents of as an implementation detail. - final web.ShadowRoot glassPaneShadow = web.document - .querySelector('flt-glass-pane')! - .shadowRoot!; + final web.ShadowRoot glassPaneShadow = web.document.querySelector('flt-glass-pane')!.shadowRoot!; // Use `round` below to ensure clicks always fall *inside* the located // element, rather than truncating the decimals. // Truncating decimals makes some tests fail when a centered element (in high diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart b/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart index e845fded8499..0fe8dd51adf8 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart +++ b/packages/pointer_interceptor/pointer_interceptor_web/example/lib/main.dart @@ -15,13 +15,12 @@ const double _containerWidth = 640; const double _containerHeight = 480; /// The html.Element that will be rendered underneath the flutter UI. -final web.Element _htmlElement = - (web.document.createElement('div') as web.HTMLDivElement) - ..style.width = '100%' - ..style.height = '100%' - ..style.backgroundColor = '#fabada' - ..style.cursor = 'auto' - ..id = 'background-html-view'; +final web.Element _htmlElement = (web.document.createElement('div') as web.HTMLDivElement) + ..style.width = '100%' + ..style.height = '100%' + ..style.backgroundColor = '#fabada' + ..style.cursor = 'auto' + ..id = 'background-html-view'; // See other examples commented out below... @@ -57,10 +56,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Stopping Clicks with PointerInterceptor', - home: MyHomePage(), - ); + return const MaterialApp(title: 'Stopping Clicks with PointerInterceptor', home: MyHomePage()); } } @@ -141,9 +137,7 @@ class _MyHomePageState extends State { intercepting: false, child: ElevatedButton( key: const Key('wrapped-transparent-button'), - child: const Text( - 'Never calls onPressed transparent', - ), + child: const Text('Never calls onPressed transparent'), onPressed: () { _clickedOn('wrapped-transparent-button'); }, diff --git a/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart b/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart index cd54f2cf8fdb..82e75e0f0aaa 100644 --- a/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions/example/integration_test/quick_actions_test.dart @@ -18,9 +18,6 @@ void main() { localizedTitle: 'Action one', icon: 'AppIcon', ); - expect( - quickActions.setShortcutItems([shortCutItem]), - completes, - ); + expect(quickActions.setShortcutItems([shortCutItem]), completes); }); } diff --git a/packages/quick_actions/quick_actions/example/lib/main.dart b/packages/quick_actions/quick_actions/example/lib/main.dart index 0c08713fb5fe..9f51c2d2a5b4 100644 --- a/packages/quick_actions/quick_actions/example/lib/main.dart +++ b/packages/quick_actions/quick_actions/example/lib/main.dart @@ -57,11 +57,7 @@ class _MyHomePageState extends State { ), // NOTE: This second action icon will only work on Android. // In a real world project keep the same file name for both platforms. - const ShortcutItem( - type: 'action_two', - localizedTitle: 'Action two', - icon: 'ic_launcher', - ), + const ShortcutItem(type: 'action_two', localizedTitle: 'Action two', icon: 'ic_launcher'), ]) .then((void _) { setState(() { diff --git a/packages/quick_actions/quick_actions/lib/quick_actions.dart b/packages/quick_actions/quick_actions/lib/quick_actions.dart index 0bb00502ad42..401500ebb6c9 100644 --- a/packages/quick_actions/quick_actions/lib/quick_actions.dart +++ b/packages/quick_actions/quick_actions/lib/quick_actions.dart @@ -25,6 +25,5 @@ class QuickActions { QuickActionsPlatform.instance.setShortcutItems(items); /// Removes all [ShortcutItem]s registered for the app. - Future clearShortcutItems() => - QuickActionsPlatform.instance.clearShortcutItems(); + Future clearShortcutItems() => QuickActionsPlatform.instance.clearShortcutItems(); } diff --git a/packages/quick_actions/quick_actions/test/quick_actions_test.dart b/packages/quick_actions/quick_actions/test/quick_actions_test.dart index 7ce442feece4..6e09718709cb 100644 --- a/packages/quick_actions/quick_actions/test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions/test/quick_actions_test.dart @@ -34,9 +34,7 @@ void main() { quickActions.setShortcutItems([]); verify(QuickActionsPlatform.instance.initialize(handler)).called(1); - verify( - QuickActionsPlatform.instance.setShortcutItems([]), - ).called(1); + verify(QuickActionsPlatform.instance.setShortcutItems([])).called(1); }); test('clearShortcutItems() PlatformInterface', () { @@ -64,6 +62,6 @@ class MockQuickActionsPlatform extends Mock super.noSuchMethod(Invocation.method(#initialize, [handler])); @override - Future setShortcutItems(List? items) async => super - .noSuchMethod(Invocation.method(#setShortcutItems, [items])); + Future setShortcutItems(List? items) async => + super.noSuchMethod(Invocation.method(#setShortcutItems, [items])); } diff --git a/packages/quick_actions/quick_actions_android/example/lib/main.dart b/packages/quick_actions/quick_actions_android/example/lib/main.dart index 4f3fe3e3eae3..af149b9c30ce 100644 --- a/packages/quick_actions/quick_actions_android/example/lib/main.dart +++ b/packages/quick_actions/quick_actions_android/example/lib/main.dart @@ -47,16 +47,8 @@ class _MyHomePageState extends State { quickActions .setShortcutItems([ - const ShortcutItem( - type: 'action_one', - localizedTitle: 'Action one', - icon: 'AppIcon', - ), - const ShortcutItem( - type: 'action_two', - localizedTitle: 'Action two', - icon: 'ic_launcher', - ), + const ShortcutItem(type: 'action_one', localizedTitle: 'Action one', icon: 'AppIcon'), + const ShortcutItem(type: 'action_two', localizedTitle: 'Action two', icon: 'ic_launcher'), ]) .then((void _) { setState(() { diff --git a/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart b/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart index 496fd0daced1..0184f50f2b4d 100644 --- a/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart +++ b/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart @@ -37,9 +37,7 @@ class QuickActionsAndroid extends QuickActionsPlatform { @override Future setShortcutItems(List items) async { - await _hostApi.setShortcutItems( - items.map(_shortcutItemToShortcutItemMessage).toList(), - ); + await _hostApi.setShortcutItems(items.map(_shortcutItemToShortcutItemMessage).toList()); } @override diff --git a/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart b/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart index 3912c5d2ceb7..6796eeae2c8e 100644 --- a/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart +++ b/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart @@ -37,11 +37,7 @@ Object? _extractReplyValueOrThrow( return replyList.firstOrNull; } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -63,9 +59,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -116,11 +110,7 @@ int _deepHash(Object? value) { /// Home screen quick-action shortcut item. class ShortcutItemMessage { - ShortcutItemMessage({ - required this.type, - required this.localizedTitle, - this.icon, - }); + ShortcutItemMessage({required this.type, required this.localizedTitle, this.icon}); /// The identifier of this item; should be unique within the app. String type; @@ -197,13 +187,11 @@ class AndroidQuickActionsApi { /// Constructor for [AndroidQuickActionsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - AndroidQuickActionsApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + AndroidQuickActionsApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -239,16 +227,10 @@ class AndroidQuickActionsApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [itemsList], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemsList]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } /// Removes all dynamic shortcuts. @@ -263,11 +245,7 @@ class AndroidQuickActionsApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } } @@ -282,9 +260,7 @@ abstract class AndroidQuickActionsFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction$messageChannelSuffix', diff --git a/packages/quick_actions/quick_actions_android/pigeons/messages.dart b/packages/quick_actions/quick_actions_android/pigeons/messages.dart index ed34960d920a..6dee99994841 100644 --- a/packages/quick_actions/quick_actions_android/pigeons/messages.dart +++ b/packages/quick_actions/quick_actions_android/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/quickactions/Messages.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/quickactions/Messages.kt', kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.quickactions'), copyrightHeader: 'pigeons/copyright.txt', ), diff --git a/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart b/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart index dc7acffcca69..df253494bb48 100644 --- a/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart +++ b/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart @@ -14,11 +14,7 @@ const String LAUNCH_ACTION_STRING = 'aString'; /// Conversion tool to change [ShortcutItemMessage] back to [ShortcutItem] ShortcutItem shortcutItemMessageToShortcutItem(ShortcutItemMessage item) { - return ShortcutItem( - type: item.type, - localizedTitle: item.localizedTitle, - icon: item.icon, - ); + return ShortcutItem(type: item.type, localizedTitle: item.localizedTitle, icon: item.icon); } void main() { @@ -49,11 +45,7 @@ void main() { test('setShortCutItems', () async { await quickActions.initialize((String type) {}); - const item = ShortcutItem( - type: 'test', - localizedTitle: 'title', - icon: 'icon.svg', - ); + const item = ShortcutItem(type: 'test', localizedTitle: 'title', icon: 'icon.svg'); await quickActions.setShortcutItems([item]); expect(api.items.first.type, item.type); @@ -63,11 +55,7 @@ void main() { test('clearShortCutItems', () { quickActions.initialize((String type) {}); - const item = ShortcutItem( - type: 'test', - localizedTitle: 'title', - icon: 'icon.svg', - ); + const item = ShortcutItem(type: 'test', localizedTitle: 'title', icon: 'icon.svg'); quickActions.setShortcutItems([item]); quickActions.clearShortcutItems(); @@ -79,11 +67,7 @@ void main() { const localizedTitle = 'title'; const icon = 'foo'; - const item = ShortcutItem( - type: type, - localizedTitle: localizedTitle, - icon: icon, - ); + const item = ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon); expect(item.type, type); expect(item.localizedTitle, localizedTitle); diff --git a/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart b/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart index 328da2f4b829..2df594d38c82 100644 --- a/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart @@ -18,9 +18,6 @@ void main() { localizedTitle: 'Action one', icon: 'AppIcon', ); - expect( - quickActions.setShortcutItems([shortCutItem]), - completes, - ); + expect(quickActions.setShortcutItems([shortCutItem]), completes); }); } diff --git a/packages/quick_actions/quick_actions_ios/example/lib/main.dart b/packages/quick_actions/quick_actions_ios/example/lib/main.dart index 768638538ced..ad3dedea989a 100644 --- a/packages/quick_actions/quick_actions_ios/example/lib/main.dart +++ b/packages/quick_actions/quick_actions_ios/example/lib/main.dart @@ -53,11 +53,7 @@ class _MyHomePageState extends State { localizedSubtitle: 'Action one subtitle', icon: 'AppIcon', ), - const ShortcutItem( - type: 'action_two', - localizedTitle: 'Action two', - icon: 'ic_launcher', - ), + const ShortcutItem(type: 'action_two', localizedTitle: 'Action two', icon: 'ic_launcher'), ]) .then((void _) { setState(() { diff --git a/packages/quick_actions/quick_actions_ios/lib/messages.g.dart b/packages/quick_actions/quick_actions_ios/lib/messages.g.dart index f8767cfe6a80..bc3dc1d6a663 100644 --- a/packages/quick_actions/quick_actions_ios/lib/messages.g.dart +++ b/packages/quick_actions/quick_actions_ios/lib/messages.g.dart @@ -18,11 +18,7 @@ PlatformException _createConnectionError(String channelName) { ); } -List wrapResponse({ - Object? result, - PlatformException? error, - bool empty = false, -}) { +List wrapResponse({Object? result, PlatformException? error, bool empty = false}) { if (empty) { return []; } @@ -35,9 +31,7 @@ List wrapResponse({ bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -136,13 +130,11 @@ class IOSQuickActionsApi { /// Constructor for [IOSQuickActionsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - IOSQuickActionsApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + IOSQuickActionsApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -153,17 +145,13 @@ class IOSQuickActionsApi { Future setShortcutItems(List itemsList) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.setShortcutItems$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [itemsList], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([itemsList]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -181,15 +169,13 @@ class IOSQuickActionsApi { Future clearShortcutItems() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsApi.clearShortcutItems$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -215,12 +201,9 @@ abstract class IOSQuickActionsFlutterApi { BinaryMessenger? binaryMessenger, String messageChannelSuffix = '', }) { - messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.quick_actions_ios.IOSQuickActionsFlutterApi.launchAction$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, diff --git a/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart b/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart index 4c057f6553ec..0092a026c26d 100644 --- a/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart +++ b/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart @@ -33,9 +33,7 @@ class QuickActionsIos extends QuickActionsPlatform { @override Future setShortcutItems(List items) async { - await _hostApi.setShortcutItems( - items.map(_shortcutItemToShortcutItemMessage).toList(), - ); + await _hostApi.setShortcutItems(items.map(_shortcutItemToShortcutItemMessage).toList()); } @override diff --git a/packages/quick_actions/quick_actions_ios/pigeons/messages.dart b/packages/quick_actions/quick_actions_ios/pigeons/messages.dart index 53c95fff5c85..08554e795933 100644 --- a/packages/quick_actions/quick_actions_ios/pigeons/messages.dart +++ b/packages/quick_actions/quick_actions_ios/pigeons/messages.dart @@ -7,19 +7,13 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/messages.g.dart', - swiftOut: - 'ios/quick_actions_ios/Sources/quick_actions_ios/messages.g.swift', + swiftOut: 'ios/quick_actions_ios/Sources/quick_actions_ios/messages.g.swift', copyrightHeader: 'pigeons/copyright.txt', ), ) /// Home screen quick-action shortcut item. class ShortcutItemMessage { - ShortcutItemMessage( - this.type, - this.localizedTitle, - this.localizedSubtitle, - this.icon, - ); + ShortcutItemMessage(this.type, this.localizedTitle, this.localizedSubtitle, this.icon); /// The identifier of this item; should be unique within the app. String type; diff --git a/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart b/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart index 3cbdba1b705a..4996ee54fbb5 100644 --- a/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart +++ b/packages/quick_actions/quick_actions_platform_interface/lib/method_channel/method_channel_quick_actions.dart @@ -8,9 +8,7 @@ import 'package:flutter/services.dart'; import '../platform_interface/quick_actions_platform.dart'; import '../types/types.dart'; -const MethodChannel _channel = MethodChannel( - 'plugins.flutter.io/quick_actions', -); +const MethodChannel _channel = MethodChannel('plugins.flutter.io/quick_actions'); /// An implementation of [QuickActionsPlatform] that uses method channels. class MethodChannelQuickActions extends QuickActionsPlatform { @@ -24,9 +22,7 @@ class MethodChannelQuickActions extends QuickActionsPlatform { assert(call.method == 'launch'); handler(call.arguments as String); }); - final String? action = await channel.invokeMethod( - 'getLaunchAction', - ); + final String? action = await channel.invokeMethod('getLaunchAction'); if (action != null) { handler(action); } @@ -34,22 +30,18 @@ class MethodChannelQuickActions extends QuickActionsPlatform { @override Future setShortcutItems(List items) async { - final List> itemsList = items - .map(_serializeItem) - .toList(); + final List> itemsList = items.map(_serializeItem).toList(); await channel.invokeMethod('setShortcutItems', itemsList); } @override - Future clearShortcutItems() => - channel.invokeMethod('clearShortcutItems'); + Future clearShortcutItems() => channel.invokeMethod('clearShortcutItems'); Map _serializeItem(ShortcutItem item) { return { 'type': item.type, 'localizedTitle': item.localizedTitle, - if (item.localizedSubtitle != null) - 'localizedSubtitle': item.localizedSubtitle, + if (item.localizedSubtitle != null) 'localizedSubtitle': item.localizedSubtitle, 'icon': item.icon, }; } diff --git a/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart b/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart index d9f5b7cfe148..891a611c22d7 100644 --- a/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart +++ b/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart @@ -18,13 +18,13 @@ void main() { final log = []; setUp(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(quickActions.channel, ( - MethodCall methodCall, - ) async { - log.add(methodCall); - return ''; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + quickActions.channel, + (MethodCall methodCall) async { + log.add(methodCall); + return ''; + }, + ); log.clear(); }); @@ -33,19 +33,13 @@ void main() { test('passes getLaunchAction on launch method', () { quickActions.initialize((String type) {}); - expect(log, [ - isMethodCall('getLaunchAction', arguments: null), - ]); + expect(log, [isMethodCall('getLaunchAction', arguments: null)]); }); test('initialize', () async { final quickActionsHandler = Completer(); - await quickActions.initialize( - (_) => quickActionsHandler.complete(true), - ); - expect(log, [ - isMethodCall('getLaunchAction', arguments: null), - ]); + await quickActions.initialize((_) => quickActionsHandler.complete(true)); + expect(log, [isMethodCall('getLaunchAction', arguments: null)]); log.clear(); expect(quickActionsHandler.future, completion(isTrue)); @@ -80,33 +74,22 @@ void main() { ]); }); - test( - 'passes shortcutItem through channel with null localizedSubtitle', - () { - quickActions.initialize((String type) {}); - quickActions.setShortcutItems([ - const ShortcutItem( - type: 'test', - localizedTitle: 'title', - icon: 'icon.svg', - ), - ]); - - expect(log, [ - isMethodCall('getLaunchAction', arguments: null), - isMethodCall( - 'setShortcutItems', - arguments: >[ - { - 'type': 'test', - 'localizedTitle': 'title', - 'icon': 'icon.svg', - }, - ], - ), - ]); - }, - ); + test('passes shortcutItem through channel with null localizedSubtitle', () { + quickActions.initialize((String type) {}); + quickActions.setShortcutItems([ + const ShortcutItem(type: 'test', localizedTitle: 'title', icon: 'icon.svg'), + ]); + + expect(log, [ + isMethodCall('getLaunchAction', arguments: null), + isMethodCall( + 'setShortcutItems', + arguments: >[ + {'type': 'test', 'localizedTitle': 'title', 'icon': 'icon.svg'}, + ], + ), + ]); + }); test('setShortcutItems with demo data', () async { const type = 'type'; @@ -151,9 +134,7 @@ void main() { test('clearShortcutItems', () { quickActions.clearShortcutItems(); - expect(log, [ - isMethodCall('clearShortcutItems', arguments: null), - ]); + expect(log, [isMethodCall('clearShortcutItems', arguments: null)]); log.clear(); }); }); diff --git a/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart b/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart index 7614088b9cfe..c9c9c2c6a023 100644 --- a/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart +++ b/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart @@ -35,47 +35,32 @@ void main() { QuickActionsPlatform.instance = ExtendsQuickActionsPlatform(); }); - test( - 'Default implementation of initialize() should throw unimplemented error', - () { - // Arrange - final quickActionsPlatform = ExtendsQuickActionsPlatform(); + test('Default implementation of initialize() should throw unimplemented error', () { + // Arrange + final quickActionsPlatform = ExtendsQuickActionsPlatform(); - // Act & Assert - expect( - () => quickActionsPlatform.initialize((String type) {}), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => quickActionsPlatform.initialize((String type) {}), throwsUnimplementedError); + }); - test( - 'Default implementation of setShortcutItems() should throw unimplemented error', - () { - // Arrange - final quickActionsPlatform = ExtendsQuickActionsPlatform(); + test('Default implementation of setShortcutItems() should throw unimplemented error', () { + // Arrange + final quickActionsPlatform = ExtendsQuickActionsPlatform(); - // Act & Assert - expect( - () => quickActionsPlatform.setShortcutItems([]), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect( + () => quickActionsPlatform.setShortcutItems([]), + throwsUnimplementedError, + ); + }); - test( - 'Default implementation of clearShortcutItems() should throw unimplemented error', - () { - // Arrange - final quickActionsPlatform = ExtendsQuickActionsPlatform(); + test('Default implementation of clearShortcutItems() should throw unimplemented error', () { + // Arrange + final quickActionsPlatform = ExtendsQuickActionsPlatform(); - // Act & Assert - expect( - () => quickActionsPlatform.clearShortcutItems(), - throwsUnimplementedError, - ); - }, - ); + // Act & Assert + expect(() => quickActionsPlatform.clearShortcutItems(), throwsUnimplementedError); + }); }); } diff --git a/packages/rfw/example/local/lib/main.dart b/packages/rfw/example/local/lib/main.dart index 7ff576b6cba8..c9509994fbe7 100644 --- a/packages/rfw/example/local/lib/main.dart +++ b/packages/rfw/example/local/lib/main.dart @@ -49,10 +49,7 @@ class _ExampleState extends State { static WidgetLibrary _createLocalWidgets() { return LocalWidgetLibrary({ 'GreenBox': (BuildContext context, DataSource source) { - return ColoredBox( - color: const Color(0xFF002211), - child: source.child(['child']), - ); + return ColoredBox(color: const Color(0xFF002211), child: source.child(['child'])); }, 'Hello': (BuildContext context, DataSource source) { return Center( diff --git a/packages/rfw/example/remote/lib/main.dart b/packages/rfw/example/remote/lib/main.dart index 368f6da11c5f..a73b911f43b6 100644 --- a/packages/rfw/example/remote/lib/main.dart +++ b/packages/rfw/example/remote/lib/main.dart @@ -11,7 +11,8 @@ import 'package:path/path.dart' as path; import 'package:path_provider/path_provider.dart'; import 'package:rfw/rfw.dart'; -const String urlPrefix = 'https://raw.githubusercontent.com/flutter/packages/main/packages/rfw/example/remote/remote_widget_libraries'; +const String urlPrefix = + 'https://raw.githubusercontent.com/flutter/packages/main/packages/rfw/example/remote/remote_widget_libraries'; void main() { runApp(const MaterialApp(home: Example())); @@ -57,7 +58,10 @@ class _ExampleState extends State { final currentFile = File(path.join(home.path, 'current.rfw')); if (currentFile.existsSync()) { try { - _runtime.update(const LibraryName(['main']), decodeLibraryBlob(await currentFile.readAsBytes())); + _runtime.update( + const LibraryName(['main']), + decodeLibraryBlob(await currentFile.readAsBytes()), + ); setState(() { _ready = true; }); @@ -66,7 +70,9 @@ class _ExampleState extends State { } } print('Fetching: $urlPrefix/$nextFile'); // ignore: avoid_print - final HttpClientResponse client = await (await HttpClient().getUrl(Uri.parse('$urlPrefix/$nextFile'))).close(); + final HttpClientResponse client = await (await HttpClient().getUrl( + Uri.parse('$urlPrefix/$nextFile'), + )).close(); await currentFile.writeAsBytes(await client.expand((List chunk) => chunk).toList()); await settingsFile.writeAsString(nextFile); } @@ -94,19 +100,57 @@ class _ExampleState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding(padding: EdgeInsets.only(right: 100.0), child: Text('REMOTE', textAlign: TextAlign.center, style: TextStyle(letterSpacing: 12.0))), - Expanded(child: DecoratedBox(decoration: FlutterLogoDecoration(style: FlutterLogoStyle.horizontal))), - Padding(padding: EdgeInsets.only(left: 100.0), child: Text('WIDGETS', textAlign: TextAlign.center, style: TextStyle(letterSpacing: 12.0))), + Padding( + padding: EdgeInsets.only(right: 100.0), + child: Text( + 'REMOTE', + textAlign: TextAlign.center, + style: TextStyle(letterSpacing: 12.0), + ), + ), + Expanded( + child: DecoratedBox( + decoration: FlutterLogoDecoration(style: FlutterLogoStyle.horizontal), + ), + ), + Padding( + padding: EdgeInsets.only(left: 100.0), + child: Text( + 'WIDGETS', + textAlign: TextAlign.center, + style: TextStyle(letterSpacing: 12.0), + ), + ), Spacer(), - Expanded(child: Text('Every time this program is run, it fetches a new remote widgets library.', textAlign: TextAlign.center)), - Expanded(child: Text('The interface that it shows is whatever library was last fetched.', textAlign: TextAlign.center)), - Expanded(child: Text('Restart this application to see the new interface!', textAlign: TextAlign.center)), + Expanded( + child: Text( + 'Every time this program is run, it fetches a new remote widgets library.', + textAlign: TextAlign.center, + ), + ), + Expanded( + child: Text( + 'The interface that it shows is whatever library was last fetched.', + textAlign: TextAlign.center, + ), + ), + Expanded( + child: Text( + 'Restart this application to see the new interface!', + textAlign: TextAlign.center, + ), + ), ], ), ), ), ); } - return AnimatedSwitcher(duration: const Duration(milliseconds: 1250), switchOutCurve: Curves.easeOut, switchInCurve: Curves.easeOut, child: result); + return AnimatedSwitcher( + duration: const Duration(milliseconds: 1250), + switchOutCurve: Curves.easeOut, + switchInCurve: Curves.easeOut, + child: result, + ); } } diff --git a/packages/rfw/lib/src/dart/binary.dart b/packages/rfw/lib/src/dart/binary.dart index a49190407f6c..67575fe7aea9 100644 --- a/packages/rfw/lib/src/dart/binary.dart +++ b/packages/rfw/lib/src/dart/binary.dart @@ -378,12 +378,14 @@ class _BlobDecoder { case _msInt64: return _readInt64(); default: - throw FormatException('Invalid reference type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding blob.'); + throw FormatException( + 'Invalid reference type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding blob.', + ); } }); } - Map? _readMap(Object Function() readNode, { bool nullIfEmpty = false }) { + Map? _readMap(Object Function() readNode, {bool nullIfEmpty = false}) { final int count = _readInt64(); if (count == 0 && nullIfEmpty) { return null; @@ -391,10 +393,7 @@ class _BlobDecoder { return DynamicMap.fromEntries( Iterable>.generate( count, - (int index) => MapEntry( - _readString(), - readNode(), - ), + (int index) => MapEntry(_readString(), readNode()), ), ); } @@ -413,10 +412,7 @@ class _BlobDecoder { final cases = Map.fromEntries( Iterable>.generate( count, - (int index) => MapEntry( - _readSwitchKey(), - _readArgument(), - ), + (int index) => MapEntry(_readSwitchKey(), _readArgument()), ), ); return Switch(value, cases); @@ -438,7 +434,10 @@ class _BlobDecoder { return DynamicList.generate(_readInt64(), (int index) => readNode()); case _msMap: return _readMap(readNode)!; - default: throw FormatException('Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding blob.'); + default: + throw FormatException( + 'Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding blob.', + ); } } @@ -490,7 +489,9 @@ class _BlobDecoder { final String argumentName = _readString(); final int type = _readByte(); if (type != _msWidget && type != _msSwitch) { - throw FormatException('Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding widget builder blob.'); + throw FormatException( + 'Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding widget builder blob.', + ); } final BlobNode widget = type == _msWidget ? _readWidget() : _readSwitch(); return WidgetBuilderDeclaration(argumentName, widget); @@ -507,7 +508,9 @@ class _BlobDecoder { case _msWidget: root = _readWidget(); default: - throw FormatException('Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding widget declaration root.'); + throw FormatException( + 'Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding widget declaration root.', + ); } return WidgetDeclaration(name, initialState, root); } @@ -543,7 +546,7 @@ class _BlobDecoder { throw FormatException( 'File signature mismatch. ' 'Expected ${signature.map((int byte) => byte.toRadixString(16).toUpperCase().padLeft(2, "0")).join(" ")} ' - 'but found ${bytes.map((int byte) => byte.toRadixString(16).toUpperCase().padLeft(2, "0")).join(" ")}.' + 'but found ${bytes.map((int byte) => byte.toRadixString(16).toUpperCase().padLeft(2, "0")).join(" ")}.', ); } } @@ -560,9 +563,13 @@ class _BlobEncoder { _BlobEncoder(); static final Uint8List _scratchOut = Uint8List(8); - static final ByteData _scratchIn = _scratchOut.buffer.asByteData(_scratchOut.offsetInBytes, _scratchOut.lengthInBytes); + static final ByteData _scratchIn = _scratchOut.buffer.asByteData( + _scratchOut.offsetInBytes, + _scratchOut.lengthInBytes, + ); - final BytesBuilder bytes = BytesBuilder(); // copying builder -- we repeatedly add _scratchOut after changing it + final BytesBuilder bytes = + BytesBuilder(); // copying builder -- we repeatedly add _scratchOut after changing it void _writeInt64(int value) { if (_has64Bits) { @@ -570,12 +577,17 @@ class _BlobEncoder { } else { // We use division rather than bit shifts because >> truncates to 32 bits when compiled to JS: // https://dart.dev/guides/language/numbers#bitwise-operations - if (value >= 0) { // dead code on VM target + if (value >= 0) { + // dead code on VM target _scratchIn.setInt32(0, value, _blobEndian); // dead code on VM target _scratchIn.setInt32(4, value ~/ 0x100000000, _blobEndian); // dead code on VM target } else { _scratchIn.setInt32(0, value, _blobEndian); // dead code on VM target - _scratchIn.setInt32(4, -((-value) ~/ 0x100000000 + 1), _blobEndian); // dead code on VM target + _scratchIn.setInt32( + 4, + -((-value) ~/ 0x100000000 + 1), + _blobEndian, + ); // dead code on VM target } } bytes.add(_scratchOut); @@ -612,7 +624,8 @@ class _BlobEncoder { bytes.addByte(_msFalse); } else if (value == true) { bytes.addByte(_msTrue); - } else if (value is double && value is! int) { // When compiled to JS, a Number can be both. + } else if (value is double && value is! int) { + // When compiled to JS, a Number can be both. bytes.addByte(_msBinary64); _scratchIn.setFloat64(0, value, _blobEndian); bytes.add(_scratchOut); diff --git a/packages/rfw/lib/src/dart/model.dart b/packages/rfw/lib/src/dart/model.dart index 2af5adeca276..ec614065a5db 100644 --- a/packages/rfw/lib/src/dart/model.dart +++ b/packages/rfw/lib/src/dart/model.dart @@ -61,9 +61,7 @@ class SourceLocation implements Comparable { if (other.runtimeType != SourceLocation) { return false; } - return other is SourceLocation - && source == other.source - && offset == other.offset; + return other is SourceLocation && source == other.source && offset == other.offset; } @override @@ -137,8 +135,11 @@ class SourceRange { /// /// They must have identical [SourceLocation.source] objects. SourceRange(this.start, this.end) - : assert(start.source == end.source, 'The start and end locations have inconsistent source information.'), - assert(start < end, 'The start location must be before the end location.'); + : assert( + start.source == end.source, + 'The start and end locations have inconsistent source information.', + ), + assert(start < end, 'The start location must be before the end location.'); /// The start of a contiguous region of a source file that corresponds to a /// particular [BlobNode]. @@ -157,9 +158,7 @@ class SourceRange { if (other.runtimeType != SourceRange) { return false; } - return other is SourceRange - && start == other.start - && end == other.end; + return other is SourceRange && start == other.start && end == other.end; } @override @@ -278,8 +277,7 @@ class LibraryName implements Comparable { if (other.runtimeType != runtimeType) { return false; } - return other is LibraryName - && _listEquals(parts, other.parts); + return other is LibraryName && _listEquals(parts, other.parts); } @override @@ -323,8 +321,7 @@ class FullyQualifiedWidgetName implements Comparable { if (other.runtimeType != runtimeType) { return false; } - return other is FullyQualifiedWidgetName - && library == other.library && widget == other.widget; + return other is FullyQualifiedWidgetName && library == other.library && widget == other.widget; } @override @@ -514,7 +511,7 @@ class BoundArgsReference extends Reference { /// The parameters must not be mutated after the object is created. /// /// Generally this class is created using [ArgsReference.bind]. - const BoundArgsReference(this.arguments, List parts): super(parts); + const BoundArgsReference(this.arguments, List parts) : super(parts); /// The object into which [parts] will be indexed. /// @@ -586,7 +583,7 @@ class LoopReference extends Reference { /// Wraps the given [loop] and [parts] as a [LoopReference]. /// /// The [parts] must not be mutated after the object is created. - const LoopReference(this.loop, List parts): super(parts); + const LoopReference(this.loop, List parts) : super(parts); /// The index to the referenced loop. /// @@ -643,7 +640,7 @@ class BoundLoopReference extends Reference { /// The [parts] must not be mutated after the object is created. /// /// Generally this class is created using [LoopReference.bind]. - const BoundLoopReference(this.value, List parts): super(parts); + const BoundLoopReference(this.value, List parts) : super(parts); /// The object into which [parts] will index. /// @@ -724,7 +721,7 @@ class BoundStateReference extends AnyStateReference { /// The [parts] must not be mutated after the object is created. /// /// Generally this class is created using [StateReference.bind]. - const BoundStateReference(this.depth, List parts): super(parts); + const BoundStateReference(this.depth, List parts) : super(parts); /// The widget to whose state the state reference refers. /// @@ -849,7 +846,8 @@ class WidgetDeclaration extends BlobNode { /// Binds the given [name] to the definition given by [root]. /// /// The [initialState] may be null. If it is not, this represents a stateful widget. - const WidgetDeclaration(this.name, this.initialState, this.root) : assert(root is ConstructorCall || root is Switch); + const WidgetDeclaration(this.name, this.initialState, this.root) + : assert(root is ConstructorCall || root is Switch); /// The name of the widget that this declaration represents. /// @@ -900,5 +898,6 @@ class RemoteWidgetLibrary extends WidgetLibrary { final List widgets; @override - String toString() => const Iterable.empty().followedBy(imports).followedBy(widgets).join('\n'); + String toString() => + const Iterable.empty().followedBy(imports).followedBy(widgets).join('\n'); } diff --git a/packages/rfw/lib/src/dart/text.dart b/packages/rfw/lib/src/dart/text.dart index b036490fc75d..7af99f76146b 100644 --- a/packages/rfw/lib/src/dart/text.dart +++ b/packages/rfw/lib/src/dart/text.dart @@ -627,7 +627,7 @@ DynamicMap parseDataFile(String file) { /// * [parseDataFile], which uses a subset of this format to decode /// Remote Flutter Widgets text data files. /// * [decodeLibraryBlob], which decodes the binary variant of this format. -RemoteWidgetLibrary parseLibraryFile(String file, { Object? sourceIdentifier }) { +RemoteWidgetLibrary parseLibraryFile(String file, {Object? sourceIdentifier}) { final parser = _Parser(_tokenize(file), sourceIdentifier); return parser.readLibraryFile(); } @@ -657,7 +657,8 @@ sealed class _Token { } class _SymbolToken extends _Token { - _SymbolToken(this.symbol, int line, int column, int start, int end): super(line, column, start, end); + _SymbolToken(this.symbol, int line, int column, int start, int end) + : super(line, column, start, end); final int symbol; static const int dot = 0x2E; @@ -679,7 +680,8 @@ class _SymbolToken extends _Token { } class _IntegerToken extends _Token { - _IntegerToken(this.value, int line, int column, int start, int end): super(line, column, start, end); + _IntegerToken(this.value, int line, int column, int start, int end) + : super(line, column, start, end); final int value; @override @@ -687,7 +689,8 @@ class _IntegerToken extends _Token { } class _DoubleToken extends _Token { - _DoubleToken(this.value, int line, int column, int start, int end): super(line, column, start, end); + _DoubleToken(this.value, int line, int column, int start, int end) + : super(line, column, start, end); final double value; @override @@ -695,7 +698,8 @@ class _DoubleToken extends _Token { } class _IdentifierToken extends _Token { - _IdentifierToken(this.value, int line, int column, int start, int end): super(line, column, start, end); + _IdentifierToken(this.value, int line, int column, int start, int end) + : super(line, column, start, end); final String value; @override @@ -703,7 +707,8 @@ class _IdentifierToken extends _Token { } class _StringToken extends _Token { - _StringToken(this.value, int line, int column, int start, int end): super(line, column, start, end); + _StringToken(this.value, int line, int column, int start, int end) + : super(line, column, start, end); final String value; @override @@ -836,7 +841,6 @@ Iterable<_Token> _tokenize(String file) sync* { } index += 1; switch (mode) { - case _TokenizerMode.main: switch (current) { case -1: @@ -966,7 +970,11 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.minusInteger; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} after minus sign (expected digit)', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after minus sign (expected digit)', + line, + column, + ); } case _TokenizerMode.zero: // "0" @@ -1021,18 +1029,34 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.x; buffer.clear(); default: - throw ParserException('Unexpected character ${_describeRune(current)} after zero', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after zero', + line, + column, + ); } case _TokenizerMode.minusInteger: // "-0" switch (current) { case -1: - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); yield _EofToken(line, column, index - 1, index); return; case 0x0A: // U+000A LINE FEED (LF) case 0x20: // U+0020 SPACE character - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); start = index; mode = _TokenizerMode.main; @@ -1046,7 +1070,13 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x5D: // U+005D RIGHT SQUARE BRACKET character (]) case 0x7B: // U+007B LEFT CURLY BRACKET character ({) case 0x7D: // U+007D RIGHT CURLY BRACKET character (}) - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _SymbolToken(current, line, column, index - 1, index); start = index; @@ -1071,19 +1101,35 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.e; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} after negative zero', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after negative zero', + line, + column, + ); } case _TokenizerMode.integer: // "00", "1", "-00" switch (current) { case -1: - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _EofToken(line, column, index - 1, index); return; case 0x0A: // U+000A LINE FEED (LF) case 0x20: // U+0020 SPACE character - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); start = index; mode = _TokenizerMode.main; @@ -1097,7 +1143,13 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x5D: // U+005D RIGHT SQUARE BRACKET character (]) case 0x7B: // U+007B LEFT CURLY BRACKET character ({) case 0x7D: // U+007D RIGHT CURLY BRACKET character (}) - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _SymbolToken(current, line, column, index - 1, index); start = index; @@ -1127,13 +1179,25 @@ Iterable<_Token> _tokenize(String file) sync* { case _TokenizerMode.integerOnly: switch (current) { case -1: - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _EofToken(line, column, index - 1, index); return; case 0x0A: // U+000A LINE FEED (LF) case 0x20: // U+0020 SPACE character - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); start = index; mode = _TokenizerMode.main; @@ -1147,13 +1211,25 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x5D: // U+005D RIGHT SQUARE BRACKET character (]) case 0x7B: // U+007B LEFT CURLY BRACKET character ({) case 0x7D: // U+007D RIGHT CURLY BRACKET character (}) - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _SymbolToken(current, line, column, index - 1, index); start = index; mode = _TokenizerMode.main; case 0x2E: // U+002E FULL STOP character (.) - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 10), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 10), + line, + column, + start, + index - 1, + ); buffer.clear(); start = index; mode = _TokenizerMode.dot1; @@ -1169,7 +1245,11 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x39: // U+0039 DIGIT NINE character (9) buffer.add(current); // https://github.com/dart-lang/sdk/issues/53349 default: - throw ParserException('Unexpected character ${_describeRune(current)} in integer', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in integer', + line, + column, + ); } case _TokenizerMode.numericDot: // "0.", "-0.", "00.", "1.", "-00." @@ -1189,18 +1269,34 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.fraction; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} in fraction component', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in fraction component', + line, + column, + ); } case _TokenizerMode.fraction: // "0.0", "-0.0", "00.0", "1.0", "-00.0" switch (current) { case -1: - yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1); + yield _DoubleToken( + double.parse(String.fromCharCodes(buffer)), + line, + column, + start, + index - 1, + ); yield _EofToken(line, column, index - 1, index); return; case 0x0A: // U+000A LINE FEED (LF) case 0x20: // U+0020 SPACE character - yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1); + yield _DoubleToken( + double.parse(String.fromCharCodes(buffer)), + line, + column, + start, + index - 1, + ); buffer.clear(); start = index; mode = _TokenizerMode.main; @@ -1214,7 +1310,13 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x5D: // U+005D RIGHT SQUARE BRACKET character (]) case 0x7B: // U+007B LEFT CURLY BRACKET character ({) case 0x7D: // U+007D RIGHT CURLY BRACKET character (}) - yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1); + yield _DoubleToken( + double.parse(String.fromCharCodes(buffer)), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _SymbolToken(current, line, column, index - 1, index); start = index; @@ -1235,10 +1337,15 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.e; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} in fraction component', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in fraction component', + line, + column, + ); } - case _TokenizerMode.e: // "0e", "-0e", "00e", "1e", "-00e", "0.0e", "-0.0e", "00.0e", "1.0e", "-00.0e" + case _TokenizerMode + .e: // "0e", "-0e", "00e", "1e", "-00e", "0.0e", "-0.0e", "00.0e", "1.0e", "-00.0e" switch (current) { case -1: throw ParserException('Unexpected end of file after exponent separator', line, column); @@ -1258,13 +1365,22 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.exponent; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} after exponent separator', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after exponent separator', + line, + column, + ); } - case _TokenizerMode.negativeExponent: // "0e-", "-0e-", "00e-", "1e-", "-00e-", "0.0e-", "-0.0e-", "00.0e-", "1.0e-", "-00.0e-" + case _TokenizerMode + .negativeExponent: // "0e-", "-0e-", "00e-", "1e-", "-00e-", "0.0e-", "-0.0e-", "00.0e-", "1.0e-", "-00.0e-" switch (current) { case -1: - throw ParserException('Unexpected end of file after exponent separator and minus sign', line, column); + throw ParserException( + 'Unexpected end of file after exponent separator and minus sign', + line, + column, + ); case 0x30: // U+0030 DIGIT ZERO character (0) case 0x31: // U+0031 DIGIT ONE character (1) case 0x32: // U+0032 DIGIT TWO character (2) @@ -1278,18 +1394,35 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.exponent; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} in exponent', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in exponent', + line, + column, + ); } - case _TokenizerMode.exponent: // "0e0", "-0e0", "00e0", "1e0", "-00e0", "0.0e0", "-0.0e0", "00.0e0", "1.0e0", "-00.0e0", "0e-0", "-0e-0", "00e-0", "1e-0", "-00e-0", "0.0e-0", "-0.0e-0", "00.0e-0", "1.0e-0", "-00.0e-0" + case _TokenizerMode + .exponent: // "0e0", "-0e0", "00e0", "1e0", "-00e0", "0.0e0", "-0.0e0", "00.0e0", "1.0e0", "-00.0e0", "0e-0", "-0e-0", "00e-0", "1e-0", "-00e-0", "0.0e-0", "-0.0e-0", "00.0e-0", "1.0e-0", "-00.0e-0" switch (current) { case -1: - yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1); + yield _DoubleToken( + double.parse(String.fromCharCodes(buffer)), + line, + column, + start, + index - 1, + ); yield _EofToken(line, column, index - 1, index); return; case 0x0A: // U+000A LINE FEED (LF) case 0x20: // U+0020 SPACE character - yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1); + yield _DoubleToken( + double.parse(String.fromCharCodes(buffer)), + line, + column, + start, + index - 1, + ); buffer.clear(); start = index; mode = _TokenizerMode.main; @@ -1303,7 +1436,13 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x5D: // U+005D RIGHT SQUARE BRACKET character (]) case 0x7B: // U+007B LEFT CURLY BRACKET character ({) case 0x7D: // U+007D RIGHT CURLY BRACKET character (}) - yield _DoubleToken(double.parse(String.fromCharCodes(buffer)), line, column, start, index - 1); + yield _DoubleToken( + double.parse(String.fromCharCodes(buffer)), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _SymbolToken(current, line, column, index - 1, index); start = index; @@ -1320,7 +1459,11 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x39: // U+0039 DIGIT NINE character (9) buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} in exponent', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in exponent', + line, + column, + ); } case _TokenizerMode.x: // "0x", "0X" @@ -1352,18 +1495,34 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.hex; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} after 0x prefix', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after 0x prefix', + line, + column, + ); } case _TokenizerMode.hex: switch (current) { case -1: - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 16), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 16), + line, + column, + start, + index - 1, + ); yield _EofToken(line, column, index - 1, index); return; case 0x0A: // U+000A LINE FEED (LF) case 0x20: // U+0020 SPACE character - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 16), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 16), + line, + column, + start, + index - 1, + ); buffer.clear(); start = index; mode = _TokenizerMode.main; @@ -1377,7 +1536,13 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x5D: // U+005D RIGHT SQUARE BRACKET character (]) case 0x7B: // U+007B LEFT CURLY BRACKET character ({) case 0x7D: // U+007D RIGHT CURLY BRACKET character (}) - yield _IntegerToken(int.parse(String.fromCharCodes(buffer), radix: 16), line, column, start, index - 1); + yield _IntegerToken( + int.parse(String.fromCharCodes(buffer), radix: 16), + line, + column, + start, + index - 1, + ); buffer.clear(); yield _SymbolToken(current, line, column, index - 1, index); start = index; @@ -1406,7 +1571,11 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x66: // U+0066 LATIN SMALL LETTER F character buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} in hex literal', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in hex literal', + line, + column, + ); } case _TokenizerMode.dot1: // "." @@ -1520,7 +1689,11 @@ Iterable<_Token> _tokenize(String file) sync* { mode = _TokenizerMode.identifier; buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} after period', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after period', + line, + column, + ); } case _TokenizerMode.dot2: // ".." @@ -1532,7 +1705,11 @@ Iterable<_Token> _tokenize(String file) sync* { start = index; mode = _TokenizerMode.main; default: - throw ParserException('Unexpected character ${_describeRune(current)} inside "..." symbol', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} inside "..." symbol', + line, + column, + ); } case _TokenizerMode.identifier: @@ -1632,7 +1809,11 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x5F: // U+005F LOW LINE character (_) buffer.add(current); default: - throw ParserException('Unexpected character ${_describeRune(current)} inside identifier', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} inside identifier', + line, + column, + ); } case _TokenizerMode.quote: @@ -1681,7 +1862,11 @@ Iterable<_Token> _tokenize(String file) sync* { assert(buffer2.isEmpty); mode = _TokenizerMode.quoteEscapeUnicode1; default: - throw ParserException('Unexpected character ${_describeRune(current)} after backslash in string', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after backslash in string', + line, + column, + ); } case _TokenizerMode.quoteEscapeUnicode1: @@ -1713,7 +1898,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.add(current); mode = _TokenizerMode.quoteEscapeUnicode2; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.quoteEscapeUnicode2: @@ -1745,7 +1934,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.add(current); mode = _TokenizerMode.quoteEscapeUnicode3; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.quoteEscapeUnicode3: @@ -1777,7 +1970,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.add(current); mode = _TokenizerMode.quoteEscapeUnicode4; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.quoteEscapeUnicode4: @@ -1811,7 +2008,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.clear(); mode = _TokenizerMode.quote; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.doubleQuote: @@ -1860,7 +2061,11 @@ Iterable<_Token> _tokenize(String file) sync* { assert(buffer2.isEmpty); mode = _TokenizerMode.doubleQuoteEscapeUnicode1; default: - throw ParserException('Unexpected character ${_describeRune(current)} after backslash in string', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after backslash in string', + line, + column, + ); } case _TokenizerMode.doubleQuoteEscapeUnicode1: @@ -1892,7 +2097,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.add(current); mode = _TokenizerMode.doubleQuoteEscapeUnicode2; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.doubleQuoteEscapeUnicode2: @@ -1924,7 +2133,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.add(current); mode = _TokenizerMode.doubleQuoteEscapeUnicode3; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.doubleQuoteEscapeUnicode3: @@ -1956,7 +2169,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.add(current); mode = _TokenizerMode.doubleQuoteEscapeUnicode4; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.doubleQuoteEscapeUnicode4: @@ -1990,7 +2207,11 @@ Iterable<_Token> _tokenize(String file) sync* { buffer2.clear(); mode = _TokenizerMode.doubleQuote; default: - throw ParserException('Unexpected character ${_describeRune(current)} in Unicode escape', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} in Unicode escape', + line, + column, + ); } case _TokenizerMode.endQuote: @@ -2018,7 +2239,11 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x2E: // U+002E FULL STOP character (.) mode = _TokenizerMode.dot1; default: - throw ParserException('Unexpected character ${_describeRune(current)} after end quote', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} after end quote', + line, + column, + ); } case _TokenizerMode.slash: @@ -2030,7 +2255,11 @@ Iterable<_Token> _tokenize(String file) sync* { case 0x2F: // U+002F SOLIDUS character (/) mode = _TokenizerMode.comment; default: - throw ParserException('Unexpected character ${_describeRune(current)} inside comment delimiter', line, column); + throw ParserException( + 'Unexpected character ${_describeRune(current)} inside comment delimiter', + line, + column, + ); } case _TokenizerMode.comment: @@ -2100,17 +2329,14 @@ class _Parser { T _withSourceRange(T node, SourceLocation? start) { if (sourceIdentifier != null && start != null) { - node.associateSource(SourceRange( - start, - SourceLocation(sourceIdentifier!, _previousEnd), - )); + node.associateSource(SourceRange(start, SourceLocation(sourceIdentifier!, _previousEnd))); } return node; } bool _foundIdentifier(String identifier) { - return (_source.current is _IdentifierToken) - && ((_source.current as _IdentifierToken).value == identifier); + return (_source.current is _IdentifierToken) && + ((_source.current as _IdentifierToken).value == identifier); } void _expectIdentifier(String value) { @@ -2142,8 +2368,8 @@ class _Parser { } bool _foundSymbol(int symbol) { - return (_source.current is _SymbolToken) - && ((_source.current as _SymbolToken).symbol == symbol); + return (_source.current is _SymbolToken) && + ((_source.current as _SymbolToken).symbol == symbol); } bool _maybeReadSymbol(int symbol) { @@ -2243,10 +2469,7 @@ class _Parser { _loopIdentifiers.removeLast(); results.add(_withSourceRange(Loop(collection, template), start)); } else { - final Object value = _readValue( - widgetBuilderScope: widgetBuilderScope, - extended: extended, - ); + final Object value = _readValue(widgetBuilderScope: widgetBuilderScope, extended: extended); results.add(value); } if (_foundSymbol(_SymbolToken.comma)) { @@ -2259,9 +2482,7 @@ class _Parser { return results; } - Switch _readSwitch(SourceLocation? start, { - List widgetBuilderScope = const [], - }) { + Switch _readSwitch(SourceLocation? start, {List widgetBuilderScope = const []}) { final Object value = _readValue(extended: true, widgetBuilderScope: widgetBuilderScope); final cases = {}; _expectSymbol(_SymbolToken.openBrace); @@ -2276,7 +2497,10 @@ class _Parser { } else { key = _readValue(extended: true, widgetBuilderScope: widgetBuilderScope); if (cases.containsKey(key)) { - throw ParserException._fromToken('Switch has duplicate cases for key $key', _source.current); + throw ParserException._fromToken( + 'Switch has duplicate cases for key $key', + _source.current, + ); } } _expectSymbol(_SymbolToken.colon); @@ -2292,7 +2516,7 @@ class _Parser { return _withSourceRange(Switch(value, cases), start); } - List _readParts({ bool optional = false }) { + List _readParts({bool optional = false}) { if (optional && !_foundSymbol(_SymbolToken.dot)) { return const []; } @@ -2392,7 +2616,10 @@ class _Parser { _advance(); final SourceLocation? innerStart = _getSourceLocation(); _expectIdentifier('state'); - final StateReference stateReference = _withSourceRange(StateReference(_readParts()), innerStart); + final StateReference stateReference = _withSourceRange( + StateReference(_readParts()), + innerStart, + ); _expectSymbol(_SymbolToken.equals); final Object value = _readValue(widgetBuilderScope: widgetBuilderScope, extended: true); return _withSourceRange(SetStateHandler(stateReference, value), start); @@ -2406,7 +2633,10 @@ class _Parser { if (index > 0) { final SourceLocation? start = _getSourceLocation(); _advance(); - return _withSourceRange(LoopReference(_loopIdentifiers.length - index, _readParts(optional: true)), start); + return _withSourceRange( + LoopReference(_loopIdentifiers.length - index, _readParts(optional: true)), + start, + ); } return _readConstructorCall(widgetBuilderScope: widgetBuilderScope); } @@ -2429,14 +2659,15 @@ class _Parser { widgetBuilderScope: [...widgetBuilderScope, argumentName], ); if (widget is! ConstructorCall && widget is! Switch) { - throw ParserException._fromToken('Expecting a switch or constructor call got $widget', valueToken); + throw ParserException._fromToken( + 'Expecting a switch or constructor call got $widget', + valueToken, + ); } return WidgetBuilderDeclaration(argumentName, widget as BlobNode); } - ConstructorCall _readConstructorCall({ - List widgetBuilderScope = const [], - }) { + ConstructorCall _readConstructorCall({List widgetBuilderScope = const []}) { final SourceLocation? start = _getSourceLocation(); final String name = _readIdentifier(); _expectSymbol(_SymbolToken.openParen); @@ -2499,10 +2730,7 @@ class _Parser { } RemoteWidgetLibrary readLibraryFile() { - final result = RemoteWidgetLibrary( - _readImports().toList(), - _readWidgetDeclarations().toList(), - ); + final result = RemoteWidgetLibrary(_readImports().toList(), _readWidgetDeclarations().toList()); if (result.widgets.isEmpty) { _expectEof('keywords "import" or "widget", or end of file'); } else { diff --git a/packages/rfw/lib/src/flutter/argument_decoders.dart b/packages/rfw/lib/src/flutter/argument_decoders.dart index 8da61794e49c..fe34f9194872 100644 --- a/packages/rfw/lib/src/flutter/argument_decoders.dart +++ b/packages/rfw/lib/src/flutter/argument_decoders.dart @@ -27,12 +27,7 @@ class AnimationDefaults extends InheritedWidget { /// /// The [duration] and [curve] are optional, and default to 200ms and /// [Curves.fastOutSlowIn] respectively. - const AnimationDefaults({ - super.key, - this.duration, - this.curve, - required super.child, - }); + const AnimationDefaults({super.key, this.duration, this.curve, required super.child}); /// The default duration that [ArgumentsDecoder.duration] should use. /// @@ -48,18 +43,21 @@ class AnimationDefaults extends InheritedWidget { /// ambient [AnimationDefaults] or if the nearest [AnimationDefaults] has a /// null [duration]. static Duration durationOf(BuildContext context) { - return context.dependOnInheritedWidgetOfExactType()?.duration ?? const Duration(milliseconds: 200); + return context.dependOnInheritedWidgetOfExactType()?.duration ?? + const Duration(milliseconds: 200); } /// Return the ambient [AnimationDefaults.curve], or [Curves.fastOutSlowIn] if /// there is no ambient [AnimationDefaults] or if the nearest /// [AnimationDefaults] has a null [curve]. static Curve curveOf(BuildContext context) { - return context.dependOnInheritedWidgetOfExactType()?.curve ?? Curves.fastOutSlowIn; + return context.dependOnInheritedWidgetOfExactType()?.curve ?? + Curves.fastOutSlowIn; } @override - bool updateShouldNotify(AnimationDefaults oldWidget) => duration != oldWidget.duration || curve != oldWidget.curve; + bool updateShouldNotify(AnimationDefaults oldWidget) => + duration != oldWidget.duration || curve != oldWidget.curve; } /// Signature for methods that decode structured values from a [DataSource], @@ -147,12 +145,7 @@ class ArgumentDecoders { final BorderSide? b = borderSide(source, [...key, 1]); final BorderSide? c = borderSide(source, [...key, 2]); final BorderSide? d = borderSide(source, [...key, 3]); - return BorderDirectional( - start: a, - top: b ?? a, - end: c ?? a, - bottom: d ?? b ?? a, - ); + return BorderDirectional(start: a, top: b ?? a, end: c ?? a, bottom: d ?? b ?? a); } /// Returns a [BorderRadiusDirectional] from the specified list. @@ -198,7 +191,9 @@ class ArgumentDecoders { return BorderSide( color: color(source, [...key, 'color']) ?? const Color(0xFF000000), width: source.v([...key, 'width']) ?? 1.0, - style: enumValue(BorderStyle.values, source, [...key, 'style']) ?? BorderStyle.solid, + style: + enumValue(BorderStyle.values, source, [...key, 'style']) ?? + BorderStyle.solid, ); } @@ -270,7 +265,8 @@ class ArgumentDecoders { case 'mode': return ColorFilter.mode( color(source, [...key, 'color']) ?? const Color(0xFF000000), - enumValue(BlendMode.values, source, [...key, 'blendMode']) ?? BlendMode.srcOver, + enumValue(BlendMode.values, source, [...key, 'blendMode']) ?? + BlendMode.srcOver, ); case 'srgbToLinearGamma': return const ColorFilter.srgbToLinearGamma(); @@ -284,7 +280,8 @@ class ArgumentDecoders { } /// Extension mechanism for [colorFilter]. - static final Map> colorFilterDecoders = >{}; + static final Map> colorFilterDecoders = + >{}; /// Returns a list of 20 doubles from the specified list. /// @@ -446,7 +443,8 @@ class ArgumentDecoders { /// /// The given key will specify a string, which is known to not match any of /// the values in [Curves]. - static final Map> curveDecoders = >{}; + static final Map> curveDecoders = + >{}; /// Returns a [Decoration] from the specified map. /// @@ -489,14 +487,22 @@ class ArgumentDecoders { borderRadius: borderRadius(source, [...key, 'borderRadius']), boxShadow: list(source, [...key, 'boxShadow'], boxShadow), gradient: gradient(source, [...key, 'gradient']), - backgroundBlendMode: enumValue(BlendMode.values, source, [...key, 'backgroundBlendMode']), - shape: enumValue(BoxShape.values, source, [...key, 'shape']) ?? BoxShape.rectangle, + backgroundBlendMode: enumValue(BlendMode.values, source, [ + ...key, + 'backgroundBlendMode', + ]), + shape: + enumValue(BoxShape.values, source, [...key, 'shape']) ?? BoxShape.rectangle, ); case 'flutterLogo': return FlutterLogoDecoration( textColor: color(source, [...key, 'color']) ?? const Color(0xFF757575), - style: enumValue(FlutterLogoStyle.values, source, [...key, 'style']) ?? FlutterLogoStyle.markOnly, - margin: (edgeInsets(source, [...key, 'margin']) ?? EdgeInsets.zero).resolve(TextDirection.ltr), + style: + enumValue(FlutterLogoStyle.values, source, [...key, 'style']) ?? + FlutterLogoStyle.markOnly, + margin: (edgeInsets(source, [...key, 'margin']) ?? EdgeInsets.zero).resolve( + TextDirection.ltr, + ), ); case 'shape': return ShapeDecoration( @@ -516,7 +522,8 @@ class ArgumentDecoders { } /// Extension mechanism for [decoration]. - static final Map> decorationDecoders = >{}; + static final Map> decorationDecoders = + >{}; /// Returns a [DecorationImage] from the specified map. /// @@ -539,7 +546,10 @@ class ArgumentDecoders { return DecorationImage( image: provider, onError: (Object exception, StackTrace? stackTrace) { - final VoidCallback? handler = source.voidHandler([...key, 'onError'], { 'exception': exception.toString(), 'stackTrack': stackTrace.toString() }); + final VoidCallback? handler = source.voidHandler( + [...key, 'onError'], + {'exception': exception.toString(), 'stackTrack': stackTrace.toString()}, + ); if (handler != null) { handler(); } @@ -548,9 +558,13 @@ class ArgumentDecoders { fit: enumValue(BoxFit.values, source, [...key, 'fit']), alignment: alignment(source, [...key, 'alignment']) ?? Alignment.center, centerSlice: rect(source, [...key, 'centerSlice']), - repeat: enumValue(ImageRepeat.values, source, [...key, 'repeat']) ?? ImageRepeat.noRepeat, + repeat: + enumValue(ImageRepeat.values, source, [...key, 'repeat']) ?? + ImageRepeat.noRepeat, matchTextDirection: source.v([...key, 'matchTextDirection']) ?? false, - filterQuality: enumValue(FilterQuality.values, source, [...key, 'filterQuality']) ?? FilterQuality.medium, + filterQuality: + enumValue(FilterQuality.values, source, [...key, 'filterQuality']) ?? + FilterQuality.medium, ); } @@ -598,12 +612,7 @@ class ArgumentDecoders { final double? b = source.v([...key, 1]); final double? c = source.v([...key, 2]); final double? d = source.v([...key, 3]); - return EdgeInsetsDirectional.fromSTEB( - a, - b ?? a, - c ?? a, - d ?? b ?? a, - ); + return EdgeInsetsDirectional.fromSTEB(a, b ?? a, c ?? a, d ?? b ?? a); } /// Returns one of the values of the specified enum `T`, from the specified string. @@ -640,7 +649,10 @@ class ArgumentDecoders { /// /// As this never returns null, it is possible to use it with [list]. static FontFeature fontFeature(DataSource source, List key) { - return FontFeature(source.v([...key, 'feature']) ?? 'NONE', source.v([...key, 'value']) ?? 1); + return FontFeature( + source.v([...key, 'feature']) ?? 'NONE', + source.v([...key, 'value']) ?? 1, + ); } /// Returns a [Gradient] from the specified map. @@ -689,18 +701,24 @@ class ArgumentDecoders { return LinearGradient( begin: alignment(source, [...key, 'begin']) ?? Alignment.centerLeft, end: alignment(source, [...key, 'end']) ?? Alignment.centerRight, - colors: list(source, [...key, 'colors'], colorOrBlack) ?? const [Color(0xFF000000), Color(0xFFFFFFFF)], + colors: + list(source, [...key, 'colors'], colorOrBlack) ?? + const [Color(0xFF000000), Color(0xFFFFFFFF)], stops: list(source, [...key, 'stops'], doubleOrZero), - tileMode: enumValue(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, + tileMode: + enumValue(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, // transform: GradientTransformMatrix(matrix(source, [...key, 'transform'])), // blocked by https://github.com/flutter/flutter/issues/87208 ); case 'radial': return RadialGradient( center: alignment(source, [...key, 'center']) ?? Alignment.center, radius: source.v([...key, 'radius']) ?? 0.5, - colors: list(source, [...key, 'colors'], colorOrBlack) ?? const [Color(0xFF000000), Color(0xFFFFFFFF)], + colors: + list(source, [...key, 'colors'], colorOrBlack) ?? + const [Color(0xFF000000), Color(0xFFFFFFFF)], stops: list(source, [...key, 'stops'], doubleOrZero), - tileMode: enumValue(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, + tileMode: + enumValue(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, focal: alignment(source, [...key, 'focal']), focalRadius: source.v([...key, 'focalRadius']) ?? 0.0, // transform: GradientTransformMatrix(matrix(source, [...key, 'transform'])), // blocked by https://github.com/flutter/flutter/issues/87208 @@ -710,9 +728,12 @@ class ArgumentDecoders { center: alignment(source, [...key, 'center']) ?? Alignment.center, startAngle: source.v([...key, 'startAngle']) ?? 0.0, endAngle: source.v([...key, 'endAngle']) ?? math.pi * 2, - colors: list(source, [...key, 'colors'], colorOrBlack) ?? const [Color(0xFF000000), Color(0xFFFFFFFF)], + colors: + list(source, [...key, 'colors'], colorOrBlack) ?? + const [Color(0xFF000000), Color(0xFFFFFFFF)], stops: list(source, [...key, 'stops'], doubleOrZero), - tileMode: enumValue(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, + tileMode: + enumValue(TileMode.values, source, [...key, 'tileMode']) ?? TileMode.clamp, // transform: GradientTransformMatrix(matrix(source, [...key, 'transform'])), // blocked by https://github.com/flutter/flutter/issues/87208 ); default: @@ -725,7 +746,8 @@ class ArgumentDecoders { } /// Extension mechanism for [gradient]. - static final Map> gradientDecoders = >{}; + static final Map> gradientDecoders = + >{}; /// Returns a [SliverGridDelegate] from the specified map. /// @@ -780,7 +802,8 @@ class ArgumentDecoders { } /// Extension mechanism for [gridDelegate]. - static final Map> gridDelegateDecoders = >{}; + static final Map> gridDelegateDecoders = + >{}; /// Returns an [IconData] from the specified map. /// @@ -870,7 +893,8 @@ class ArgumentDecoders { } /// Extension mechanism for [imageProvider]. - static final Map> imageProviderDecoders = >{}; + static final Map> imageProviderDecoders = + >{}; /// Returns a [List] of `T` values from the specified list, using the given /// `decoder` to parse each value. @@ -921,7 +945,11 @@ class ArgumentDecoders { return Locale(subtags[0], subtags[1]); } // TODO(ianh): verify this is correct (I tried looking up the Unicode spec but it was... confusing) - return Locale.fromSubtags(languageCode: subtags[0], scriptCode: subtags[1], countryCode: subtags[2]); + return Locale.fromSubtags( + languageCode: subtags[0], + scriptCode: subtags[1], + countryCode: subtags[2], + ); } /// Returns a list of 16 doubles from the specified list. @@ -988,7 +1016,8 @@ class ArgumentDecoders { } /// Extension mechanism for [maskFilter]. - static final Map> maskFilterDecoders = >{}; + static final Map> maskFilterDecoders = + >{}; /// Returns an [Offset] from the specified map. /// @@ -1035,7 +1064,10 @@ class ArgumentDecoders { return null; } final result = Paint(); - final BlendMode? paintBlendMode = enumValue(BlendMode.values, source, [...key, 'blendMode']); + final BlendMode? paintBlendMode = enumValue(BlendMode.values, source, [ + ...key, + 'blendMode', + ]); if (paintBlendMode != null) { result.blendMode = paintBlendMode; } @@ -1047,7 +1079,11 @@ class ArgumentDecoders { if (paintColorFilter != null) { result.colorFilter = paintColorFilter; } - final FilterQuality? paintFilterQuality = enumValue(FilterQuality.values, source, [...key, 'filterQuality']); + final FilterQuality? paintFilterQuality = enumValue( + FilterQuality.values, + source, + [...key, 'filterQuality'], + ); if (paintFilterQuality != null) { result.filterQuality = paintFilterQuality; } @@ -1176,7 +1212,9 @@ class ArgumentDecoders { static ShapeBorder? shapeBorder(DataSource source, List key) { final List? shapes = list(source, key, shapeBorder); if (shapes != null) { - return shapes.where((ShapeBorder? a) => a != null).reduce((ShapeBorder? a, ShapeBorder? b) => a! + b!); + return shapes + .where((ShapeBorder? a) => a != null) + .reduce((ShapeBorder? a, ShapeBorder? b) => a! + b!); } final String? type = source.v([...key, 'type']); switch (type) { @@ -1190,9 +1228,7 @@ class ArgumentDecoders { borderRadius: borderRadius(source, [...key, 'borderRadius']) ?? BorderRadius.zero, ); case 'circle': - return CircleBorder( - side: borderSide(source, [...key, 'side']) ?? BorderSide.none, - ); + return CircleBorder(side: borderSide(source, [...key, 'side']) ?? BorderSide.none); case 'continuous': return ContinuousRectangleBorder( side: borderSide(source, [...key, 'side']) ?? BorderSide.none, @@ -1204,9 +1240,7 @@ class ArgumentDecoders { borderRadius: borderRadius(source, [...key, 'borderRadius']) ?? BorderRadius.zero, ); case 'stadium': - return StadiumBorder( - side: borderSide(source, [...key, 'side']) ?? BorderSide.none, - ); + return StadiumBorder(side: borderSide(source, [...key, 'side']) ?? BorderSide.none); default: final ArgumentDecoder? decoder = shapeBorderDecoders[type]; if (decoder == null) { @@ -1217,7 +1251,8 @@ class ArgumentDecoders { } /// Extension mechanism for [shapeBorder]. - static final Map> shapeBorderDecoders = >{}; + static final Map> shapeBorderDecoders = + >{}; /// Returns a [Shader] based on the specified map. /// @@ -1243,7 +1278,9 @@ class ArgumentDecoders { case 'sweep': return gradient(source, key)!.createShader( rect(source, [...key, 'rect']) ?? Rect.zero, - textDirection: enumValue(TextDirection.values, source, ['textDirection']) ?? TextDirection.ltr, + textDirection: + enumValue(TextDirection.values, source, ['textDirection']) ?? + TextDirection.ltr, ); default: final ArgumentDecoder? decoder = shaderDecoders[type]; @@ -1255,7 +1292,8 @@ class ArgumentDecoders { } /// Extension mechanism for [shader]. - static final Map> shaderDecoders = >{}; + static final Map> shaderDecoders = + >{}; /// Returns a string from the specified string. /// @@ -1287,7 +1325,11 @@ class ArgumentDecoders { fontFamilyFallback: list(source, [...key, 'fontFamilyFallback'], string), fontSize: source.v([...key, 'fontSize']), height: source.v([...key, 'height']), - leadingDistribution: enumValue(TextLeadingDistribution.values, source, [...key, 'leadingDistribution']), + leadingDistribution: enumValue( + TextLeadingDistribution.values, + source, + [...key, 'leadingDistribution'], + ), leading: source.v([...key, 'leading']), fontWeight: enumValue(FontWeight.values, source, [...key, 'fontWeight']), fontStyle: enumValue(FontStyle.values, source, [...key, 'fontStyle']), @@ -1311,7 +1353,12 @@ class ArgumentDecoders { return TextHeightBehavior( applyHeightToFirstAscent: source.v([...key, 'applyHeightToFirstAscent']) ?? true, applyHeightToLastDescent: source.v([...key, 'applyHeightToLastDescent']) ?? true, - leadingDistribution: enumValue(TextLeadingDistribution.values, source, [...key, 'leadingDistribution']) ?? TextLeadingDistribution.proportional, + leadingDistribution: + enumValue(TextLeadingDistribution.values, source, [ + ...key, + 'leadingDistribution', + ]) ?? + TextLeadingDistribution.proportional, ); } @@ -1375,7 +1422,11 @@ class ArgumentDecoders { wordSpacing: source.v([...key, 'wordSpacing']), textBaseline: enumValue(TextBaseline.values, source, ['textBaseline']), height: source.v([...key, 'height']), - leadingDistribution: enumValue(TextLeadingDistribution.values, source, [...key, 'leadingDistribution']), + leadingDistribution: enumValue( + TextLeadingDistribution.values, + source, + [...key, 'leadingDistribution'], + ), locale: locale(source, [...key, 'locale']), foreground: paint(source, [...key, 'foreground']), background: paint(source, [...key, 'background']), @@ -1383,7 +1434,10 @@ class ArgumentDecoders { fontFeatures: list(source, [...key, 'fontFeatures'], fontFeature), decoration: textDecoration(source, [...key, 'decoration']), decorationColor: color(source, [...key, 'decorationColor']), - decorationStyle: enumValue(TextDecorationStyle.values, source, [...key, 'decorationStyle']), + decorationStyle: enumValue(TextDecorationStyle.values, source, [ + ...key, + 'decorationStyle', + ]), decorationThickness: source.v([...key, 'decorationThickness']), fontFamily: source.v([...key, 'fontFamily']), fontFamilyFallback: list(source, [...key, 'fontFamilyFallback'], string), diff --git a/packages/rfw/lib/src/flutter/content.dart b/packages/rfw/lib/src/flutter/content.dart index 949f1f624e31..f24ec0fb11ce 100644 --- a/packages/rfw/lib/src/flutter/content.dart +++ b/packages/rfw/lib/src/flutter/content.dart @@ -26,11 +26,16 @@ Object? deepClone(Object? template) { if (template == null) { return null; } else if (template is DynamicMap) { - return template.map((String key, Object? value) => MapEntry(key, deepClone(value))); + return template.map( + (String key, Object? value) => MapEntry(key, deepClone(value)), + ); } else if (template is DynamicList) { return template.map((Object? value) => deepClone(value)).toList(); } else { - assert(template is int || template is double || template is bool || template is String, 'unexpected state object type: ${template.runtimeType} ($template)'); + assert( + template is int || template is double || template is bool || template is String, + 'unexpected state object type: ${template.runtimeType} ($template)', + ); return template; } } @@ -134,7 +139,7 @@ class DynamicContent { /// /// The `initialData` argument, if provided, is used to update all the keys /// in the [DynamicContent], as if [updateAll] had been called. - DynamicContent([ DynamicMap? initialData ]) { + DynamicContent([DynamicMap? initialData]) { if (initialData != null) { updateAll(initialData); } @@ -219,9 +224,13 @@ class DynamicContent { // Node in the [DynamicContent] tree. This should contain no [BlobNode]s. class _DynamicNode { - _DynamicNode(this._key, this._parent, this._value) : assert(_value == missing || _hasValidType(_value)); + _DynamicNode(this._key, this._parent, this._value) + : assert(_value == missing || _hasValidType(_value)); - _DynamicNode.root() : _key = missing, _parent = null, _value = DynamicMap(); // ignore: prefer_collection_literals + _DynamicNode.root() + : _key = missing, + _parent = null, + _value = DynamicMap(); // ignore: prefer_collection_literals final Object _key; final _DynamicNode? _parent; @@ -269,10 +278,7 @@ class _DynamicNode { if (value is DynamicList) { return value.every(_hasValidType); } - return value is int - || value is double - || value is bool - || value is String; + return value is int || value is double || value is bool || value is String; } _DynamicNode _prepare(Object childKey) { diff --git a/packages/rfw/lib/src/flutter/core_widgets.dart b/packages/rfw/lib/src/flutter/core_widgets.dart index b8f479f9646d..8f4537169348 100644 --- a/packages/rfw/lib/src/flutter/core_widgets.dart +++ b/packages/rfw/lib/src/flutter/core_widgets.dart @@ -232,10 +232,8 @@ LocalWidgetLibrary createCoreWidgets() => LocalWidgetLibrary(_coreWidgetsDefinit // In these widgets we make an effort to expose every single argument available. Map get _coreWidgetsDefinitions => { - // Keep these in alphabetical order and add any new widgets to the list // in the documentation above. - 'AnimationDefaults': (BuildContext context, DataSource source) { return AnimationDefaults( duration: ArgumentDecoders.duration(source, ['duration'], context), @@ -275,7 +273,8 @@ Map get _coreWidgetsDefinitions => clipper, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.antiAlias, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.antiAlias, child: source.optionalChild(['child']), ); }, @@ -289,12 +288,30 @@ Map get _coreWidgetsDefinitions => (MainAxisAlignment.values, source, ['mainAxisAlignment']) ?? MainAxisAlignment.start, - mainAxisSize: ArgumentDecoders.enumValue(MainAxisSize.values, source, ['mainAxisSize']) ?? MainAxisSize.max, - crossAxisAlignment: ArgumentDecoders.enumValue(CrossAxisAlignment.values, source, ['crossAxisAlignment']) ?? CrossAxisAlignment.center, - textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, ['textDirection']), - verticalDirection: ArgumentDecoders.enumValue(VerticalDirection.values, source, ['verticalDirection']) ?? VerticalDirection.down, - textBaseline: ArgumentDecoders.enumValue(TextBaseline.values, source, ['textBaseline']), + mainAxisAlignment: + ArgumentDecoders.enumValue(MainAxisAlignment.values, source, [ + 'mainAxisAlignment', + ]) ?? + MainAxisAlignment.start, + mainAxisSize: + ArgumentDecoders.enumValue(MainAxisSize.values, source, ['mainAxisSize']) ?? + MainAxisSize.max, + crossAxisAlignment: + ArgumentDecoders.enumValue(CrossAxisAlignment.values, source, [ + 'crossAxisAlignment', + ]) ?? + CrossAxisAlignment.center, + textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]), + verticalDirection: + ArgumentDecoders.enumValue(VerticalDirection.values, source, [ + 'verticalDirection', + ]) ?? + VerticalDirection.down, + textBaseline: ArgumentDecoders.enumValue(TextBaseline.values, source, [ + 'textBaseline', + ]), children: source.childList(['children']), ); }, @@ -314,7 +331,8 @@ Map get _coreWidgetsDefinitions => (Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); @@ -327,9 +345,15 @@ Map get _coreWidgetsDefinitions => (TextAlign.values, source, ['textAlign']), softWrap: source.v(['softWrap']) ?? true, - overflow: ArgumentDecoders.enumValue(TextOverflow.values, source, ['overflow']) ?? TextOverflow.clip, + overflow: + ArgumentDecoders.enumValue(TextOverflow.values, source, ['overflow']) ?? + TextOverflow.clip, maxLines: source.v(['maxLines']), - textWidthBasis: ArgumentDecoders.enumValue(TextWidthBasis.values, source, ['textWidthBasis']) ?? TextWidthBasis.parent, + textWidthBasis: + ArgumentDecoders.enumValue(TextWidthBasis.values, source, [ + 'textWidthBasis', + ]) ?? + TextWidthBasis.parent, textHeightBehavior: ArgumentDecoders.textHeightBehavior(source, ['textHeightBehavior']), onEnd: source.voidHandler(['onEnd']), child: source.child(['child']), @@ -338,16 +362,17 @@ Map get _coreWidgetsDefinitions => (TextDirection.values, source, ['textDirection']) ?? TextDirection.ltr, + textDirection: + ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]) ?? + TextDirection.ltr, child: source.child(['child']), ); }, 'Expanded': (BuildContext context, DataSource source) { - return Expanded( - flex: source.v(['flex']) ?? 1, - child: source.child(['child']), - ); + return Expanded(flex: source.v(['flex']) ?? 1, child: source.child(['child'])); }, 'Flexible': (BuildContext context, DataSource source) { @@ -362,7 +387,8 @@ Map get _coreWidgetsDefinitions => (BoxFit.values, source, ['fit']) ?? BoxFit.contain, alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.optionalChild(['child']), ); }, @@ -379,26 +405,40 @@ Map get _coreWidgetsDefinitions => (TapDownDetails details) => trigger()), - onTapUp: source.handler(['onTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), + onTapDown: source.handler( + ['onTapDown'], + (VoidCallback trigger) => + (TapDownDetails details) => trigger(), + ), + onTapUp: source.handler( + ['onTapUp'], + (VoidCallback trigger) => + (TapUpDetails details) => trigger(), + ), onTapCancel: source.voidHandler(['onTapCancel']), onDoubleTap: source.voidHandler(['onDoubleTap']), onLongPress: source.voidHandler(['onLongPress']), - behavior: ArgumentDecoders.enumValue(HitTestBehavior.values, source, ['behavior']), + behavior: ArgumentDecoders.enumValue(HitTestBehavior.values, source, [ + 'behavior', + ]), child: source.optionalChild(['child']), ); }, 'GridView': (BuildContext context, DataSource source) { return GridView.builder( - scrollDirection: ArgumentDecoders.enumValue(Axis.values, source, ['scrollDirection']) ?? Axis.vertical, + scrollDirection: + ArgumentDecoders.enumValue(Axis.values, source, ['scrollDirection']) ?? + Axis.vertical, reverse: source.v(['reverse']) ?? false, // controller, primary: source.v(['primary']), // physics, shrinkWrap: source.v(['shrinkWrap']) ?? false, padding: ArgumentDecoders.edgeInsets(source, ['padding']), - gridDelegate: ArgumentDecoders.gridDelegate(source, ['gridDelegate']) ?? const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + gridDelegate: + ArgumentDecoders.gridDelegate(source, ['gridDelegate']) ?? + const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), itemBuilder: (BuildContext context, int index) => source.child(['children', index]), itemCount: source.length(['children']), addAutomaticKeepAlives: source.v(['addAutomaticKeepAlives']) ?? true, @@ -406,10 +446,21 @@ Map get _coreWidgetsDefinitions => (['addSemanticIndexes']) ?? true, cacheExtent: source.v(['cacheExtent']), semanticChildCount: source.v(['semanticChildCount']), - dragStartBehavior: ArgumentDecoders.enumValue(DragStartBehavior.values, source, ['dragStartBehavior']) ?? DragStartBehavior.start, - keyboardDismissBehavior: ArgumentDecoders.enumValue(ScrollViewKeyboardDismissBehavior.values, source, ['keyboardDismissBehavior']) ?? ScrollViewKeyboardDismissBehavior.manual, + dragStartBehavior: + ArgumentDecoders.enumValue(DragStartBehavior.values, source, [ + 'dragStartBehavior', + ]) ?? + DragStartBehavior.start, + keyboardDismissBehavior: + ArgumentDecoders.enumValue( + ScrollViewKeyboardDismissBehavior.values, + source, + ['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehavior.manual, restorationId: source.v(['restorationId']), - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, ); }, @@ -419,7 +470,9 @@ Map get _coreWidgetsDefinitions => (['size']), color: ArgumentDecoders.color(source, ['color']), semanticLabel: source.v(['semanticLabel']), - textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, ['textDirection']), + textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]), ); }, @@ -431,9 +484,7 @@ Map get _coreWidgetsDefinitions => get _coreWidgetsDefinitions => (['height']), color: ArgumentDecoders.color(source, ['color']), // Animation? opacity, - colorBlendMode: ArgumentDecoders.enumValue(BlendMode.values, source, ['blendMode']), + colorBlendMode: ArgumentDecoders.enumValue(BlendMode.values, source, [ + 'blendMode', + ]), fit: ArgumentDecoders.enumValue(BoxFit.values, source, ['fit']), alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center, - repeat: ArgumentDecoders.enumValue(ImageRepeat.values, source, ['repeat']) ?? ImageRepeat.noRepeat, + repeat: + ArgumentDecoders.enumValue(ImageRepeat.values, source, ['repeat']) ?? + ImageRepeat.noRepeat, centerSlice: ArgumentDecoders.rect(source, ['centerSlice']), matchTextDirection: source.v(['matchTextDirection']) ?? false, gaplessPlayback: source.v(['gaplessPlayback']) ?? false, isAntiAlias: source.v(['isAntiAlias']) ?? false, - filterQuality: ArgumentDecoders.enumValue(FilterQuality.values, source, ['filterQuality']) ?? FilterQuality.low, + filterQuality: + ArgumentDecoders.enumValue(FilterQuality.values, source, [ + 'filterQuality', + ]) ?? + FilterQuality.low, ); }, 'ListBody': (BuildContext context, DataSource source) { return ListBody( - mainAxis: ArgumentDecoders.enumValue(Axis.values, source, ['mainAxis']) ?? Axis.vertical, + mainAxis: + ArgumentDecoders.enumValue(Axis.values, source, ['mainAxis']) ?? Axis.vertical, reverse: source.v(['reverse']) ?? false, children: source.childList(['children']), ); @@ -478,7 +538,9 @@ Map get _coreWidgetsDefinitions => (Axis.values, source, ['scrollDirection']) ?? Axis.vertical, + scrollDirection: + ArgumentDecoders.enumValue(Axis.values, source, ['scrollDirection']) ?? + Axis.vertical, reverse: source.v(['reverse']) ?? false, // ScrollController? controller, primary: source.v(['primary']), @@ -489,14 +551,25 @@ Map get _coreWidgetsDefinitions => source.child(['children', index]), - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, addAutomaticKeepAlives: source.v(['addAutomaticKeepAlives']) ?? true, addRepaintBoundaries: source.v(['addRepaintBoundaries']) ?? true, addSemanticIndexes: source.v(['addSemanticIndexes']) ?? true, cacheExtent: source.v(['cacheExtent']), semanticChildCount: source.v(['semanticChildCount']), - dragStartBehavior: ArgumentDecoders.enumValue(DragStartBehavior.values, source, ['dragStartBehavior']) ?? DragStartBehavior.start, - keyboardDismissBehavior: ArgumentDecoders.enumValue(ScrollViewKeyboardDismissBehavior.values, source, ['keyboardDismissBehavior']) ?? ScrollViewKeyboardDismissBehavior.manual, + dragStartBehavior: + ArgumentDecoders.enumValue(DragStartBehavior.values, source, [ + 'dragStartBehavior', + ]) ?? + DragStartBehavior.start, + keyboardDismissBehavior: + ArgumentDecoders.enumValue( + ScrollViewKeyboardDismissBehavior.values, + source, + ['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehavior.manual, restorationId: source.v(['restorationId']), ); }, @@ -551,8 +624,12 @@ Map get _coreWidgetsDefinitions => (['turns']) ?? 0.0, - alignment: (ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center).resolve(Directionality.of(context)), - filterQuality: ArgumentDecoders.enumValue(FilterQuality.values, source, ['filterQuality']), + alignment: (ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center).resolve( + Directionality.of(context), + ), + filterQuality: ArgumentDecoders.enumValue(FilterQuality.values, source, [ + 'filterQuality', + ]), onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); @@ -562,24 +639,44 @@ Map get _coreWidgetsDefinitions => (MainAxisAlignment.values, source, ['mainAxisAlignment']) ?? MainAxisAlignment.start, - mainAxisSize: ArgumentDecoders.enumValue(MainAxisSize.values, source, ['mainAxisSize']) ?? MainAxisSize.max, - crossAxisAlignment: ArgumentDecoders.enumValue(CrossAxisAlignment.values, source, ['crossAxisAlignment']) ?? CrossAxisAlignment.center, - textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, ['textDirection']), - verticalDirection: ArgumentDecoders.enumValue(VerticalDirection.values, source, ['verticalDirection']) ?? VerticalDirection.down, - textBaseline: ArgumentDecoders.enumValue(TextBaseline.values, source, ['textBaseline']), + mainAxisAlignment: + ArgumentDecoders.enumValue(MainAxisAlignment.values, source, [ + 'mainAxisAlignment', + ]) ?? + MainAxisAlignment.start, + mainAxisSize: + ArgumentDecoders.enumValue(MainAxisSize.values, source, ['mainAxisSize']) ?? + MainAxisSize.max, + crossAxisAlignment: + ArgumentDecoders.enumValue(CrossAxisAlignment.values, source, [ + 'crossAxisAlignment', + ]) ?? + CrossAxisAlignment.center, + textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]), + verticalDirection: + ArgumentDecoders.enumValue(VerticalDirection.values, source, [ + 'verticalDirection', + ]) ?? + VerticalDirection.down, + textBaseline: ArgumentDecoders.enumValue(TextBaseline.values, source, [ + 'textBaseline', + ]), children: source.childList(['children']), ); }, - // #enddocregion Row + // #enddocregion Row 'SafeArea': (BuildContext context, DataSource source) { return SafeArea( left: source.v(['left']) ?? true, top: source.v(['top']) ?? true, right: source.v(['right']) ?? true, bottom: source.v(['bottom']) ?? true, - minimum: (ArgumentDecoders.edgeInsets(source, ['minimum']) ?? EdgeInsets.zero).resolve(Directionality.of(context)), + minimum: (ArgumentDecoders.edgeInsets(source, ['minimum']) ?? EdgeInsets.zero).resolve( + Directionality.of(context), + ), maintainBottomViewPadding: source.v(['maintainBottomViewPadding']) ?? false, child: source.child(['child']), ); @@ -590,8 +687,12 @@ Map get _coreWidgetsDefinitions => (['scale']) ?? 1.0, - alignment: (ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center).resolve(Directionality.of(context)), - filterQuality: ArgumentDecoders.enumValue(FilterQuality.values, source, ['filterQuality']), + alignment: (ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center).resolve( + Directionality.of(context), + ), + filterQuality: ArgumentDecoders.enumValue(FilterQuality.values, source, [ + 'filterQuality', + ]), onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); @@ -599,14 +700,27 @@ Map get _coreWidgetsDefinitions => (Axis.values, source, ['scrollDirection']) ?? Axis.vertical, + scrollDirection: + ArgumentDecoders.enumValue(Axis.values, source, ['scrollDirection']) ?? + Axis.vertical, reverse: source.v(['reverse']) ?? false, padding: ArgumentDecoders.edgeInsets(source, ['padding']), primary: source.v(['primary']) ?? true, - dragStartBehavior: ArgumentDecoders.enumValue(DragStartBehavior.values, source, ['dragStartBehavior']) ?? DragStartBehavior.start, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, + dragStartBehavior: + ArgumentDecoders.enumValue(DragStartBehavior.values, source, [ + 'dragStartBehavior', + ]) ?? + DragStartBehavior.start, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, restorationId: source.v(['restorationId']), - keyboardDismissBehavior: ArgumentDecoders.enumValue(ScrollViewKeyboardDismissBehavior.values, source, ['keyboardDismissBehavior']) ?? ScrollViewKeyboardDismissBehavior.manual, + keyboardDismissBehavior: + ArgumentDecoders.enumValue( + ScrollViewKeyboardDismissBehavior.values, + source, + ['keyboardDismissBehavior'], + ) ?? + ScrollViewKeyboardDismissBehavior.manual, // ScrollPhysics? physics, // ScrollController? controller, child: source.optionalChild(['child']), @@ -622,29 +736,26 @@ Map get _coreWidgetsDefinitions => (['flex']) ?? 1, - ); + return Spacer(flex: source.v(['flex']) ?? 1); }, 'Stack': (BuildContext context, DataSource source) { return Stack( alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? AlignmentDirectional.topStart, - textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, ['textDirection']), + textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]), fit: ArgumentDecoders.enumValue(StackFit.values, source, ['fit']) ?? StackFit.loose, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, children: source.childList(['children']), ); }, @@ -665,31 +776,52 @@ Map get _coreWidgetsDefinitions => (TextAlign.values, source, ['textAlign']), - textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, ['textDirection']), + textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]), locale: ArgumentDecoders.locale(source, ['locale']), softWrap: source.v(['softWrap']), overflow: ArgumentDecoders.enumValue(TextOverflow.values, source, ['overflow']), textScaler: textScaleFactor == null ? null : TextScaler.linear(textScaleFactor), maxLines: source.v(['maxLines']), semanticsLabel: source.v(['semanticsLabel']), - textWidthBasis: ArgumentDecoders.enumValue(TextWidthBasis.values, source, ['textWidthBasis']), + textWidthBasis: ArgumentDecoders.enumValue(TextWidthBasis.values, source, [ + 'textWidthBasis', + ]), textHeightBehavior: ArgumentDecoders.textHeightBehavior(source, ['textHeightBehavior']), ); }, 'Wrap': (BuildContext context, DataSource source) { return Wrap( - direction: ArgumentDecoders.enumValue(Axis.values, source, ['direction']) ?? Axis.horizontal, - alignment: ArgumentDecoders.enumValue(WrapAlignment.values, source, ['alignment']) ?? WrapAlignment.start, + direction: + ArgumentDecoders.enumValue(Axis.values, source, ['direction']) ?? Axis.horizontal, + alignment: + ArgumentDecoders.enumValue(WrapAlignment.values, source, ['alignment']) ?? + WrapAlignment.start, spacing: source.v(['spacing']) ?? 0.0, - runAlignment: ArgumentDecoders.enumValue(WrapAlignment.values, source, ['runAlignment']) ?? WrapAlignment.start, + runAlignment: + ArgumentDecoders.enumValue(WrapAlignment.values, source, [ + 'runAlignment', + ]) ?? + WrapAlignment.start, runSpacing: source.v(['runSpacing']) ?? 0.0, - crossAxisAlignment: ArgumentDecoders.enumValue(WrapCrossAlignment.values, source, ['crossAxisAlignment']) ?? WrapCrossAlignment.start, - textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, ['textDirection']), - verticalDirection: ArgumentDecoders.enumValue(VerticalDirection.values, source, ['verticalDirection']) ?? VerticalDirection.down, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + crossAxisAlignment: + ArgumentDecoders.enumValue(WrapCrossAlignment.values, source, [ + 'crossAxisAlignment', + ]) ?? + WrapCrossAlignment.start, + textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]), + verticalDirection: + ArgumentDecoders.enumValue(VerticalDirection.values, source, [ + 'verticalDirection', + ]) ?? + VerticalDirection.down, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, children: source.childList(['children']), ); }, - }; diff --git a/packages/rfw/lib/src/flutter/material_widgets.dart b/packages/rfw/lib/src/flutter/material_widgets.dart index 25689bbbae58..96b9cf1457c7 100644 --- a/packages/rfw/lib/src/flutter/material_widgets.dart +++ b/packages/rfw/lib/src/flutter/material_widgets.dart @@ -101,9 +101,7 @@ import 'runtime.dart'; LocalWidgetLibrary createMaterialWidgets() => LocalWidgetLibrary(_materialWidgetsDefinitions); Map get _materialWidgetsDefinitions => { - // Keep these in alphabetical order. - 'AboutListTile': (BuildContext context, DataSource source) { return AboutListTile( icon: source.optionalChild(['icon']), @@ -156,14 +154,28 @@ Map get _materialWidgetsDefinitions => (ButtonBarLayoutBehavior.values, source, ['layoutBehavior']) - ?? ButtonBarLayoutBehavior.padded; + final EdgeInsetsGeometry buttonPadding = + ArgumentDecoders.edgeInsets(source, ['buttonPadding']) ?? const EdgeInsets.all(8.0); + final ButtonBarLayoutBehavior layoutBehavior = + ArgumentDecoders.enumValue( + ButtonBarLayoutBehavior.values, + source, + ['layoutBehavior'], + ) ?? + ButtonBarLayoutBehavior.padded; Widget overflowBar = OverflowBar( - alignment: ArgumentDecoders.enumValue(MainAxisAlignment.values, source, ['alignment']) ?? MainAxisAlignment.start, + alignment: + ArgumentDecoders.enumValue(MainAxisAlignment.values, source, [ + 'alignment', + ]) ?? + MainAxisAlignment.start, spacing: buttonPadding.horizontal / 2, - overflowDirection: ArgumentDecoders.enumValue(VerticalDirection.values, source, ['overflowDirection']) ?? VerticalDirection.down, + overflowDirection: + ArgumentDecoders.enumValue(VerticalDirection.values, source, [ + 'overflowDirection', + ]) ?? + VerticalDirection.down, overflowSpacing: source.v(['overflowButtonSpacing']) ?? 0.0, children: source.childList(['children']), ); @@ -186,7 +198,8 @@ Map get _materialWidgetsDefinitions => (MainAxisSize.values, source, ['mainAxisSize']) == MainAxisSize.min) { + if (ArgumentDecoders.enumValue(MainAxisSize.values, source, ['mainAxisSize']) == + MainAxisSize.min) { return IntrinsicWidth(child: overflowBar); } @@ -196,13 +209,23 @@ Map get _materialWidgetsDefinitions => (['spacing']) ?? 0.0, - alignment: ArgumentDecoders.enumValue(MainAxisAlignment.values, source, ['alignment']), + alignment: ArgumentDecoders.enumValue(MainAxisAlignment.values, source, [ + 'alignment', + ]), overflowSpacing: source.v(['overflowSpacing']) ?? 0.0, - overflowAlignment: ArgumentDecoders.enumValue(OverflowBarAlignment.values, source, ['overflowAlignment']) - ?? OverflowBarAlignment.start, - overflowDirection: ArgumentDecoders.enumValue(VerticalDirection.values, source, ['overflowDirection']) - ?? VerticalDirection.down, - textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, ['textDirection']), + overflowAlignment: + ArgumentDecoders.enumValue(OverflowBarAlignment.values, source, [ + 'overflowAlignment', + ]) ?? + OverflowBarAlignment.start, + overflowDirection: + ArgumentDecoders.enumValue(VerticalDirection.values, source, [ + 'overflowDirection', + ]) ?? + VerticalDirection.down, + textDirection: ArgumentDecoders.enumValue(TextDirection.values, source, [ + 'textDirection', + ]), children: source.childList(['children']), ); }, @@ -215,7 +238,8 @@ Map get _materialWidgetsDefinitions => (['borderOnForeground']) ?? true, margin: ArgumentDecoders.edgeInsets(source, ['margin']), - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, semanticContainer: source.v(['semanticContainer']) ?? true, child: source.optionalChild(['child']), ); @@ -257,7 +281,9 @@ Map get _materialWidgetsDefinitions => get _materialWidgetsDefinitions => DropdownMenuItem( onTap: source.voidHandler(['items', index, 'onTap']), - value: source.v(['items', index, 'value']) ?? source.v(['items', index, 'value']) ?? source.v(['items', index, 'value']) ?? source.v(['items', index, 'value']), + value: + source.v(['items', index, 'value']) ?? + source.v(['items', index, 'value']) ?? + source.v(['items', index, 'value']) ?? + source.v(['items', index, 'value']), enabled: source.v(['items', index, 'enabled']) ?? true, - alignment: ArgumentDecoders.alignment(source, ['items', index, 'alignment']) ?? AlignmentDirectional.centerStart, + alignment: + ArgumentDecoders.alignment(source, ['items', index, 'alignment']) ?? + AlignmentDirectional.centerStart, child: source.child(['items', index, 'child']), ), ); return DropdownButton( items: dropdownMenuItems, - value: source.v(['value']) ?? source.v(['value']) ?? source.v(['value']) ?? source.v(['value']), + value: + source.v(['value']) ?? + source.v(['value']) ?? + source.v(['value']) ?? + source.v(['value']), disabledHint: source.optionalChild(['disabledHint']), - onChanged: source.handler(['onChanged'], (HandlerTrigger trigger) => (Object? value) => trigger({'value': value})), + onChanged: source.handler( + ['onChanged'], + (HandlerTrigger trigger) => + (Object? value) => trigger({'value': value}), + ), onTap: source.voidHandler(['onTap']), elevation: source.v(['elevation']) ?? 8, style: ArgumentDecoders.textStyle(source, ['style']), @@ -296,8 +336,11 @@ Map get _materialWidgetsDefinitions => (['menuMaxHeight']), enableFeedback: source.v(['enableFeedback']), - alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? AlignmentDirectional.centerStart, - borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius'])?.resolve(Directionality.of(context)), + alignment: + ArgumentDecoders.alignment(source, ['alignment']) ?? AlignmentDirectional.centerStart, + borderRadius: ArgumentDecoders.borderRadius(source, [ + 'borderRadius', + ])?.resolve(Directionality.of(context)), padding: ArgumentDecoders.edgeInsets(source, ['padding']), ); }, @@ -308,7 +351,8 @@ Map get _materialWidgetsDefinitions => (['autofocus']) ?? false, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.child(['child']), ); }, @@ -331,9 +375,14 @@ Map get _materialWidgetsDefinitions => (['mini']) ?? false, shape: ArgumentDecoders.shapeBorder(source, ['shape']), - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, autofocus: source.v(['autofocus']) ?? false, - materialTapTargetSize: ArgumentDecoders.enumValue(MaterialTapTargetSize.values, source, ['materialTapTargetSize']), + materialTapTargetSize: ArgumentDecoders.enumValue( + MaterialTapTargetSize.values, + source, + ['materialTapTargetSize'], + ), isExtended: source.v(['isExtended']) ?? false, enableFeedback: source.v(['enableFeedback']), child: source.child(['child']), @@ -344,21 +393,49 @@ Map get _materialWidgetsDefinitions => (TapDownDetails details) => trigger()), - onTapUp: source.handler(['onTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), + onTapDown: source.handler( + ['onTapDown'], + (VoidCallback trigger) => + (TapDownDetails details) => trigger(), + ), + onTapUp: source.handler( + ['onTapUp'], + (VoidCallback trigger) => + (TapUpDetails details) => trigger(), + ), onTapCancel: source.voidHandler(['onTapCancel']), onDoubleTap: source.voidHandler(['onDoubleTap']), onLongPress: source.voidHandler(['onLongPress']), onSecondaryTap: source.voidHandler(['onSecondaryTap']), - onSecondaryTapUp: source.handler(['onSecondaryTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), - onSecondaryTapDown: source.handler(['onSecondaryTapDown'], (VoidCallback trigger) => (TapDownDetails details) => trigger()), + onSecondaryTapUp: source.handler( + ['onSecondaryTapUp'], + (VoidCallback trigger) => + (TapUpDetails details) => trigger(), + ), + onSecondaryTapDown: source.handler( + ['onSecondaryTapDown'], + (VoidCallback trigger) => + (TapDownDetails details) => trigger(), + ), onSecondaryTapCancel: source.voidHandler(['onSecondaryTapCancel']), - onHighlightChanged: source.handler(['onHighlightChanged'], (VoidCallback trigger) => (bool highlighted) => trigger()), - onHover: source.handler(['onHover'], (VoidCallback trigger) => (bool hovered) => trigger()), + onHighlightChanged: source.handler( + ['onHighlightChanged'], + (VoidCallback trigger) => + (bool highlighted) => trigger(), + ), + onHover: source.handler( + ['onHover'], + (VoidCallback trigger) => + (bool hovered) => trigger(), + ), containedInkWell: source.v(['containedInkWell']) ?? false, - highlightShape: ArgumentDecoders.enumValue(BoxShape.values, source, ['highlightShape']) ?? BoxShape.circle, + highlightShape: + ArgumentDecoders.enumValue(BoxShape.values, source, ['highlightShape']) ?? + BoxShape.circle, radius: source.v(['radius']), - borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius'])?.resolve(Directionality.of(context)), + borderRadius: ArgumentDecoders.borderRadius(source, [ + 'borderRadius', + ])?.resolve(Directionality.of(context)), customBorder: ArgumentDecoders.shapeBorder(source, ['customBorder']), focusColor: ArgumentDecoders.color(source, ['focusColor']), hoverColor: ArgumentDecoders.color(source, ['hoverColor']), @@ -367,7 +444,11 @@ Map get _materialWidgetsDefinitions => (['enableFeedback']) ?? true, excludeFromSemantics: source.v(['excludeFromSemantics']) ?? false, canRequestFocus: source.v(['canRequestFocus']) ?? true, - onFocusChange: source.handler(['onFocusChange'], (VoidCallback trigger) => (bool focus) => trigger()), + onFocusChange: source.handler( + ['onFocusChange'], + (VoidCallback trigger) => + (bool focus) => trigger(), + ), autofocus: source.v(['autofocus']) ?? false, hoverDuration: ArgumentDecoders.duration(source, ['hoverDuration'], context), child: source.optionalChild(['child']), @@ -380,20 +461,42 @@ Map get _materialWidgetsDefinitions => (TapDownDetails details) => trigger()), + onTapDown: source.handler( + ['onTapDown'], + (VoidCallback trigger) => + (TapDownDetails details) => trigger(), + ), onTapCancel: source.voidHandler(['onTapCancel']), onSecondaryTap: source.voidHandler(['onSecondaryTap']), - onSecondaryTapUp: source.handler(['onSecondaryTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), - onSecondaryTapDown: source.handler(['onSecondaryTapDown'], (VoidCallback trigger) => (TapDownDetails details) => trigger()), + onSecondaryTapUp: source.handler( + ['onSecondaryTapUp'], + (VoidCallback trigger) => + (TapUpDetails details) => trigger(), + ), + onSecondaryTapDown: source.handler( + ['onSecondaryTapDown'], + (VoidCallback trigger) => + (TapDownDetails details) => trigger(), + ), onSecondaryTapCancel: source.voidHandler(['onSecondaryTapCancel']), - onHighlightChanged: source.handler(['onHighlightChanged'], (VoidCallback trigger) => (bool highlighted) => trigger()), - onHover: source.handler(['onHover'], (VoidCallback trigger) => (bool hovered) => trigger()), + onHighlightChanged: source.handler( + ['onHighlightChanged'], + (VoidCallback trigger) => + (bool highlighted) => trigger(), + ), + onHover: source.handler( + ['onHover'], + (VoidCallback trigger) => + (bool hovered) => trigger(), + ), focusColor: ArgumentDecoders.color(source, ['focusColor']), hoverColor: ArgumentDecoders.color(source, ['hoverColor']), highlightColor: ArgumentDecoders.color(source, ['highlightColor']), splashColor: ArgumentDecoders.color(source, ['splashColor']), radius: source.v(['radius']), - borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius'])?.resolve(Directionality.of(context)), + borderRadius: ArgumentDecoders.borderRadius(source, [ + 'borderRadius', + ])?.resolve(Directionality.of(context)), customBorder: ArgumentDecoders.shapeBorder(source, ['customBorder']), enableFeedback: source.v(['enableFeedback']) ?? true, excludeFromSemantics: source.v(['excludeFromSemantics']) ?? false, @@ -444,7 +547,9 @@ Map get _materialWidgetsDefinitions => (MaterialType.values,source, ['type']) ?? MaterialType.canvas, + type: + ArgumentDecoders.enumValue(MaterialType.values, source, ['type']) ?? + MaterialType.canvas, elevation: source.v(['elevation']) ?? 0.0, color: ArgumentDecoders.color(source, ['color']), shadowColor: ArgumentDecoders.color(source, ['shadowColor']), @@ -453,7 +558,8 @@ Map get _materialWidgetsDefinitions => (['borderOnForeground']) ?? true, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, animationDuration: ArgumentDecoders.duration(source, ['animationDuration'], context), child: source.child(['child']), ); @@ -465,7 +571,8 @@ Map get _materialWidgetsDefinitions => (['autofocus']) ?? false, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.child(['child']), ); }, @@ -475,10 +582,12 @@ Map get _materialWidgetsDefinitions => persistentFooterButtons = source.childList(['persistentFooterButtons']); return Scaffold( - appBar: appBarWidget == null ? null : PreferredSize( - preferredSize: Size.fromHeight(source.v(['bottomHeight']) ?? 56.0), - child: appBarWidget, - ), + appBar: appBarWidget == null + ? null + : PreferredSize( + preferredSize: Size.fromHeight(source.v(['bottomHeight']) ?? 56.0), + child: appBarWidget, + ), body: source.optionalChild(['body']), floatingActionButton: source.optionalChild(['floatingActionButton']), persistentFooterButtons: persistentFooterButtons.isEmpty ? null : persistentFooterButtons, @@ -489,7 +598,11 @@ Map get _materialWidgetsDefinitions => (['resizeToAvoidBottomInset']), primary: source.v(['primary']) ?? true, - drawerDragStartBehavior: ArgumentDecoders.enumValue(DragStartBehavior.values, source, ['drawerDragStartBehavior']) ?? DragStartBehavior.start, + drawerDragStartBehavior: + ArgumentDecoders.enumValue(DragStartBehavior.values, source, [ + 'drawerDragStartBehavior', + ]) ?? + DragStartBehavior.start, extendBody: source.v(['extendBody']) ?? false, extendBodyBehindAppBar: source.v(['extendBodyBehindAppBar']) ?? false, drawerScrimColor: ArgumentDecoders.color(source, ['drawerScrimColor']), @@ -505,22 +618,30 @@ Map get _materialWidgetsDefinitions => (['min']) ?? 0.0; final double value = source.v(['value']) ?? min; final String? labelText = source.v(['label']); - final String label = labelText != null ? '$labelText: ${value.toStringAsFixed(2)}' : value.toStringAsFixed(2); + final String label = labelText != null + ? '$labelText: ${value.toStringAsFixed(2)}' + : value.toStringAsFixed(2); return Slider( value: value, secondaryTrackValue: source.v(['secondaryTrackValue']), - onChanged: source.handler(['onChanged'], - (HandlerTrigger trigger) => (double value) { - trigger({'value': value}); - }), - onChangeStart: source.handler(['onChangeStart'], - (HandlerTrigger trigger) => (double value) { - trigger({'value': value}); - }), - onChangeEnd: source.handler(['onChangeEnd'], - (HandlerTrigger trigger) => (double value) { - trigger({'value': value}); - }), + onChanged: source.handler( + ['onChanged'], + (HandlerTrigger trigger) => (double value) { + trigger({'value': value}); + }, + ), + onChangeStart: source.handler( + ['onChangeStart'], + (HandlerTrigger trigger) => (double value) { + trigger({'value': value}); + }, + ), + onChangeEnd: source.handler( + ['onChangeEnd'], + (HandlerTrigger trigger) => (double value) { + trigger({'value': value}); + }, + ), min: min, max: source.v(['max']) ?? 1.0, divisions: source.v(['divisions']), @@ -529,7 +650,11 @@ Map get _materialWidgetsDefinitions => (SliderInteraction.values, source, ['allowedInteraction']), + allowedInteraction: ArgumentDecoders.enumValue( + SliderInteraction.values, + source, + ['allowedInteraction'], + ), ); }, @@ -539,7 +664,8 @@ Map get _materialWidgetsDefinitions => (['autofocus']) ?? false, - clipBehavior: ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, + clipBehavior: + ArgumentDecoders.enumValue(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.child(['child']), ); }, @@ -553,5 +679,4 @@ Map get _materialWidgetsDefinitions => { } void _runtimeChanged() { - setState(() { /* widget probably changed */ }); + setState(() { + /* widget probably changed */ + }); } void _eventHandler(String eventName, DynamicMap eventArguments) { diff --git a/packages/rfw/lib/src/flutter/runtime.dart b/packages/rfw/lib/src/flutter/runtime.dart index 9087ef1c43b5..7628a3d31b21 100644 --- a/packages/rfw/lib/src/flutter/runtime.dart +++ b/packages/rfw/lib/src/flutter/runtime.dart @@ -157,7 +157,7 @@ abstract class DataSource { /// both the arguments specified in the remote widget declaration and the /// argument provided to this method have the same name), the arguments /// specified here take precedence. - VoidCallback? voidHandler(List argsKey, [ DynamicMap? extraArguments ]); + VoidCallback? voidHandler(List argsKey, [DynamicMap? extraArguments]); /// Gets an event handler at the given key. /// @@ -282,11 +282,15 @@ class Runtime extends ChangeNotifier { /// /// * [update] and [clearLibraries], functions that populate this map. UnmodifiableMapView get libraries { - return UnmodifiableMapView(Map.from(_libraries)); + return UnmodifiableMapView( + Map.from(_libraries), + ); } - final Map _cachedConstructors = {}; - final Map _widgets = {}; + final Map _cachedConstructors = + {}; + final Map _widgets = + {}; void _clearCache() { _cachedConstructors.clear(); @@ -356,7 +360,7 @@ class Runtime extends ChangeNotifier { return (context.widget as _Widget).curriedWidget; } - void _checkForImportLoops(LibraryName name, [ Set? visited ]) { + void _checkForImportLoops(LibraryName name, [Set? visited]) { final WidgetLibrary? library = _libraries[name]; if (library is RemoteWidgetLibrary) { visited ??= {}; @@ -375,7 +379,9 @@ class Runtime extends ChangeNotifier { assert(path.single == dependency); throw RemoteFlutterWidgetsException('Library $dependency depends on itself.'); } else { - throw RemoteFlutterWidgetsException('Library $dependency indirectly depends on itself via ${path.reversed.join(" which depends on ")}.'); + throw RemoteFlutterWidgetsException( + 'Library $dependency indirectly depends on itself via ${path.reversed.join(" which depends on ")}.', + ); } } _checkForImportLoops(dependency, visited.toSet()); @@ -397,7 +403,9 @@ class Runtime extends ChangeNotifier { } for (final Import import in library.imports) { final LibraryName dependency = import.name; - final _ResolvedConstructor? result = _findConstructor(FullyQualifiedWidgetName(dependency, fullName.widget)); + final _ResolvedConstructor? result = _findConstructor( + FullyQualifiedWidgetName(dependency, fullName.widget), + ); if (result != null) { // We cache the constructor under each name that we tried to look it up with, so // that next time it takes less time to find it. @@ -410,7 +418,9 @@ class Runtime extends ChangeNotifier { return _cachedConstructors[fullName] = _ResolvedConstructor(fullName, constructor); } } else { - assert(library is Null); // ignore: prefer_void_to_null, type_check_with_null, https://github.com/dart-lang/sdk/issues/47017#issuecomment-907562014 + assert( + library is Null, + ); // ignore: prefer_void_to_null, type_check_with_null, https://github.com/dart-lang/sdk/issues/47017#issuecomment-907562014 } _cachedConstructors[fullName] = null; return null; @@ -515,13 +525,16 @@ class Runtime extends ChangeNotifier { 'possibly because some dependencies were missing: ${missingLibraries.join(", ")}', )..propagateSource(source); } - return _CurriedLocalWidget.error(fullName, 'Could not find remote widget named ${fullName.widget} in ${fullName.library}.') - ..propagateSource(source); + return _CurriedLocalWidget.error( + fullName, + 'Could not find remote widget named ${fullName.widget} in ${fullName.library}.', + )..propagateSource(source); } Object _bindArguments( FullyQualifiedWidgetName context, - Object node, Object arguments, + Object node, + Object arguments, DynamicMap widgetBuilderScope, int stateDepth, Set usedWidgets, @@ -546,7 +559,7 @@ class Runtime extends ChangeNotifier { } if (node is WidgetBuilderDeclaration) { return (DynamicMap widgetBuilderArg) { - final newWidgetBuilderScope = { + final newWidgetBuilderScope = { ...widgetBuilderScope, node.argumentName: widgetBuilderArg, }; @@ -569,7 +582,7 @@ class Runtime extends ChangeNotifier { } return result as _CurriedWidget; }; - } + } if (node is DynamicMap) { return node.map( (String name, Object? value) => MapEntry( @@ -593,22 +606,42 @@ class Runtime extends ChangeNotifier { ); } if (node is Loop) { - final Object input = _bindArguments(context, node.input, arguments, widgetBuilderScope, stateDepth, usedWidgets); - final Object output = _bindArguments(context, node.output, arguments, widgetBuilderScope, stateDepth, usedWidgets); - return Loop(input, output) - ..propagateSource(node); + final Object input = _bindArguments( + context, + node.input, + arguments, + widgetBuilderScope, + stateDepth, + usedWidgets, + ); + final Object output = _bindArguments( + context, + node.output, + arguments, + widgetBuilderScope, + stateDepth, + usedWidgets, + ); + return Loop(input, output)..propagateSource(node); } if (node is Switch) { return Switch( _bindArguments(context, node.input, arguments, widgetBuilderScope, stateDepth, usedWidgets), - node.outputs.map( - (Object? key, Object value) { - return MapEntry( - key == null ? key : _bindArguments(context, key, arguments, widgetBuilderScope, stateDepth, usedWidgets), - _bindArguments(context, value, arguments, widgetBuilderScope, stateDepth, usedWidgets), - ); - }, - ), + node.outputs.map((Object? key, Object value) { + return MapEntry( + key == null + ? key + : _bindArguments( + context, + key, + arguments, + widgetBuilderScope, + stateDepth, + usedWidgets, + ), + _bindArguments(context, value, arguments, widgetBuilderScope, stateDepth, usedWidgets), + ); + }), )..propagateSource(node); } if (node is ArgsReference) { @@ -632,7 +665,9 @@ class Runtime extends ChangeNotifier { } if (node is SetStateHandler) { assert(node.stateReference is StateReference); - final BoundStateReference stateReference = (node.stateReference as StateReference).bind(stateDepth); + final BoundStateReference stateReference = (node.stateReference as StateReference).bind( + stateDepth, + ); return SetStateHandler( stateReference, _bindArguments(context, node.value, arguments, widgetBuilderScope, stateDepth, usedWidgets), @@ -662,12 +697,7 @@ typedef _StateResolverCallback = Object Function(List stateKey, int dept typedef _WidgetBuilderArgResolverCallback = Object Function(List argKey); abstract class _CurriedWidget extends BlobNode { - const _CurriedWidget( - this.fullName, - this.arguments, - this.widgetBuilderScope, - this.initialState, - ); + const _CurriedWidget(this.fullName, this.arguments, this.widgetBuilderScope, this.initialState); final FullyQualifiedWidgetName fullName; final DynamicMap arguments; @@ -677,7 +707,8 @@ abstract class _CurriedWidget extends BlobNode { static Object _bindLoopVariable(Object node, Object argument, int depth) { if (node is DynamicMap) { return node.map( - (String name, Object? value) => MapEntry(name, _bindLoopVariable(value!, argument, depth)), + (String name, Object? value) => + MapEntry(name, _bindLoopVariable(value!, argument, depth)), ); } if (node is DynamicList) { @@ -688,8 +719,10 @@ abstract class _CurriedWidget extends BlobNode { ); } if (node is Loop) { - return Loop(_bindLoopVariable(node.input, argument, depth), _bindLoopVariable(node.output, argument, depth + 1)) - ..propagateSource(node); + return Loop( + _bindLoopVariable(node.input, argument, depth), + _bindLoopVariable(node.output, argument, depth + 1), + )..propagateSource(node); } if (node is Switch) { return Switch( @@ -699,7 +732,7 @@ abstract class _CurriedWidget extends BlobNode { key == null ? null : _bindLoopVariable(key, argument, depth), _bindLoopVariable(value, argument, depth), ), - ) + ), )..propagateSource(node); } if (node is _CurriedLocalWidget) { @@ -739,8 +772,10 @@ abstract class _CurriedWidget extends BlobNode { ..propagateSource(node); } if (node is EventHandler) { - return EventHandler(node.eventName, _bindLoopVariable(node.eventArguments, argument, depth) as DynamicMap) - ..propagateSource(node); + return EventHandler( + node.eventName, + _bindLoopVariable(node.eventArguments, argument, depth) as DynamicMap, + )..propagateSource(node); } if (node is SetStateHandler) { return SetStateHandler(node.stateReference, _bindLoopVariable(node.value, argument, depth)) @@ -763,9 +798,12 @@ abstract class _CurriedWidget extends BlobNode { _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { - var currentIndex = 0; // where we are in `list` (some entries of which might represent multiple values, because they are themselves loops) - var effectiveIndex = 0; // where we are in the fully expanded list (the coordinate space in which we're aiming for `targetEffectiveIndex`) - while ((effectiveIndex <= targetEffectiveIndex || targetEffectiveIndex < 0) && currentIndex < list.length) { + var currentIndex = + 0; // where we are in `list` (some entries of which might represent multiple values, because they are themselves loops) + var effectiveIndex = + 0; // where we are in the fully expanded list (the coordinate space in which we're aiming for `targetEffectiveIndex`) + while ((effectiveIndex <= targetEffectiveIndex || targetEffectiveIndex < 0) && + currentIndex < list.length) { final Object node = list[currentIndex]!; if (node is Loop) { Object inputList = node.input; @@ -781,9 +819,10 @@ abstract class _CurriedWidget extends BlobNode { } else if (inputList is DataReference) { inputList = dataResolver(inputList.parts); } else if (inputList is WidgetBuilderArgReference) { - inputList = widgetBuilderArgResolver( - [inputList.argumentName, ...inputList.parts], - ); + inputList = widgetBuilderArgResolver([ + inputList.argumentName, + ...inputList.parts, + ]); } else if (inputList is BoundStateReference) { inputList = stateResolver(inputList.parts, inputList.depth); } else if (inputList is BoundLoopReference) { @@ -820,7 +859,8 @@ abstract class _CurriedWidget extends BlobNode { return _ResolvedDynamicList(null, boundResult, null); } effectiveIndex += entry.length!; - } else { // list[currentIndex] is not a Loop + } else { + // list[currentIndex] is not a Loop if (effectiveIndex == targetEffectiveIndex) { return _ResolvedDynamicList(null, list[currentIndex], null); } @@ -899,7 +939,8 @@ abstract class _CurriedWidget extends BlobNode { if (current is EventHandler) { current = EventHandler( current.eventName, - _fix(current.eventArguments, stateResolver, dataResolver, widgetBuilderArgResolver) as DynamicMap, + _fix(current.eventArguments, stateResolver, dataResolver, widgetBuilderArgResolver) + as DynamicMap, ); } else if (current is SetStateHandler) { current = SetStateHandler( @@ -921,13 +962,15 @@ abstract class _CurriedWidget extends BlobNode { if (parts[index] is! int) { return missing; } - current = _listLookup( - current, - parts[index] as int, - stateResolver, - dataResolver, - widgetBuilderArgResolver, - ).result ?? missing; + current = + _listLookup( + current, + parts[index] as int, + stateResolver, + dataResolver, + widgetBuilderArgResolver, + ).result ?? + missing; } else { assert(current is! ArgsReference); assert(current is! StateReference); @@ -936,7 +979,10 @@ abstract class _CurriedWidget extends BlobNode { } index += 1; } - assert(current is! Reference, 'Unexpected unbound reference (of type ${current.runtimeType}): $current'); + assert( + current is! Reference, + 'Unexpected unbound reference (of type ${current.runtimeType}): $current', + ); assert(current is! Switch); assert(current is! Loop); return current; @@ -949,8 +995,8 @@ abstract class _CurriedWidget extends BlobNode { _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, ) { if (root is DynamicMap) { - return root.map((String key, Object? value) => - MapEntry( + return root.map( + (String key, Object? value) => MapEntry( key, _fix(root[key]!, stateResolver, dataResolver, widgetBuilderArgResolver), ), @@ -967,7 +1013,7 @@ abstract class _CurriedWidget extends BlobNode { return DynamicList.generate( length, (int index) => _fix( - _listLookup(root, index, stateResolver, dataResolver, widgetBuilderArgResolver).result!, + _listLookup(root, index, stateResolver, dataResolver, widgetBuilderArgResolver).result!, stateResolver, dataResolver, widgetBuilderArgResolver, @@ -980,7 +1026,13 @@ abstract class _CurriedWidget extends BlobNode { ); } } else if (root is BlobNode) { - return _resolveFrom(root, const [], stateResolver, dataResolver, widgetBuilderArgResolver); + return _resolveFrom( + root, + const [], + stateResolver, + dataResolver, + widgetBuilderArgResolver, + ); } else { return root; } @@ -993,7 +1045,13 @@ abstract class _CurriedWidget extends BlobNode { _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, { required bool expandLists, }) { - Object result = _resolveFrom(arguments, parts, stateResolver, dataResolver, widgetBuilderArgResolver); + Object result = _resolveFrom( + arguments, + parts, + stateResolver, + dataResolver, + widgetBuilderArgResolver, + ); if (result is DynamicList && expandLists) { result = _listLookup(result, -1, stateResolver, dataResolver, widgetBuilderArgResolver); } @@ -1039,7 +1097,7 @@ class _CurriedLocalWidget extends _CurriedWidget { this.child, DynamicMap arguments, DynamicMap widgetBuilderScope, - ) : super(fullName, arguments, widgetBuilderScope, null); + ) : super(fullName, arguments, widgetBuilderScope, null); factory _CurriedLocalWidget.error(FullyQualifiedWidgetName fullName, String message) { return _CurriedLocalWidget( @@ -1062,7 +1120,7 @@ class _CurriedLocalWidget extends _CurriedWidget { _StateResolverCallback stateResolver, _DataResolverCallback dataResolver, _WidgetBuilderArgResolverCallback widgetBuilderArgResolver, - ) { + ) { return child(context, source); } } @@ -1128,7 +1186,9 @@ class _CurriedSwitch extends _CurriedWidget { if (resolvedWidget is _CurriedWidget) { return resolvedWidget.build(context, data, remoteEventTarget, states); } - return _buildErrorWidget('Switch in $fullName did not resolve to a widget (got $resolvedWidget).'); + return _buildErrorWidget( + 'Switch in $fullName did not resolve to a widget (got $resolvedWidget).', + ); } @override @@ -1142,7 +1202,7 @@ class _Widget extends StatefulWidget { required this.widgetBuilderScope, required this.remoteEventTarget, required this.states, - }); + }); final _CurriedWidget curriedWidget; @@ -1175,7 +1235,9 @@ class _WidgetState extends State<_Widget> implements DataSource { if (oldWidget.curriedWidget != widget.curriedWidget) { _updateState(); } - if (oldWidget.data != widget.data || oldWidget.curriedWidget != widget.curriedWidget || oldWidget.states != widget.states) { + if (oldWidget.data != widget.data || + oldWidget.curriedWidget != widget.curriedWidget || + oldWidget.states != widget.states) { _unsubscribe(); } } @@ -1213,10 +1275,14 @@ class _WidgetState extends State<_Widget> implements DataSource { final Object subindex = parts[index]; if (current is DynamicMap) { if (subindex is! String) { - throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); + throw RemoteFlutterWidgetsException( + '${parts.join(".")} does not identify existing state.', + ); } if (!current.containsKey(subindex)) { - throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); + throw RemoteFlutterWidgetsException( + '${parts.join(".")} does not identify existing state.', + ); } if (index == parts.length - 1) { current[subindex] = value; @@ -1225,10 +1291,14 @@ class _WidgetState extends State<_Widget> implements DataSource { } } else if (current is DynamicList) { if (subindex is! int) { - throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); + throw RemoteFlutterWidgetsException( + '${parts.join(".")} does not identify existing state.', + ); } if (subindex < 0 || subindex >= current.length) { - throw RemoteFlutterWidgetsException('${parts.join(".")} does not identify existing state.'); + throw RemoteFlutterWidgetsException( + '${parts.join(".")} does not identify existing state.', + ); } if (index == parts.length - 1) { current[subindex] = value; @@ -1266,8 +1336,7 @@ class _WidgetState extends State<_Widget> implements DataSource { @override bool isList(List argsKey) { final Object value = _fetch(argsKey, expandLists: false); - return value is _ResolvedDynamicList - || value is DynamicList; + return value is _ResolvedDynamicList || value is DynamicList; } @override @@ -1295,7 +1364,9 @@ class _WidgetState extends State<_Widget> implements DataSource { if (value is _CurriedWidget) { return value.build(context, widget.data, widget.remoteEventTarget, widget.states); } - return _buildErrorWidget('Not a widget at $argsKey (got $value) for ${widget.curriedWidget.fullName}.'); + return _buildErrorWidget( + 'Not a widget at $argsKey (got $value) for ${widget.curriedWidget.fullName}.', + ); } @override @@ -1313,26 +1384,27 @@ class _WidgetState extends State<_Widget> implements DataSource { if (value is _ResolvedDynamicList) { assert(value.length != null); final DynamicList fullList = _fetchList(argsKey, value.length!); - return List.generate( - fullList.length, - (int index) { - final Object? node = fullList[index]; - if (node is _CurriedWidget) { - return node.build(context, widget.data, widget.remoteEventTarget, _states); - } - return _buildErrorWidget('Not a widget at $argsKey (got $node) for ${widget.curriedWidget.fullName}.'); - }, - ); + return List.generate(fullList.length, (int index) { + final Object? node = fullList[index]; + if (node is _CurriedWidget) { + return node.build(context, widget.data, widget.remoteEventTarget, _states); + } + return _buildErrorWidget( + 'Not a widget at $argsKey (got $node) for ${widget.curriedWidget.fullName}.', + ); + }); } if (value == missing) { return const []; } return [ - _buildErrorWidget('Not a widget list at $argsKey (got $value) for ${widget.curriedWidget.fullName}.'), + _buildErrorWidget( + 'Not a widget list at $argsKey (got $value) for ${widget.curriedWidget.fullName}.', + ), ]; } - @override + @override Widget builder(List argsKey, DynamicMap builderArg) { return _fetchBuilder(argsKey, builderArg, optional: false)!; } @@ -1342,36 +1414,33 @@ class _WidgetState extends State<_Widget> implements DataSource { return _fetchBuilder(argsKey, builderArg); } - Widget? _fetchBuilder( - List argsKey, - DynamicMap builderArg, { - bool optional = true, - }) { + Widget? _fetchBuilder(List argsKey, DynamicMap builderArg, {bool optional = true}) { final Object value = _fetch(argsKey, expandLists: false); if (value is _RemoteWidgetBuilder) { final _CurriedWidget curriedWidget = value(builderArg); - return curriedWidget.build( - context, - widget.data, - widget.remoteEventTarget, - widget.states, - ); + return curriedWidget.build(context, widget.data, widget.remoteEventTarget, widget.states); } return optional - ? null - : _buildErrorWidget('Not a builder at $argsKey (got $value) for ${widget.curriedWidget.fullName}.'); + ? null + : _buildErrorWidget( + 'Not a builder at $argsKey (got $value) for ${widget.curriedWidget.fullName}.', + ); } @override - VoidCallback? voidHandler(List argsKey, [ DynamicMap? extraArguments ]) { - return handler(argsKey, (HandlerTrigger callback) => () => callback(extraArguments)); + VoidCallback? voidHandler(List argsKey, [DynamicMap? extraArguments]) { + return handler( + argsKey, + (HandlerTrigger callback) => + () => callback(extraArguments), + ); } @override T? handler(List argsKey, HandlerGenerator generator) { Object value = _fetch(argsKey, expandLists: true); if (value is AnyEventHandler) { - value = [ value ]; + value = [value]; } else if (value is _ResolvedDynamicList) { value = _fetchList(argsKey, value.length!); } @@ -1383,12 +1452,18 @@ class _WidgetState extends State<_Widget> implements DataSource { if (entry is EventHandler) { DynamicMap arguments = entry.eventArguments; if (extraArguments != null) { - arguments = DynamicMap.fromEntries(arguments.entries.followedBy(extraArguments.entries)); + arguments = DynamicMap.fromEntries( + arguments.entries.followedBy(extraArguments.entries), + ); } widget.remoteEventTarget(entry.eventName, arguments); } else if (entry is SetStateHandler) { assert(entry.stateReference is BoundStateReference); - _handleSetState((entry.stateReference as BoundStateReference).depth, entry.stateReference.parts, entry.value); + _handleSetState( + (entry.stateReference as BoundStateReference).depth, + entry.stateReference.parts, + entry.value, + ); } } }); @@ -1403,7 +1478,7 @@ class _WidgetState extends State<_Widget> implements DataSource { bool _debugFetching = false; final List<_Subscription> _dependencies = <_Subscription>[]; - Object _fetch(List argsKey, { required bool expandLists }) { + Object _fetch(List argsKey, {required bool expandLists}) { final key = _Key(_kArgsSection, argsKey); final Object? value = _argsCache[key]; if (value != null && (value is! DynamicList || !expandLists)) { @@ -1465,7 +1540,9 @@ class _WidgetState extends State<_Widget> implements DataSource { final _Subscription subscription; if (!_subscriptions.containsKey(stateKey)) { if (depth >= _states.length) { - throw const RemoteFlutterWidgetsException('Reference to state value did not correspond to any stateful remote widget.'); + throw const RemoteFlutterWidgetsException( + 'Reference to state value did not correspond to any stateful remote widget.', + ); } final DynamicContent? state = _states[depth]._state; if (state == null) { @@ -1527,9 +1604,11 @@ class _Key { @override bool operator ==(Object other) { - return other is _Key // _Key has no subclasses, don't need to check runtimeType - && section == other.section - && listEquals(parts, other.parts); + return other + is _Key // _Key has no subclasses, don't need to check runtimeType + && + section == other.section && + listEquals(parts, other.parts); } @override diff --git a/packages/rfw/test/argument_decoders_test.dart b/packages/rfw/test/argument_decoders_test.dart index a23aadbec8bb..27ae70597485 100644 --- a/packages/rfw/test/argument_decoders_test.dart +++ b/packages/rfw/test/argument_decoders_test.dart @@ -62,15 +62,21 @@ void main() { var buildCount = 0; final runtime = Runtime() ..update(const LibraryName(['core']), createCoreWidgets()) - ..update(const LibraryName(['builder']), LocalWidgetLibrary({ - 'Test': (BuildContext context, DataSource source) { - buildCount += 1; - duration = AnimationDefaults.durationOf(context); - curve = AnimationDefaults.curveOf(context); - return const SizedBox.shrink(); - }, - })) - ..update(const LibraryName(['test']), parseLibraryFile('import core; widget root = SizedBox();')); + ..update( + const LibraryName(['builder']), + LocalWidgetLibrary({ + 'Test': (BuildContext context, DataSource source) { + buildCount += 1; + duration = AnimationDefaults.durationOf(context); + curve = AnimationDefaults.curveOf(context); + return const SizedBox.shrink(); + }, + }), + ) + ..update( + const LibraryName(['test']), + parseLibraryFile('import core; widget root = SizedBox();'), + ); addTearDown(runtime.dispose); final data = DynamicContent(); final eventLog = []; @@ -81,134 +87,188 @@ void main() { widget: const FullyQualifiedWidgetName(LibraryName(['test']), 'root'), onEvent: (String eventName, DynamicMap eventArguments) { eventLog.add(eventName); - expect(eventArguments, const { 'argument': true }); + expect(eventArguments, const {'argument': true}); }, ), ); expect(find.byType(SizedBox), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Align(alignment: { x: 0.25, y: 0.75 }); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(Align)).alignment, const Alignment(0.25, 0.75)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Align(alignment: { start: 0.25, y: 0.75 }); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(Align)).alignment, const Alignment(0.25, 0.75)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; import builder; widget root = AnimationDefaults(curve: "easeOut", duration: 5000, child: Test()); - ''')); + '''), + ); await tester.pump(); expect(buildCount, 1); expect(duration, const Duration(seconds: 5)); expect(curve, Curves.easeOut); - ArgumentDecoders.curveDecoders['saw3'] = (DataSource source, List key) => const SawTooth(3); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + ArgumentDecoders.curveDecoders['saw3'] = (DataSource source, List key) => + const SawTooth(3); + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; import builder; widget root = AnimationDefaults(curve: "saw3", child: Test()); - ''')); + '''), + ); await tester.pump(); expect(curve, isA()); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = AspectRatio(aspectRatio: 0.5); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(AspectRatio)).aspectRatio, 0.5); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Center(widthFactor: 0.25); - ''')); + '''), + ); await tester.pump(); expect(tester.widget
(find.byType(Center)).widthFactor, 0.25); expect(tester.widget
(find.byType(Center)).heightFactor, null); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = ColoredBox(color: 0xFF112233); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF112233)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Column( mainAxisAlignment: "center", children: [ ColoredBox(color: 1), ColoredBox(color: 2) ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(Column)).mainAxisAlignment, MainAxisAlignment.center); - expect(tester.widget(find.byType(Column)).crossAxisAlignment, CrossAxisAlignment.center); + expect( + tester.widget(find.byType(Column)).crossAxisAlignment, + CrossAxisAlignment.center, + ); expect(tester.widget(find.byType(Column)).verticalDirection, VerticalDirection.down); expect(tester.widget(find.byType(Column)).children, hasLength(2)); - expect(tester.widgetList(find.byType(ColoredBox)).toList()[0].color, const Color(0x00000001)); - expect(tester.widgetList(find.byType(ColoredBox)).toList()[1].color, const Color(0x00000002)); + expect( + tester.widgetList(find.byType(ColoredBox)).toList()[0].color, + const Color(0x00000001), + ); + expect( + tester.widgetList(find.byType(ColoredBox)).toList()[1].color, + const Color(0x00000002), + ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = ColoredBox(color: 0xFF112233); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF112233)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = DefaultTextStyle( textHeightBehavior: { applyHeightToLastDescent: false }, child: SizedBoxShrink(), ); - ''')); + '''), + ); await tester.pump(); expect( tester.widget(find.byType(DefaultTextStyle)).textHeightBehavior, const TextHeightBehavior(applyHeightToLastDescent: false), ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", child: SizedBoxShrink(), ); - ''')); + '''), + ); await tester.pump(); - expect(tester.widget(find.byType(Directionality)).textDirection, TextDirection.ltr); + expect( + tester.widget(find.byType(Directionality)).textDirection, + TextDirection.ltr, + ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = FittedBox( fit: "cover", ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(FittedBox)).fit, BoxFit.cover); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = GestureDetector( onTap: event 'tap' { argument: true }, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(eventLog, ['tap']); eventLog.clear(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -217,18 +277,22 @@ void main() { fontFamily: 'FONT', ), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(Icon)).icon!.codePoint, 1); expect(tester.widget(find.byType(Icon)).icon!.fontFamily, 'FONT'); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = IconTheme( color: 0x12345678, child: SizedBoxShrink(), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(IconTheme)).data.color, const Color(0x12345678)); }); @@ -236,8 +300,11 @@ void main() { testWidgets('golden checks', (WidgetTester tester) async { final runtime = Runtime() ..update(const LibraryName(['core']), createCoreWidgets()) - ..update(const LibraryName(['test']), parseLibraryFile('import core; widget root = SizedBox();')); - addTearDown(runtime.dispose); + ..update( + const LibraryName(['test']), + parseLibraryFile('import core; widget root = SizedBox();'), + ); + addTearDown(runtime.dispose); final data = DynamicContent(); final eventLog = []; await tester.pumpWidget( @@ -257,7 +324,9 @@ void main() { ArgumentDecoders.decorationDecoders['tab'] = (DataSource source, List key) { return UnderlineTabIndicator( - borderSide: ArgumentDecoders.borderSide(source, [...key, 'side']) ?? const BorderSide(width: 2.0, color: Color(0xFFFFFFFF)), + borderSide: + ArgumentDecoders.borderSide(source, [...key, 'side']) ?? + const BorderSide(width: 2.0, color: Color(0xFFFFFFFF)), insets: ArgumentDecoders.edgeInsets(source, ['insets']) ?? EdgeInsets.zero, ); }; @@ -265,18 +334,22 @@ void main() { return const RadialGradient( center: Alignment(0.7, -0.6), radius: 0.2, - colors: [ Color(0xFFFFFF00), Color(0xFF0099FF) ], + colors: [Color(0xFFFFFF00), Color(0xFF0099FF)], stops: [0.4, 1.0], ); }; ArgumentDecoders.shapeBorderDecoders['custom'] = (DataSource source, List key) { return StarBorder( - side: ArgumentDecoders.borderSide(source, [...key, 'side']) ?? const BorderSide(width: 2.0, color: Color(0xFFFFFFFF)), + side: + ArgumentDecoders.borderSide(source, [...key, 'side']) ?? + const BorderSide(width: 2.0, color: Color(0xFFFFFFFF)), points: source.v([...key, 'points']) ?? 5.0, ); }; - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Container( margin: [20.0, 10.0, 30.0, 5.0], @@ -369,11 +442,17 @@ void main() { ), ), ); - ''')); + '''), + ); await tester.pump(); if (!kIsWeb) { expect(eventLog, hasLength(1)); - expect(eventLog.first, startsWith('image-error-event {exception: HTTP request failed, statusCode: 400, x-invalid:')); + expect( + eventLog.first, + startsWith( + 'image-error-event {exception: HTTP request failed, statusCode: 400, x-invalid:', + ), + ); eventLog.clear(); } await expectLater( @@ -385,16 +464,44 @@ void main() { ); expect(find.byType(DecoratedBox), findsNWidgets(6)); - final DecorationImage assetImage = (tester.widgetList(find.byType(DecoratedBox)).toList()[1].decoration as BoxDecoration).image!; + final DecorationImage assetImage = + (tester.widgetList(find.byType(DecoratedBox)).toList()[1].decoration + as BoxDecoration) + .image!; expect(assetImage.image, isA()); expect((assetImage.image as AssetImage).assetName, 'asset'); expect( - assetImage.colorFilter, - const ColorFilter.matrix([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])); + assetImage.colorFilter, + const ColorFilter.matrix([ + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + ]), + ); expect(assetImage.centerSlice, const Rect.fromLTRB(5.0, 8.0, 105.0, 78.0)); expect(assetImage.filterQuality, FilterQuality.none); - final DecorationImage networkImage = (tester.widgetList(find.byType(DecoratedBox)).toList()[0].decoration as BoxDecoration).image!; + final DecorationImage networkImage = + (tester.widgetList(find.byType(DecoratedBox)).toList()[0].decoration + as BoxDecoration) + .image!; expect(networkImage.image, isA()); expect((networkImage.image as NetworkImage).url, 'x-invalid://'); expect(networkImage.colorFilter, const ColorFilter.mode(Color(0xFF8811FF), BlendMode.xor)); @@ -407,10 +514,15 @@ void main() { return const MaskFilter.blur(BlurStyle.outer, 0.5); }; ArgumentDecoders.shaderDecoders['custom'] = (DataSource source, List key) { - return ui.Gradient.linear(Offset.zero, const Offset(100.0, 100.0), const [Color(0xFFFFFF00), Color(0xFF00FFFF)]); + return ui.Gradient.linear(Offset.zero, const Offset(100.0, 100.0), const [ + Color(0xFFFFFF00), + Color(0xFF00FFFF), + ]); }; - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Column( children: [ @@ -463,17 +575,30 @@ void main() { ), ], ); - ''')); + '''), + ); await tester.pump(); - expect(tester.firstWidget(find.byType(Text)).style!.fontFamilyFallback, [ 'a', 'b' ]); - expect(tester.widgetList(find.byType(Text)).map((Text widget) => widget.locale!), const [Locale('en', 'US'), Locale('en'), Locale.fromSubtags(languageCode: 'en', scriptCode: 'latin', countryCode: 'GB')]); + expect(tester.firstWidget(find.byType(Text)).style!.fontFamilyFallback, [ + 'a', + 'b', + ]); + expect( + tester.widgetList(find.byType(Text)).map((Text widget) => widget.locale!), + const [ + Locale('en', 'US'), + Locale('en'), + Locale.fromSubtags(languageCode: 'en', scriptCode: 'latin', countryCode: 'GB'), + ], + ); await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/argument_decoders_test.text.png'), skip: !runGoldens, ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = GridView( gridDelegate: { type: 'fixedCrossAxisCount', crossAxisCount: 3 }, @@ -488,7 +613,8 @@ void main() { ColoredBox(color: 0xFF992288), ], ); - ''')); + '''), + ); await tester.pump(); await expectLater( find.byType(RemoteWidget), @@ -496,7 +622,9 @@ void main() { skip: !runGoldens, ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = GridView( gridDelegate: { type: 'maxCrossAxisExtent', maxCrossAxisExtent: 50.0 }, @@ -511,7 +639,8 @@ void main() { ColoredBox(color: 0xFF992288), ], ); - ''')); + '''), + ); await tester.pump(); await expectLater( find.byType(RemoteWidget), @@ -524,7 +653,9 @@ void main() { sawGridDelegateDecoder += 1; return null; }; - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = GridView( gridDelegate: { type: 'custom' }, @@ -539,7 +670,8 @@ void main() { ColoredBox(color: 0xFF992288), ], ); - ''')); + '''), + ); expect(sawGridDelegateDecoder, 0); await tester.pump(); expect(sawGridDelegateDecoder, 1); diff --git a/packages/rfw/test/binary_test.dart b/packages/rfw/test/binary_test.dart index 857dbaf88112..d53dde448571 100644 --- a/packages/rfw/test/binary_test.dart +++ b/packages/rfw/test/binary_test.dart @@ -17,7 +17,26 @@ const int largeNumber = 9007199254730661; void main() { testWidgets('String example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob('Hello'); - expect(bytes, [ 0xFE, 0x52, 0x57, 0x44, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F ]); + expect(bytes, [ + 0xFE, + 0x52, + 0x57, + 0x44, + 0x04, + 0x05, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x48, + 0x65, + 0x6C, + 0x6C, + 0x6F, + ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); expect(value, 'Hello'); @@ -26,7 +45,21 @@ void main() { testWidgets('Big integer example', (WidgetTester tester) async { // This value is intentionally inside the JS Number range but above 2^32. final Uint8List bytes = encodeDataBlob(largeNumber); - expect(bytes, [ 0xfe, 0x52, 0x57, 0x44, 0x02, 0xa5, 0xd7, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, ]); + expect(bytes, [ + 0xfe, + 0x52, + 0x57, + 0x44, + 0x02, + 0xa5, + 0xd7, + 0xff, + 0xff, + 0xff, + 0xff, + 0x1f, + 0x00, + ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); expect(value, largeNumber); @@ -34,7 +67,21 @@ void main() { testWidgets('Big negative integer example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(-largeNumber); - expect(bytes, [ 0xfe, 0x52, 0x57, 0x44, 0x02, 0x5b, 0x28, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, ]); + expect(bytes, [ + 0xfe, + 0x52, + 0x57, + 0x44, + 0x02, + 0x5b, + 0x28, + 0x00, + 0x00, + 0x00, + 0x00, + 0xe0, + 0xff, + ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); expect(value, -largeNumber); @@ -42,7 +89,21 @@ void main() { testWidgets('Small integer example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(1); - expect(bytes, [ 0xfe, 0x52, 0x57, 0x44, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); + expect(bytes, [ + 0xfe, + 0x52, + 0x57, + 0x44, + 0x02, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); expect(value, 1); @@ -50,7 +111,21 @@ void main() { testWidgets('Small negative integer example', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(-1); - expect(bytes, [ 0xfe, 0x52, 0x57, 0x44, 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ]); + expect(bytes, [ + 0xfe, + 0x52, + 0x57, + 0x44, + 0x02, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); expect(value, -1); @@ -59,47 +134,162 @@ void main() { testWidgets('Zero integer example', (WidgetTester tester) async { // This value is intentionally inside the JS Number range but above 2^32. final Uint8List bytes = encodeDataBlob(0); - expect(bytes, [ 0xfe, 0x52, 0x57, 0x44, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]); + expect(bytes, [ + 0xfe, + 0x52, + 0x57, + 0x44, + 0x02, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); expect(value, 0); }); testWidgets('Map example', (WidgetTester tester) async { - final Uint8List bytes = encodeDataBlob(const { 'a': 15 }); + final Uint8List bytes = encodeDataBlob(const {'a': 15}); expect(bytes, [ - 0xFE, 0x52, 0x57, 0x44, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x02, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFE, + 0x52, + 0x57, + 0x44, + 0x07, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x02, + 0x0F, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); - expect(value, const { 'a': 15 }); + expect(value, const {'a': 15}); }); testWidgets('Signature check in decoders', (WidgetTester tester) async { try { - decodeDataBlob(Uint8List.fromList([ 0xFE, 0x52, 0x46, 0x57, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F ])); + decodeDataBlob( + Uint8List.fromList([ + 0xFE, + 0x52, + 0x46, + 0x57, + 0x04, + 0x05, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x48, + 0x65, + 0x6C, + 0x6C, + 0x6F, + ]), + ); fail('did not throw exception'); } on FormatException catch (e) { - expect('$e', contains('File signature mismatch. Expected FE 52 57 44 but found FE 52 46 57.')); + expect( + '$e', + contains('File signature mismatch. Expected FE 52 57 44 but found FE 52 46 57.'), + ); } try { - decodeLibraryBlob(Uint8List.fromList([ 0xFE, 0x52, 0x57, 0x44, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F ])); + decodeLibraryBlob( + Uint8List.fromList([ + 0xFE, + 0x52, + 0x57, + 0x44, + 0x04, + 0x05, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x48, + 0x65, + 0x6C, + 0x6C, + 0x6F, + ]), + ); fail('did not throw exception'); } on FormatException catch (e) { - expect('$e', contains('File signature mismatch. Expected FE 52 46 57 but found FE 52 57 44.')); + expect( + '$e', + contains('File signature mismatch. Expected FE 52 46 57 but found FE 52 57 44.'), + ); } }); testWidgets('Trailing byte check', (WidgetTester tester) async { try { - decodeDataBlob(Uint8List.fromList([ 0xFE, 0x52, 0x57, 0x44, 0x00, 0x00 ])); + decodeDataBlob(Uint8List.fromList([0xFE, 0x52, 0x57, 0x44, 0x00, 0x00])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Unexpected trailing bytes after value.')); } try { - decodeLibraryBlob(Uint8List.fromList([ 0xFE, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ])); + decodeLibraryBlob( + Uint8List.fromList([ + 0xFE, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ]), + ); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Unexpected trailing bytes after constructors.')); @@ -108,13 +298,13 @@ void main() { testWidgets('Incomplete files in signatures', (WidgetTester tester) async { try { - decodeDataBlob(Uint8List.fromList([ 0xFE, 0x52, 0x57 ])); + decodeDataBlob(Uint8List.fromList([0xFE, 0x52, 0x57])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read byte at offset 3: unexpected end of file.')); } try { - decodeLibraryBlob(Uint8List.fromList([ 0xFE, 0x52, 0x46 ])); + decodeLibraryBlob(Uint8List.fromList([0xFE, 0x52, 0x46])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read byte at offset 3: unexpected end of file.')); @@ -123,13 +313,13 @@ void main() { testWidgets('Incomplete files after signatures', (WidgetTester tester) async { try { - decodeDataBlob(Uint8List.fromList([ 0xFE, 0x52, 0x57, 0x44 ])); + decodeDataBlob(Uint8List.fromList([0xFE, 0x52, 0x57, 0x44])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read byte at offset 4: unexpected end of file.')); } try { - decodeLibraryBlob(Uint8List.fromList([ 0xFE, 0x52, 0x46, 0x57 ])); + decodeLibraryBlob(Uint8List.fromList([0xFE, 0x52, 0x46, 0x57])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Could not read int64 at offset 4: unexpected end of file.')); @@ -138,7 +328,7 @@ void main() { testWidgets('Invalid value tag', (WidgetTester tester) async { try { - decodeDataBlob(Uint8List.fromList([ 0xFE, 0x52, 0x57, 0x44, 0xCC ])); + decodeDataBlob(Uint8List.fromList([0xFE, 0x52, 0x57, 0x44, 0xCC])); fail('did not throw exception'); } on FormatException catch (e) { expect('$e', contains('Unrecognized data type 0xCC while decoding blob.')); @@ -146,19 +336,80 @@ void main() { }); testWidgets('Library encoder smoke test', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [])); - expect(bytes, [ 0xFE, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], []), + ); + expect(bytes, [ + 0xFE, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); expect(value.widgets, isEmpty); }); testWidgets('Library encoder: imports', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([Import(LibraryName(['a']))], [])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([ + Import(LibraryName(['a'])), + ], []), + ); expect(bytes, [ - 0xFE, 0x52, 0x46, 0x57, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, + 0xFE, + 0x52, + 0x46, + 0x57, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, hasLength(1)); @@ -168,7 +419,21 @@ void main() { testWidgets('Doubles', (WidgetTester tester) async { final Uint8List bytes = encodeDataBlob(0.25); - expect(bytes, [ 0xFE, 0x52, 0x57, 0x44, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x3F ]); + expect(bytes, [ + 0xFE, + 0x52, + 0x57, + 0x44, + 0x03, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xD0, + 0x3F, + ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); expect(value, 0.25); @@ -176,9 +441,44 @@ void main() { testWidgets('Library decoder: invalid widget declaration root', (WidgetTester tester) async { final bytes = Uint8List.fromList([ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xEF, ]); try { decodeLibraryBlob(bytes); @@ -188,17 +488,121 @@ void main() { }); testWidgets('Library encoder: args references', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': [ ArgsReference(['d', 5]) ] })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', { + 'c': [ + ArgsReference(['d', 5]), + ], + }), + ), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x02, 0x05, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x05, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0a, + 0x02, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x64, + 0x02, + 0x05, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -210,17 +614,45 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, ['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], hasLength(1)); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0], isA()); - expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as ArgsReference).parts, hasLength(2)); - expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as ArgsReference).parts[0], 'd'); - expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as ArgsReference).parts[1], 5); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0], + isA(), + ); + expect( + (((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! + as ArgsReference) + .parts, + hasLength(2), + ); + expect( + (((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! + as ArgsReference) + .parts[0], + 'd', + ); + expect( + (((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! + as ArgsReference) + .parts[1], + 5, + ); }); testWidgets('Library encoder: invalid args references', (WidgetTester tester) async { try { - encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': [ ArgsReference([false]) ] })), - ])); + encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', { + 'c': [ + ArgsReference([false]), + ], + }), + ), + ]), + ); } on StateError catch (e) { expect('$e', contains('Unexpected type bool while encoding blob.')); } @@ -228,36 +660,177 @@ void main() { testWidgets('Library decoder: invalid args references', (WidgetTester tester) async { final bytes = Uint8List.fromList([ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xAC, - ]); - try { - decodeLibraryBlob(bytes); - } on FormatException catch (e) { - expect('$e', contains('Invalid reference type 0xAC while decoding blob.')); - } - }); - - testWidgets('Library encoder: switches', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, Switch('b', { null: 'c' })), - ])); - expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x63, - ]); - final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); - expect(value.imports, isEmpty); - expect(value.widgets, hasLength(1)); - expect(value.widgets.first.name, 'a'); - expect(value.widgets.first.initialState, isNull); + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x05, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0a, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xAC, + ]); + try { + decodeLibraryBlob(bytes); + } on FormatException catch (e) { + expect('$e', contains('Invalid reference type 0xAC while decoding blob.')); + } + }); + + testWidgets('Library encoder: switches', (WidgetTester tester) async { + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration('a', null, Switch('b', {null: 'c'})), + ]), + ); + expect(bytes, [ + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0f, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x10, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + ]); + final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); + expect(value.imports, isEmpty); + expect(value.widgets, hasLength(1)); + expect(value.widgets.first.name, 'a'); + expect(value.widgets.first.initialState, isNull); expect(value.widgets.first.root, isA()); expect((value.widgets.first.root as Switch).input, 'b'); expect((value.widgets.first.root as Switch).outputs, hasLength(1)); @@ -266,15 +839,88 @@ void main() { }); testWidgets('Library encoder: switches', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, Switch('b', { 'c': 'd' })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration('a', null, Switch('b', {'c': 'd'})), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x63, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0f, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x64, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -289,30 +935,174 @@ void main() { }); testWidgets('Bools', (WidgetTester tester) async { - final Uint8List bytes = encodeDataBlob(const [ false, true ]); + final Uint8List bytes = encodeDataBlob(const [false, true]); expect(bytes, [ - 0xFE, 0x52, 0x57, 0x44, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0xFE, + 0x52, + 0x57, + 0x44, + 0x05, + 0x02, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, ]); final Object value = decodeDataBlob(bytes); expect(value, isA()); - expect(value, const { false, true }); + expect(value, const {false, true}); }); testWidgets('Library encoder: loops', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': [ - Loop([], ConstructorCall('d', { 'e': LoopReference(0, []) })), - ] })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', { + 'c': [ + Loop( + [], + ConstructorCall('d', {'e': LoopReference(0, [])}), + ), + ], + }), + ), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x0c, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x05, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x08, + 0x05, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x64, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x65, + 0x0c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -324,27 +1114,157 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, ['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], hasLength(1)); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0], isA()); - expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).input, isEmpty); - expect((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output, isA()); - expect(((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).name, 'd'); - expect(((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments, hasLength(1)); - expect(((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments['e'], isA()); - expect((((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments['e']! as LoopReference).loop, 0); - expect((((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop).output as ConstructorCall).arguments['e']! as LoopReference).parts, isEmpty); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0], + isA(), + ); + expect( + (((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop) + .input, + isEmpty, + ); + expect( + (((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop) + .output, + isA(), + ); + expect( + ((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop) + .output + as ConstructorCall) + .name, + 'd', + ); + expect( + ((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop) + .output + as ConstructorCall) + .arguments, + hasLength(1), + ); + expect( + ((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop) + .output + as ConstructorCall) + .arguments['e'], + isA(), + ); + expect( + (((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop) + .output + as ConstructorCall) + .arguments['e']! + as LoopReference) + .loop, + 0, + ); + expect( + (((((value.widgets.first.root as ConstructorCall).arguments['c']! as DynamicList)[0]! as Loop) + .output + as ConstructorCall) + .arguments['e']! + as LoopReference) + .parts, + isEmpty, + ); }); testWidgets('Library encoder: data references', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': DataReference(['d']) })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', { + 'c': DataReference(['d']), + }), + ), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x0B, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x64, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x0B, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x64, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -356,20 +1276,108 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, ['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA()); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as DataReference).parts, const [ 'd' ]); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as DataReference).parts, + const ['d'], + ); }); testWidgets('Library encoder: state references', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': StateReference(['d']) })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', { + 'c': StateReference(['d']), + }), + ), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x0D, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x64, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x0D, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x64, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -381,20 +1389,105 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, ['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA()); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as StateReference).parts, const [ 'd' ]); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as StateReference).parts, + const ['d'], + ); }); testWidgets('Library encoder: event handler', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': EventHandler('d', {}) })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', {'c': EventHandler('d', {})}), + ), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x0E, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x0E, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x64, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -406,21 +1499,114 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, ['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA()); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as EventHandler).eventName, 'd'); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as EventHandler).eventArguments, isEmpty); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as EventHandler).eventName, + 'd', + ); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as EventHandler) + .eventArguments, + isEmpty, + ); }); testWidgets('Library encoder: state setter', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': SetStateHandler(StateReference(['d']), false) })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', { + 'c': SetStateHandler(StateReference(['d']), false), + }), + ), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x11, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x64, 0x00, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x11, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x64, + 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -432,20 +1618,103 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments, hasLength(1)); expect((value.widgets.first.root as ConstructorCall).arguments.keys, ['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA()); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as SetStateHandler).stateReference.parts, ['d']); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as SetStateHandler).value, false); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as SetStateHandler) + .stateReference + .parts, + ['d'], + ); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as SetStateHandler).value, + false, + ); }); testWidgets('Library encoder: switch', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', null, ConstructorCall('b', { 'c': Switch(false, {} ) })), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + null, + ConstructorCall('b', {'c': Switch(false, {})}), + ), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x01, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, - 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x0F, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -458,18 +1727,74 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments.keys, ['c']); expect((value.widgets.first.root as ConstructorCall).arguments['c'], isA()); expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as Switch).input, false); - expect(((value.widgets.first.root as ConstructorCall).arguments['c']! as Switch).outputs, isEmpty); + expect( + ((value.widgets.first.root as ConstructorCall).arguments['c']! as Switch).outputs, + isEmpty, + ); }); testWidgets('Library encoder: initial state', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', {}, ConstructorCall('b', {})), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration('a', {}, ConstructorCall('b', {})), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); expect(value.imports, isEmpty); @@ -482,14 +1807,78 @@ void main() { }); testWidgets('Library encoder: initial state', (WidgetTester tester) async { - final Uint8List bytes = encodeLibraryBlob(const RemoteWidgetLibrary([], [ - WidgetDeclaration('a', { 'b': false }, ConstructorCall('c', {})), - ])); + final Uint8List bytes = encodeLibraryBlob( + const RemoteWidgetLibrary([], [ + WidgetDeclaration('a', { + 'b': false, + }, ConstructorCall('c', {})), + ]), + ); expect(bytes, [ - 0xfe, 0x52, 0x46, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x01, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x09, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xfe, + 0x52, + 0x46, + 0x57, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x61, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x62, + 0x00, + 0x09, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x63, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, 0x00, ]); final RemoteWidgetLibrary value = decodeLibraryBlob(bytes); @@ -504,7 +1893,7 @@ void main() { expect((value.widgets.first.root as ConstructorCall).arguments, isEmpty); }); - testWidgets('Library encoder: widget builders work', (WidgetTester tester) async { + testWidgets('Library encoder: widget builders work', (WidgetTester tester) async { const source = ''' widget Foo = Builder( builder: (scope) => Text(text: scope.text), @@ -517,22 +1906,16 @@ void main() { expect(library.toString(), decoded.toString()); }); - testWidgets('Library encoder: widget builders throws', (WidgetTester tester) async { - const remoteWidgetLibrary = RemoteWidgetLibrary( - [], - [ - WidgetDeclaration( - 'a', - {}, - ConstructorCall( - 'c', - { - 'builder': WidgetBuilderDeclaration('scope', ArgsReference([])), - }, - ), - ), - ], - ); + testWidgets('Library encoder: widget builders throws', (WidgetTester tester) async { + const remoteWidgetLibrary = RemoteWidgetLibrary([], [ + WidgetDeclaration( + 'a', + {}, + ConstructorCall('c', { + 'builder': WidgetBuilderDeclaration('scope', ArgsReference([])), + }), + ), + ]); try { decodeLibraryBlob(encodeLibraryBlob(remoteWidgetLibrary)); fail('did not throw exception'); diff --git a/packages/rfw/test/core_widgets_test.dart b/packages/rfw/test/core_widgets_test.dart index 421e983e7e5e..a243453f7839 100644 --- a/packages/rfw/test/core_widgets_test.dart +++ b/packages/rfw/test/core_widgets_test.dart @@ -14,8 +14,7 @@ import 'package:rfw/rfw.dart'; void main() { testWidgets('Core widgets', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); final eventLog = []; @@ -31,7 +30,9 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = GestureDetector( onTapDown: event 'tapdown' { }, @@ -39,49 +40,106 @@ void main() { onTap: event 'tap' { }, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(eventLog, ['tapdown {}', 'tapup {}', 'tap {}']); eventLog.clear(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = IntrinsicHeight(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(IntrinsicHeight), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = IntrinsicWidth(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(IntrinsicWidth), findsOneWidget); ArgumentDecoders.imageProviderDecoders['beepboop'] = (DataSource source, List key) { - return MemoryImage(Uint8List.fromList([ - 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0xff, 0x00, 0xc0, 0xc0, 0xc0, - 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b, - ])); + return MemoryImage( + Uint8List.fromList([ + 0x47, + 0x49, + 0x46, + 0x38, + 0x39, + 0x61, + 0x01, + 0x00, + 0x01, + 0x00, + 0x80, + 0xff, + 0x00, + 0xc0, + 0xc0, + 0xc0, + 0x00, + 0x00, + 0x00, + 0x21, + 0xf9, + 0x04, + 0x01, + 0x00, + 0x00, + 0x00, + 0x00, + 0x2c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x01, + 0x00, + 0x00, + 0x02, + 0x02, + 0x44, + 0x01, + 0x00, + 0x3b, + ]), + ); }; - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Image(source: 'beepboop'); - ''')); + '''), + ); await tester.pump(); expect(find.byType(Image), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = SingleChildScrollView(child: ListBody()); - ''')); + '''), + ); await tester.pump(); expect(find.byType(SingleChildScrollView), findsOneWidget); expect(find.byType(ListBody), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", @@ -100,46 +158,70 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(ListView), findsOneWidget); expect(find.byType(Container), findsNWidgets(9)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Opacity( onEnd: event 'end' {}, child: Placeholder(), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(AnimatedOpacity)).onEnd, isNot(isNull)); expect(eventLog, isEmpty); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality(textDirection: "ltr", child: Padding(padding: [12.0])); - ''')); + '''), + ); await tester.pump(); - expect(tester.widget(find.byType(Padding)).padding.resolve(TextDirection.ltr), const EdgeInsets.all(12.0)); + expect( + tester.widget(find.byType(Padding)).padding.resolve(TextDirection.ltr), + const EdgeInsets.all(12.0), + ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality(textDirection: "ltr", child: Padding(padding: [24.0])); - ''')); + '''), + ); await tester.pump(); - expect(tester.widget(find.byType(Padding)).padding.resolve(TextDirection.ltr), const EdgeInsets.all(12.0)); + expect( + tester.widget(find.byType(Padding)).padding.resolve(TextDirection.ltr), + const EdgeInsets.all(12.0), + ); await tester.pump(const Duration(seconds: 4)); - expect(tester.widget(find.byType(Padding)).padding.resolve(TextDirection.ltr), const EdgeInsets.all(24.0)); + expect( + tester.widget(find.byType(Padding)).padding.resolve(TextDirection.ltr), + const EdgeInsets.all(24.0), + ); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Placeholder(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(Placeholder), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -155,35 +237,44 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(Stack), findsOneWidget); expect(find.byType(Positioned), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", child: Rotation(turns: 0.0), ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(AnimatedRotation), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", child: Rotation(turns: 1.0, onEnd: event 'end' { from: "rotation" }), ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(AnimatedRotation), findsOneWidget); expect(eventLog, isEmpty); await tester.pump(const Duration(seconds: 1)); expect(eventLog, ['end {from: rotation}']); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", @@ -192,11 +283,14 @@ void main() { children: [SizedBox(width: 10.0)] ), ); - ''')); + '''), + ); await tester.pump(); expect(tester.getTopLeft(find.byType(SizedBox)), const Offset(790.0, 0.0)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "rtl", @@ -205,25 +299,34 @@ void main() { children: [Spacer()] ), ); - ''')); + '''), + ); await tester.pump(); expect(tester.getTopLeft(find.byType(SizedBox)), Offset.zero); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = SizedBoxExpand(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(SizedBox), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = SizedBoxShrink(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(SizedBox), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -236,20 +339,23 @@ void main() { ), ), ); - ''')); + '''), + ); await tester.pump(); final Size fractionallySizedBoxSize = tester.getSize(find.byType(FractionallySizedBox)); final Size childSize = tester.getSize(find.text('test')); expect(childSize.width, fractionallySizedBoxSize.width * 0.5); expect(childSize.height, fractionallySizedBoxSize.height * 0.8); expect(tester.widget(find.text('test')).textScaler, const TextScaler.linear(3)); - expect(tester.widget(find.byType(FractionallySizedBox)).alignment, Alignment.center); + expect( + tester.widget(find.byType(FractionallySizedBox)).alignment, + Alignment.center, + ); imageCache.clear(); }); testWidgets('More core widgets', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); final eventLog = []; @@ -267,33 +373,45 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = SafeArea( child: SizedBoxShrink(), ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(SafeArea), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Scale(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(AnimatedScale), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Wrap(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(Wrap), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = ClipRRect(); - ''')); + '''), + ); await tester.pump(); expect(find.byType(ClipRRect), findsOneWidget); final RenderClipRRect renderClip = tester.allRenderObjects.whereType().first; @@ -302,12 +420,13 @@ void main() { }); testWidgets('Flexible widget with default values', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -319,7 +438,8 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pumpWidget( RemoteWidget( @@ -336,12 +456,13 @@ void main() { }); testWidgets('Flexible widget with custom flex value', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -354,7 +475,8 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pumpWidget( RemoteWidget( @@ -371,12 +493,13 @@ void main() { }); testWidgets('Flexible widget with fit tight', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -390,7 +513,8 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pumpWidget( RemoteWidget( @@ -407,12 +531,13 @@ void main() { }); testWidgets('Flexible widget with fit loose', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -426,7 +551,8 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pumpWidget( RemoteWidget( @@ -443,12 +569,13 @@ void main() { }); testWidgets('Multiple Flexible widgets in Column', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Directionality( textDirection: "ltr", @@ -471,7 +598,8 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pumpWidget( RemoteWidget( @@ -483,7 +611,9 @@ void main() { await tester.pump(); expect(find.byType(Flexible), findsNWidgets(3)); - final List flexibleWidgets = tester.widgetList(find.byType(Flexible)).toList(); + final List flexibleWidgets = tester + .widgetList(find.byType(Flexible)) + .toList(); expect(flexibleWidgets[0].flex, equals(1)); expect(flexibleWidgets[0].fit, equals(FlexFit.loose)); expect(flexibleWidgets[1].flex, equals(2)); diff --git a/packages/rfw/test/material_widgets_test.dart b/packages/rfw/test/material_widgets_test.dart index c0fa13e335f4..af47185a8a45 100644 --- a/packages/rfw/test/material_widgets_test.dart +++ b/packages/rfw/test/material_widgets_test.dart @@ -11,8 +11,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart' show parseLibraryFile; import 'package:rfw/rfw.dart'; -import 'tolerant_comparator.dart' - if (dart.library.js_interop) 'tolerant_comparator_web.dart'; +import 'tolerant_comparator.dart' if (dart.library.js_interop) 'tolerant_comparator_web.dart'; import 'utils.dart'; /// A const to tell apart Wasm from JS web. @@ -58,10 +57,7 @@ void main() { ), ), ); - expect( - tester.takeException().toString(), - contains('Could not find remote widget named'), - ); + expect(tester.takeException().toString(), contains('Could not find remote widget named')); runtime.update( const LibraryName(['test']), @@ -241,10 +237,7 @@ void main() { await tester.tap(find.text('second')); await tester.pumpAndSettle(); expect(eventLog, contains('menu_item {args: second}')); - expect( - eventLog, - contains(kIsJS ? 'dropdown {value: 2}' : 'dropdown {value: 2.0}'), - ); + expect(eventLog, contains(kIsJS ? 'dropdown {value: 2}' : 'dropdown {value: 2.0}')); await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(); @@ -273,10 +266,7 @@ void main() { ), ), ); - expect( - tester.takeException().toString(), - contains('Could not find remote widget named'), - ); + expect(tester.takeException().toString(), contains('Could not find remote widget named')); addTearDown(() async { await tester.binding.setSurfaceSize(null); @@ -331,16 +321,12 @@ void main() { await expectLater( find.byType(RemoteWidget), - matchesGoldenFile( - 'goldens/material_test.button_bar_properties.overflow.png', - ), + matchesGoldenFile('goldens/material_test.button_bar_properties.overflow.png'), skip: !runGoldens || true, ); }); - testWidgets('OverflowBar configured to resemble ButtonBar', ( - WidgetTester tester, - ) async { + testWidgets('OverflowBar configured to resemble ButtonBar', (WidgetTester tester) async { final Runtime runtime = setupRuntime(); final data = DynamicContent(); final eventLog = []; @@ -357,10 +343,7 @@ void main() { ), ), ); - expect( - tester.takeException().toString(), - contains('Could not find remote widget named'), - ); + expect(tester.takeException().toString(), contains('Could not find remote widget named')); runtime.update( testName, @@ -397,9 +380,7 @@ void main() { await tester.pump(); await expectLater( find.byType(RemoteWidget), - matchesGoldenFile( - 'goldens/material_test.overflow_bar_resembles_button_bar.png', - ), + matchesGoldenFile('goldens/material_test.overflow_bar_resembles_button_bar.png'), // TODO(louisehsu): Unskip once golden file is updated. See // https://github.com/flutter/flutter/issues/151995 skip: !runGoldens || true, @@ -423,10 +404,7 @@ void main() { ), ), ); - expect( - tester.takeException().toString(), - contains('Could not find remote widget named'), - ); + expect(tester.takeException().toString(), contains('Could not find remote widget named')); addTearDown(() async { await tester.binding.setSurfaceSize(null); @@ -478,9 +456,7 @@ void main() { await expectLater( find.byType(RemoteWidget), - matchesGoldenFile( - 'goldens/material_test.overflow_bar_properties.overflow.png', - ), + matchesGoldenFile('goldens/material_test.overflow_bar_properties.overflow.png'), // TODO(louisehsu): Unskip once golden file is updated. See // https://github.com/flutter/flutter/issues/151995 skip: !runGoldens || true, @@ -504,10 +480,7 @@ void main() { ), ), ); - expect( - tester.takeException().toString(), - contains('Could not find remote widget named'), - ); + expect(tester.takeException().toString(), contains('Could not find remote widget named')); runtime.update( testName, @@ -537,9 +510,7 @@ void main() { // Hover final Offset center = tester.getCenter(find.byType(InkResponse)); - final TestGesture gesture = await tester.createGesture( - kind: PointerDeviceKind.mouse, - ); + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); addTearDown(gesture.removePointer); await gesture.moveTo(center); @@ -555,9 +526,7 @@ void main() { // Tap await gesture.down(center); await tester.pump(); // start gesture - await tester.pump( - const Duration(milliseconds: 200), - ); // wait for splash to be well under way + await tester.pump(const Duration(milliseconds: 200)); // wait for splash to be well under way await expectLater( find.byType(RemoteWidget), @@ -587,10 +556,7 @@ void main() { ), ), ); - expect( - tester.takeException().toString(), - contains('Could not find remote widget named'), - ); + expect(tester.takeException().toString(), contains('Could not find remote widget named')); runtime.update( testName, @@ -618,10 +584,7 @@ void main() { tester.widget(find.byType(Material)).animationDuration, const Duration(milliseconds: 300), ); - expect( - tester.widget(find.byType(Material)).borderOnForeground, - false, - ); + expect(tester.widget(find.byType(Material)).borderOnForeground, false); await expectLater( find.byType(RemoteWidget), matchesGoldenFile('goldens/material_test.material_properties.png'), @@ -647,10 +610,7 @@ void main() { ); await tester.pump(); - expect( - tester.widget(find.byType(Material)).clipBehavior, - Clip.antiAlias, - ); + expect(tester.widget(find.byType(Material)).clipBehavior, Clip.antiAlias); }); testWidgets('Slider properties', (WidgetTester tester) async { @@ -670,10 +630,7 @@ void main() { ), ), ); - expect( - tester.takeException().toString(), - contains('Could not find remote widget named'), - ); + expect(tester.takeException().toString(), contains('Could not find remote widget named')); runtime.update( testName, @@ -732,18 +689,9 @@ void main() { //drag slider await _slideToValue(tester, sliderFinder, 20.0); await tester.pumpAndSettle(); - expect( - eventLog, - contains(kIsJS ? 'slider {value: 20}' : 'slider {value: 20.0}'), - ); - expect( - eventLog, - contains(kIsJS ? 'slider.start {value: 0}' : 'slider.start {value: 0.0}'), - ); - expect( - eventLog, - contains(kIsJS ? 'slider.end {value: 20}' : 'slider.end {value: 20.0}'), - ); + expect(eventLog, contains(kIsJS ? 'slider {value: 20}' : 'slider {value: 20.0}')); + expect(eventLog, contains(kIsJS ? 'slider.start {value: 0}' : 'slider.start {value: 0.0}')); + expect(eventLog, contains(kIsJS ? 'slider.end {value: 20}' : 'slider.end {value: 20.0}')); }); } @@ -757,8 +705,7 @@ Future _slideToValue( final Offset zeroPoint = widgetTester.getTopLeft(slider) + Offset(paddingOffset, widgetTester.getSize(slider).height / 2); - final double totalWidth = - widgetTester.getSize(slider).width - (2 * paddingOffset); + final double totalWidth = widgetTester.getSize(slider).width - (2 * paddingOffset); final double calculateOffset = value * (totalWidth / 100); await widgetTester.dragFrom(zeroPoint, Offset(calculateOffset, 0)); } diff --git a/packages/rfw/test/model_test.dart b/packages/rfw/test/model_test.dart index 683f2b5a884b..d44ba7224fc2 100644 --- a/packages/rfw/test/model_test.dart +++ b/packages/rfw/test/model_test.dart @@ -67,9 +67,20 @@ void main() { expect('${const EventHandler("a", {})}', 'event a {}'); expect('${const SetStateHandler(StateReference(["a"]), false)}', 'set state.a = false'); expect('${const Import(LibraryName(["a"]))}', 'import a;'); - expect('${const WidgetDeclaration("a", null, ConstructorCall("b", {}))}', 'widget a = b({});'); - expect('${const WidgetDeclaration("a", { "x": false }, ConstructorCall("b", {}))}', 'widget a = b({});'); - expect('${const RemoteWidgetLibrary([Import(LibraryName(["a"]))], [WidgetDeclaration("a", null, ConstructorCall("b", {}))])}', 'import a;\nwidget a = b({});'); + expect( + '${const WidgetDeclaration("a", null, ConstructorCall("b", {}))}', + 'widget a = b({});', + ); + expect( + '${const WidgetDeclaration("a", {"x": false}, ConstructorCall("b", {}))}', + 'widget a = b({});', + ); + expect( + '${const RemoteWidgetLibrary([ + Import(LibraryName(["a"])), + ], [WidgetDeclaration("a", null, ConstructorCall("b", {}))])}', + 'import a;\nwidget a = b({});', + ); }); testWidgets('$BoundArgsReference', (WidgetTester tester) async { @@ -85,19 +96,25 @@ void main() { }); testWidgets('$LoopReference', (WidgetTester tester) async { - final LoopReference result = const LoopReference(9, [0]).constructReference([1]); + final LoopReference result = const LoopReference(9, [ + 0, + ]).constructReference([1]); expect(result.parts, const [0, 1]); }); testWidgets('$BoundLoopReference', (WidgetTester tester) async { final target = Object(); - final BoundLoopReference result = const LoopReference(9, [0]).bind(target).constructReference([1]); + final BoundLoopReference result = const LoopReference(9, [ + 0, + ]).bind(target).constructReference([1]); expect(result.value, target); expect(result.parts, const [0, 1]); }); testWidgets('$BoundStateReference', (WidgetTester tester) async { - final BoundStateReference result = const StateReference([0]).bind(9).constructReference([1]); + final BoundStateReference result = const StateReference([ + 0, + ]).bind(9).constructReference([1]); expect(result.depth, 9); expect(result.parts, const [0, 1]); }); @@ -125,10 +142,7 @@ void main() { expect(test2 > test1, isTrue); expect(test2 >= test1, isTrue); // map - final map = { - test1: test1, - test2: test2, - }; + final map = {test1: test1, test2: test2}; expect(map[test1], test1); expect(map[test2], test2); }); @@ -161,10 +175,7 @@ void main() { expect(range1 == range2, isFalse); expect(range2 == range1, isFalse); // map - final map = { - range1: range1, - range2: range2, - }; + final map = {range1: range1, range2: range2}; expect(map[range1], range1); expect(map[range2], range2); }); diff --git a/packages/rfw/test/readme_test.dart b/packages/rfw/test/readme_test.dart index 46dd327c1f58..ec2317c61477 100644 --- a/packages/rfw/test/readme_test.dart +++ b/packages/rfw/test/readme_test.dart @@ -12,7 +12,7 @@ import 'package:rfw/formats.dart'; import 'package:rfw/rfw.dart'; const Map rawRemoteWidgetSnippets = { -'root': ''' + 'root': ''' // #docregion root import local; widget root = GreenBox( @@ -21,7 +21,7 @@ widget root = GreenBox( // #enddocregion root ''', -'fruit': ''' + 'fruit': ''' import local; // #docregion fruit widget fruit = Foo( @@ -30,7 +30,7 @@ widget fruit = Foo( // #enddocregion fruit ''', -'example1': ''' + 'example1': ''' import local; // #docregion example1 widget example1 = GreenBox( @@ -41,7 +41,7 @@ widget example1 = GreenBox( // #enddocregion example1 ''', -'example2': ''' + 'example2': ''' import local; // #docregion example2 widget example2 = GreenBox( @@ -52,7 +52,7 @@ widget example2 = GreenBox( // #enddocregion example2 ''', -'example3': ''' + 'example3': ''' import local; // #docregion example3 widget example3 = GreenBox( @@ -63,7 +63,7 @@ widget example3 = GreenBox( // #enddocregion example3 ''', -'tap': ''' + 'tap': ''' import local; import core; widget tap = GestureDetector( @@ -72,7 +72,7 @@ widget tap = GestureDetector( ); ''', -'tapDown': ''' + 'tapDown': ''' import local; import core; widget tapDown = GestureDetector( @@ -81,7 +81,7 @@ widget tapDown = GestureDetector( ); ''', -'Shop': ''' + 'Shop': ''' // #docregion Shop import core; @@ -97,7 +97,7 @@ widget Product = Text(text: args.product.name, softWrap: false, overflow: "fade" // #enddocregion Shop ''', -'MaterialShop': ''' + 'MaterialShop': ''' // #docregion MaterialShop import core; import material; @@ -121,7 +121,7 @@ widget Product = ListTile( // #enddocregion MaterialShop ''', -'CalculatorPad': ''' + 'CalculatorPad': ''' import core; widget CalculatorPad = Column( @@ -142,7 +142,7 @@ widget CalculatorPad = Column( ); ''', -'CalculatorButton': ''' + 'CalculatorButton': ''' import core; // #docregion CalculatorButton @@ -162,8 +162,7 @@ widget CalculatorButton = Padding( }; // The empty docregion at the end of the following causes the snippet to end with "// ...". -const String gameData = -''' +const String gameData = ''' // #docregion game-data { "games": [ {"rating": 8.219, "users-rated": 16860, "name": "Twilight Struggle", "rank": 1, "link": "/boardgame/12333/twilight-struggle", "id": 12333}, @@ -179,16 +178,26 @@ const String gameData = List _createLocalWidgets(String region) { switch (region) { case 'root': - return [LocalWidgetLibrary({ - // #docregion defaultLocalWidgets - 'GreenBox': (BuildContext context, DataSource source) { - return ColoredBox(color: const Color(0xFF002211), child: source.child(['child'])); - }, - 'Hello': (BuildContext context, DataSource source) { - return Center(child: Text('Hello, ${source.v(["name"])}!', textDirection: TextDirection.ltr)); - }, - // #enddocregion defaultLocalWidgets - })]; + return [ + LocalWidgetLibrary({ + // #docregion defaultLocalWidgets + 'GreenBox': (BuildContext context, DataSource source) { + return ColoredBox( + color: const Color(0xFF002211), + child: source.child(['child']), + ); + }, + 'Hello': (BuildContext context, DataSource source) { + return Center( + child: Text( + 'Hello, ${source.v(["name"])}!', + textDirection: TextDirection.ltr, + ), + ); + }, + // #enddocregion defaultLocalWidgets + }), + ]; case 'fruit': return [ LocalWidgetLibrary({ @@ -202,7 +211,10 @@ List _createLocalWidgets(String region) { // #docregion isList 'Foo': (BuildContext context, DataSource source) { if (source.isList(['bar', 'quux'])) { - return Text('${source.v(['bar', 'quux', 2])}', textDirection: TextDirection.ltr); + return Text( + '${source.v(['bar', 'quux', 2])}', + textDirection: TextDirection.ltr, + ); } return Text('${source.v(['baz'])}', textDirection: TextDirection.ltr); }, @@ -211,42 +223,55 @@ List _createLocalWidgets(String region) { ]; case 'example1': case 'example2': - return [LocalWidgetLibrary({ - // #docregion child - 'GreenBox': (BuildContext context, DataSource source) { - return ColoredBox(color: const Color(0xFF002211), child: source.child(['child'])); - }, - // #enddocregion child - // #docregion isMap - 'Foo': (BuildContext context, DataSource source) { - if (source.isMap(['bar'])) { - return Text('${source.v(['bar', 'name'])}', textDirection: TextDirection.ltr); - } - return Text('${source.v(['bar'])}', textDirection: TextDirection.ltr); - }, - // #enddocregion isMap - })]; + return [ + LocalWidgetLibrary({ + // #docregion child + 'GreenBox': (BuildContext context, DataSource source) { + return ColoredBox( + color: const Color(0xFF002211), + child: source.child(['child']), + ); + }, + // #enddocregion child + // #docregion isMap + 'Foo': (BuildContext context, DataSource source) { + if (source.isMap(['bar'])) { + return Text( + '${source.v(['bar', 'name'])}', + textDirection: TextDirection.ltr, + ); + } + return Text('${source.v(['bar'])}', textDirection: TextDirection.ltr); + }, + // #enddocregion isMap + }), + ]; case 'example3': - return [LocalWidgetLibrary({ - // #docregion optionalChild - 'GreenBox': (BuildContext context, DataSource source) { - return ColoredBox(color: const Color(0xFF002211), child: source.optionalChild(['child'])); - }, - // #enddocregion optionalChild - // #docregion length - 'Foo': (BuildContext context, DataSource source) { - final int length = source.length(['text']); - if (length > 0) { - final text = StringBuffer(); - for (var index = 0; index < length; index += 1) { - text.write(source.v(['text', index])); + return [ + LocalWidgetLibrary({ + // #docregion optionalChild + 'GreenBox': (BuildContext context, DataSource source) { + return ColoredBox( + color: const Color(0xFF002211), + child: source.optionalChild(['child']), + ); + }, + // #enddocregion optionalChild + // #docregion length + 'Foo': (BuildContext context, DataSource source) { + final int length = source.length(['text']); + if (length > 0) { + final text = StringBuffer(); + for (var index = 0; index < length; index += 1) { + text.write(source.v(['text', index])); + } + return Text(text.toString(), textDirection: TextDirection.ltr); } - return Text(text.toString(), textDirection: TextDirection.ltr); - } - return const Text('', textDirection: TextDirection.ltr); - }, - // #enddocregion length - })]; + return const Text('', textDirection: TextDirection.ltr); + }, + // #enddocregion length + }), + ]; case 'tap': // #docregion onTap return [ @@ -264,14 +289,18 @@ List _createLocalWidgets(String region) { }, }), ]; - // #enddocregion onTap + // #enddocregion onTap case 'tapDown': return [ LocalWidgetLibrary({ 'GestureDetector': (BuildContext context, DataSource source) { // #docregion onTapDown return GestureDetector( - onTapDown: source.handler(['onTapDown'], (HandlerTrigger trigger) => (TapDownDetails details) => trigger()), + onTapDown: source.handler( + ['onTapDown'], + (HandlerTrigger trigger) => + (TapDownDetails details) => trigger(), + ), child: source.optionalChild(['child']), ); // #enddocregion onTapDown @@ -282,10 +311,13 @@ List _createLocalWidgets(String region) { // #docregion onTapDown-long return GestureDetector( // onTapDown expects a function that takes a TapDownDetails - onTapDown: source.handler( // this returns a function that takes a TapDownDetails + onTapDown: source.handler( + // this returns a function that takes a TapDownDetails ['onTapDown'], - (HandlerTrigger trigger) { // "trigger" is the function that will send the event to RemoteWidget.onEvent - return (TapDownDetails details) { // this is the function that is returned by handler() above + (HandlerTrigger trigger) { + // "trigger" is the function that will send the event to RemoteWidget.onEvent + return (TapDownDetails details) { + // this is the function that is returned by handler() above trigger(); // the function calls "trigger" }; }, @@ -337,8 +369,7 @@ void main() { await tester.pumpWidget( MaterialApp( home: RemoteWidget( - runtime: runtime - ..update(const LibraryName(['local']), localWidgets), + runtime: runtime..update(const LibraryName(['local']), localWidgets), data: data, widget: FullyQualifiedWidgetName(LibraryName([region]), region), ), diff --git a/packages/rfw/test/remote_widget_test.dart b/packages/rfw/test/remote_widget_test.dart index 1665bdbd105c..6e7d66658434 100644 --- a/packages/rfw/test/remote_widget_test.dart +++ b/packages/rfw/test/remote_widget_test.dart @@ -34,10 +34,7 @@ void main() { RemoteWidget( runtime: runtime1, data: data, - widget: const FullyQualifiedWidgetName( - LibraryName(['test']), - 'root', - ), + widget: const FullyQualifiedWidgetName(LibraryName(['test']), 'root'), ), ); expect(find.byType(RemoteWidget), findsOneWidget); @@ -48,10 +45,7 @@ void main() { RemoteWidget( runtime: runtime2, data: data, - widget: const FullyQualifiedWidgetName( - LibraryName(['test']), - 'root', - ), + widget: const FullyQualifiedWidgetName(LibraryName(['test']), 'root'), ), ); expect(find.byType(RemoteWidget), findsOneWidget); diff --git a/packages/rfw/test/runtime_test.dart b/packages/rfw/test/runtime_test.dart index 9d51c71e94c6..0032ca134ff4 100644 --- a/packages/rfw/test/runtime_test.dart +++ b/packages/rfw/test/runtime_test.dart @@ -16,11 +16,10 @@ import 'package:rfw/rfw.dart'; void main() { testWidgets('list lookup', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent({ - 'list': [ 0, 1, 2, 3, 4 ], + 'list': [0, 1, 2, 3, 4], }); await tester.pumpWidget( RemoteWidget( @@ -33,14 +32,17 @@ void main() { expect(tester.takeException().toString(), contains('Could not find remote widget named')); expect(find.byType(ErrorWidget), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Column( children: [ ...for v in data.list: Text(text: v, textDirection: "ltr"), ], ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(Text), findsNWidgets(5)); }); @@ -49,19 +51,22 @@ void main() { var buildCount = 0; int? lastValue; final runtime = Runtime() - ..update(const LibraryName(['core']), LocalWidgetLibrary({ - 'Test': (BuildContext context, DataSource source) { - buildCount += 1; - lastValue = source.v(['value']); - return const SizedBox.shrink(); - }, - })); + ..update( + const LibraryName(['core']), + LocalWidgetLibrary({ + 'Test': (BuildContext context, DataSource source) { + buildCount += 1; + lastValue = source.v(['value']); + return const SizedBox.shrink(); + }, + }), + ); addTearDown(runtime.dispose); final data = DynamicContent({ 'list': [ - { 'a': 0 }, - { 'a': 1 }, - { 'a': 2 }, + {'a': 0}, + {'a': 1}, + {'a': 2}, ], }); await tester.pumpWidget( @@ -75,41 +80,44 @@ void main() { expect(buildCount, 0); expect(lastValue, isNull); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Test(value: data.list.1.a); - ''')); + '''), + ); await tester.pump(); expect(buildCount, 1); expect(lastValue, 1); data.update('list', [ - { 'a': 0 }, - { 'a': 3 }, - { 'a': 2 }, + {'a': 0}, + {'a': 3}, + {'a': 2}, ]); await tester.pump(); expect(buildCount, 2); expect(lastValue, 3); data.update('list', [ - { 'a': 1 }, - { 'a': 3 }, + {'a': 1}, + {'a': 3}, ]); await tester.pump(); expect(buildCount, 2); expect(lastValue, 3); data.update('list', [ - { 'a': 1 }, - { }, + {'a': 1}, + {}, ]); await tester.pump(); expect(buildCount, 3); expect(lastValue, null); data.update('list', [ - { 'a': 1 }, + {'a': 1}, ]); await tester.pump(); expect(buildCount, 3); @@ -122,17 +130,14 @@ void main() { testWidgets('deepClone', (WidgetTester tester) async { final map = { - 'outer': { - 'inner': true, - } + 'outer': {'inner': true}, }; expect(identical(deepClone(map), map), isFalse); expect(deepClone(map), equals(map)); }); testWidgets('updateText, updateBinary, clearLibraries', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -146,17 +151,27 @@ void main() { expect(tester.takeException().toString(), contains('Could not find remote widget named')); expect(find.byType(ErrorWidget), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = ColoredBox(color: 0xFF000000); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000000)); - runtime.update(const LibraryName(['test']), decodeLibraryBlob(encodeLibraryBlob(parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + decodeLibraryBlob( + encodeLibraryBlob( + parseLibraryFile(''' import core; widget root = ColoredBox(color: 0xFF000001); - ''')))); + '''), + ), + ), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000001)); @@ -168,8 +183,7 @@ void main() { }); testWidgets('Runtime cached build', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -201,12 +215,18 @@ void main() { testWidgets('Import loops', (WidgetTester tester) async { final runtime = Runtime() - ..update(const LibraryName(['a']), parseLibraryFile(''' + ..update( + const LibraryName(['a']), + parseLibraryFile(''' import b; - ''')) - ..update(const LibraryName(['b']), parseLibraryFile(''' + '''), + ) + ..update( + const LibraryName(['b']), + parseLibraryFile(''' import a; - ''')); + '''), + ); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -216,14 +236,20 @@ void main() { widget: const FullyQualifiedWidgetName(LibraryName(['a']), 'widget'), ), ); - expect(tester.takeException().toString(), 'Library a indirectly depends on itself via b which depends on a.'); + expect( + tester.takeException().toString(), + 'Library a indirectly depends on itself via b which depends on a.', + ); }); testWidgets('Import loops', (WidgetTester tester) async { final runtime = Runtime() - ..update(const LibraryName(['a']), parseLibraryFile(''' + ..update( + const LibraryName(['a']), + parseLibraryFile(''' import a; - ''')); + '''), + ); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -238,9 +264,12 @@ void main() { testWidgets('Missing libraries in import', (WidgetTester tester) async { final runtime = Runtime() - ..update(const LibraryName(['a']), parseLibraryFile(''' + ..update( + const LibraryName(['a']), + parseLibraryFile(''' import b; - ''')); + '''), + ); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -251,7 +280,12 @@ void main() { ), ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - expect(tester.widget(find.byType(ErrorWidget)).message, contains('Could not find remote widget named widget in a, possibly because some dependencies were missing: b')); + expect( + tester.widget(find.byType(ErrorWidget)).message, + contains( + 'Could not find remote widget named widget in a, possibly because some dependencies were missing: b', + ), + ); }); testWidgets('Missing libraries in specified widget', (WidgetTester tester) async { @@ -266,15 +300,23 @@ void main() { ), ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - expect(tester.widget(find.byType(ErrorWidget)).message, contains('Could not find remote widget named widget in a, possibly because some dependencies were missing: a')); + expect( + tester.widget(find.byType(ErrorWidget)).message, + contains( + 'Could not find remote widget named widget in a, possibly because some dependencies were missing: a', + ), + ); }); testWidgets('Missing libraries in import via dependency', (WidgetTester tester) async { final runtime = Runtime() - ..update(const LibraryName(['a']), parseLibraryFile(''' + ..update( + const LibraryName(['a']), + parseLibraryFile(''' import b; widget widget = test(); - ''')); + '''), + ); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -285,12 +327,16 @@ void main() { ), ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - expect(tester.widget(find.byType(ErrorWidget)).message, contains('Could not find remote widget named test in a, possibly because some dependencies were missing: b')); + expect( + tester.widget(find.byType(ErrorWidget)).message, + contains( + 'Could not find remote widget named test in a, possibly because some dependencies were missing: b', + ), + ); }); testWidgets('Missing widget', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['a']), parseLibraryFile('')); + final runtime = Runtime()..update(const LibraryName(['a']), parseLibraryFile('')); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -301,12 +347,14 @@ void main() { ), ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - expect(tester.widget(find.byType(ErrorWidget)).message, contains('Could not find remote widget named widget in a.')); + expect( + tester.widget(find.byType(ErrorWidget)).message, + contains('Could not find remote widget named widget in a.'), + ); }); testWidgets('Runtime', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -318,26 +366,31 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { level: 0 } = inner(level: state.level); widget inner { level: 1 } = ColoredBox(color: args.level); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000000)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { level: 0 } = inner(level: state.level); widget inner { level: 1 } = ColoredBox(color: state.level); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000001)); }); testWidgets('Runtime', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -349,19 +402,21 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { level: 0 } = switch state.level { 0: ColoredBox(color: 2), }; - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000002)); }); testWidgets('Runtime', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); expect(runtime.libraries.length, 1); final LibraryName libraryName = runtime.libraries.entries.first.key; @@ -373,8 +428,7 @@ void main() { }); testWidgets('Runtime', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -386,13 +440,16 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { level: 0 } = GestureDetector( onTap: set state.level = 1, child: ColoredBox(color: state.level), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000000)); await tester.tap(find.byType(ColoredBox)); @@ -401,8 +458,7 @@ void main() { }); testWidgets('DynamicContent', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -414,10 +470,13 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = ColoredBox(color: data.color.value); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000000)); @@ -429,15 +488,20 @@ void main() { await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000002)); - data.update('color', decodeDataBlob(Uint8List.fromList([ - 0xFE, 0x52, 0x57, 0x44, // signature - 0x07, // data is a map - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which has one key - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which has five letters - 0x76, 0x61, 0x6c, 0x75, 0x65, // ...which are "value" - 0x02, // and the value is an integer - 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which is the number 2 - ]))); + data.update( + 'color', + decodeDataBlob( + Uint8List.fromList([ + 0xFE, 0x52, 0x57, 0x44, // signature + 0x07, // data is a map + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which has one key + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which has five letters + 0x76, 0x61, 0x6c, 0x75, 0x65, // ...which are "value" + 0x02, // and the value is an integer + 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ...which is the number 2 + ]), + ), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000002)); }); @@ -448,14 +512,13 @@ void main() { }); testWidgets('binding loop variables', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent({ 'list': [ { - 'a': { 'b': 0xEE }, - 'c': [ 0xDD ], + 'a': {'b': 0xEE}, + 'c': [0xDD], }, ], }); @@ -474,7 +537,9 @@ void main() { expect(tester.takeException().toString(), contains('Could not find remote widget named')); expect(find.byType(ErrorWidget), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify = ColoredBox(color: args.value.0.q.0); widget root = verify( @@ -484,11 +549,14 @@ void main() { }, ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x000000EE)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify = ColoredBox(color: args.value.0.q.0); widget root = verify( @@ -498,11 +566,14 @@ void main() { }, ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x000000DD)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify = ColoredBox(color: args.value.0.q); widget root = verify( @@ -515,11 +586,14 @@ void main() { }, ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x000000CC)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify { state: true } = ColoredBox(color: args.value.c.0); widget remote = SizedBox(child: args.corn.0); @@ -529,11 +603,14 @@ void main() { verify(value: v), ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x000000DD)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify { state: true } = ColoredBox(color: args.value); widget remote = SizedBox(child: args.corn.0); @@ -547,11 +624,14 @@ void main() { }), ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF0D0D0D)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify { state: true } = switch args.value.c.0 { 0xDD: ColoredBox(color: 0xFF0D0D0D), @@ -564,11 +644,14 @@ void main() { verify(value: v), ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF0D0D0D)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify { state: true } = GestureDetector( onTap: event 'test' { test: args.value.a.b }, @@ -581,14 +664,17 @@ void main() { verify(value: v), ], ); - ''')); + '''), + ); expect(eventLog, isEmpty); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(eventLog, ['test {test: ${0xEE}}']); eventLog.clear(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget verify { state: 0x00 } = GestureDetector( onTap: set state.state = args.value.a.b, @@ -604,18 +690,17 @@ void main() { verify(value: v), ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000001)); await tester.tap(find.byType(ColoredBox)); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000002)); - }); testWidgets('list lookup of esoteric values', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -627,7 +712,9 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = test(list: ['A'], loop: [...for b in ["B", "C"]: b]); widget test = Text( @@ -639,11 +726,14 @@ void main() { '<', ], ); - ''')); + '''), + ); await tester.pump(); expect(find.text('>ABC<'), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Text( textDirection: "ltr", @@ -653,11 +743,14 @@ void main() { '<', ], ); - ''')); + '''), + ); await tester.pump(); expect(find.text('><'), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = test(list: [test()]); widget test = Text( @@ -668,11 +761,14 @@ void main() { '<', ], ); - ''')); + '''), + ); await tester.pump(); expect(find.text('><'), findsOneWidget); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { list: [ 0x01 ] } = GestureDetector( onTap: set state.list = [ 0x02, 0x03 ], @@ -683,7 +779,8 @@ void main() { ], ), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000001)); await tester.tap(find.byType(ColoredBox)); @@ -691,7 +788,9 @@ void main() { expect(tester.firstWidget(find.byType(ColoredBox)).color, const Color(0x00000002)); expect(find.byType(ColoredBox), findsNWidgets(2)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Column( children: [ @@ -701,11 +800,14 @@ void main() { }: v, ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000001)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = Column( children: [ @@ -715,11 +817,14 @@ void main() { }: v, ], ); - ''')); + '''), + ); await tester.pump(); expect(find.byType(ColoredBox), findsNothing); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = test( list: [...for w in [ColoredBox(color: 0xFF00FF00)]: w], @@ -729,17 +834,19 @@ void main() { ...for v in args.list: v, ], ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF00FF00)); }); testWidgets('data lookup', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent({ - 'map': { 'list': [ 0xAB ] }, + 'map': { + 'list': [0xAB], + }, }); await tester.pumpWidget( RemoteWidget( @@ -750,18 +857,20 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = test(list: data.map.list); widget test = ColoredBox(color: args.list.0); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x000000AB)); }); testWidgets('args lookup', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -773,19 +882,21 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = test1(map: { 'list': [ 0xAC ] }); widget test1 = test2(list: args.map.list); widget test2 = ColoredBox(color: args.list.0); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x000000AC)); }); testWidgets('state lookup', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -797,18 +908,20 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { map: { 'list': [ 0xAD ] } } = test(list: state.map.list); widget test = ColoredBox(color: args.list.0); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x000000AD)); }); testWidgets('switch', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -820,13 +933,16 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = ColoredBox(color: switch data.a.b { 0: 0x11111111, default: 0x22222222, }); - ''')); + '''), + ); data.update('a', parseDataFile('{ b: 1 }')); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x22222222)); @@ -834,17 +950,22 @@ void main() { await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x11111111)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = switch true {}; - ''')); + '''), + ); await tester.pump(); - expect(tester.takeException().toString(), 'Switch in test:root did not resolve to a widget (got ).'); + expect( + tester.takeException().toString(), + 'Switch in test:root did not resolve to a widget (got ).', + ); }); testWidgets('events with arguments', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); final eventLog = []; @@ -860,7 +981,9 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = GestureDetector( onTap: event 'tap' { @@ -868,7 +991,8 @@ void main() { }, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000000)); expect(eventLog, isEmpty); @@ -876,13 +1000,16 @@ void main() { expect(eventLog, ['tap {list: [0, 1]}']); eventLog.clear(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root = GestureDetector( onTap: [ event 'tap' { a: 1 }, event 'tap' { a: 2 }, event 'final tap' { } ], child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000000)); expect(eventLog, isEmpty); @@ -892,16 +1019,18 @@ void main() { }); testWidgets('_CurriedWidget toStrings', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget stateless = ColoredBox(color: 0xAA); widget stateful { test: false } = ColoredBox(color: 0xBB); widget switchy = switch true { default: ColoredBox(color: 0xCC) }; - ''')); + '''), + ); expect( (runtime.build( tester.element(find.byType(View)), @@ -932,8 +1061,7 @@ void main() { }); testWidgets('state setting', (WidgetTester tester) async { - final runtime = Runtime() - ..update(const LibraryName(['core']), createCoreWidgets()); + final runtime = Runtime()..update(const LibraryName(['core']), createCoreWidgets()); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -945,105 +1073,132 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: 0 } = GestureDetector( onTap: set state.b = 0, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(tester.takeException().toString(), 'b does not identify existing state.'); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: 0 } = GestureDetector( onTap: set state.0 = 0, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(tester.takeException().toString(), '0 does not identify existing state.'); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: [] } = GestureDetector( onTap: set state.a.b = 0, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(tester.takeException().toString(), 'a.b does not identify existing state.'); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: [] } = GestureDetector( onTap: set state.a.0 = 0, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(tester.takeException().toString(), 'a.0 does not identify existing state.'); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: true } = GestureDetector( onTap: set state.a.0 = 0, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(tester.takeException().toString(), 'a.0 does not identify existing state.'); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: true } = GestureDetector( onTap: set state.a.b = 0, child: ColoredBox(), ); - ''')); + '''), + ); await tester.pump(); await tester.tap(find.byType(ColoredBox)); expect(tester.takeException().toString(), 'a.b does not identify existing state.'); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: { b: 0 } } = GestureDetector( onTap: set state.a = 15, child: ColoredBox(color: state.a), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000000)); await tester.tap(find.byType(ColoredBox)); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x0000000F)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: [ 0 ] } = GestureDetector( onTap: set state.a = 10, child: ColoredBox(color: state.a), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xFF000000)); await tester.tap(find.byType(ColoredBox)); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x0000000A)); - runtime.update(const LibraryName(['test']), parseLibraryFile(''' + runtime.update( + const LibraryName(['test']), + parseLibraryFile(''' import core; widget root { a: [ [ 1 ] ] } = GestureDetector( onTap: set state.a.0.0 = 11, child: ColoredBox(color: state.a.0.0), ); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0x00000001)); await tester.tap(find.byType(ColoredBox)); @@ -1068,32 +1223,47 @@ void main() { ); expect(tester.takeException().toString(), contains('Could not find remote widget named')); - runtime.update(const LibraryName(['local']), LocalWidgetLibrary({ - 'Test': (BuildContext context, DataSource source) { - expect(source.isList(['a']), isFalse); - expect(source.isList(['b']), isTrue); - expect(source.length(['b']), 1); - expect(source.child(['missing']), isA()); - expect(tester.takeException().toString(), 'Not a widget at [missing] (got ) for local:Test.'); - expect(source.childList(['a']), [isA()]); - expect(tester.takeException().toString(), 'Not a widget list at [a] (got 0) for local:Test.'); - expect(source.childList(['b']), [isA()]); - expect(tester.takeException().toString(), 'Not a widget at [b] (got 1) for local:Test.'); - expect(eventLog, isEmpty); - source.voidHandler(['callback'], { 'extra': 4, 'b': 3 })!(); - expect(eventLog, ['e {a: 1, b: 3, extra: 4}']); - return const ColoredBox(color: Color(0xAABBCCDD)); - }, - })); - runtime.update(const LibraryName(['remote']), parseLibraryFile(''' + runtime.update( + const LibraryName(['local']), + LocalWidgetLibrary({ + 'Test': (BuildContext context, DataSource source) { + expect(source.isList(['a']), isFalse); + expect(source.isList(['b']), isTrue); + expect(source.length(['b']), 1); + expect(source.child(['missing']), isA()); + expect( + tester.takeException().toString(), + 'Not a widget at [missing] (got ) for local:Test.', + ); + expect(source.childList(['a']), [isA()]); + expect( + tester.takeException().toString(), + 'Not a widget list at [a] (got 0) for local:Test.', + ); + expect(source.childList(['b']), [isA()]); + expect(tester.takeException().toString(), 'Not a widget at [b] (got 1) for local:Test.'); + expect(eventLog, isEmpty); + source.voidHandler(['callback'], {'extra': 4, 'b': 3})!(); + expect(eventLog, ['e {a: 1, b: 3, extra: 4}']); + return const ColoredBox(color: Color(0xAABBCCDD)); + }, + }), + ); + runtime.update( + const LibraryName(['remote']), + parseLibraryFile(''' import local; widget test = Test(a: 0, b: [1], callback: event 'e' { a: 1, b: 2 }); - ''')); + '''), + ); await tester.pump(); expect(tester.widget(find.byType(ColoredBox)).color, const Color(0xAABBCCDD)); var tested = false; tester.element(find.byType(ColoredBox)).visitAncestorElements((Element node) { - expect(node.toString(), equalsIgnoringHashCodes('_Widget(state: _WidgetState#00000(name: "local:Test"))')); + expect( + node.toString(), + equalsIgnoringHashCodes('_Widget(state: _WidgetState#00000(name: "local:Test"))'), + ); tested = true; return false; }); @@ -1106,12 +1276,20 @@ void main() { 'a': [0, 1], 'b': ['q', 'r'], }); - data.subscribe([], (Object value) { log.add('root: $value'); }); - data.subscribe(['a', 0], (Object value) { log.add('leaf: $value'); }); + data.subscribe([], (Object value) { + log.add('root: $value'); + }); + data.subscribe(['a', 0], (Object value) { + log.add('leaf: $value'); + }); data.update('a', [2, 3]); expect(log, ['leaf: 2', 'root: {a: [2, 3], b: [q, r]}']); data.update('c', 'test'); - expect(log, ['leaf: 2', 'root: {a: [2, 3], b: [q, r]}', 'root: {a: [2, 3], b: [q, r], c: test}']); + expect(log, [ + 'leaf: 2', + 'root: {a: [2, 3], b: [q, r]}', + 'root: {a: [2, 3], b: [q, r], c: test}', + ]); }); testWidgets('Data source - optional builder works', (WidgetTester tester) async { @@ -1122,26 +1300,33 @@ void main() { addTearDown(runtime.dispose); final data = DynamicContent(); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Builder': (BuildContext context, DataSource source) { - final Widget? builder = source.optionalBuilder(['builder'], {}); - return builder ?? const Text('Hello World!', textDirection: TextDirection.ltr); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Builder': (BuildContext context, DataSource source) { + final Widget? builder = source.optionalBuilder(['builder'], {}); + return builder ?? const Text('Hello World!', textDirection: TextDirection.ltr); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; widget test = Builder( builder: Text(text: 'Not a builder :/'), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); - + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); final Finder textFinder = find.byType(Text); expect(textFinder, findsOneWidget); @@ -1155,41 +1340,51 @@ void main() { final runtime = Runtime(); addTearDown(runtime.dispose); final data = DynamicContent(); - const expectedErrorMessage = 'Not a builder at [builder] (got core:Text {} {text: Not a builder :/}) for local:Builder.'; + const expectedErrorMessage = + 'Not a builder at [builder] (got core:Text {} {text: Not a builder :/}) for local:Builder.'; runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Builder': (BuildContext context, DataSource source) { - return source.builder(['builder'], {}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Builder': (BuildContext context, DataSource source) { + return source.builder(['builder'], {}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; widget test = Builder( builder: Text(text: 'Not a builder :/'), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(tester.takeException().toString(), contains(expectedErrorMessage)); expect(find.byType(ErrorWidget), findsOneWidget); - expect(tester.widget(find.byType(ErrorWidget)).message, contains(expectedErrorMessage)); + expect( + tester.widget(find.byType(ErrorWidget)).message, + contains(expectedErrorMessage), + ); }); - testWidgets('Customized error widget', (WidgetTester tester) async { final ErrorWidgetBuilder oldBuilder = ErrorWidget.builder; ErrorWidget.builder = (FlutterErrorDetails details) { return const Text('oopsie!', textDirection: TextDirection.ltr); }; - final runtime = Runtime() - ..update(const LibraryName(['a']), parseLibraryFile('')); + final runtime = Runtime()..update(const LibraryName(['a']), parseLibraryFile('')); addTearDown(runtime.dispose); final data = DynamicContent(); await tester.pumpWidget( @@ -1215,24 +1410,32 @@ void main() { final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Builder': (BuildContext context, DataSource source) { - return source.builder(['builder'], {}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Builder': (BuildContext context, DataSource source) { + return source.builder(['builder'], {}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; widget test = Builder( builder: (scope) => Text(text: 'Hello World!', textDirection: 'ltr'), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, 'Hello World!'); @@ -1248,25 +1451,33 @@ void main() { final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'HelloWorld': (BuildContext context, DataSource source) { - const result = 'Hello World!'; - return source.builder(['builder'], {'result': result}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'HelloWorld': (BuildContext context, DataSource source) { + const result = 'Hello World!'; + return source.builder(['builder'], {'result': result}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; widget test = HelloWorld( builder: (result) => Text(text: result.result, textDirection: 'ltr'), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, 'Hello World!'); @@ -1282,14 +1493,19 @@ void main() { final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'IntToString': (BuildContext context, DataSource source) { - final int value = source.v(['value'])!; - final result = value.toString(); - return source.builder(['builder'], {'result': result}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'IntToString': (BuildContext context, DataSource source) { + final int value = source.v(['value'])!; + final result = value.toString(); + return source.builder(['builder'], {'result': result}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1297,18 +1513,20 @@ void main() { value: state.value, builder: (result) => Text(text: result.result, textDirection: 'ltr'), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, '0'); }); - testWidgets('Widget builders - work with data', (WidgetTester tester) async { const coreLibraryName = LibraryName(['core']); const localLibraryName = LibraryName(['local']); @@ -1319,14 +1537,19 @@ void main() { final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'IntToString': (BuildContext context, DataSource source) { - final int value = source.v(['value'])!; - final result = value.toString(); - return source.builder(['builder'], {'result': result}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'IntToString': (BuildContext context, DataSource source) { + final int value = source.v(['value'])!; + final result = value.toString(); + return source.builder(['builder'], {'result': result}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1334,12 +1557,15 @@ void main() { value: data.value, builder: (result) => Text(text: result.result, textDirection: 'ltr'), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, '0'); @@ -1360,12 +1586,17 @@ void main() { final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Zero': (BuildContext context, DataSource source) { - return source.builder(['builder'], {'result': 0}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Zero': (BuildContext context, DataSource source) { + return source.builder(['builder'], {'result': 0}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1375,14 +1606,17 @@ void main() { child: Text(text: 'Tap to trigger an event.', textDirection: 'ltr'), ), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - onEvent: (String eventName, DynamicMap eventArguments) => - dispatchedEvents.add(RfwEvent(eventName, eventArguments)), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + onEvent: (String eventName, DynamicMap eventArguments) => + dispatchedEvents.add(RfwEvent(eventName, eventArguments)), + ), + ); await tester.tap(textFinder); await tester.pump(); @@ -1400,20 +1634,25 @@ void main() { final data = DynamicContent(); final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Sum': (BuildContext context, DataSource source) { - final int operand1 = source.v(['operand1'])!; - final int operand2 = source.v(['operand2'])!; - final int result = operand1 + operand2; - return source.builder(['builder'], {'result': result}); - }, - 'IntToString': (BuildContext context, DataSource source) { - final int value = source.v(['value'])!; - final result = value.toString(); - return source.builder(['builder'], {'result': result}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Sum': (BuildContext context, DataSource source) { + final int operand1 = source.v(['operand1'])!; + final int operand2 = source.v(['operand2'])!; + final int result = operand1 + operand2; + return source.builder(['builder'], {'result': result}); + }, + 'IntToString': (BuildContext context, DataSource source) { + final int value = source.v(['value'])!; + final result = value.toString(); + return source.builder(['builder'], {'result': result}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1425,12 +1664,15 @@ void main() { builder: (result2) => Text(text: ['1 + 2 = ', result2.result], textDirection: 'ltr'), ), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, '1 + 2 = 3'); @@ -1443,26 +1685,31 @@ void main() { final handlers = {}; final runtime = Runtime(); addTearDown(runtime.dispose); - final data = DynamicContent({ - 'a1': 'apricot', - 'b1': 'blueberry', - }); + final data = DynamicContent({'a1': 'apricot', 'b1': 'blueberry'}); final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Builder': (BuildContext context, DataSource source) { - final String? id = source.v(['id']); - if (id != null) { - handlers[id] = source.voidHandler(['handler'])!; - } - return source.builder(['builder'], { - 'param1': source.v(['arg1']), - 'param2': source.v(['arg2']), - }); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Builder': (BuildContext context, DataSource source) { + final String? id = source.v(['id']); + if (id != null) { + handlers[id] = source.voidHandler(['handler'])!; + } + return source.builder( + ['builder'], + { + 'param1': source.v(['arg1']), + 'param2': source.v(['arg2']), + }, + ); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1482,12 +1729,15 @@ void main() { ), ), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(tester.widget(textFinder).data, 'strawberry apricot apple blueberry banana'); @@ -1514,12 +1764,17 @@ void main() { final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Builder': (BuildContext context, DataSource source) { - return source.builder(['builder'], {}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Builder': (BuildContext context, DataSource source) { + return source.builder(['builder'], {}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1536,19 +1791,21 @@ void main() { ), }, ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); - + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, 'The builder is disabled.'); - await tester.tap(textFinder); - await tester.pump(); + await tester.tap(textFinder); + await tester.pump(); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, 'The builder is enabled.'); }); @@ -1562,13 +1819,18 @@ void main() { final data = DynamicContent(); final Finder textFinder = find.byType(Text); runtime.update(coreLibraryName, createCoreWidgets()); - runtime.update(localLibraryName, LocalWidgetLibrary( { - 'Inverter': (BuildContext context, DataSource source) { - final bool value = source.v(['value'])!; - return source.builder(['builder'], {'result': !value}); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + runtime.update( + localLibraryName, + LocalWidgetLibrary({ + 'Inverter': (BuildContext context, DataSource source) { + final bool value = source.v(['value'])!; + return source.builder(['builder'], {'result': !value}); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1591,18 +1853,21 @@ void main() { ), }, ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, 'The input is false, the output is true'); - await tester.tap(textFinder); - await tester.pump(); + await tester.tap(textFinder); + await tester.pump(); expect(textFinder, findsOneWidget); expect(tester.widget(textFinder).data, 'The input is true, the output is false'); }); @@ -1618,18 +1883,21 @@ void main() { runtime.update(coreLibraryName, createCoreWidgets()); runtime.update( - localLibraryName, - LocalWidgetLibrary({ - 'Builder': (BuildContext context, DataSource source) { - return source.builder( - ['builder'], - { - 'values': ['Value1', 'Value2', 'Value3'], - }, - ); - }, - })); - runtime.update(remoteLibraryName, parseLibraryFile(''' + localLibraryName, + LocalWidgetLibrary({ + 'Builder': (BuildContext context, DataSource source) { + return source.builder( + ['builder'], + { + 'values': ['Value1', 'Value2', 'Value3'], + }, + ); + }, + }), + ); + runtime.update( + remoteLibraryName, + parseLibraryFile(''' import core; import local; @@ -1642,12 +1910,15 @@ void main() { ], ), ); - ''')); - await tester.pumpWidget(RemoteWidget( - runtime: runtime, - data: data, - widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), - )); + '''), + ); + await tester.pumpWidget( + RemoteWidget( + runtime: runtime, + data: data, + widget: const FullyQualifiedWidgetName(remoteLibraryName, 'test'), + ), + ); expect(textFinder, findsNWidgets(3)); expect((textFinder.at(0).evaluate().first.widget as Text).data, 'Value1'); diff --git a/packages/rfw/test/source_locations_test.dart b/packages/rfw/test/source_locations_test.dart index 2b9369fa9760..e3684c3549d3 100644 --- a/packages/rfw/test/source_locations_test.dart +++ b/packages/rfw/test/source_locations_test.dart @@ -31,7 +31,10 @@ void main() { }); testWidgets('parseLibraryFile: source location tracking', (WidgetTester tester) async { - String extract(BlobNode node) => (node.source!.start.source as String).substring(node.source!.start.offset, node.source!.end.offset); + String extract(BlobNode node) => (node.source!.start.source as String).substring( + node.source!.start.offset, + node.source!.end.offset, + ); // We use the actual source text as the sourceIdentifier to make it trivial to find the source contents. // In normal operation, the sourceIdentifier would be the file name or some similar object. final RemoteWidgetLibrary test = parseLibraryFile(sourceFile, sourceIdentifier: sourceFile); @@ -48,19 +51,26 @@ widget verify { state: true } = switch args.value.c.0 { if (node.source == null) { printOnFailure('This node had no source information: ${node.runtimeType} $node'); } - return (node.source!.start.source as String).substring(node.source!.start.offset, node.source!.end.offset); + return (node.source!.start.source as String).substring( + node.source!.start.offset, + node.source!.end.offset, + ); } + final runtime = Runtime() ..update(const LibraryName(['core']), createCoreWidgets()) // We use the actual source text as the sourceIdentifier to make it trivial to find the source contents. // In normal operation, the sourceIdentifier would be the file name or some similar object. - ..update(const LibraryName(['test']), parseLibraryFile(sourceFile, sourceIdentifier: sourceFile)); + ..update( + const LibraryName(['test']), + parseLibraryFile(sourceFile, sourceIdentifier: sourceFile), + ); addTearDown(runtime.dispose); final data = DynamicContent({ 'list': [ { - 'a': { 'b': 0xEE }, - 'c': [ 0xDD ], + 'a': {'b': 0xEE}, + 'c': [0xDD], }, ], }); @@ -74,6 +84,9 @@ widget verify { state: true } = switch args.value.c.0 { }, ), ); - expect(extract(Runtime.blobNodeFor(tester.firstElement(find.byType(ColoredBox)))!), 'ColoredBox(color: 0xFF0D0D0D)'); + expect( + extract(Runtime.blobNodeFor(tester.firstElement(find.byType(ColoredBox)))!), + 'ColoredBox(color: 0xFF0D0D0D)', + ); }); } diff --git a/packages/rfw/test/text_test.dart b/packages/rfw/test/text_test.dart index bb3010992869..f35c78700995 100644 --- a/packages/rfw/test/text_test.dart +++ b/packages/rfw/test/text_test.dart @@ -11,7 +11,7 @@ import 'package:rfw/formats.dart'; void main() { testWidgets('empty parseDataFile', (WidgetTester tester) async { final DynamicMap result = parseDataFile('{}'); - expect(result, { }); + expect(result, {}); }); testWidgets('empty parseLibraryFile', (WidgetTester tester) async { @@ -22,7 +22,7 @@ void main() { testWidgets('space parseDataFile', (WidgetTester tester) async { final DynamicMap result = parseDataFile(' \n {} \n '); - expect(result, { }); + expect(result, {}); }); testWidgets('space parseLibraryFile', (WidgetTester tester) async { @@ -40,6 +40,7 @@ void main() { expect('$e', expectedMessage); } } + test('', 'Expected symbol "{" but found at line 1 column 0.'); test('}', 'Expected symbol "{" but found } at line 1 column 1.'); test('1', 'Expected symbol "{" but found 1 at line 1 column 1.'); @@ -56,11 +57,20 @@ void main() { test('{ ... }', 'Expected symbol "}" but found … at line 1 column 5.'); test('{ a: ... }', 'Unexpected … at line 1 column 8.'); test('{ a: -', 'Unexpected end of file after minus sign at line 1 column 6.'); - test('{ a: -a', 'Unexpected character U+0061 ("a") after minus sign (expected digit) at line 1 column 7.'); + test( + '{ a: -a', + 'Unexpected character U+0061 ("a") after minus sign (expected digit) at line 1 column 7.', + ); test('{ a: 0', 'Expected symbol "}" but found at line 1 column 6.'); test('{ a: 0e', 'Unexpected end of file after exponent separator at line 1 column 7.'); - test('{ a: 0ee', 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 8.'); - test('{ a: 0e-', 'Unexpected end of file after exponent separator and minus sign at line 1 column 8.'); + test( + '{ a: 0ee', + 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 8.', + ); + test( + '{ a: 0e-', + 'Unexpected end of file after exponent separator and minus sign at line 1 column 8.', + ); test('{ a: 0e-e', 'Unexpected character U+0065 ("e") in exponent at line 1 column 9.'); test('{ a: 0e-f', 'Unexpected character U+0066 ("f") in exponent at line 1 column 9.'); test('{ a: 0e-.', 'Unexpected character U+002E (".") in exponent at line 1 column 9.'); @@ -75,8 +85,14 @@ void main() { test('{ a: 0. ', 'Unexpected character U+0020 in fraction component at line 1 column 8.'); test('{ a: 00', 'Expected symbol "}" but found at line 1 column 7.'); test('{ a: 00e', 'Unexpected end of file after exponent separator at line 1 column 8.'); - test('{ a: 00ee', 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 9.'); - test('{ a: 00e-', 'Unexpected end of file after exponent separator and minus sign at line 1 column 9.'); + test( + '{ a: 00ee', + 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 9.', + ); + test( + '{ a: 00e-', + 'Unexpected end of file after exponent separator and minus sign at line 1 column 9.', + ); test('{ a: 00 ', 'Expected symbol "}" but found at line 1 column 8.'); test('{ a: -0', 'Expected symbol "}" but found at line 1 column 7.'); test('{ a: -0.', 'Unexpected end of file after decimal point at line 1 column 8.'); @@ -84,9 +100,18 @@ void main() { test('{ a: -0.0', 'Expected symbol "}" but found at line 1 column 9.'); test('{ a: -0.0 ', 'Expected symbol "}" but found at line 1 column 10.'); test('{ a: -0.0e', 'Unexpected end of file after exponent separator at line 1 column 10.'); - test('{ a: -0.0ee', 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 11.'); - test('{ a: -0.0e-', 'Unexpected end of file after exponent separator and minus sign at line 1 column 11.'); - test('{ a: -0.0f', 'Unexpected character U+0066 ("f") in fraction component at line 1 column 10.'); + test( + '{ a: -0.0ee', + 'Unexpected character U+0065 ("e") after exponent separator at line 1 column 11.', + ); + test( + '{ a: -0.0e-', + 'Unexpected end of file after exponent separator and minus sign at line 1 column 11.', + ); + test( + '{ a: -0.0f', + 'Unexpected character U+0066 ("f") in fraction component at line 1 column 10.', + ); test('{ a: -00', 'Expected symbol "}" but found at line 1 column 8.'); test('{ a: 0f', 'Unexpected character U+0066 ("f") after zero at line 1 column 7.'); test('{ a: -0f', 'Unexpected character U+0066 ("f") after negative zero at line 1 column 8.'); @@ -110,7 +135,10 @@ void main() { test('{ a: ."hello"', 'Unexpected . at line 1 column 7.'); test('{ "a": \'hello\'.\'hello\'', 'Expected symbol "}" but found . at line 1 column 16.'); test('{ "a": \'hello\'', 'Expected symbol "}" but found at line 1 column 14.'); - test('{ "a": \'hello\'h', 'Unexpected character U+0068 ("h") after end quote at line 1 column 15.'); + test( + '{ "a": \'hello\'h', + 'Unexpected character U+0068 ("h") after end quote at line 1 column 15.', + ); test('{ "a": \'\n\'', 'Unexpected end of line inside string at line 2 column 0.'); test('{ "a": \'hello\n\'', 'Unexpected end of line inside string at line 2 column 0.'); test('{ "a": \'\\', 'Unexpected end of file inside string at line 1 column 9.'); @@ -120,12 +148,27 @@ void main() { test('{ "a": \'\\u00', 'Unexpected end of file inside Unicode escape at line 1 column 12.'); test('{ "a": \'\\u000', 'Unexpected end of file inside Unicode escape at line 1 column 13.'); test('{ "a": \'\\u0000', 'Unexpected end of file inside string at line 1 column 14.'); - test('{ "a": \'\\u|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 11.'); - test('{ "a": \'\\u0|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 12.'); - test('{ "a": \'\\u00|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 13.'); - test('{ "a": \'\\u000|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 14.'); + test( + '{ "a": \'\\u|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 11.', + ); + test( + '{ "a": \'\\u0|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 12.', + ); + test( + '{ "a": \'\\u00|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 13.', + ); + test( + '{ "a": \'\\u000|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 14.', + ); test('{ "a": \'\\u0000|', 'Unexpected end of file inside string at line 1 column 15.'); - test('{ "a": \'\\U263A\' }', 'Unexpected character U+0055 ("U") after backslash in string at line 1 column 10.'); + test( + '{ "a": \'\\U263A\' }', + 'Unexpected character U+0055 ("U") after backslash in string at line 1 column 10.', + ); test('{ "a": "\\', 'Unexpected end of file inside string at line 1 column 9.'); test('{ "a": "\\"', 'Unexpected end of file inside string at line 1 column 10.'); test('{ "a": "\\u', 'Unexpected end of file inside Unicode escape at line 1 column 10.'); @@ -133,15 +176,33 @@ void main() { test('{ "a": "\\u00', 'Unexpected end of file inside Unicode escape at line 1 column 12.'); test('{ "a": "\\u000', 'Unexpected end of file inside Unicode escape at line 1 column 13.'); test('{ "a": "\\u0000', 'Unexpected end of file inside string at line 1 column 14.'); - test('{ "a": "\\u|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 11.'); - test('{ "a": "\\u0|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 12.'); - test('{ "a": "\\u00|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 13.'); - test('{ "a": "\\u000|', 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 14.'); + test( + '{ "a": "\\u|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 11.', + ); + test( + '{ "a": "\\u0|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 12.', + ); + test( + '{ "a": "\\u00|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 13.', + ); + test( + '{ "a": "\\u000|', + 'Unexpected character U+007C ("|") in Unicode escape at line 1 column 14.', + ); test('{ "a": "\\u0000|', 'Unexpected end of file inside string at line 1 column 15.'); - test('{ "a": "\\U263A" }', 'Unexpected character U+0055 ("U") after backslash in string at line 1 column 10.'); + test( + '{ "a": "\\U263A" }', + 'Unexpected character U+0055 ("U") after backslash in string at line 1 column 10.', + ); test('{ "a": ', 'Unexpected at line 1 column 7.'); test('{ "a": /', 'Unexpected end of file inside comment delimiter at line 1 column 8.'); - test('{ "a": /.', 'Unexpected character U+002E (".") inside comment delimiter at line 1 column 9.'); + test( + '{ "a": /.', + 'Unexpected character U+002E (".") inside comment delimiter at line 1 column 9.', + ); test('{ "a": //', 'Unexpected at line 1 column 9.'); test('{ "a": /*', 'Unexpected end of file in block comment at line 1 column 9.'); test('{ "a": /*/', 'Unexpected end of file in block comment at line 1 column 10.'); @@ -150,91 +211,103 @@ void main() { }); testWidgets('valid values in parseDataFile', (WidgetTester tester) async { - expect(parseDataFile('{ }\n\n \n\n'), { }); - expect(parseDataFile('{ a: "b" }'), { 'a': 'b' }); - expect(parseDataFile('{ a: [ "b", 9 ] }'), { 'a': [ 'b', 9 ] }); - expect(parseDataFile('{ a: { } }'), { 'a': { } }); - expect(parseDataFile('{ a: 123.456e7 }'), { 'a': 123.456e7 }); - expect(parseDataFile('{ a: true }'), { 'a': true }); - expect(parseDataFile('{ a: false }'), { 'a': false }); - expect(parseDataFile('{ "a": 0 }'), { 'a': 0 }); - expect(parseDataFile('{ "a": -0, b: "x" }'), { 'a': 0, 'b': 'x' }); - expect(parseDataFile('{ "a": null }'), { }); - expect(parseDataFile('{ "a": -6 }'), { 'a': -6 }); - expect(parseDataFile('{ "a": -7 }'), { 'a': -7 }); - expect(parseDataFile('{ "a": -8 }'), { 'a': -8 }); - expect(parseDataFile('{ "a": -9 }'), { 'a': -9 }); - expect(parseDataFile('{ "a": 01 }'), { 'a': 1 }); - expect(parseDataFile('{ "a": 0e0 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": 0e1 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": 0e8 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": 1e9 }'), { 'a': 1000000000.0 }); - expect(parseDataFile('{ "a": -0e1 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": 00e1 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": -00e1 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": 00.0e1 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": -00.0e1 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": -00.0e-1 }'), { 'a': 0.0 }); - expect(parseDataFile('{ "a": -1e-1 }'), { 'a': -0.1 }); - expect(parseDataFile('{ "a": -1e-2 }'), { 'a': -0.01 }); - expect(parseDataFile('{ "a": -1e-3 }'), { 'a': -0.001 }); - expect(parseDataFile('{ "a": -1e-4 }'), { 'a': -0.0001 }); - expect(parseDataFile('{ "a": -1e-5 }'), { 'a': -0.00001 }); - expect(parseDataFile('{ "a": -1e-6 }'), { 'a': -0.000001 }); - expect(parseDataFile('{ "a": -1e-7 }'), { 'a': -0.0000001 }); - expect(parseDataFile('{ "a": -1e-8 }'), { 'a': -0.00000001 }); - expect(parseDataFile('{ "a": -1e-9 }'), { 'a': -0.000000001 }); - expect(parseDataFile('{ "a": -1e-10 }'), { 'a': -0.0000000001 }); - expect(parseDataFile('{ "a": -1e-11 }'), { 'a': -0.00000000001 }); - expect(parseDataFile('{ "a": -1e-12 }'), { 'a': -0.000000000001 }); - expect(parseDataFile('{ "a": -1e-13 }'), { 'a': -0.0000000000001 }); - expect(parseDataFile('{ "a": -1e-14 }'), { 'a': -0.00000000000001 }); - expect(parseDataFile('{ "a": -1e-15 }'), { 'a': -0.000000000000001 }); - expect(parseDataFile('{ "a": -1e-16 }'), { 'a': -0.0000000000000001 }); - expect(parseDataFile('{ "a": -1e-17 }'), { 'a': -0.00000000000000001 }); - expect(parseDataFile('{ "a": -1e-18 }'), { 'a': -0.000000000000000001 }); - expect(parseDataFile('{ "a": -1e-19 }'), { 'a': -0.0000000000000000001 }); - expect(parseDataFile('{ "a": 0x0 }'), { 'a': 0 }); - expect(parseDataFile('{ "a": 0x1 }'), { 'a': 1 }); - expect(parseDataFile('{ "a": 0x01 }'), { 'a': 1 }); - expect(parseDataFile('{ "a": 0xa }'), { 'a': 10 }); - expect(parseDataFile('{ "a": 0xb }'), { 'a': 11 }); - expect(parseDataFile('{ "a": 0xc }'), { 'a': 12 }); - expect(parseDataFile('{ "a": 0xd }'), { 'a': 13 }); - expect(parseDataFile('{ "a": 0xe }'), { 'a': 14 }); - expect(parseDataFile('{ "a": 0xfa }'), { 'a': 250 }); - expect(parseDataFile('{ "a": 0xfb }'), { 'a': 251 }); - expect(parseDataFile('{ "a": 0xfc }'), { 'a': 252 }); - expect(parseDataFile('{ "a": 0xfd }'), { 'a': 253 }); - expect(parseDataFile('{ "a": 0xfe }'), { 'a': 254 }); - expect(parseDataFile('{ "a": "\\"\\/\\\'\\b\\f\\n\\r\\t\\\\" }'), { 'a': '\x22\x2F\x27\x08\x0C\x0A\x0D\x09\x5C' }); - expect(parseDataFile('{ "a": \'\\"\\/\\\'\\b\\f\\n\\r\\t\\\\\' }'), { 'a': '\x22\x2F\x27\x08\x0C\x0A\x0D\x09\x5C' }); - expect(parseDataFile('{ "a": \'\\u263A\' }'), { 'a': '☺' }); - expect(parseDataFile('{ "a": \'\\u0000\' }'), { 'a': '\x00' }); - expect(parseDataFile('{ "a": \'\\u1111\' }'), { 'a': 'ᄑ' }); - expect(parseDataFile('{ "a": \'\\u2222\' }'), { 'a': '∢' }); - expect(parseDataFile('{ "a": \'\\u3333\' }'), { 'a': '㌳' }); - expect(parseDataFile('{ "a": \'\\u4444\' }'), { 'a': '䑄' }); - expect(parseDataFile('{ "a": \'\\u5555\' }'), { 'a': '啕' }); - expect(parseDataFile('{ "a": \'\\u6666\' }'), { 'a': '晦' }); - expect(parseDataFile('{ "a": \'\\u7777\' }'), { 'a': '睷' }); - expect(parseDataFile('{ "a": \'\\u8888\' }'), { 'a': '袈' }); - expect(parseDataFile('{ "a": \'\\u9999\' }'), { 'a': '香' }); - expect(parseDataFile('{ "a": \'\\uaaaa\' }'), { 'a': 'ꪪ' }); - expect(parseDataFile('{ "a": \'\\ubbbb\' }'), { 'a': '뮻' }); - expect(parseDataFile('{ "a": \'\\ucccc\' }'), { 'a': '쳌' }); - expect(parseDataFile('{ "a": \'\\udddd\' }'), { 'a': '\u{dddd}' }); // low surragate - expect(parseDataFile('{ "a": \'\\ueeee\' }'), { 'a': '\u{eeee}' }); // private use area - expect(parseDataFile('{ "a": \'\\uffff\' }'), { 'a': '\u{ffff}' }); // not technically a valid Unicode character - expect(parseDataFile('{ "a": \'\\uAAAA\' }'), { 'a': 'ꪪ' }); - expect(parseDataFile('{ "a": \'\\uBBBB\' }'), { 'a': '뮻' }); - expect(parseDataFile('{ "a": \'\\uCCCC\' }'), { 'a': '쳌' }); - expect(parseDataFile('{ "a": \'\\uDDDD\' }'), { 'a': '\u{dddd}' }); - expect(parseDataFile('{ "a": \'\\uEEEE\' }'), { 'a': '\u{eeee}' }); - expect(parseDataFile('{ "a": \'\\uFFFF\' }'), { 'a': '\u{ffff}' }); - expect(parseDataFile('{ "a": /**/ "1" }'), { 'a': '1' }); - expect(parseDataFile('{ "a": /* */ "1" }'), { 'a': '1' }); - expect(parseDataFile('{ "a": /*\n*/ "1" }'), { 'a': '1' }); + expect(parseDataFile('{ }\n\n \n\n'), {}); + expect(parseDataFile('{ a: "b" }'), {'a': 'b'}); + expect(parseDataFile('{ a: [ "b", 9 ] }'), { + 'a': ['b', 9], + }); + expect(parseDataFile('{ a: { } }'), {'a': {}}); + expect(parseDataFile('{ a: 123.456e7 }'), {'a': 123.456e7}); + expect(parseDataFile('{ a: true }'), {'a': true}); + expect(parseDataFile('{ a: false }'), {'a': false}); + expect(parseDataFile('{ "a": 0 }'), {'a': 0}); + expect(parseDataFile('{ "a": -0, b: "x" }'), {'a': 0, 'b': 'x'}); + expect(parseDataFile('{ "a": null }'), {}); + expect(parseDataFile('{ "a": -6 }'), {'a': -6}); + expect(parseDataFile('{ "a": -7 }'), {'a': -7}); + expect(parseDataFile('{ "a": -8 }'), {'a': -8}); + expect(parseDataFile('{ "a": -9 }'), {'a': -9}); + expect(parseDataFile('{ "a": 01 }'), {'a': 1}); + expect(parseDataFile('{ "a": 0e0 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": 0e1 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": 0e8 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": 1e9 }'), {'a': 1000000000.0}); + expect(parseDataFile('{ "a": -0e1 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": 00e1 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": -00e1 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": 00.0e1 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": -00.0e1 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": -00.0e-1 }'), {'a': 0.0}); + expect(parseDataFile('{ "a": -1e-1 }'), {'a': -0.1}); + expect(parseDataFile('{ "a": -1e-2 }'), {'a': -0.01}); + expect(parseDataFile('{ "a": -1e-3 }'), {'a': -0.001}); + expect(parseDataFile('{ "a": -1e-4 }'), {'a': -0.0001}); + expect(parseDataFile('{ "a": -1e-5 }'), {'a': -0.00001}); + expect(parseDataFile('{ "a": -1e-6 }'), {'a': -0.000001}); + expect(parseDataFile('{ "a": -1e-7 }'), {'a': -0.0000001}); + expect(parseDataFile('{ "a": -1e-8 }'), {'a': -0.00000001}); + expect(parseDataFile('{ "a": -1e-9 }'), {'a': -0.000000001}); + expect(parseDataFile('{ "a": -1e-10 }'), {'a': -0.0000000001}); + expect(parseDataFile('{ "a": -1e-11 }'), {'a': -0.00000000001}); + expect(parseDataFile('{ "a": -1e-12 }'), {'a': -0.000000000001}); + expect(parseDataFile('{ "a": -1e-13 }'), {'a': -0.0000000000001}); + expect(parseDataFile('{ "a": -1e-14 }'), {'a': -0.00000000000001}); + expect(parseDataFile('{ "a": -1e-15 }'), {'a': -0.000000000000001}); + expect(parseDataFile('{ "a": -1e-16 }'), {'a': -0.0000000000000001}); + expect(parseDataFile('{ "a": -1e-17 }'), {'a': -0.00000000000000001}); + expect(parseDataFile('{ "a": -1e-18 }'), {'a': -0.000000000000000001}); + expect(parseDataFile('{ "a": -1e-19 }'), {'a': -0.0000000000000000001}); + expect(parseDataFile('{ "a": 0x0 }'), {'a': 0}); + expect(parseDataFile('{ "a": 0x1 }'), {'a': 1}); + expect(parseDataFile('{ "a": 0x01 }'), {'a': 1}); + expect(parseDataFile('{ "a": 0xa }'), {'a': 10}); + expect(parseDataFile('{ "a": 0xb }'), {'a': 11}); + expect(parseDataFile('{ "a": 0xc }'), {'a': 12}); + expect(parseDataFile('{ "a": 0xd }'), {'a': 13}); + expect(parseDataFile('{ "a": 0xe }'), {'a': 14}); + expect(parseDataFile('{ "a": 0xfa }'), {'a': 250}); + expect(parseDataFile('{ "a": 0xfb }'), {'a': 251}); + expect(parseDataFile('{ "a": 0xfc }'), {'a': 252}); + expect(parseDataFile('{ "a": 0xfd }'), {'a': 253}); + expect(parseDataFile('{ "a": 0xfe }'), {'a': 254}); + expect(parseDataFile('{ "a": "\\"\\/\\\'\\b\\f\\n\\r\\t\\\\" }'), { + 'a': '\x22\x2F\x27\x08\x0C\x0A\x0D\x09\x5C', + }); + expect(parseDataFile('{ "a": \'\\"\\/\\\'\\b\\f\\n\\r\\t\\\\\' }'), { + 'a': '\x22\x2F\x27\x08\x0C\x0A\x0D\x09\x5C', + }); + expect(parseDataFile('{ "a": \'\\u263A\' }'), {'a': '☺'}); + expect(parseDataFile('{ "a": \'\\u0000\' }'), {'a': '\x00'}); + expect(parseDataFile('{ "a": \'\\u1111\' }'), {'a': 'ᄑ'}); + expect(parseDataFile('{ "a": \'\\u2222\' }'), {'a': '∢'}); + expect(parseDataFile('{ "a": \'\\u3333\' }'), {'a': '㌳'}); + expect(parseDataFile('{ "a": \'\\u4444\' }'), {'a': '䑄'}); + expect(parseDataFile('{ "a": \'\\u5555\' }'), {'a': '啕'}); + expect(parseDataFile('{ "a": \'\\u6666\' }'), {'a': '晦'}); + expect(parseDataFile('{ "a": \'\\u7777\' }'), {'a': '睷'}); + expect(parseDataFile('{ "a": \'\\u8888\' }'), {'a': '袈'}); + expect(parseDataFile('{ "a": \'\\u9999\' }'), {'a': '香'}); + expect(parseDataFile('{ "a": \'\\uaaaa\' }'), {'a': 'ꪪ'}); + expect(parseDataFile('{ "a": \'\\ubbbb\' }'), {'a': '뮻'}); + expect(parseDataFile('{ "a": \'\\ucccc\' }'), {'a': '쳌'}); + expect(parseDataFile('{ "a": \'\\udddd\' }'), { + 'a': '\u{dddd}', + }); // low surragate + expect(parseDataFile('{ "a": \'\\ueeee\' }'), { + 'a': '\u{eeee}', + }); // private use area + expect(parseDataFile('{ "a": \'\\uffff\' }'), { + 'a': '\u{ffff}', + }); // not technically a valid Unicode character + expect(parseDataFile('{ "a": \'\\uAAAA\' }'), {'a': 'ꪪ'}); + expect(parseDataFile('{ "a": \'\\uBBBB\' }'), {'a': '뮻'}); + expect(parseDataFile('{ "a": \'\\uCCCC\' }'), {'a': '쳌'}); + expect(parseDataFile('{ "a": \'\\uDDDD\' }'), {'a': '\u{dddd}'}); + expect(parseDataFile('{ "a": \'\\uEEEE\' }'), {'a': '\u{eeee}'}); + expect(parseDataFile('{ "a": \'\\uFFFF\' }'), {'a': '\u{ffff}'}); + expect(parseDataFile('{ "a": /**/ "1" }'), {'a': '1'}); + expect(parseDataFile('{ "a": /* */ "1" }'), {'a': '1'}); + expect(parseDataFile('{ "a": /*\n*/ "1" }'), {'a': '1'}); }); testWidgets('error handling in parseLibraryFile', (WidgetTester tester) async { @@ -246,8 +319,15 @@ void main() { expect('$e', expectedMessage); } } - test('2', 'Expected keywords "import" or "widget", or end of file but found 2 at line 1 column 1.'); - test('impor', 'Expected keywords "import" or "widget", or end of file but found impor at line 1 column 5.'); + + test( + '2', + 'Expected keywords "import" or "widget", or end of file but found 2 at line 1 column 1.', + ); + test( + 'impor', + 'Expected keywords "import" or "widget", or end of file but found impor at line 1 column 5.', + ); test('import', 'Expected string but found at line 1 column 6.'); test('import 2', 'Expected string but found 2 at line 1 column 8.'); test('import foo', 'Expected symbol ";" but found at line 1 column 10.'); @@ -260,17 +340,32 @@ void main() { test('import foo. "', 'Unexpected end of file inside string at line 1 column 13.'); test('import foo.\'', 'Unexpected end of file inside string at line 1 column 12.'); test('import foo. \'', 'Unexpected end of file inside string at line 1 column 13.'); - test('widget a = b(c: [ ...for args in []: "e" ]);', 'args is a reserved word at line 1 column 30.'); - test('widget a = switch 0 { 0: a(), 0: b() };', 'Switch has duplicate cases for key 0 at line 1 column 32.'); - test('widget a = switch 0 { default: a(), default: b() };', 'Switch has multiple default cases at line 1 column 44.'); + test( + 'widget a = b(c: [ ...for args in []: "e" ]);', + 'args is a reserved word at line 1 column 30.', + ); + test( + 'widget a = switch 0 { 0: a(), 0: b() };', + 'Switch has duplicate cases for key 0 at line 1 column 32.', + ); + test( + 'widget a = switch 0 { default: a(), default: b() };', + 'Switch has multiple default cases at line 1 column 44.', + ); test('widget a = b(c: args)', 'Expected symbol "." but found ) at line 1 column 21.'); test('widget a = b(c: args.=)', 'Unexpected = at line 1 column 22.'); test('widget a = b(c: args.0', 'Expected symbol ")" but found at line 1 column 22.'); test('widget a = b(c: args.0 ', 'Expected symbol ")" but found at line 1 column 23.'); test('widget a = b(c: args.0)', 'Expected symbol ";" but found at line 1 column 23.'); - test('widget a = b(c: args.0f', 'Unexpected character U+0066 ("f") in integer at line 1 column 23.'); + test( + 'widget a = b(c: args.0f', + 'Unexpected character U+0066 ("f") in integer at line 1 column 23.', + ); test('widget a = b(c: [ ..', 'Unexpected end of file inside "..." symbol at line 1 column 20.'); - test('widget a = b(c: [ .. ]);', 'Unexpected character U+0020 inside "..." symbol at line 1 column 21.'); + test( + 'widget a = b(c: [ .. ]);', + 'Unexpected character U+0020 inside "..." symbol at line 1 column 21.', + ); test('widget a = b(c: [ ... ]);', 'Expected identifier but found ] at line 1 column 23.'); test('widget a = b(c: [ ...baa ]);', 'Expected for but found baa at line 1 column 25.'); test('widget a = 0;', 'Expected identifier but found 0 at line 1 column 13.'); @@ -288,50 +383,145 @@ void main() { }); testWidgets('parseLibraryFile: loops', (WidgetTester tester) async { - final RemoteWidgetLibrary result = parseLibraryFile('widget a = b(c: [ ...for d in []: "e" ]);'); + final RemoteWidgetLibrary result = parseLibraryFile( + 'widget a = b(c: [ ...for d in []: "e" ]);', + ); expect(result.imports, isEmpty); expect(result.widgets, hasLength(1)); expect(result.widgets.single.toString(), 'widget a = b({c: [...for loop in []: e]});'); }); testWidgets('parseLibraryFile: switch', (WidgetTester tester) async { - expect(parseLibraryFile('widget a = switch 0 { 0: a() };').toString(), 'widget a = switch 0 {0: a({})};'); - expect(parseLibraryFile('widget a = switch 0 { default: a() };').toString(), 'widget a = switch 0 {null: a({})};'); - expect(parseLibraryFile('widget a = b(c: switch 1 { 2: 3 });').toString(), 'widget a = b({c: switch 1 {2: 3}});'); + expect( + parseLibraryFile('widget a = switch 0 { 0: a() };').toString(), + 'widget a = switch 0 {0: a({})};', + ); + expect( + parseLibraryFile('widget a = switch 0 { default: a() };').toString(), + 'widget a = switch 0 {null: a({})};', + ); + expect( + parseLibraryFile('widget a = b(c: switch 1 { 2: 3 });').toString(), + 'widget a = b({c: switch 1 {2: 3}});', + ); }); testWidgets('parseLibraryFile: references', (WidgetTester tester) async { - expect(parseLibraryFile('widget a = b(c:data.11234567890."e");').toString(), 'widget a = b({c: data.11234567890.e});'); - expect(parseLibraryFile('widget a = b(c: [...for d in []: d]);').toString(), 'widget a = b({c: [...for loop in []: loop0.]});'); - expect(parseLibraryFile('widget a = b(c:args.foo.bar);').toString(), 'widget a = b({c: args.foo.bar});'); - expect(parseLibraryFile('widget a = b(c:data.foo.bar);').toString(), 'widget a = b({c: data.foo.bar});'); - expect(parseLibraryFile('widget a = b(c:state.foo.bar);').toString(), 'widget a = b({c: state.foo.bar});'); - expect(parseLibraryFile('widget a = b(c: [...for d in []: d.bar]);').toString(), 'widget a = b({c: [...for loop in []: loop0.bar]});'); - expect(parseLibraryFile('widget a = b(c:args.foo."bar");').toString(), 'widget a = b({c: args.foo.bar});'); - expect(parseLibraryFile('widget a = b(c:data.foo."bar");').toString(), 'widget a = b({c: data.foo.bar});'); - expect(parseLibraryFile('widget a = b(c:state.foo."bar");').toString(), 'widget a = b({c: state.foo.bar});'); - expect(parseLibraryFile('widget a = b(c: [...for d in []: d."bar"]);').toString(), 'widget a = b({c: [...for loop in []: loop0.bar]});'); - expect(parseLibraryFile('widget a = b(c:args.foo.9);').toString(), 'widget a = b({c: args.foo.9});'); - expect(parseLibraryFile('widget a = b(c:data.foo.9);').toString(), 'widget a = b({c: data.foo.9});'); - expect(parseLibraryFile('widget a = b(c:state.foo.9);').toString(), 'widget a = b({c: state.foo.9});'); - expect(parseLibraryFile('widget a = b(c: [...for d in []: d.9]);').toString(), 'widget a = b({c: [...for loop in []: loop0.9]});'); - expect(parseLibraryFile('widget a = b(c:args.foo.12);').toString(), 'widget a = b({c: args.foo.12});'); - expect(parseLibraryFile('widget a = b(c:data.foo.12);').toString(), 'widget a = b({c: data.foo.12});'); - expect(parseLibraryFile('widget a = b(c:state.foo.12);').toString(), 'widget a = b({c: state.foo.12});'); - expect(parseLibraryFile('widget a = b(c: [...for d in []: d.12]);').toString(), 'widget a = b({c: [...for loop in []: loop0.12]});'); - expect(parseLibraryFile('widget a = b(c:args.foo.98);').toString(), 'widget a = b({c: args.foo.98});'); - expect(parseLibraryFile('widget a = b(c:data.foo.98);').toString(), 'widget a = b({c: data.foo.98});'); - expect(parseLibraryFile('widget a = b(c:state.foo.98);').toString(), 'widget a = b({c: state.foo.98});'); - expect(parseLibraryFile('widget a = b(c: [...for d in []: d.98]);').toString(), 'widget a = b({c: [...for loop in []: loop0.98]});'); - expect(parseLibraryFile('widget a = b(c:args.foo.000);').toString(), 'widget a = b({c: args.foo.0});'); - expect(parseLibraryFile('widget a = b(c:data.foo.000);').toString(), 'widget a = b({c: data.foo.0});'); - expect(parseLibraryFile('widget a = b(c:state.foo.000);').toString(), 'widget a = b({c: state.foo.0});'); - expect(parseLibraryFile('widget a = b(c: [...for d in []: d.000]);').toString(), 'widget a = b({c: [...for loop in []: loop0.0]});'); + expect( + parseLibraryFile('widget a = b(c:data.11234567890."e");').toString(), + 'widget a = b({c: data.11234567890.e});', + ); + expect( + parseLibraryFile('widget a = b(c: [...for d in []: d]);').toString(), + 'widget a = b({c: [...for loop in []: loop0.]});', + ); + expect( + parseLibraryFile('widget a = b(c:args.foo.bar);').toString(), + 'widget a = b({c: args.foo.bar});', + ); + expect( + parseLibraryFile('widget a = b(c:data.foo.bar);').toString(), + 'widget a = b({c: data.foo.bar});', + ); + expect( + parseLibraryFile('widget a = b(c:state.foo.bar);').toString(), + 'widget a = b({c: state.foo.bar});', + ); + expect( + parseLibraryFile('widget a = b(c: [...for d in []: d.bar]);').toString(), + 'widget a = b({c: [...for loop in []: loop0.bar]});', + ); + expect( + parseLibraryFile('widget a = b(c:args.foo."bar");').toString(), + 'widget a = b({c: args.foo.bar});', + ); + expect( + parseLibraryFile('widget a = b(c:data.foo."bar");').toString(), + 'widget a = b({c: data.foo.bar});', + ); + expect( + parseLibraryFile('widget a = b(c:state.foo."bar");').toString(), + 'widget a = b({c: state.foo.bar});', + ); + expect( + parseLibraryFile('widget a = b(c: [...for d in []: d."bar"]);').toString(), + 'widget a = b({c: [...for loop in []: loop0.bar]});', + ); + expect( + parseLibraryFile('widget a = b(c:args.foo.9);').toString(), + 'widget a = b({c: args.foo.9});', + ); + expect( + parseLibraryFile('widget a = b(c:data.foo.9);').toString(), + 'widget a = b({c: data.foo.9});', + ); + expect( + parseLibraryFile('widget a = b(c:state.foo.9);').toString(), + 'widget a = b({c: state.foo.9});', + ); + expect( + parseLibraryFile('widget a = b(c: [...for d in []: d.9]);').toString(), + 'widget a = b({c: [...for loop in []: loop0.9]});', + ); + expect( + parseLibraryFile('widget a = b(c:args.foo.12);').toString(), + 'widget a = b({c: args.foo.12});', + ); + expect( + parseLibraryFile('widget a = b(c:data.foo.12);').toString(), + 'widget a = b({c: data.foo.12});', + ); + expect( + parseLibraryFile('widget a = b(c:state.foo.12);').toString(), + 'widget a = b({c: state.foo.12});', + ); + expect( + parseLibraryFile('widget a = b(c: [...for d in []: d.12]);').toString(), + 'widget a = b({c: [...for loop in []: loop0.12]});', + ); + expect( + parseLibraryFile('widget a = b(c:args.foo.98);').toString(), + 'widget a = b({c: args.foo.98});', + ); + expect( + parseLibraryFile('widget a = b(c:data.foo.98);').toString(), + 'widget a = b({c: data.foo.98});', + ); + expect( + parseLibraryFile('widget a = b(c:state.foo.98);').toString(), + 'widget a = b({c: state.foo.98});', + ); + expect( + parseLibraryFile('widget a = b(c: [...for d in []: d.98]);').toString(), + 'widget a = b({c: [...for loop in []: loop0.98]});', + ); + expect( + parseLibraryFile('widget a = b(c:args.foo.000);').toString(), + 'widget a = b({c: args.foo.0});', + ); + expect( + parseLibraryFile('widget a = b(c:data.foo.000);').toString(), + 'widget a = b({c: data.foo.0});', + ); + expect( + parseLibraryFile('widget a = b(c:state.foo.000);').toString(), + 'widget a = b({c: state.foo.0});', + ); + expect( + parseLibraryFile('widget a = b(c: [...for d in []: d.000]);').toString(), + 'widget a = b({c: [...for loop in []: loop0.0]});', + ); }); testWidgets('parseLibraryFile: event handlers', (WidgetTester tester) async { - expect(parseLibraryFile('widget a = b(c: event "d" { });').toString(), 'widget a = b({c: event d {}});'); - expect(parseLibraryFile('widget a = b(c: set state.d = 0);').toString(), 'widget a = b({c: set state.d = 0});'); + expect( + parseLibraryFile('widget a = b(c: event "d" { });').toString(), + 'widget a = b({c: event d {}});', + ); + expect( + parseLibraryFile('widget a = b(c: set state.d = 0);').toString(), + 'widget a = b({c: set state.d = 0});', + ); }); testWidgets('parseLibraryFile: stateful widgets', (WidgetTester tester) async { @@ -352,10 +542,15 @@ void main() { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = Builder(builder: (scope) => Container(width: scope.width)); '''); - expect(libraryFile.toString(), 'widget a = Builder({builder: (scope) => Container({width: scope.width})});'); + expect( + libraryFile.toString(), + 'widget a = Builder({builder: (scope) => Container({width: scope.width})});', + ); }); - testWidgets('parseLibraryFile: widgetBuilder arguments are lexical scoped', (WidgetTester tester) async { + testWidgets('parseLibraryFile: widgetBuilder arguments are lexical scoped', ( + WidgetTester tester, + ) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( a: (s1) => B( @@ -363,10 +558,15 @@ void main() { ), ); '''); - expect(libraryFile.toString(), 'widget a = A({a: (s1) => B({b: (s2) => T({s1: s1.s1, s2: s2.s2})})});'); + expect( + libraryFile.toString(), + 'widget a = A({a: (s1) => B({b: (s2) => T({s1: s1.s1, s2: s2.s2})})});', + ); }); - testWidgets('parseLibraryFile: widgetBuilder arguments can be shadowed', (WidgetTester tester) async { + testWidgets('parseLibraryFile: widgetBuilder arguments can be shadowed', ( + WidgetTester tester, + ) async { final RemoteWidgetLibrary libraryFile = parseLibraryFile(''' widget a = A( a: (s1) => B( @@ -377,7 +577,9 @@ void main() { expect(libraryFile.toString(), 'widget a = A({a: (s1) => B({b: (s1) => T({t: s1.foo})})});'); }); - testWidgets('parseLibraryFile: widgetBuilders check the returned value', (WidgetTester tester) async { + testWidgets('parseLibraryFile: widgetBuilders check the returned value', ( + WidgetTester tester, + ) async { void test(String input, String expectedMessage) { try { parseLibraryFile(input); @@ -388,7 +590,7 @@ void main() { } const expectedErrorMessage = - 'Expecting a switch or constructor call got 1 at line 1 column 27.'; + 'Expecting a switch or constructor call got 1 at line 1 column 27.'; test('widget a = B(b: (foo) => 1);', expectedErrorMessage); }); @@ -402,13 +604,15 @@ void main() { } } - const expectedErrorMessage = - 'args is a reserved word at line 1 column 34.'; - test('widget a = Builder(builder: (args) => Container(width: args.width));', expectedErrorMessage); + const expectedErrorMessage = 'args is a reserved word at line 1 column 34.'; + test( + 'widget a = Builder(builder: (args) => Container(width: args.width));', + expectedErrorMessage, + ); }); testWidgets('parseLibraryFile: widgetBuilders check reserved words', (WidgetTester tester) async { - void test(String input, String expectedMessage) { + void test(String input, String expectedMessage) { try { parseDataFile(input); fail('parsing `$input` did not result in an error (expected "$expectedMessage").'); @@ -417,9 +621,11 @@ void main() { } } - const expectedErrorMessage = - 'Expected symbol "{" but found widget at line 1 column 7.'; - test('widget a = Builder(builder: (args) => Container(width: args.width));', expectedErrorMessage); + const expectedErrorMessage = 'Expected symbol "{" but found widget at line 1 column 7.'; + test( + 'widget a = Builder(builder: (args) => Container(width: args.width));', + expectedErrorMessage, + ); }); testWidgets('parseLibraryFile: switch works with widgetBuilders', (WidgetTester tester) async { @@ -431,7 +637,10 @@ void main() { } ); '''); - expect(libraryFile.toString(), 'widget a = A({b: switch args.down {true: (foo) => B({}), false: (bar) => C({})}});'); + expect( + libraryFile.toString(), + 'widget a = A({b: switch args.down {true: (foo) => B({}), false: (bar) => C({})}});', + ); }); testWidgets('parseLibraryFile: widgetBuilders work with switch', (WidgetTester tester) async { @@ -443,7 +652,10 @@ void main() { }, ); '''); - expect(libraryFile.toString(), 'widget a = A({b: (foo) => switch foo.letter {a: A({}), b: B({})}});'); + expect( + libraryFile.toString(), + 'widget a = A({b: (foo) => switch foo.letter {a: A({}), b: B({})}});', + ); }); testWidgets('parseLibraryFile: widgetBuilders work with lists', (WidgetTester tester) async { @@ -452,7 +664,7 @@ void main() { b: (s1) => B(c: [s1.c]), ); '''); - expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({c: [s1.c]})});' ); + expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({c: [s1.c]})});'); }); testWidgets('parseLibraryFile: widgetBuilders work with maps', (WidgetTester tester) async { @@ -470,7 +682,10 @@ void main() { b: (s1) => B(onTap: set state.foo = s1.foo), ); '''); - expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({onTap: set state.foo = s1.foo})});'); + expect( + libraryFile.toString(), + 'widget a = A({b: (s1) => B({onTap: set state.foo = s1.foo})});', + ); }); testWidgets('parseLibraryFile: widgetBuilders work with events', (WidgetTester tester) async { @@ -479,6 +694,9 @@ void main() { b: (s1) => B(onTap: event "foo" {result: s1.result}) ); '''); - expect(libraryFile.toString(), 'widget a = A({b: (s1) => B({onTap: event foo {result: s1.result}})});'); + expect( + libraryFile.toString(), + 'widget a = A({b: (s1) => B({onTap: event foo {result: s1.result}})});', + ); }); } diff --git a/packages/rfw/test/tolerant_comparator.dart b/packages/rfw/test/tolerant_comparator.dart index 77dce43c6766..46f72cd5e73c 100644 --- a/packages/rfw/test/tolerant_comparator.dart +++ b/packages/rfw/test/tolerant_comparator.dart @@ -7,10 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; /// Sets [_TolerantGoldenFileComparator] as the default golden file comparator /// in tests. -void setUpTolerantComparator({ - required String testPath, - required double precisionTolerance, -}) { +void setUpTolerantComparator({required String testPath, required double precisionTolerance}) { final GoldenFileComparator oldComparator = goldenFileComparator; final newComparator = _TolerantGoldenFileComparator( Uri.parse(testPath), @@ -23,14 +20,12 @@ void setUpTolerantComparator({ } class _TolerantGoldenFileComparator extends LocalFileComparator { - _TolerantGoldenFileComparator( - super.testFile, { - required double precisionTolerance, - }) : assert( - 0 <= precisionTolerance && precisionTolerance <= 1, - 'precisionTolerance must be between 0 and 1', - ), - _precisionTolerance = precisionTolerance; + _TolerantGoldenFileComparator(super.testFile, {required double precisionTolerance}) + : assert( + 0 <= precisionTolerance && precisionTolerance <= 1, + 'precisionTolerance must be between 0 and 1', + ), + _precisionTolerance = precisionTolerance; /// How much the golden image can differ from the test image. /// @@ -45,8 +40,7 @@ class _TolerantGoldenFileComparator extends LocalFileComparator { await getGoldenBytes(golden), ); - final bool passed = - result.passed || result.diffPercent <= _precisionTolerance; + final bool passed = result.passed || result.diffPercent <= _precisionTolerance; if (passed) { result.dispose(); return true; diff --git a/packages/rfw/test/tolerant_comparator_web.dart b/packages/rfw/test/tolerant_comparator_web.dart index cc309561e2f7..797c3433c93e 100644 --- a/packages/rfw/test/tolerant_comparator_web.dart +++ b/packages/rfw/test/tolerant_comparator_web.dart @@ -2,7 +2,4 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -void setUpTolerantComparator({ - required String testPath, - required double precisionTolerance, -}) {} +void setUpTolerantComparator({required String testPath, required double precisionTolerance}) {} diff --git a/packages/rfw/test_coverage/bin/test_coverage.dart b/packages/rfw/test_coverage/bin/test_coverage.dart index 4a16b701e30a..9f9e020a74e5 100644 --- a/packages/rfw/test_coverage/bin/test_coverage.dart +++ b/packages/rfw/test_coverage/bin/test_coverage.dart @@ -36,9 +36,7 @@ final class LcovLine { @override bool operator ==(Object other) { - return other is LcovLine && - other.line == line && - other.filename == filename; + return other is LcovLine && other.line == line && other.filename == filename; } @override @@ -100,9 +98,7 @@ Future main(List arguments) async { } } - final List records = await lcov.Parser.parse( - 'coverage/lcov.info', - ); + final List records = await lcov.Parser.parse('coverage/lcov.info'); var totalLines = 0; var coveredLines = 0; var deadLinesError = false; @@ -114,10 +110,7 @@ Future main(List arguments) async { for (var index = 0; index < record.lines!.details!.length; index += 1) { if (record.lines!.details![index].hit != null && record.lines!.details![index].line != null) { - final line = LcovLine( - record.file!, - record.lines!.details![index].line!, - ); + final line = LcovLine(record.file!, record.lines!.details![index].line!); if (flakyLines.contains(line)) { totalLines -= 1; if (record.lines!.details![index].hit! > 0) { @@ -128,9 +121,7 @@ Future main(List arguments) async { deadLines.remove(line); totalLines -= 1; if (record.lines!.details![index].hit! > 0) { - print( - '$line: Line is marked as being dead code but was nonetheless covered.', - ); + print('$line: Line is marked as being dead code but was nonetheless covered.'); deadLinesError = true; } } @@ -145,9 +136,7 @@ Future main(List arguments) async { '$line: Line is marked as being undetectably dead code but was not considered reachable.', ); } - print( - 'Consider removing the "dead code on VM target" comment from affected lines.', - ); + print('Consider removing the "dead code on VM target" comment from affected lines.'); exit(1); } if (totalLines <= 0 || totalLines < coveredLines) { @@ -155,8 +144,7 @@ Future main(List arguments) async { exit(1); } - final String coveredPercent = (100.0 * coveredLines / totalLines) - .toStringAsFixed(1); + final String coveredPercent = (100.0 * coveredLines / totalLines).toStringAsFixed(1); if (targetLines != null) { if (targetLines! < totalLines) { diff --git a/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_migration_util_test.dart b/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_migration_util_test.dart index 63f6ef30b77d..5c7a6461cf24 100644 --- a/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_migration_util_test.dart +++ b/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_migration_util_test.dart @@ -78,33 +78,25 @@ void runAllGroups( group('file name (or equivalent) sharedPreferencesAsyncOptions', () { final SharedPreferencesOptions sharedPreferencesAsyncOptions; if (Platform.isAndroid) { - sharedPreferencesAsyncOptions = - const SharedPreferencesAsyncAndroidOptions( - backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, - originalSharedPreferencesOptions: - AndroidSharedPreferencesStoreOptions(fileName: 'fileName'), - ); + sharedPreferencesAsyncOptions = const SharedPreferencesAsyncAndroidOptions( + backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, + originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions( + fileName: 'fileName', + ), + ); } else if (Platform.isIOS || Platform.isMacOS) { sharedPreferencesAsyncOptions = SharedPreferencesAsyncFoundationOptions( suiteName: 'group.fileName', ); } else if (Platform.isLinux) { - sharedPreferencesAsyncOptions = const SharedPreferencesLinuxOptions( - fileName: 'fileName', - ); + sharedPreferencesAsyncOptions = const SharedPreferencesLinuxOptions(fileName: 'fileName'); } else if (Platform.isWindows) { - sharedPreferencesAsyncOptions = const SharedPreferencesWindowsOptions( - fileName: 'fileName', - ); + sharedPreferencesAsyncOptions = const SharedPreferencesWindowsOptions(fileName: 'fileName'); } else { sharedPreferencesAsyncOptions = const SharedPreferencesOptions(); } - runTests( - sharedPreferencesAsyncOptions, - legacySharedPrefsConfig, - stringValue: stringValue, - ); + runTests(sharedPreferencesAsyncOptions, legacySharedPrefsConfig, stringValue: stringValue); }); if (Platform.isAndroid) { @@ -112,15 +104,10 @@ void runAllGroups( const SharedPreferencesOptions sharedPreferencesAsyncOptions = SharedPreferencesAsyncAndroidOptions( backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, - originalSharedPreferencesOptions: - AndroidSharedPreferencesStoreOptions(), + originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions(), ); - runTests( - sharedPreferencesAsyncOptions, - legacySharedPrefsConfig, - stringValue: stringValue, - ); + runTests(sharedPreferencesAsyncOptions, legacySharedPrefsConfig, stringValue: stringValue); }); } } @@ -146,9 +133,7 @@ void runTests( }); tearDown(() async { - await SharedPreferencesAsync( - options: sharedPreferencesAsyncOptions, - ).clear(); + await SharedPreferencesAsync(options: sharedPreferencesAsyncOptions).clear(); }); testWidgets('data is successfully transferred to new system', (_) async { @@ -159,9 +144,7 @@ void runTests( migrationCompletedKey: migrationCompletedKey, ); - final asyncPreferences = SharedPreferencesAsync( - options: sharedPreferencesAsyncOptions, - ); + final asyncPreferences = SharedPreferencesAsync(options: sharedPreferencesAsyncOptions); expect(await asyncPreferences.getBool(boolKey), testBool); expect(await asyncPreferences.getInt(intKey), testInt); @@ -178,9 +161,7 @@ void runTests( migrationCompletedKey: migrationCompletedKey, ); - final asyncPreferences = SharedPreferencesAsync( - options: sharedPreferencesAsyncOptions, - ); + final asyncPreferences = SharedPreferencesAsync(options: sharedPreferencesAsyncOptions); expect(await asyncPreferences.getBool(migrationCompletedKey), true); }); @@ -188,17 +169,14 @@ void runTests( testWidgets( 're-running migration tool does not overwrite data', (_) async { - final SharedPreferences preferences = - await SharedPreferences.getInstance(); + final SharedPreferences preferences = await SharedPreferences.getInstance(); await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary( legacySharedPreferencesInstance: preferences, sharedPreferencesAsyncOptions: sharedPreferencesAsyncOptions, migrationCompletedKey: migrationCompletedKey, ); - final asyncPreferences = SharedPreferencesAsync( - options: sharedPreferencesAsyncOptions, - ); + final asyncPreferences = SharedPreferencesAsync(options: sharedPreferencesAsyncOptions); await preferences.setInt(intKey, -0); await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary( legacySharedPreferencesInstance: preferences, @@ -210,9 +188,6 @@ void runTests( // Skips platforms that would be adding the preferences to the same file. skip: keysAndNamesCollide && - (Platform.isWindows || - Platform.isLinux || - Platform.isMacOS || - Platform.isIOS), + (Platform.isWindows || Platform.isLinux || Platform.isMacOS || Platform.isIOS), ); } diff --git a/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart index 3146949126a4..cb1bf351e275 100644 --- a/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences/example/integration_test/shared_preferences_test.dart @@ -360,17 +360,16 @@ void main() { }, throwsA(isA())); }); - testWidgets( - 'throws TypeError when returned getString type is incorrect', - (WidgetTester _) async { - final SharedPreferencesAsync preferences = await getPreferences(); - await preferences.setInt(stringKey, testInt); - - expect(() async { - await preferences.getString(stringKey); - }, throwsA(isA())); - }, - ); + testWidgets('throws TypeError when returned getString type is incorrect', ( + WidgetTester _, + ) async { + final SharedPreferencesAsync preferences = await getPreferences(); + await preferences.setInt(stringKey, testInt); + + expect(() async { + await preferences.getString(stringKey); + }, throwsA(isA())); + }); testWidgets('throws TypeError when returned getInt type is incorrect', ( WidgetTester _, @@ -383,89 +382,78 @@ void main() { }, throwsA(isA())); }); - testWidgets( - 'throws TypeError when returned getDouble type is incorrect', - (WidgetTester _) async { - final SharedPreferencesAsync preferences = await getPreferences(); - await preferences.setString(stringKey, testString); - - expect(() async { - await preferences.getDouble(stringKey); - }, throwsA(isA())); - }, - ); - - testWidgets( - 'throws TypeError when returned getStringList type is incorrect', - (WidgetTester _) async { - final SharedPreferencesAsync preferences = await getPreferences(); - await preferences.setString(stringKey, testString); - - expect(() async { - await preferences.getStringList(stringKey); - }, throwsA(isA())); - }, - ); + testWidgets('throws TypeError when returned getDouble type is incorrect', ( + WidgetTester _, + ) async { + final SharedPreferencesAsync preferences = await getPreferences(); + await preferences.setString(stringKey, testString); + + expect(() async { + await preferences.getDouble(stringKey); + }, throwsA(isA())); + }); + + testWidgets('throws TypeError when returned getStringList type is incorrect', ( + WidgetTester _, + ) async { + final SharedPreferencesAsync preferences = await getPreferences(); + await preferences.setString(stringKey, testString); + + expect(() async { + await preferences.getStringList(stringKey); + }, throwsA(isA())); + }); }); group('withCache', () { - Future<(SharedPreferencesWithCache, Map)> - getPreferences() async { + Future<(SharedPreferencesWithCache, Map)> getPreferences() async { final cache = {}; - final SharedPreferencesWithCache preferences = - await SharedPreferencesWithCache.create( - cache: cache, - cacheOptions: const SharedPreferencesWithCacheOptions(), - ); + final SharedPreferencesWithCache preferences = await SharedPreferencesWithCache.create( + cache: cache, + cacheOptions: const SharedPreferencesWithCacheOptions(), + ); await preferences.clear(); return (preferences, cache); } testWidgets('set and get String', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); }); testWidgets('set and get bool', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setBool(boolKey, testBool); expect(preferences.getBool(boolKey), testBool); }); testWidgets('set and get int', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setInt(intKey, testInt); expect(preferences.getInt(intKey), testInt); }); testWidgets('set and get double', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setDouble(doubleKey, testDouble); expect(preferences.getDouble(doubleKey), testDouble); }); testWidgets('set and get StringList', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setStringList(listKey, testList); expect(preferences.getStringList(listKey), testList); }); testWidgets('reloading', (WidgetTester _) async { - final ( - SharedPreferencesWithCache preferences, - Map cache, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, Map cache) = + await getPreferences(); await preferences.clear(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); @@ -478,8 +466,7 @@ void main() { }); testWidgets('containsKey', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); const key = 'testKey'; expect(false, preferences.containsKey(key)); @@ -489,8 +476,7 @@ void main() { }); testWidgets('getKeys', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -510,8 +496,7 @@ void main() { }); testWidgets('clear', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -529,96 +514,71 @@ void main() { }); group('withCache with filter', () { - Future<(SharedPreferencesWithCache, Map)> - getPreferences() async { + Future<(SharedPreferencesWithCache, Map)> getPreferences() async { final cache = {}; - final SharedPreferencesWithCache preferences = - await SharedPreferencesWithCache.create( - cache: cache, - cacheOptions: const SharedPreferencesWithCacheOptions( - allowList: { - stringKey, - boolKey, - intKey, - doubleKey, - listKey, - }, - ), - ); + final SharedPreferencesWithCache preferences = await SharedPreferencesWithCache.create( + cache: cache, + cacheOptions: const SharedPreferencesWithCacheOptions( + allowList: {stringKey, boolKey, intKey, doubleKey, listKey}, + ), + ); await preferences.clear(); return (preferences, cache); } - testWidgets('throws ArgumentError if key is not included in filter', ( - WidgetTester _, - ) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + testWidgets('throws ArgumentError if key is not included in filter', (WidgetTester _) async { + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); const key = 'testKey'; - expect( - () async => preferences.setString(key, 'test'), - throwsArgumentError, - ); + expect(() async => preferences.setString(key, 'test'), throwsArgumentError); }); testWidgets('set and get String', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); }); testWidgets('set and get bool', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setBool(boolKey, testBool); expect(preferences.getBool(boolKey), testBool); }); testWidgets('set and get int', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setInt(intKey, testInt); expect(preferences.getInt(intKey), testInt); }); testWidgets('set and get double', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setDouble(doubleKey, testDouble); expect(preferences.getDouble(doubleKey), testDouble); }); testWidgets('set and get StringList', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setStringList(listKey, testList); expect(preferences.getStringList(listKey), testList); }); - testWidgets('get StringList handles List', ( - WidgetTester _, - ) async { - final ( - SharedPreferencesWithCache preferences, - Map cache, - ) = await getPreferences(); + testWidgets('get StringList handles List', (WidgetTester _) async { + final (SharedPreferencesWithCache preferences, Map cache) = + await getPreferences(); final listObject = ['one', 'two']; cache[listKey] = listObject; expect(preferences.getStringList(listKey), listObject); }); testWidgets('reloading', (WidgetTester _) async { - final ( - SharedPreferencesWithCache preferences, - Map cache, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, Map cache) = + await getPreferences(); await preferences.clear(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); @@ -631,8 +591,7 @@ void main() { }); testWidgets('containsKey', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); expect(false, preferences.containsKey(stringKey)); @@ -641,8 +600,7 @@ void main() { }); testWidgets('getKeys', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -662,8 +620,7 @@ void main() { }); testWidgets('clear', (WidgetTester _) async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), diff --git a/packages/shared_preferences/shared_preferences/example/lib/main.dart b/packages/shared_preferences/shared_preferences/example/lib/main.dart index 092cfbafb403..1ac5c0f99ebc 100644 --- a/packages/shared_preferences/shared_preferences/example/lib/main.dart +++ b/packages/shared_preferences/shared_preferences/example/lib/main.dart @@ -10,6 +10,7 @@ import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; // #docregion migrate import 'package:shared_preferences/util/legacy_to_async_migration_util.dart'; + // #enddocregion migrate void main() { @@ -36,13 +37,12 @@ class SharedPreferencesDemo extends StatefulWidget { } class SharedPreferencesDemoState extends State { - final Future _prefs = - SharedPreferencesWithCache.create( - cacheOptions: const SharedPreferencesWithCacheOptions( - // This cache will only accept the key 'counter'. - allowList: {'counter'}, - ), - ); + final Future _prefs = SharedPreferencesWithCache.create( + cacheOptions: const SharedPreferencesWithCacheOptions( + // This cache will only accept the key 'counter'. + allowList: {'counter'}, + ), + ); late Future _counter; int _externalCounter = 0; @@ -135,10 +135,7 @@ class SharedPreferencesDemoState extends State { /// Waits for the [initialized] future to complete before rendering [builder]. class _WaitForInitialization extends StatelessWidget { - const _WaitForInitialization({ - required this.initialized, - required this.builder, - }); + const _WaitForInitialization({required this.initialized, required this.builder}); final Future initialized; final WidgetBuilder builder; diff --git a/packages/shared_preferences/shared_preferences/example/lib/readme_excerpts.dart b/packages/shared_preferences/shared_preferences/example/lib/readme_excerpts.dart index b917383df8b6..2d2a7ebfa42b 100644 --- a/packages/shared_preferences/shared_preferences/example/lib/readme_excerpts.dart +++ b/packages/shared_preferences/shared_preferences/example/lib/readme_excerpts.dart @@ -6,6 +6,7 @@ import 'package:shared_preferences/shared_preferences.dart'; // #docregion Android_Options1 import 'package:shared_preferences_android/shared_preferences_android.dart'; + // #enddocregion Android_Options1 Future readmeSnippets() async { @@ -64,8 +65,7 @@ Future readmeSnippetsAsync() async { Future readmeSnippetsWithCache() async { // #docregion WithCache - final SharedPreferencesWithCache - prefsWithCache = await SharedPreferencesWithCache.create( + final SharedPreferencesWithCache prefsWithCache = await SharedPreferencesWithCache.create( cacheOptions: const SharedPreferencesWithCacheOptions( // When an allowlist is included, any keys that aren't included cannot be used. allowList: {'repeat', 'action'}, @@ -97,11 +97,10 @@ Future readmeTestSnippets() async { } // #docregion Android_Options2 -const SharedPreferencesAsyncAndroidOptions options = - SharedPreferencesAsyncAndroidOptions( - backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, - originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions( - fileName: 'the_name_of_a_file', - ), - ); +const SharedPreferencesAsyncAndroidOptions options = SharedPreferencesAsyncAndroidOptions( + backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, + originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions( + fileName: 'the_name_of_a_file', + ), +); // #enddocregion Android_Options2 diff --git a/packages/shared_preferences/shared_preferences/example/test/example_app_test.dart b/packages/shared_preferences/shared_preferences/example/test/example_app_test.dart index 07413ee64df1..563fecfadfd8 100644 --- a/packages/shared_preferences/shared_preferences/example/test/example_app_test.dart +++ b/packages/shared_preferences/shared_preferences/example/test/example_app_test.dart @@ -30,15 +30,11 @@ void main() { // import the relative path ../../test/shared_preferences_async_test.dart on the // web platform, we had to copy it here for use in this test library. base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { - final InMemorySharedPreferencesAsync backend = - InMemorySharedPreferencesAsync.empty(); + final InMemorySharedPreferencesAsync backend = InMemorySharedPreferencesAsync.empty(); final List log = []; @override - Future clear( - ClearPreferencesParameters parameters, - SharedPreferencesOptions options, - ) { + Future clear(ClearPreferencesParameters parameters, SharedPreferencesOptions options) { log.add(MethodCall('clear', [...?parameters.filter.allowList])); return backend.clear(parameters, options); } @@ -75,9 +71,7 @@ base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { GetPreferencesParameters parameters, SharedPreferencesOptions options, ) { - log.add( - MethodCall('getPreferences', [...?parameters.filter.allowList]), - ); + log.add(MethodCall('getPreferences', [...?parameters.filter.allowList])); return backend.getPreferences(parameters, options); } @@ -88,30 +82,19 @@ base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) { + Future?> getStringList(String key, SharedPreferencesOptions options) { log.add(MethodCall('getStringList', [key])); return backend.getStringList(key, options); } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) { + Future setBool(String key, bool value, SharedPreferencesOptions options) { log.add(MethodCall('setBool', [key, value])); return backend.setBool(key, value, options); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) { + Future setDouble(String key, double value, SharedPreferencesOptions options) { log.add(MethodCall('setDouble', [key, value])); return backend.setDouble(key, value, options); } @@ -123,21 +106,13 @@ base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) { + Future setString(String key, String value, SharedPreferencesOptions options) { log.add(MethodCall('setString', [key, value])); return backend.setString(key, value, options); } @override - Future setStringList( - String key, - List value, - SharedPreferencesOptions options, - ) { + Future setStringList(String key, List value, SharedPreferencesOptions options) { log.add(MethodCall('setStringList', [key, value])); return backend.setStringList(key, value, options); } diff --git a/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart b/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart index 9ea7bede7302..069ed53d6aa1 100644 --- a/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart +++ b/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -export 'package:shared_preferences_platform_interface/types.dart' - show SharedPreferencesOptions; +export 'package:shared_preferences_platform_interface/types.dart' show SharedPreferencesOptions; export 'src/shared_preferences_async.dart'; export 'src/shared_preferences_legacy.dart'; diff --git a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_async.dart b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_async.dart index 5fd079d7a963..f5974ae3531d 100644 --- a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_async.dart +++ b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_async.dart @@ -18,13 +18,10 @@ import 'shared_preferences_devtools_extension_data.dart'; @immutable class SharedPreferencesAsync { /// Creates a new instance with the given [options]. - SharedPreferencesAsync({ - SharedPreferencesOptions options = const SharedPreferencesOptions(), - }) : _options = options { + SharedPreferencesAsync({SharedPreferencesOptions options = const SharedPreferencesOptions()}) + : _options = options { if (SharedPreferencesAsyncPlatform.instance == null) { - throw StateError( - 'The SharedPreferencesAsyncPlatform instance must be set.', - ); + throw StateError('The SharedPreferencesAsyncPlatform instance must be set.'); } else { _platform = SharedPreferencesAsyncPlatform.instance!; } @@ -42,9 +39,7 @@ class SharedPreferencesAsync { /// /// Ignores any keys whose values are types which are incompatible with shared_preferences. Future> getKeys({Set? allowList}) async { - final parameters = GetPreferencesParameters( - filter: PreferencesFilters(allowList: allowList), - ); + final parameters = GetPreferencesParameters(filter: PreferencesFilters(allowList: allowList)); return _platform.getKeys(parameters, _options); } @@ -54,9 +49,7 @@ class SharedPreferencesAsync { /// /// Ignores any entries of types which are incompatible with shared_preferences. Future> getAll({Set? allowList}) async { - final parameters = GetPreferencesParameters( - filter: PreferencesFilters(allowList: allowList), - ); + final parameters = GetPreferencesParameters(filter: PreferencesFilters(allowList: allowList)); return _platform.getPreferences(parameters, _options); } @@ -129,9 +122,7 @@ class SharedPreferencesAsync { /// Removes an entry from the platform. Future remove(String key) { return _platform.clear( - ClearPreferencesParameters( - filter: PreferencesFilters(allowList: {key}), - ), + ClearPreferencesParameters(filter: PreferencesFilters(allowList: {key})), _options, ); } @@ -145,9 +136,7 @@ class SharedPreferencesAsync { /// /// It is highly recommended that an [allowList] be provided to this call. Future clear({Set? allowList}) { - final parameters = ClearPreferencesParameters( - filter: PreferencesFilters(allowList: allowList), - ); + final parameters = ClearPreferencesParameters(filter: PreferencesFilters(allowList: allowList)); return _platform.clear(parameters, _options); } } @@ -184,16 +173,13 @@ class SharedPreferencesWithCache { required SharedPreferencesWithCacheOptions cacheOptions, Map? cache, }) : _cacheOptions = cacheOptions, - _platformMethods = SharedPreferencesAsync( - options: sharedPreferencesOptions, - ), + _platformMethods = SharedPreferencesAsync(options: sharedPreferencesOptions), _cache = cache ?? {}; /// Creates a new instance with the given options and reloads the cache from /// the platform data. static Future create({ - SharedPreferencesOptions sharedPreferencesOptions = - const SharedPreferencesOptions(), + SharedPreferencesOptions sharedPreferencesOptions = const SharedPreferencesOptions(), required SharedPreferencesWithCacheOptions cacheOptions, Map? cache, }) async { @@ -227,9 +213,7 @@ class SharedPreferencesWithCache { /// preference storage directly. Future reloadCache() async { _cache.clear(); - _cache.addAll( - await _platformMethods.getAll(allowList: _cacheOptions.allowList), - ); + _cache.addAll(await _platformMethods.getAll(allowList: _cacheOptions.allowList)); } /// Returns true if cache contains the given [key]. @@ -237,9 +221,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. bool containsKey(String key) { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } return _cache.containsKey(key); } @@ -252,9 +234,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. Object? get(String key) { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } return _cache[key]; } @@ -265,9 +245,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. bool? getBool(String key) { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } return get(key) as bool?; } @@ -278,9 +256,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. int? getInt(String key) { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } return get(key) as int?; } @@ -291,9 +267,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. double? getDouble(String key) { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } return get(key) as double?; } @@ -304,9 +278,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. String? getString(String key) { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } return get(key) as String?; } @@ -317,9 +289,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. List? getStringList(String key) { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } // Make a copy of the list so that later mutations won't propagate return (_cache[key] as List?)?.cast().toList(); @@ -330,9 +300,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. Future setBool(String key, bool value) async { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } _cache[key] = value; return _platformMethods.setBool(key, value); @@ -343,9 +311,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. Future setInt(String key, int value) async { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } _cache[key] = value; return _platformMethods.setInt(key, value); @@ -359,9 +325,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. Future setDouble(String key, double value) async { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } _cache[key] = value; return _platformMethods.setDouble(key, value); @@ -377,9 +341,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. Future setString(String key, String value) async { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } _cache[key] = value; return _platformMethods.setString(key, value); @@ -390,9 +352,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. Future setStringList(String key, List value) async { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } _cache[key] = value; return _platformMethods.setStringList(key, value); @@ -403,9 +363,7 @@ class SharedPreferencesWithCache { /// Throws an [ArgumentError] if [key] is not in this instance's filter. Future remove(String key) async { if (!_isValidKey(key)) { - throw ArgumentError( - '$key is not included in the PreferencesFilter allowlist', - ); + throw ArgumentError('$key is not included in the PreferencesFilter allowlist'); } _cache.remove(key); return _platformMethods.remove(key); @@ -426,5 +384,4 @@ class SharedPreferencesWithCache { // when running `flutter run -d chrome`. // Check this discussion for more info: https://github.com/flutter/packages/pull/6749/files/6eb1b4fdce1eba107294770d581713658ff971e9#discussion_r1755375409 // ignore: unused_element -final bool _fieldToKeepDevtoolsExtensionReachable = - fieldToKeepDevtoolsExtensionLibraryAlive; +final bool _fieldToKeepDevtoolsExtensionReachable = fieldToKeepDevtoolsExtensionLibraryAlive; diff --git a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_devtools_extension_data.dart b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_devtools_extension_data.dart index 5bd3eb7e82db..93f980d962a9 100644 --- a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_devtools_extension_data.dart +++ b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_devtools_extension_data.dart @@ -13,8 +13,7 @@ const String _eventPrefix = 'shared_preferences.'; /// A typedef for the post event function. @visibleForTesting -typedef PostEvent = - void Function(String eventKind, Map eventData); +typedef PostEvent = void Function(String eventKind, Map eventData); /// A helper class that provides data to the DevTools extension. /// @@ -24,9 +23,7 @@ class SharedPreferencesDevToolsExtensionData { /// The default constructor for [SharedPreferencesDevToolsExtensionData]. /// /// Accepts an optional [PostEvent] that should only be overwritten when testing. - const SharedPreferencesDevToolsExtensionData([ - this._postEvent = developer.postEvent, - ]); + const SharedPreferencesDevToolsExtensionData([this._postEvent = developer.postEvent]); final PostEvent _postEvent; @@ -46,8 +43,7 @@ class SharedPreferencesDevToolsExtensionData { Future requestValue(String key, bool legacy) async { final Object? value; if (legacy) { - final SharedPreferences legacyPrefs = - await SharedPreferences.getInstance(); + final SharedPreferences legacyPrefs = await SharedPreferences.getInstance(); value = legacyPrefs.get(key); } else { value = await SharedPreferencesAsync() @@ -72,8 +68,7 @@ class SharedPreferencesDevToolsExtensionData { ) async { final Object? value = jsonDecode(serializedValue); if (legacy) { - final SharedPreferences legacyPrefs = - await SharedPreferences.getInstance(); + final SharedPreferences legacyPrefs = await SharedPreferences.getInstance(); // we need to check the kind because sometimes a double // gets interpreted as an int. If this was not an issue // we'd only need to do a simple pattern matching on value. @@ -87,10 +82,7 @@ class SharedPreferencesDevToolsExtensionData { case 'String': await legacyPrefs.setString(key, value! as String); case 'List': - await legacyPrefs.setStringList( - key, - (value! as List).cast(), - ); + await legacyPrefs.setStringList(key, (value! as List).cast()); } } else { final prefs = SharedPreferencesAsync(); @@ -116,8 +108,7 @@ class SharedPreferencesDevToolsExtensionData { /// Requests a key removal and posts an empty event when removed. Future requestRemoveKey(String key, bool legacy) async { if (legacy) { - final SharedPreferences legacyPrefs = - await SharedPreferences.getInstance(); + final SharedPreferences legacyPrefs = await SharedPreferences.getInstance(); await legacyPrefs.remove(key); } else { await SharedPreferencesAsync().remove(key); diff --git a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart index 06d89f0010c8..d7007c5f041e 100644 --- a/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart +++ b/packages/shared_preferences/shared_preferences/lib/src/shared_preferences_legacy.dart @@ -27,8 +27,7 @@ class SharedPreferences { static Completer? _completer; - static SharedPreferencesStorePlatform get _store => - SharedPreferencesStorePlatform.instance; + static SharedPreferencesStorePlatform get _store => SharedPreferencesStorePlatform.instance; /// Sets the prefix that is attached to all keys for all shared preferences /// read or written via this class. @@ -81,8 +80,7 @@ class SharedPreferences { final completer = Completer(); _completer = completer; try { - final Map preferencesMap = - await _getSharedPreferencesMap(); + final Map preferencesMap = await _getSharedPreferencesMap(); completer.complete(SharedPreferences._(preferencesMap)); } catch (e) { // If there's an error, explicitly return the future with an error. @@ -149,8 +147,7 @@ class SharedPreferences { /// Saves a double [value] to persistent storage in the background. /// /// Android doesn't support storing doubles, so it will be stored as a float. - Future setDouble(String key, double value) => - _setValue('Double', key, value); + Future setDouble(String key, double value) => _setValue('Double', key, value); /// Saves a string [value] to persistent storage in the background. /// @@ -160,12 +157,10 @@ class SharedPreferences { /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu' /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy' /// - 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu' - Future setString(String key, String value) => - _setValue('String', key, value); + Future setString(String key, String value) => _setValue('String', key, value); /// Saves a list of strings [value] to persistent storage in the background. - Future setStringList(String key, List value) => - _setValue('StringList', key, value); + Future setStringList(String key, List value) => _setValue('StringList', key, value); /// Removes an entry from persistent storage. Future remove(String key) { @@ -221,8 +216,7 @@ Either update the implementation to support setPrefix, or do not call setPrefix. /// Use this method to observe modifications that were made in native code /// (without using the plugin) while the app is running. Future reload() async { - final Map preferences = - await SharedPreferences._getSharedPreferencesMap(); + final Map preferences = await SharedPreferences._getSharedPreferencesMap(); _preferenceCache.clear(); _preferenceCache.addAll(preferences); } @@ -270,18 +264,14 @@ Either update the implementation to support setPrefix, or do not call setPrefix. /// If the singleton instance has been initialized already, it is nullified. @visibleForTesting static void setMockInitialValues(Map values) { - final Map newValues = values.map(( - String key, - Object value, - ) { + final Map newValues = values.map((String key, Object value) { var newKey = key; if (!key.startsWith(_prefix)) { newKey = '$_prefix$key'; } return MapEntry(newKey, value); }); - SharedPreferencesStorePlatform.instance = - InMemorySharedPreferencesStore.withData(newValues); + SharedPreferencesStorePlatform.instance = InMemorySharedPreferencesStore.withData(newValues); _completer = null; } } @@ -290,5 +280,4 @@ Either update the implementation to support setPrefix, or do not call setPrefix. // when running `flutter run -d chrome`. // Check this discussion for more info: https://github.com/flutter/packages/pull/6749/files/6eb1b4fdce1eba107294770d581713658ff971e9#discussion_r1755375409 // ignore: unused_element -final bool _fieldToKeepDevtoolsExtensionReachable = - fieldToKeepDevtoolsExtensionLibraryAlive; +final bool _fieldToKeepDevtoolsExtensionReachable = fieldToKeepDevtoolsExtensionLibraryAlive; diff --git a/packages/shared_preferences/shared_preferences/lib/util/legacy_to_async_migration_util.dart b/packages/shared_preferences/shared_preferences/lib/util/legacy_to_async_migration_util.dart index 439c7c8c9cfd..a883e724004d 100644 --- a/packages/shared_preferences/shared_preferences/lib/util/legacy_to_async_migration_util.dart +++ b/packages/shared_preferences/shared_preferences/lib/util/legacy_to_async_migration_util.dart @@ -60,9 +60,7 @@ Future migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary({ key, (value! as List).cast(), ); - } on TypeError catch ( - _ - ) {} // Pass over Lists containing non-String values. + } on TypeError catch (_) {} // Pass over Lists containing non-String values. } } diff --git a/packages/shared_preferences/shared_preferences/test/shared_preferences_async_test.dart b/packages/shared_preferences/shared_preferences/test/shared_preferences_async_test.dart index 3eeef53821d3..a18b3b208464 100755 --- a/packages/shared_preferences/shared_preferences/test/shared_preferences_async_test.dart +++ b/packages/shared_preferences/shared_preferences/test/shared_preferences_async_test.dart @@ -31,10 +31,8 @@ void main() { } test('set and get String', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); await preferences.setString(stringKey, testString); expect(store.log, [ isMethodCall('setString', arguments: [stringKey, testString]), @@ -47,10 +45,8 @@ void main() { }); test('set and get bool', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); await preferences.setBool(boolKey, testBool); expect(store.log, [ isMethodCall('setBool', arguments: [boolKey, testBool]), @@ -63,10 +59,8 @@ void main() { }); test('set and get int', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); await preferences.setInt(intKey, testInt); expect(store.log, [ isMethodCall('setInt', arguments: [intKey, testInt]), @@ -80,10 +74,8 @@ void main() { }); test('set and get double', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); await preferences.setDouble(doubleKey, testDouble); expect(store.log, [ isMethodCall('setDouble', arguments: [doubleKey, testDouble]), @@ -96,10 +88,8 @@ void main() { }); test('set and get StringList', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); await preferences.setStringList(listKey, testList); expect(store.log, [ isMethodCall('setStringList', arguments: [listKey, testList]), @@ -151,19 +141,13 @@ void main() { }); test('remove', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); const key = 'testKey'; await preferences.remove(key); expect( store.log, - List.filled( - 1, - isMethodCall('clear', arguments: [key]), - growable: true, - ), + List.filled(1, isMethodCall('clear', arguments: [key]), growable: true), ); }); @@ -197,9 +181,7 @@ void main() { preferences.setStringList(listKey, testList), ]); - final Set keys = await preferences.getKeys( - allowList: {stringKey, boolKey}, - ); + final Set keys = await preferences.getKeys(allowList: {stringKey, boolKey}); expect(keys.length, 2); expect(keys, contains(stringKey)); @@ -217,10 +199,8 @@ void main() { }); test('clear', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -230,9 +210,7 @@ void main() { ]); store.log.clear(); await preferences.clear(); - expect(store.log, [ - isMethodCall('clear', arguments: []), - ]); + expect(store.log, [isMethodCall('clear', arguments: [])]); expect(await preferences.getString(stringKey), null); expect(await preferences.getBool(boolKey), null); expect(await preferences.getInt(intKey), null); @@ -241,10 +219,8 @@ void main() { }); test('clear with filter', () async { - final ( - SharedPreferencesAsync preferences, - FakeSharedPreferencesAsync store, - ) = getPreferences(); + final (SharedPreferencesAsync preferences, FakeSharedPreferencesAsync store) = + getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -266,32 +242,22 @@ void main() { }); group('withCache', () { - Future< - ( - SharedPreferencesWithCache, - FakeSharedPreferencesAsync, - Map, - ) - > + Future<(SharedPreferencesWithCache, FakeSharedPreferencesAsync, Map)> getPreferences() async { final cache = {}; final store = FakeSharedPreferencesAsync(); SharedPreferencesAsyncPlatform.instance = store; - final SharedPreferencesWithCache preferences = - await SharedPreferencesWithCache.create( - cache: cache, - cacheOptions: const SharedPreferencesWithCacheOptions(), - ); + final SharedPreferencesWithCache preferences = await SharedPreferencesWithCache.create( + cache: cache, + cacheOptions: const SharedPreferencesWithCacheOptions(), + ); store.log.clear(); return (preferences, store, cache); } test('set and get String', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setString(stringKey, testString); expect(store.log, [ isMethodCall('setString', arguments: [stringKey, testString]), @@ -302,11 +268,8 @@ void main() { }); test('set and get bool', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setBool(boolKey, testBool); expect(store.log, [ isMethodCall('setBool', arguments: [boolKey, testBool]), @@ -317,11 +280,8 @@ void main() { }); test('set and get int', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setInt(intKey, testInt); expect(store.log, [ isMethodCall('setInt', arguments: [intKey, testInt]), @@ -333,11 +293,8 @@ void main() { }); test('set and get double', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setDouble(doubleKey, testDouble); expect(store.log, [ isMethodCall('setDouble', arguments: [doubleKey, testDouble]), @@ -348,11 +305,8 @@ void main() { }); test('set and get StringList', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setStringList(listKey, testList); expect(store.log, [ isMethodCall('setStringList', arguments: [listKey, testList]), @@ -363,11 +317,8 @@ void main() { }); test('reloading', () async { - final ( - SharedPreferencesWithCache preferences, - _, - Map cache, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, _, Map cache) = + await getPreferences(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); @@ -379,8 +330,7 @@ void main() { }); test('containsKey', () async { - final (SharedPreferencesWithCache preferences, _, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _, _) = await getPreferences(); const key = 'testKey'; expect(false, preferences.containsKey(key)); @@ -390,8 +340,7 @@ void main() { }); test('getKeys', () async { - final (SharedPreferencesWithCache preferences, _, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -411,29 +360,19 @@ void main() { }); test('remove', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); const key = 'testKey'; await preferences.remove(key); expect( store.log, - List.filled( - 1, - isMethodCall('clear', arguments: [key]), - growable: true, - ), + List.filled(1, isMethodCall('clear', arguments: [key]), growable: true), ); }); test('clear', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -443,9 +382,7 @@ void main() { ]); store.log.clear(); await preferences.clear(); - expect(store.log, [ - isMethodCall('clear', arguments: []), - ]); + expect(store.log, [isMethodCall('clear', arguments: [])]); expect(preferences.getString(stringKey), null); expect(preferences.getBool(boolKey), null); expect(preferences.getInt(intKey), null); @@ -455,40 +392,24 @@ void main() { }); group('withCache with filter', () { - Future< - ( - SharedPreferencesWithCache, - FakeSharedPreferencesAsync, - Map, - ) - > + Future<(SharedPreferencesWithCache, FakeSharedPreferencesAsync, Map)> getPreferences() async { final cache = {}; final store = FakeSharedPreferencesAsync(); SharedPreferencesAsyncPlatform.instance = store; - final SharedPreferencesWithCache preferences = - await SharedPreferencesWithCache.create( - cache: cache, - cacheOptions: const SharedPreferencesWithCacheOptions( - allowList: { - stringKey, - boolKey, - intKey, - doubleKey, - listKey, - }, - ), - ); + final SharedPreferencesWithCache preferences = await SharedPreferencesWithCache.create( + cache: cache, + cacheOptions: const SharedPreferencesWithCacheOptions( + allowList: {stringKey, boolKey, intKey, doubleKey, listKey}, + ), + ); store.log.clear(); return (preferences, store, cache); } test('set and get String', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setString(stringKey, testString); expect(store.log, [ isMethodCall('setString', arguments: [stringKey, testString]), @@ -499,11 +420,8 @@ void main() { }); test('set and get bool', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setBool(boolKey, testBool); expect(store.log, [ isMethodCall('setBool', arguments: [boolKey, testBool]), @@ -514,11 +432,8 @@ void main() { }); test('set and get int', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setInt(intKey, testInt); expect(store.log, [ isMethodCall('setInt', arguments: [intKey, testInt]), @@ -530,11 +445,8 @@ void main() { }); test('set and get double', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setDouble(doubleKey, testDouble); expect(store.log, [ isMethodCall('setDouble', arguments: [doubleKey, testDouble]), @@ -545,11 +457,8 @@ void main() { }); test('set and get StringList', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.setStringList(listKey, testList); expect(store.log, [ isMethodCall('setStringList', arguments: [listKey, testList]), @@ -559,11 +468,8 @@ void main() { expect(store.log, []); }); test('reloading', () async { - final ( - SharedPreferencesWithCache preferences, - _, - Map cache, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, _, Map cache) = + await getPreferences(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); @@ -575,19 +481,14 @@ void main() { }); test('throws ArgumentError if key is not included in filter', () async { - final (SharedPreferencesWithCache preferences, _, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _, _) = await getPreferences(); const key = 'testKey'; - expect( - () async => preferences.setString(key, 'test'), - throwsArgumentError, - ); + expect(() async => preferences.setString(key, 'test'), throwsArgumentError); }); test('containsKey', () async { - final (SharedPreferencesWithCache preferences, _, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _, _) = await getPreferences(); expect(false, preferences.containsKey(stringKey)); @@ -596,8 +497,7 @@ void main() { }); test('getKeys', () async { - final (SharedPreferencesWithCache preferences, _, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -617,11 +517,8 @@ void main() { }); test('remove', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await preferences.remove(stringKey); expect( store.log, @@ -634,11 +531,8 @@ void main() { }); test('clear', () async { - final ( - SharedPreferencesWithCache preferences, - FakeSharedPreferencesAsync store, - _, - ) = await getPreferences(); + final (SharedPreferencesWithCache preferences, FakeSharedPreferencesAsync store, _) = + await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -649,10 +543,7 @@ void main() { store.log.clear(); await preferences.clear(); expect(store.log, [ - isMethodCall( - 'clear', - arguments: [stringKey, boolKey, intKey, doubleKey, listKey], - ), + isMethodCall('clear', arguments: [stringKey, boolKey, intKey, doubleKey, listKey]), ]); expect(preferences.getString(stringKey), null); @@ -668,15 +559,11 @@ void main() { } base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { - final InMemorySharedPreferencesAsync backend = - InMemorySharedPreferencesAsync.empty(); + final InMemorySharedPreferencesAsync backend = InMemorySharedPreferencesAsync.empty(); final List log = []; @override - Future clear( - ClearPreferencesParameters parameters, - SharedPreferencesOptions options, - ) { + Future clear(ClearPreferencesParameters parameters, SharedPreferencesOptions options) { log.add(MethodCall('clear', [...?parameters.filter.allowList])); return backend.clear(parameters, options); } @@ -713,9 +600,7 @@ base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { GetPreferencesParameters parameters, SharedPreferencesOptions options, ) { - log.add( - MethodCall('getPreferences', [...?parameters.filter.allowList]), - ); + log.add(MethodCall('getPreferences', [...?parameters.filter.allowList])); return backend.getPreferences(parameters, options); } @@ -726,30 +611,19 @@ base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) { + Future?> getStringList(String key, SharedPreferencesOptions options) { log.add(MethodCall('getStringList', [key])); return backend.getStringList(key, options); } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) { + Future setBool(String key, bool value, SharedPreferencesOptions options) { log.add(MethodCall('setBool', [key, value])); return backend.setBool(key, value, options); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) { + Future setDouble(String key, double value, SharedPreferencesOptions options) { log.add(MethodCall('setDouble', [key, value])); return backend.setDouble(key, value, options); } @@ -761,21 +635,13 @@ base class FakeSharedPreferencesAsync extends SharedPreferencesAsyncPlatform { } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) { + Future setString(String key, String value, SharedPreferencesOptions options) { log.add(MethodCall('setString', [key, value])); return backend.setString(key, value, options); } @override - Future setStringList( - String key, - List value, - SharedPreferencesOptions options, - ) { + Future setStringList(String key, List value, SharedPreferencesOptions options) { log.add(MethodCall('setStringList', [key, value])); return backend.setStringList(key, value, options); } diff --git a/packages/shared_preferences/shared_preferences/test/shared_preferences_devtools_extension_data_test.dart b/packages/shared_preferences/shared_preferences/test/shared_preferences_devtools_extension_data_test.dart index 4e9813c7c4d7..dc5738f2759b 100644 --- a/packages/shared_preferences/shared_preferences/test/shared_preferences_devtools_extension_data_test.dart +++ b/packages/shared_preferences/shared_preferences/test/shared_preferences_devtools_extension_data_test.dart @@ -35,18 +35,14 @@ void main() { }); test('should request all keys', () async { - SharedPreferences.setMockInitialValues({ - 'key1': 1, - 'key2': true, - }); + SharedPreferences.setMockInitialValues({'key1': 1, 'key2': true}); await asyncPreferences.setBool('key3', true); await asyncPreferences.setInt('key4', 1); await extension.requestAllKeys(); expect(fakePostEvent.eventLog.length, equals(1)); - final (String eventKind, Map eventData) = - fakePostEvent.eventLog.first; + final (String eventKind, Map eventData) = fakePostEvent.eventLog.first; expect(eventKind, equals('shared_preferences.all_keys')); expect( eventData, @@ -67,8 +63,7 @@ void main() { await extension.requestValue(key, legacy); expect(fakePostEvent.eventLog.length, equals(1)); - final (String eventKind, Map eventData) = - fakePostEvent.eventLog.first; + final (String eventKind, Map eventData) = fakePostEvent.eventLog.first; expect(eventKind, equals('shared_preferences.value')); expect(eventData, equals(expectedData)); } @@ -80,10 +75,7 @@ void main() { await testAsyncApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'bool', - }, + expectedData: {'value': expectedValue, 'kind': 'bool'}, ); }); @@ -94,10 +86,7 @@ void main() { await testAsyncApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'int', - }, + expectedData: {'value': expectedValue, 'kind': 'int'}, ); }); @@ -108,10 +97,7 @@ void main() { await testAsyncApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'double', - }, + expectedData: {'value': expectedValue, 'kind': 'double'}, ); }); @@ -122,10 +108,7 @@ void main() { await testAsyncApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'String', - }, + expectedData: {'value': expectedValue, 'kind': 'String'}, ); }); @@ -136,17 +119,11 @@ void main() { await testAsyncApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'List', - }, + expectedData: {'value': expectedValue, 'kind': 'List'}, ); }); - Future testAsyncApiValueChange( - String key, - Object expectedValue, - ) async { + Future testAsyncApiValueChange(String key, Object expectedValue) async { const legacy = false; await extension.requestValueChange( @@ -157,8 +134,7 @@ void main() { ); expect(fakePostEvent.eventLog.length, equals(1)); - final (String eventKind, Map eventData) = - fakePostEvent.eventLog.first; + final (String eventKind, Map eventData) = fakePostEvent.eventLog.first; expect(eventKind, equals('shared_preferences.change_value')); expect(eventData, equals({})); } @@ -210,10 +186,7 @@ void main() { await testAsyncApiValueChange(key, expectedValue); - expect( - await asyncPreferences.getStringList(key), - equals(expectedValue), - ); + expect(await asyncPreferences.getStringList(key), equals(expectedValue)); }); }); @@ -227,8 +200,7 @@ void main() { await extension.requestValue(key, legacy); expect(fakePostEvent.eventLog.length, equals(1)); - final (String eventKind, Map eventData) = - fakePostEvent.eventLog.first; + final (String eventKind, Map eventData) = fakePostEvent.eventLog.first; expect(eventKind, equals('shared_preferences.value')); expect(eventData, equals(expectedData)); } @@ -236,87 +208,59 @@ void main() { test('should request bool value from legacy api', () async { const key = 'key'; const expectedValue = false; - SharedPreferences.setMockInitialValues({ - key: expectedValue, - }); + SharedPreferences.setMockInitialValues({key: expectedValue}); await testLegacyApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'bool', - }, + expectedData: {'value': expectedValue, 'kind': 'bool'}, ); }); test('should request int value from legacy api', () async { const key = 'key'; const expectedValue = 42; - SharedPreferences.setMockInitialValues({ - key: expectedValue, - }); + SharedPreferences.setMockInitialValues({key: expectedValue}); await testLegacyApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'int', - }, + expectedData: {'value': expectedValue, 'kind': 'int'}, ); }); test('should request double value from legacy api', () async { const key = 'key'; const expectedValue = 42.2; - SharedPreferences.setMockInitialValues({ - key: expectedValue, - }); + SharedPreferences.setMockInitialValues({key: expectedValue}); await testLegacyApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'double', - }, + expectedData: {'value': expectedValue, 'kind': 'double'}, ); }); test('should request string value from legacy api', () async { const key = 'key'; const expectedValue = 'value'; - SharedPreferences.setMockInitialValues({ - key: expectedValue, - }); + SharedPreferences.setMockInitialValues({key: expectedValue}); await testLegacyApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'String', - }, + expectedData: {'value': expectedValue, 'kind': 'String'}, ); }); test('should request string list value from legacy api', () async { const key = 'key'; const expectedValue = ['string1', 'string2']; - SharedPreferences.setMockInitialValues({ - key: expectedValue, - }); + SharedPreferences.setMockInitialValues({key: expectedValue}); await testLegacyApiRequestValue( key, - expectedData: { - 'value': expectedValue, - 'kind': 'List', - }, + expectedData: {'value': expectedValue, 'kind': 'List'}, ); }); - Future testLegacyApiValueChange( - String key, - Object expectedValue, - ) async { + Future testLegacyApiValueChange(String key, Object expectedValue) async { const legacy = true; await extension.requestValueChange( @@ -327,8 +271,7 @@ void main() { ); expect(fakePostEvent.eventLog.length, equals(1)); - final (String eventKind, Map eventData) = - fakePostEvent.eventLog.first; + final (String eventKind, Map eventData) = fakePostEvent.eventLog.first; expect(eventKind, equals('shared_preferences.change_value')); expect(eventData, equals({})); } @@ -340,10 +283,7 @@ void main() { await testLegacyApiValueChange(key, expectedValue); - expect( - (await SharedPreferences.getInstance()).getInt(key), - equals(expectedValue), - ); + expect((await SharedPreferences.getInstance()).getInt(key), equals(expectedValue)); }); test('should request bool value change on legacy api', () async { @@ -353,10 +293,7 @@ void main() { await testLegacyApiValueChange(key, expectedValue); - expect( - (await SharedPreferences.getInstance()).getBool(key), - equals(expectedValue), - ); + expect((await SharedPreferences.getInstance()).getBool(key), equals(expectedValue)); }); test('should request double value change on legacy api', () async { @@ -366,25 +303,17 @@ void main() { await testLegacyApiValueChange(key, expectedValue); - expect( - (await SharedPreferences.getInstance()).getDouble(key), - equals(expectedValue), - ); + expect((await SharedPreferences.getInstance()).getDouble(key), equals(expectedValue)); }); test('should request string value change on legacy api', () async { const key = 'key'; const expectedValue = 'new value'; - SharedPreferences.setMockInitialValues({ - key: 'old value', - }); + SharedPreferences.setMockInitialValues({key: 'old value'}); await testLegacyApiValueChange(key, expectedValue); - expect( - (await SharedPreferences.getInstance()).getString(key), - equals(expectedValue), - ); + expect((await SharedPreferences.getInstance()).getString(key), equals(expectedValue)); }); test('should request string list value change on legacy api', () async { @@ -396,10 +325,7 @@ void main() { await testLegacyApiValueChange(key, expectedValue); - expect( - (await SharedPreferences.getInstance()).getStringList(key), - equals(expectedValue), - ); + expect((await SharedPreferences.getInstance()).getStringList(key), equals(expectedValue)); }); }); }); diff --git a/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart index f4ce136f5f7a..46973a408ee7 100755 --- a/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart @@ -70,26 +70,11 @@ void main() { preferences.setStringList('List', testList2), ]); expect(store.log, [ - isMethodCall( - 'setValue', - arguments: ['String', 'flutter.String', testString2], - ), - isMethodCall( - 'setValue', - arguments: ['Bool', 'flutter.bool', testBool2], - ), - isMethodCall( - 'setValue', - arguments: ['Int', 'flutter.int', testInt2], - ), - isMethodCall( - 'setValue', - arguments: ['Double', 'flutter.double', testDouble2], - ), - isMethodCall( - 'setValue', - arguments: ['StringList', 'flutter.List', testList2], - ), + isMethodCall('setValue', arguments: ['String', 'flutter.String', testString2]), + isMethodCall('setValue', arguments: ['Bool', 'flutter.bool', testBool2]), + isMethodCall('setValue', arguments: ['Int', 'flutter.int', testInt2]), + isMethodCall('setValue', arguments: ['Double', 'flutter.double', testDouble2]), + isMethodCall('setValue', arguments: ['StringList', 'flutter.List', testList2]), ]); store.log.clear(); @@ -106,11 +91,7 @@ void main() { await preferences.remove(key); expect( store.log, - List.filled( - 1, - isMethodCall('remove', arguments: 'flutter.$key'), - growable: true, - ), + List.filled(1, isMethodCall('remove', arguments: 'flutter.$key'), growable: true), ); }); @@ -164,18 +145,14 @@ void main() { const prefixedKey = 'flutter.$key'; test('test 1', () async { - SharedPreferences.setMockInitialValues({ - prefixedKey: 'my string', - }); + SharedPreferences.setMockInitialValues({prefixedKey: 'my string'}); final SharedPreferences prefs = await SharedPreferences.getInstance(); final String? value = prefs.getString(key); expect(value, 'my string'); }); test('test 2', () async { - SharedPreferences.setMockInitialValues({ - prefixedKey: 'my other string', - }); + SharedPreferences.setMockInitialValues({prefixedKey: 'my other string'}); final SharedPreferences prefs = await SharedPreferences.getInstance(); final String? value = prefs.getString(key); expect(value, 'my other string'); @@ -205,10 +182,8 @@ void main() { test('getInstance always returns the same instance', () async { SharedPreferencesStorePlatform.instance = SlowInitSharedPreferencesStore(); - final Future firstFuture = - SharedPreferences.getInstance(); - final Future secondFuture = - SharedPreferences.getInstance(); + final Future firstFuture = SharedPreferences.getInstance(); + final Future secondFuture = SharedPreferences.getInstance(); expect(identical(await firstFuture, await secondFuture), true); }); @@ -302,30 +277,24 @@ void main() { err = e; } expect(err, isA()); - expect( - err.toString(), - contains("Shared Preferences doesn't yet support the setPrefix method"), - ); + expect(err.toString(), contains("Shared Preferences doesn't yet support the setPrefix method")); }); - test( - 'non-Unimplemented errors pass through withParameters methods correctly', - () async { - final localStore = ThrowingSharedPreferencesStore(); - SharedPreferencesStorePlatform.instance = localStore; - SharedPreferences.resetStatic(); - SharedPreferences.setPrefix(''); - Object? err; - - try { - await SharedPreferences.getInstance(); - } catch (e) { - err = e; - } - expect(err, isA()); - expect(err.toString(), contains('State Error')); - }, - ); + test('non-Unimplemented errors pass through withParameters methods correctly', () async { + final localStore = ThrowingSharedPreferencesStore(); + SharedPreferencesStorePlatform.instance = localStore; + SharedPreferences.resetStatic(); + SharedPreferences.setPrefix(''); + Object? err; + + try { + await SharedPreferences.getInstance(); + } catch (e) { + err = e; + } + expect(err, isA()); + expect(err.toString(), contains('State Error')); + }); } class FakeSharedPreferencesStore extends SharedPreferencesStorePlatform { @@ -354,9 +323,7 @@ class FakeSharedPreferencesStore extends SharedPreferencesStorePlatform { } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) { + Future> getAllWithParameters(GetAllParameters parameters) { log.add(const MethodCall('getAllWithParameters')); return backend.getAllWithParameters(parameters); } @@ -374,8 +341,7 @@ class FakeSharedPreferencesStore extends SharedPreferencesStorePlatform { } } -class UnimplementedSharedPreferencesStore - extends SharedPreferencesStorePlatform { +class UnimplementedSharedPreferencesStore extends SharedPreferencesStorePlatform { @override Future clear() { throw UnimplementedError(); @@ -397,8 +363,7 @@ class UnimplementedSharedPreferencesStore } } -class SlowInitSharedPreferencesStore - extends UnimplementedSharedPreferencesStore { +class SlowInitSharedPreferencesStore extends UnimplementedSharedPreferencesStore { @override Future> getAll() async { await Future.delayed(const Duration(seconds: 1)); @@ -428,9 +393,7 @@ class ThrowingSharedPreferencesStore extends SharedPreferencesStorePlatform { } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) { + Future> getAllWithParameters(GetAllParameters parameters) { throw StateError('State Error'); } } diff --git a/packages/shared_preferences/shared_preferences/tool/pre_publish.dart b/packages/shared_preferences/shared_preferences/tool/pre_publish.dart index fb6ee3d81bf7..297f3684c282 100644 --- a/packages/shared_preferences/shared_preferences/tool/pre_publish.dart +++ b/packages/shared_preferences/shared_preferences/tool/pre_publish.dart @@ -20,10 +20,7 @@ Future _runCommand({ final ProcessResult pubGetResult = await Process.run( executable, arguments, - workingDirectory: p.join( - sharedPreferencesToolParent.path, - 'shared_preferences_tool', - ), + workingDirectory: p.join(sharedPreferencesToolParent.path, 'shared_preferences_tool'), ); stdout.write(pubGetResult.stdout); diff --git a/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart index c7a7406f7257..16f451273384 100644 --- a/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart @@ -52,9 +52,7 @@ void main() { }); tearDown(() async { - await preferences.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await preferences.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); }); testWidgets('reading', (WidgetTester _) async { @@ -73,56 +71,20 @@ void main() { await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); await preferences.setValue('Double', 'Double', allTestValues['Double']!); - await preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ); - await preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ); - await preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ); - await preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ); - await preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ); + await preferences.setValue('StringList', 'StringList', allTestValues['StringList']!); + await preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!); + await preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); + await preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!); + await preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ); - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -132,47 +94,19 @@ void main() { testWidgets('getAllWithPrefix', (WidgetTester _) async { await Future.wait(>[ - preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ), - preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ), + preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!), + preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!), preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!), - preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ), + preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!), preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -192,51 +126,19 @@ void main() { group('withPrefix', () { testWidgets('clearWithPrefix', (WidgetTester _) async { await Future.wait(>[ - preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ), - preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ), - preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ), - preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ), + preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!), + preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!), + preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!), + preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!), preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -259,10 +161,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { @@ -271,31 +170,11 @@ void main() { preferences.setValue('Bool', 'Bool', allTestValues['Bool']!), preferences.setValue('Int', 'Int', allTestValues['Int']!), preferences.setValue('Double', 'Double', allTestValues['Double']!), - preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('StringList', 'StringList', allTestValues['StringList']!), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -314,10 +193,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { @@ -326,31 +202,11 @@ void main() { preferences.setValue('Bool', 'Bool', allTestValues['Bool']!), preferences.setValue('Int', 'Int', allTestValues['Int']!), preferences.setValue('Double', 'Double', allTestValues['Double']!), - preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('StringList', 'StringList', allTestValues['StringList']!), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -391,10 +247,7 @@ void main() { await addData(); final Map values = await preferences.getAllWithParameters( GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.String'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.String'}), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); @@ -450,12 +303,7 @@ void main() { ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', - allowList: { - 'prefix.Double', - 'prefix.Int', - 'prefix.Bool', - 'prefix.String', - }, + allowList: {'prefix.Double', 'prefix.Int', 'prefix.Bool', 'prefix.String'}, ), ), ); @@ -479,9 +327,7 @@ void main() { testWidgets('clearWithNoPrefix', (WidgetTester _) async { await addData(); - await preferences.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await preferences.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); final Map values = await preferences.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), ); @@ -498,26 +344,10 @@ void main() { }); testWidgets('getAll', (WidgetTester _) async { - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -533,23 +363,11 @@ void main() { testWidgets('remove', (WidgetTester _) async { const key = 'testKey'; - await preferences.setValue( - 'String', - key, - allTestValues['flutter.String']!, - ); + await preferences.setValue('String', key, allTestValues['flutter.String']!); await preferences.setValue('Bool', key, allTestValues['flutter.Bool']!); await preferences.setValue('Int', key, allTestValues['flutter.Int']!); - await preferences.setValue( - 'Double', - key, - allTestValues['flutter.Double']!, - ); - await preferences.setValue( - 'StringList', - key, - allTestValues['flutter.StringList']!, - ); + await preferences.setValue('Double', key, allTestValues['flutter.Double']!); + await preferences.setValue('StringList', key, allTestValues['flutter.StringList']!); await preferences.remove(key); final Map values = await preferences.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), @@ -558,26 +376,10 @@ void main() { }); testWidgets('clear', (WidgetTester _) async { - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -611,9 +413,7 @@ void main() { testWidgets('string clash with lists and doubles', (WidgetTester _) async { const key = 'aKey'; const value = 'a string value'; - await preferences.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await preferences.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); // Special prefixes used to store datatypes that can't be stored directly // in SharedPreferences as strings instead. @@ -628,10 +428,9 @@ void main() { preferences.setValue('String', key, prefix + value), throwsA(isA()), ); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values[key], null); } }); @@ -642,32 +441,19 @@ void main() { await preferences.clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: '')), ); - await preferences.setValue( - 'String', - 'String', - allTestValues['String']!, - ); + await preferences.setValue('String', 'String', allTestValues['String']!); await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); - await preferences.setValue( - 'Double', - 'Double', - allTestValues['Double']!, + await preferences.setValue('Double', 'Double', allTestValues['Double']!); + await (preferences as SharedPreferencesAndroid).api.setDeprecatedStringList( + 'StringList', + allTestValues['StringList']! as List, ); - await (preferences as SharedPreferencesAndroid).api - .setDeprecatedStringList( - 'StringList', - allTestValues['StringList']! as List, - ); Map prefs = await preferences.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), ); expect(prefs['StringList'], allTestValues['StringList']); - await preferences.setValue( - 'StringList', - 'StringList', - prefs['StringList']!, - ); + await preferences.setValue('StringList', 'StringList', prefs['StringList']!); prefs = await preferences.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), ); @@ -689,10 +475,7 @@ void main() { const testDouble = 3.14159; const testList = ['foo', 'bar']; - SharedPreferencesAsyncAndroidOptions getOptions({ - required bool useDataStore, - String? fileName, - }) { + SharedPreferencesAsyncAndroidOptions getOptions({required bool useDataStore, String? fileName}) { return SharedPreferencesAsyncAndroidOptions( backend: useDataStore ? SharedPreferencesAndroidBackendLibrary.DataStore @@ -714,8 +497,7 @@ void main() { } SharedPreferencesAsyncPlatform getPreferences() { - final SharedPreferencesAsyncPlatform preferences = - SharedPreferencesAsyncPlatform.instance!; + final SharedPreferencesAsyncPlatform preferences = SharedPreferencesAsyncPlatform.instance!; return preferences; } @@ -771,9 +553,7 @@ void main() { expect(await preferences.getDouble(doubleKey, options), testDouble); }); - testWidgets('set and get StringList with $backend', ( - WidgetTester _, - ) async { + testWidgets('set and get StringList with $backend', (WidgetTester _) async { final SharedPreferencesAsyncAndroidOptions options = getOptions( useDataStore: useDataStore, fileName: 'notDefault', @@ -785,9 +565,7 @@ void main() { expect(await preferences.getStringList(listKey, options), testList); }); - testWidgets('getStringList returns mutable list with $backend', ( - WidgetTester _, - ) async { + testWidgets('getStringList returns mutable list with $backend', (WidgetTester _) async { final SharedPreferencesAsyncAndroidOptions options = getOptions( useDataStore: useDataStore, fileName: 'notDefault', @@ -796,10 +574,7 @@ void main() { await clearPreferences(preferences, options); await preferences.setStringList(listKey, testList, options); - final List? list = await preferences.getStringList( - listKey, - options, - ); + final List? list = await preferences.getStringList(listKey, options); list?.add('value'); expect(list?.length, testList.length + 1); }); @@ -819,10 +594,7 @@ void main() { // Internally, List is stored as a String on Android, but that // implementation detail shouldn't leak to clients; getting the wrong // type should still throw. - expect( - preferences.getStringList(listKey, options), - throwsA(isA()), - ); + expect(preferences.getStringList(listKey, options), throwsA(isA())); }); testWidgets('getPreferences with $backend', (WidgetTester _) async { @@ -853,9 +625,7 @@ void main() { expect(gotAll[listKey], testList); }); - testWidgets('getPreferences with filter with $backend', ( - WidgetTester _, - ) async { + testWidgets('getPreferences with filter with $backend', (WidgetTester _) async { final SharedPreferencesAsyncAndroidOptions options = getOptions( useDataStore: useDataStore, fileName: 'notDefault', @@ -1002,51 +772,44 @@ void main() { await clearPreferences(preferences, options); final SharedPreferencesPigeonOptions pigeonOptions = preferences .convertOptionsToPigeonOptions(options); - final SharedPreferencesAsyncApi api = preferences.getApiForBackend( - pigeonOptions, - ); + final SharedPreferencesAsyncApi api = preferences.getApiForBackend(pigeonOptions); await api.setDeprecatedStringList(listKey, testList, pigeonOptions); - final List? platformEncodedList = await preferences - .getStringList(listKey, options); - expect(platformEncodedList, testList); - await preferences.setStringList( + final List? platformEncodedList = await preferences.getStringList( listKey, - platformEncodedList!, options, ); + expect(platformEncodedList, testList); + await preferences.setStringList(listKey, platformEncodedList!, options); expect(await preferences.getStringList(listKey, options), testList); }, ); - testWidgets( - 'platform list encoding still functions with getPreferences with $backend', - (WidgetTester _) async { - final SharedPreferencesAsyncAndroidOptions options = getOptions( - useDataStore: useDataStore, - fileName: 'notDefault', - ); - final preferences = getPreferences() as SharedPreferencesAsyncAndroid; - await clearPreferences(preferences, options); - await Future.wait(>[ - preferences.setString(stringKey, testString, options), - preferences.setBool(boolKey, testBool, options), - preferences.setInt(intKey, testInt, options), - preferences.setDouble(doubleKey, testDouble, options), - ]); - final SharedPreferencesPigeonOptions pigeonOptions = preferences - .convertOptionsToPigeonOptions(options); - final SharedPreferencesAsyncApi api = preferences.getApiForBackend( - pigeonOptions, - ); - await api.setDeprecatedStringList(listKey, testList, pigeonOptions); + testWidgets('platform list encoding still functions with getPreferences with $backend', ( + WidgetTester _, + ) async { + final SharedPreferencesAsyncAndroidOptions options = getOptions( + useDataStore: useDataStore, + fileName: 'notDefault', + ); + final preferences = getPreferences() as SharedPreferencesAsyncAndroid; + await clearPreferences(preferences, options); + await Future.wait(>[ + preferences.setString(stringKey, testString, options), + preferences.setBool(boolKey, testBool, options), + preferences.setInt(intKey, testInt, options), + preferences.setDouble(doubleKey, testDouble, options), + ]); + final SharedPreferencesPigeonOptions pigeonOptions = preferences + .convertOptionsToPigeonOptions(options); + final SharedPreferencesAsyncApi api = preferences.getApiForBackend(pigeonOptions); + await api.setDeprecatedStringList(listKey, testList, pigeonOptions); - final Map prefs = await preferences.getPreferences( - const GetPreferencesParameters(filter: PreferencesFilters()), - options, - ); - expect(prefs[listKey], testList); - }, - ); + final Map prefs = await preferences.getPreferences( + const GetPreferencesParameters(filter: PreferencesFilters()), + options, + ); + expect(prefs[listKey], testList); + }); testWidgets( 'platform list encoding with getPreferences can be re-added with new encoding without data loss with $backend', @@ -1065,9 +828,7 @@ void main() { ]); final SharedPreferencesPigeonOptions pigeonOptions = preferences .convertOptionsToPigeonOptions(options); - final SharedPreferencesAsyncApi api = preferences.getApiForBackend( - pigeonOptions, - ); + final SharedPreferencesAsyncApi api = preferences.getApiForBackend(pigeonOptions); await api.setDeprecatedStringList(listKey, testList, pigeonOptions); final Map prefs = await preferences.getPreferences( @@ -1088,9 +849,7 @@ void main() { runAsyncTests(true); runAsyncTests(false); - testWidgets('Shared Preferences works with multiple files', ( - WidgetTester _, - ) async { + testWidgets('Shared Preferences works with multiple files', (WidgetTester _) async { final SharedPreferencesAsyncAndroidOptions options1 = getOptions( useDataStore: false, fileName: 'file1', @@ -1109,37 +868,20 @@ void main() { expect(await preferences.getInt(intKey, options2), 2); }); - testWidgets('Shared Preferences can read default sharedPreferences', ( - WidgetTester _, - ) async { - final SharedPreferencesAsyncAndroidOptions options = getOptions( - useDataStore: false, - ); + testWidgets('Shared Preferences can read default sharedPreferences', (WidgetTester _) async { + final SharedPreferencesAsyncAndroidOptions options = getOptions(useDataStore: false); final SharedPreferencesAsyncPlatform preferences = getPreferences(); expect( - await preferences.getString( - 'thisStringIsWrittenInTheExampleAppJavaCode', - options, - ), + await preferences.getString('thisStringIsWrittenInTheExampleAppJavaCode', options), 'testString', ); }); - testWidgets('Shared Preferences can read ints by conversion to long', ( - WidgetTester _, - ) async { - final SharedPreferencesAsyncAndroidOptions options = getOptions( - useDataStore: false, - ); + testWidgets('Shared Preferences can read ints by conversion to long', (WidgetTester _) async { + final SharedPreferencesAsyncAndroidOptions options = getOptions(useDataStore: false); final SharedPreferencesAsyncPlatform preferences = getPreferences(); - expect( - await preferences.getInt( - 'thisIntIsWrittenInTheExampleAppJavaCode', - options, - ), - 5, - ); + expect(await preferences.getInt('thisIntIsWrittenInTheExampleAppJavaCode', options), 5); }); } diff --git a/packages/shared_preferences/shared_preferences_android/example/lib/main.dart b/packages/shared_preferences/shared_preferences_android/example/lib/main.dart index 6003ba8c62a5..d5768d978147 100644 --- a/packages/shared_preferences/shared_preferences_android/example/lib/main.dart +++ b/packages/shared_preferences/shared_preferences_android/example/lib/main.dart @@ -13,13 +13,13 @@ void main() { } // #docregion Android_Options -const SharedPreferencesAsyncAndroidOptions options = - SharedPreferencesAsyncAndroidOptions( - backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, - originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions( - fileName: 'the_name_of_a_file', - ), - ); +const SharedPreferencesAsyncAndroidOptions options = SharedPreferencesAsyncAndroidOptions( + backend: SharedPreferencesAndroidBackendLibrary.SharedPreferences, + originalSharedPreferencesOptions: AndroidSharedPreferencesStoreOptions( + fileName: 'the_name_of_a_file', + ), +); + // #enddocregion Android_Options class MyApp extends StatelessWidget { @@ -27,10 +27,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'SharedPreferences Demo', - home: SharedPreferencesDemo(), - ); + return const MaterialApp(title: 'SharedPreferences Demo', home: SharedPreferencesDemo()); } } @@ -42,10 +39,8 @@ class SharedPreferencesDemo extends StatefulWidget { } class SharedPreferencesDemoState extends State { - final SharedPreferencesAsyncPlatform _prefs = - SharedPreferencesAsyncPlatform.instance!; - final SharedPreferencesAsyncAndroidOptions options = - const SharedPreferencesAsyncAndroidOptions(); + final SharedPreferencesAsyncPlatform _prefs = SharedPreferencesAsyncPlatform.instance!; + final SharedPreferencesAsyncAndroidOptions options = const SharedPreferencesAsyncAndroidOptions(); static const String _counterKey = 'counter'; late Future _counter; diff --git a/packages/shared_preferences/shared_preferences_android/lib/src/messages.g.dart b/packages/shared_preferences/shared_preferences_android/lib/src/messages.g.dart index 49456e114ecf..1c9816d7e541 100644 --- a/packages/shared_preferences/shared_preferences_android/lib/src/messages.g.dart +++ b/packages/shared_preferences/shared_preferences_android/lib/src/messages.g.dart @@ -43,13 +43,11 @@ class SharedPreferencesApi { /// Constructor for [SharedPreferencesApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - SharedPreferencesApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + SharedPreferencesApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -60,17 +58,13 @@ class SharedPreferencesApi { Future remove(String key) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.remove$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -93,17 +87,13 @@ class SharedPreferencesApi { Future setBool(String key, bool value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.setBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -126,17 +116,13 @@ class SharedPreferencesApi { Future setString(String key, String value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.setString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -159,17 +145,13 @@ class SharedPreferencesApi { Future setInt(String key, int value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.setInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -192,17 +174,13 @@ class SharedPreferencesApi { Future setDouble(String key, double value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.setDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -225,17 +203,13 @@ class SharedPreferencesApi { Future setEncodedStringList(String key, String value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.setEncodedStringList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -260,17 +234,13 @@ class SharedPreferencesApi { Future setDeprecatedStringList(String key, List value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.setDeprecatedStringList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -293,17 +263,16 @@ class SharedPreferencesApi { Future clear(String prefix, List? allowList) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.clear$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [prefix, allowList], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + prefix, + allowList, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -323,23 +292,19 @@ class SharedPreferencesApi { } /// Gets all properties from shared preferences data set with matching prefix. - Future> getAll( - String prefix, - List? allowList, - ) async { + Future> getAll(String prefix, List? allowList) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesApi.getAll$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [prefix, allowList], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + prefix, + allowList, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -354,8 +319,7 @@ class SharedPreferencesApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as Map?)! - .cast(); + return (pigeonVar_replyList[0] as Map?)!.cast(); } } } diff --git a/packages/shared_preferences/shared_preferences_android/lib/src/messages_async.g.dart b/packages/shared_preferences/shared_preferences_android/lib/src/messages_async.g.dart index 72cbe74b95d4..f556d5d145e5 100644 --- a/packages/shared_preferences/shared_preferences_android/lib/src/messages_async.g.dart +++ b/packages/shared_preferences/shared_preferences_android/lib/src/messages_async.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -74,8 +72,7 @@ class SharedPreferencesPigeonOptions { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SharedPreferencesPigeonOptions || - other.runtimeType != runtimeType) { + if (other is! SharedPreferencesPigeonOptions || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -172,13 +169,11 @@ class SharedPreferencesAsyncApi { /// Constructor for [SharedPreferencesAsyncApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - SharedPreferencesAsyncApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + SharedPreferencesAsyncApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -186,24 +181,20 @@ class SharedPreferencesAsyncApi { final String pigeonVar_messageChannelSuffix; /// Adds property to shared preferences data set of type bool. - Future setBool( - String key, - bool value, - SharedPreferencesPigeonOptions options, - ) async { + Future setBool(String key, bool value, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.setBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + key, + value, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -218,24 +209,20 @@ class SharedPreferencesAsyncApi { } /// Adds property to shared preferences data set of type String. - Future setString( - String key, - String value, - SharedPreferencesPigeonOptions options, - ) async { + Future setString(String key, String value, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.setString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + key, + value, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -250,24 +237,20 @@ class SharedPreferencesAsyncApi { } /// Adds property to shared preferences data set of type int. - Future setInt( - String key, - int value, - SharedPreferencesPigeonOptions options, - ) async { + Future setInt(String key, int value, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.setInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + key, + value, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -282,24 +265,20 @@ class SharedPreferencesAsyncApi { } /// Adds property to shared preferences data set of type double. - Future setDouble( - String key, - double value, - SharedPreferencesPigeonOptions options, - ) async { + Future setDouble(String key, double value, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.setDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + key, + value, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -321,17 +300,17 @@ class SharedPreferencesAsyncApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.setEncodedStringList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + key, + value, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -355,17 +334,17 @@ class SharedPreferencesAsyncApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.setDeprecatedStringList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + key, + value, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -380,23 +359,16 @@ class SharedPreferencesAsyncApi { } /// Gets individual String value stored with [key], if any. - Future getString( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getString(String key, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -411,23 +383,16 @@ class SharedPreferencesAsyncApi { } /// Gets individual void value stored with [key], if any. - Future getBool( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getBool(String key, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -442,23 +407,16 @@ class SharedPreferencesAsyncApi { } /// Gets individual double value stored with [key], if any. - Future getDouble( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getDouble(String key, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -473,23 +431,16 @@ class SharedPreferencesAsyncApi { } /// Gets individual int value stored with [key], if any. - Future getInt( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getInt(String key, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -510,17 +461,13 @@ class SharedPreferencesAsyncApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getPlatformEncodedStringList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -541,17 +488,13 @@ class SharedPreferencesAsyncApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getStringList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -566,23 +509,19 @@ class SharedPreferencesAsyncApi { } /// Removes all properties from shared preferences data set with matching prefix. - Future clear( - List? allowList, - SharedPreferencesPigeonOptions options, - ) async { + Future clear(List? allowList, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.clear$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [allowList, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + allowList, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -603,17 +542,16 @@ class SharedPreferencesAsyncApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getAll$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [allowList, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + allowList, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -628,8 +566,7 @@ class SharedPreferencesAsyncApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as Map?)! - .cast(); + return (pigeonVar_replyList[0] as Map?)!.cast(); } } @@ -640,17 +577,16 @@ class SharedPreferencesAsyncApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_android.SharedPreferencesAsyncApi.getKeys$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [allowList, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + allowList, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_android.dart b/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_android.dart index cc4c96bb2d6d..0ffef358d541 100644 --- a/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_android.dart +++ b/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_android.dart @@ -51,10 +51,7 @@ class SharedPreferencesAndroid extends SharedPreferencesStorePlatform { case 'Double': return api.setDouble(key, value as double); case 'StringList': - return api.setEncodedStringList( - key, - '$jsonListPrefix${jsonEncode(value)}', - ); + return api.setEncodedStringList(key, '$jsonListPrefix${jsonEncode(value)}'); } // TODO(tarrinneal): change to ArgumentError across all platforms. throw PlatformException( @@ -65,16 +62,12 @@ class SharedPreferencesAndroid extends SharedPreferencesStorePlatform { @override Future clear() async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix))); } @override Future clearWithPrefix(String prefix) async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override @@ -92,28 +85,18 @@ class SharedPreferencesAndroid extends SharedPreferencesStorePlatform { @override Future> getAllWithPrefix(String prefix) async { - return getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return getAllWithParameters(GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) async { + Future> getAllWithParameters(GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; - final Map data = await api.getAll( - filter.prefix, - filter.allowList?.toList(), - ); + final Map data = await api.getAll(filter.prefix, filter.allowList?.toList()); data.forEach((String? key, Object? value) { - if (value.runtimeType == String && - (value! as String).startsWith(jsonListPrefix)) { - data[key!] = - (jsonDecode((value as String).substring(jsonListPrefix.length)) - as List) - .cast() - .toList(); + if (value.runtimeType == String && (value! as String).startsWith(jsonListPrefix)) { + data[key!] = (jsonDecode( + (value as String).substring(jsonListPrefix.length), + ) as List).cast().toList(); } }); return data.cast(); diff --git a/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_async_android.dart b/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_async_android.dart index 866b33f3d832..eab47d35110e 100644 --- a/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_async_android.dart +++ b/packages/shared_preferences/shared_preferences_android/lib/src/shared_preferences_async_android.dart @@ -17,20 +17,16 @@ const String _listPrefix = 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu'; /// The Android implementation of [SharedPreferencesAsyncPlatform]. /// /// This class implements the `package:shared_preferences` functionality for Android. -base class SharedPreferencesAsyncAndroid - extends SharedPreferencesAsyncPlatform { +base class SharedPreferencesAsyncAndroid extends SharedPreferencesAsyncPlatform { /// Creates a new plugin implementation instance. SharedPreferencesAsyncAndroid({ @visibleForTesting SharedPreferencesAsyncApi? dataStoreApi, @visibleForTesting SharedPreferencesAsyncApi? sharedPreferencesApi, }) : _dataStoreApi = - dataStoreApi ?? - SharedPreferencesAsyncApi(messageChannelSuffix: 'data_store'), + dataStoreApi ?? SharedPreferencesAsyncApi(messageChannelSuffix: 'data_store'), _sharedPreferencesApi = sharedPreferencesApi ?? - SharedPreferencesAsyncApi( - messageChannelSuffix: 'shared_preferences', - ); + SharedPreferencesAsyncApi(messageChannelSuffix: 'shared_preferences'); final SharedPreferencesAsyncApi _dataStoreApi; final SharedPreferencesAsyncApi _sharedPreferencesApi; @@ -42,14 +38,11 @@ base class SharedPreferencesAsyncAndroid /// Returns a SharedPreferencesPigeonOptions for sending to platform. @visibleForTesting - SharedPreferencesPigeonOptions convertOptionsToPigeonOptions( - SharedPreferencesOptions options, - ) { + SharedPreferencesPigeonOptions convertOptionsToPigeonOptions(SharedPreferencesOptions options) { if (options is SharedPreferencesAsyncAndroidOptions) { return SharedPreferencesPigeonOptions( fileName: options.originalSharedPreferencesOptions?.fileName, - useDataStore: - options.backend == SharedPreferencesAndroidBackendLibrary.DataStore, + useDataStore: options.backend == SharedPreferencesAndroidBackendLibrary.DataStore, ); } return SharedPreferencesPigeonOptions(); @@ -58,9 +51,7 @@ base class SharedPreferencesAsyncAndroid /// Provides the backend (SharedPreferences or DataStore) required based on /// the passed in [SharedPreferencesPigeonOptions]. @visibleForTesting - SharedPreferencesAsyncApi getApiForBackend( - SharedPreferencesPigeonOptions options, - ) { + SharedPreferencesAsyncApi getApiForBackend(SharedPreferencesPigeonOptions options) { return options.useDataStore ? _dataStoreApi : _sharedPreferencesApi; } @@ -70,65 +61,41 @@ base class SharedPreferencesAsyncAndroid SharedPreferencesOptions options, ) async { final PreferencesFilters filter = parameters.filter; - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); - return (await api.getKeys( - filter.allowList?.toList(), - pigeonOptions, - )).toSet(); + return (await api.getKeys(filter.allowList?.toList(), pigeonOptions)).toSet(); } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) async { + Future setString(String key, String value, SharedPreferencesOptions options) async { if (value.startsWith(_listPrefix)) { throw ArgumentError( 'StorageError: This string cannot be stored as it clashes with special identifier prefixes', ); } - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); return api.setString(key, value, pigeonOptions); } @override - Future setInt( - String key, - int value, - SharedPreferencesOptions options, - ) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + Future setInt(String key, int value, SharedPreferencesOptions options) async { + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); return api.setInt(key, value, pigeonOptions); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + Future setDouble(String key, double value, SharedPreferencesOptions options) async { + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); return api.setDouble(key, value, pigeonOptions); } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + Future setBool(String key, bool value, SharedPreferencesOptions options) async { + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); return api.setBool(key, value, pigeonOptions); } @@ -139,72 +106,48 @@ base class SharedPreferencesAsyncAndroid List value, SharedPreferencesOptions options, ) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); final stringValue = '$jsonListPrefix${jsonEncode(value)}'; return api.setString(key, stringValue, pigeonOptions); } @override - Future getString( - String key, - SharedPreferencesOptions options, - ) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + Future getString(String key, SharedPreferencesOptions options) async { + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); - return _convertKnownExceptions( - () async => api.getString(key, pigeonOptions), - ); + return _convertKnownExceptions(() async => api.getString(key, pigeonOptions)); } @override Future getBool(String key, SharedPreferencesOptions options) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); - return _convertKnownExceptions( - () async => api.getBool(key, pigeonOptions), - ); + return _convertKnownExceptions(() async => api.getBool(key, pigeonOptions)); } @override - Future getDouble( - String key, - SharedPreferencesOptions options, - ) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + Future getDouble(String key, SharedPreferencesOptions options) async { + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); - return _convertKnownExceptions( - () async => api.getDouble(key, pigeonOptions), - ); + return _convertKnownExceptions(() async => api.getDouble(key, pigeonOptions)); } @override Future getInt(String key, SharedPreferencesOptions options) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); - return _convertKnownExceptions( - () async => api.getInt(key, pigeonOptions), - ); + return _convertKnownExceptions(() async => api.getInt(key, pigeonOptions)); } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) async { - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + Future?> getStringList(String key, SharedPreferencesOptions options) async { + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); // Request JSON encoded string list. - final StringListResult? result = - await _convertKnownExceptions( - () async => api.getStringList(key, pigeonOptions), - ); + final StringListResult? result = await _convertKnownExceptions( + () async => api.getStringList(key, pigeonOptions), + ); if (result == null) { return null; } @@ -212,21 +155,18 @@ base class SharedPreferencesAsyncAndroid case StringListLookupResultType.jsonEncoded: // Force-unwrap is safe because a value is always set for this type. final String jsonEncodedStringList = result.jsonEncodedValue!; - final String jsonEncodedString = jsonEncodedStringList.substring( - jsonListPrefix.length, - ); + final String jsonEncodedString = jsonEncodedStringList.substring(jsonListPrefix.length); try { - final List decodedList = - (jsonDecode(jsonEncodedString) as List).cast(); + final List decodedList = (jsonDecode(jsonEncodedString) as List) + .cast(); return decodedList; } catch (e) { throw TypeError(); } case StringListLookupResultType.platformEncoded: - final List? stringList = - await _convertKnownExceptions?>( - () async => api.getPlatformEncodedStringList(key, pigeonOptions), - ); + final List? stringList = await _convertKnownExceptions?>( + () async => api.getPlatformEncodedStringList(key, pigeonOptions), + ); return stringList?.cast().toList(); case StringListLookupResultType.unexpectedString: throw TypeError(); @@ -252,8 +192,7 @@ base class SharedPreferencesAsyncAndroid SharedPreferencesOptions options, ) async { final PreferencesFilters filter = parameters.filter; - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); return api.clear(filter.allowList?.toList(), pigeonOptions); } @@ -264,19 +203,13 @@ base class SharedPreferencesAsyncAndroid SharedPreferencesOptions options, ) async { final PreferencesFilters filter = parameters.filter; - final SharedPreferencesPigeonOptions pigeonOptions = - convertOptionsToPigeonOptions(options); + final SharedPreferencesPigeonOptions pigeonOptions = convertOptionsToPigeonOptions(options); final SharedPreferencesAsyncApi api = getApiForBackend(pigeonOptions); - final Map data = await api.getAll( - filter.allowList?.toList(), - pigeonOptions, - ); + final Map data = await api.getAll(filter.allowList?.toList(), pigeonOptions); data.forEach((String? key, Object? value) { if (value is String && value.startsWith(jsonListPrefix)) { - data[key!] = - (jsonDecode(value.substring(jsonListPrefix.length)) - as List) - .cast(); + data[key!] = (jsonDecode(value.substring(jsonListPrefix.length)) as List) + .cast(); } }); return data.cast(); diff --git a/packages/shared_preferences/shared_preferences_android/pigeons/messages.dart b/packages/shared_preferences/shared_preferences_android/pigeons/messages.dart index 282e1b547aab..bed24f747e54 100644 --- a/packages/shared_preferences/shared_preferences_android/pigeons/messages.dart +++ b/packages/shared_preferences/shared_preferences_android/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( input: 'pigeons/messages.dart', - javaOut: - 'android/src/main/java/io/flutter/plugins/sharedpreferences/Messages.java', + javaOut: 'android/src/main/java/io/flutter/plugins/sharedpreferences/Messages.java', javaOptions: JavaOptions( className: 'Messages', package: 'io.flutter.plugins.sharedpreferences', diff --git a/packages/shared_preferences/shared_preferences_android/pigeons/messages_async.dart b/packages/shared_preferences/shared_preferences_android/pigeons/messages_async.dart index a0b0ec0b8ed1..d8e89de3f902 100644 --- a/packages/shared_preferences/shared_preferences_android/pigeons/messages_async.dart +++ b/packages/shared_preferences/shared_preferences_android/pigeons/messages_async.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( input: 'pigeons/messages_async.dart', - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/sharedpreferences/MessagesAsync.g.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/sharedpreferences/MessagesAsync.g.kt', kotlinOptions: KotlinOptions( package: 'io.flutter.plugins.sharedpreferences', errorClassName: 'SharedPreferencesError', @@ -56,11 +55,7 @@ abstract class SharedPreferencesAsyncApi { /// Adds property to shared preferences data set of type `String`. @TaskQueue(type: TaskQueueType.serialBackgroundThread) - void setString( - String key, - String value, - SharedPreferencesPigeonOptions options, - ); + void setString(String key, String value, SharedPreferencesPigeonOptions options); /// Adds property to shared preferences data set of type `int`. @TaskQueue(type: TaskQueueType.serialBackgroundThread) @@ -68,19 +63,11 @@ abstract class SharedPreferencesAsyncApi { /// Adds property to shared preferences data set of type `double`. @TaskQueue(type: TaskQueueType.serialBackgroundThread) - void setDouble( - String key, - double value, - SharedPreferencesPigeonOptions options, - ); + void setDouble(String key, double value, SharedPreferencesPigeonOptions options); /// Adds property to shared preferences data set of type `List`. @TaskQueue(type: TaskQueueType.serialBackgroundThread) - void setEncodedStringList( - String key, - String value, - SharedPreferencesPigeonOptions options, - ); + void setEncodedStringList(String key, String value, SharedPreferencesPigeonOptions options); /// Adds property to shared preferences data set of type `List`. /// @@ -110,17 +97,11 @@ abstract class SharedPreferencesAsyncApi { /// Gets individual `List` value stored with [key], if any. @TaskQueue(type: TaskQueueType.serialBackgroundThread) - List? getPlatformEncodedStringList( - String key, - SharedPreferencesPigeonOptions options, - ); + List? getPlatformEncodedStringList(String key, SharedPreferencesPigeonOptions options); /// Gets the JSON-encoded `List` value stored with [key], if any. @TaskQueue(type: TaskQueueType.serialBackgroundThread) - StringListResult? getStringList( - String key, - SharedPreferencesPigeonOptions options, - ); + StringListResult? getStringList(String key, SharedPreferencesPigeonOptions options); /// Removes all properties from shared preferences data set with matching prefix. @TaskQueue(type: TaskQueueType.serialBackgroundThread) @@ -128,15 +109,9 @@ abstract class SharedPreferencesAsyncApi { /// Gets all properties from shared preferences data set with matching prefix. @TaskQueue(type: TaskQueueType.serialBackgroundThread) - Map getAll( - List? allowList, - SharedPreferencesPigeonOptions options, - ); + Map getAll(List? allowList, SharedPreferencesPigeonOptions options); /// Gets all properties from shared preferences data set with matching prefix. @TaskQueue(type: TaskQueueType.serialBackgroundThread) - List getKeys( - List? allowList, - SharedPreferencesPigeonOptions options, - ); + List getKeys(List? allowList, SharedPreferencesPigeonOptions options); } diff --git a/packages/shared_preferences/shared_preferences_android/test/shared_preferences_android_test.dart b/packages/shared_preferences/shared_preferences_android/test/shared_preferences_android_test.dart index 182cc9297e61..7eacee6f8d15 100644 --- a/packages/shared_preferences/shared_preferences_android/test/shared_preferences_android_test.dart +++ b/packages/shared_preferences/shared_preferences_android/test/shared_preferences_android_test.dart @@ -47,16 +47,11 @@ void main() { allTestValuesForComparison.addAll(prefixTestValues); allTestValuesForComparison.addAll(nonPrefixTestValues); - final allTestValuesForAddingDirectlyToCache = { - ...allTestValuesForComparison, - }; + final allTestValuesForAddingDirectlyToCache = {...allTestValuesForComparison}; - final encodedListStringValue = - '$jsonListPrefix${jsonEncode(['foo', 'bar'])}'; - allTestValuesForAddingDirectlyToCache['flutter.StringList'] = - encodedListStringValue; - allTestValuesForAddingDirectlyToCache['prefix.StringList'] = - encodedListStringValue; + final encodedListStringValue = '$jsonListPrefix${jsonEncode(['foo', 'bar'])}'; + allTestValuesForAddingDirectlyToCache['flutter.StringList'] = encodedListStringValue; + allTestValuesForAddingDirectlyToCache['prefix.StringList'] = encodedListStringValue; allTestValuesForAddingDirectlyToCache['StringList'] = encodedListStringValue; setUp(() { @@ -66,10 +61,7 @@ void main() { test('registerWith', () async { SharedPreferencesAndroid.registerWith(); - expect( - SharedPreferencesStorePlatform.instance, - isA(), - ); + expect(SharedPreferencesStorePlatform.instance, isA()); }); test('remove', () async { @@ -107,9 +99,7 @@ void main() { GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), ); expect(all.length, 5); - await plugin.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + await plugin.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: 'prefix.'))); all = await plugin.getAll(); expect(all.length, 5); all = await plugin.getAllWithParameters( @@ -129,10 +119,7 @@ void main() { expect(all.length, 5); await plugin.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.StringList'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.StringList'}), ), ); all = await plugin.getAll(); @@ -190,10 +177,7 @@ void main() { } final Map all = await plugin.getAllWithParameters( GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.Bool'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.Bool'}), ), ); expect(all.length, 1); @@ -209,14 +193,8 @@ void main() { expect(api.items['flutter.Int'], 12); expect(await plugin.setValue('String', 'flutter.String', 'hi'), isTrue); expect(api.items['flutter.String'], 'hi'); - expect( - await plugin.setValue('StringList', 'flutter.StringList', ['hi']), - isTrue, - ); - expect( - api.items['flutter.StringList'], - '$jsonListPrefix${jsonEncode(['hi'])}', - ); + expect(await plugin.setValue('StringList', 'flutter.StringList', ['hi']), isTrue); + expect(api.items['flutter.StringList'], '$jsonListPrefix${jsonEncode(['hi'])}'); }); test('setValue with unsupported type', () async { @@ -245,9 +223,7 @@ void main() { GetAllParameters(filter: PreferencesFilter(prefix: '')), ); expect(all.length, 15); - await plugin.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await plugin.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); all = await plugin.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), ); @@ -259,28 +235,21 @@ class _FakeSharedPreferencesApi implements SharedPreferencesApi { final Map items = {}; @override - Future> getAll( - String prefix, - List? allowList, - ) async { + Future> getAll(String prefix, List? allowList) async { Set? allowSet; if (allowList != null) { allowSet = Set.from(allowList); } final filteredItems = { for (final String key in items.keys) - if (key.startsWith(prefix) && - (allowSet == null || allowSet.contains(key))) + if (key.startsWith(prefix) && (allowSet == null || allowSet.contains(key))) key: items[key]!, }; filteredItems.forEach((String? key, Object? value) { - if (value.runtimeType == String && - (value! as String).startsWith(jsonListPrefix)) { - filteredItems[key!] = - (jsonDecode((value as String).substring(jsonListPrefix.length)) - as List) - .cast() - .toList(); + if (value.runtimeType == String && (value! as String).startsWith(jsonListPrefix)) { + filteredItems[key!] = (jsonDecode( + (value as String).substring(jsonListPrefix.length), + ) as List).cast().toList(); } }); return filteredItems; @@ -307,8 +276,7 @@ class _FakeSharedPreferencesApi implements SharedPreferencesApi { @override Future clear(String prefix, List? allowList) async { items.keys.toList().forEach((String key) { - if (key.startsWith(prefix) && - (allowList == null || allowList.contains(key))) { + if (key.startsWith(prefix) && (allowList == null || allowList.contains(key))) { items.remove(key); } }); diff --git a/packages/shared_preferences/shared_preferences_android/test/shared_preferences_async_test.dart b/packages/shared_preferences/shared_preferences_android/test/shared_preferences_async_test.dart index d760d5fd6c75..c23049b81b60 100755 --- a/packages/shared_preferences/shared_preferences_android/test/shared_preferences_async_test.dart +++ b/packages/shared_preferences/shared_preferences_android/test/shared_preferences_async_test.dart @@ -30,10 +30,7 @@ void main() { SharedPreferencesAsyncAndroid getPreferences(bool useDataStore) { final api = _FakeSharedPreferencesApi(); - final preferences = SharedPreferencesAsyncAndroid( - dataStoreApi: api, - sharedPreferencesApi: api, - ); + final preferences = SharedPreferencesAsyncAndroid(dataStoreApi: api, sharedPreferencesApi: api); return preferences; } @@ -48,59 +45,44 @@ void main() { ); test('set and get String with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await preferences.setString(stringKey, testString, emptyOptions); expect(await preferences.getString(stringKey, emptyOptions), testString); }); test('set and get bool with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await preferences.setBool(boolKey, testBool, emptyOptions); expect(await preferences.getBool(boolKey, emptyOptions), testBool); }); test('set and get int with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await preferences.setInt(intKey, testInt, emptyOptions); expect(await preferences.getInt(intKey, emptyOptions), testInt); }); test('set and get double with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await preferences.setDouble(doubleKey, testDouble, emptyOptions); expect(await preferences.getDouble(doubleKey, emptyOptions), testDouble); }); test('set and get StringList with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await preferences.setStringList(listKey, testList, emptyOptions); - final List? response = await preferences.getStringList( - listKey, - emptyOptions, - ); + final List? response = await preferences.getStringList(listKey, emptyOptions); expect(response, testList); }); test('getPreferences with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await Future.wait(>[ preferences.setString(stringKey, testString, emptyOptions), preferences.setBool(boolKey, testBool, emptyOptions), @@ -123,9 +105,7 @@ void main() { }); test('getPreferences with filter with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await Future.wait(>[ preferences.setString(stringKey, testString, emptyOptions), preferences.setBool(boolKey, testBool, emptyOptions), @@ -147,9 +127,7 @@ void main() { }); test('getKeys with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await Future.wait(>[ preferences.setString(stringKey, testString, emptyOptions), preferences.setBool(boolKey, testBool, emptyOptions), @@ -172,9 +150,7 @@ void main() { }); test('getKeys with filter with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await Future.wait(>[ preferences.setString(stringKey, testString, emptyOptions), preferences.setBool(boolKey, testBool, emptyOptions), @@ -196,9 +172,7 @@ void main() { }); test('clear with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await Future.wait(>[ preferences.setString(stringKey, testString, emptyOptions), preferences.setBool(boolKey, testBool, emptyOptions), @@ -218,9 +192,7 @@ void main() { }); test('clear with filter with $backend', () async { - final SharedPreferencesAsyncAndroid preferences = getPreferences( - useDataStore, - ); + final SharedPreferencesAsyncAndroid preferences = getPreferences(useDataStore); await Future.wait(>[ preferences.setString(stringKey, testString, emptyOptions), preferences.setBool(boolKey, testBool, emptyOptions), @@ -256,10 +228,7 @@ class _FakeSharedPreferencesApi implements SharedPreferencesAsyncApi { String get pigeonVar_messageChannelSuffix => throw UnimplementedError(); @override - Future clear( - List? allowList, - SharedPreferencesPigeonOptions options, - ) async { + Future clear(List? allowList, SharedPreferencesPigeonOptions options) async { if (allowList != null) { items.removeWhere((String key, _) => allowList.contains(key)); } else { @@ -282,26 +251,17 @@ class _FakeSharedPreferencesApi implements SharedPreferencesAsyncApi { } @override - Future getBool( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getBool(String key, SharedPreferencesPigeonOptions options) async { return items[key] as bool?; } @override - Future getDouble( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getDouble(String key, SharedPreferencesPigeonOptions options) async { return items[key] as double?; } @override - Future getInt( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getInt(String key, SharedPreferencesPigeonOptions options) async { return items[key] as int?; } @@ -318,10 +278,7 @@ class _FakeSharedPreferencesApi implements SharedPreferencesAsyncApi { } @override - Future getString( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getString(String key, SharedPreferencesPigeonOptions options) async { return items[key] as String?; } @@ -348,41 +305,25 @@ class _FakeSharedPreferencesApi implements SharedPreferencesAsyncApi { } @override - Future setBool( - String key, - bool value, - SharedPreferencesPigeonOptions options, - ) async { + Future setBool(String key, bool value, SharedPreferencesPigeonOptions options) async { items[key] = value; return true; } @override - Future setDouble( - String key, - double value, - SharedPreferencesPigeonOptions options, - ) async { + Future setDouble(String key, double value, SharedPreferencesPigeonOptions options) async { items[key] = value; return true; } @override - Future setInt( - String key, - int value, - SharedPreferencesPigeonOptions options, - ) async { + Future setInt(String key, int value, SharedPreferencesPigeonOptions options) async { items[key] = value; return true; } @override - Future setString( - String key, - String value, - SharedPreferencesPigeonOptions options, - ) async { + Future setString(String key, String value, SharedPreferencesPigeonOptions options) async { items[key] = value; return true; } diff --git a/packages/shared_preferences/shared_preferences_foundation/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences_foundation/example/integration_test/shared_preferences_test.dart index f58cf1ded7d2..13f1a0ff911f 100644 --- a/packages/shared_preferences/shared_preferences_foundation/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences_foundation/example/integration_test/shared_preferences_test.dart @@ -50,9 +50,7 @@ void main() { }); tearDown(() async { - await preferences.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await preferences.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); }); group('withPrefix', () { @@ -69,51 +67,19 @@ void main() { testWidgets('getAllWithPrefix', (WidgetTester _) async { await Future.wait(>[ - preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ), - preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ), - preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ), - preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ), + preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!), + preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!), + preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!), + preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!), preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -132,51 +98,19 @@ void main() { testWidgets('clearWithPrefix', (WidgetTester _) async { await Future.wait(>[ - preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ), - preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ), - preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ), - preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ), + preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!), + preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!), + preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!), + preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!), preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -199,10 +133,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { @@ -211,31 +142,11 @@ void main() { preferences.setValue('Bool', 'Bool', allTestValues['Bool']!), preferences.setValue('Int', 'Int', allTestValues['Int']!), preferences.setValue('Double', 'Double', allTestValues['Double']!), - preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('StringList', 'StringList', allTestValues['StringList']!), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -254,10 +165,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { @@ -266,31 +174,11 @@ void main() { preferences.setValue('Bool', 'Bool', allTestValues['Bool']!), preferences.setValue('Int', 'Int', allTestValues['Int']!), preferences.setValue('Double', 'Double', allTestValues['Double']!), - preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ), - preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ), - preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ), - preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ), - preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ), + preferences.setValue('StringList', 'StringList', allTestValues['StringList']!), + preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!), + preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), + preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!), + preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue( 'StringList', 'flutter.StringList', @@ -317,10 +205,9 @@ void main() { group('withParameters', () { testWidgets('reading', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], isNull); expect(values['Bool'], isNull); expect(values['Int'], isNull); @@ -329,68 +216,24 @@ void main() { }); Future addData() async { - await preferences.setValue( - 'String', - 'String', - allTestValues['String']!, - ); + await preferences.setValue('String', 'String', allTestValues['String']!); await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); - await preferences.setValue( - 'Double', - 'Double', - allTestValues['Double']!, - ); - await preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ); - await preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ); - await preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ); - await preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ); - await preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ); + await preferences.setValue('Double', 'Double', allTestValues['Double']!); + await preferences.setValue('StringList', 'StringList', allTestValues['StringList']!); + await preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!); + await preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); + await preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!); + await preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ); - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -400,10 +243,9 @@ void main() { testWidgets('get all with prefix', (WidgetTester _) async { await addData(); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -413,15 +255,11 @@ void main() { testWidgets('get all with allow list', (WidgetTester _) async { await addData(); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.String'}, - ), - ), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters( + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.String'}), + ), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -431,10 +269,9 @@ void main() { testWidgets('getAllWithNoPrefix', (WidgetTester _) async { await addData(); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -444,10 +281,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters', (WidgetTester _) async { @@ -470,22 +304,14 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); - testWidgets('clearWithParameters with allow list', ( - WidgetTester _, - ) async { + testWidgets('clearWithParameters with allow list', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.StringList'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.StringList'}), ), ); Map values = await preferences.getAllWithParameters( @@ -503,10 +329,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { @@ -514,10 +337,9 @@ void main() { await preferences.clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: '')), ); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); @@ -532,26 +354,10 @@ void main() { }); testWidgets('getAll', (WidgetTester _) async { - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -567,23 +373,11 @@ void main() { testWidgets('remove', (WidgetTester _) async { const key = 'testKey'; - await preferences.setValue( - 'String', - key, - allTestValues['flutter.String']!, - ); + await preferences.setValue('String', key, allTestValues['flutter.String']!); await preferences.setValue('Bool', key, allTestValues['flutter.Bool']!); await preferences.setValue('Int', key, allTestValues['flutter.Int']!); - await preferences.setValue( - 'Double', - key, - allTestValues['flutter.Double']!, - ); - await preferences.setValue( - 'StringList', - key, - allTestValues['flutter.StringList']!, - ); + await preferences.setValue('Double', key, allTestValues['flutter.Double']!); + await preferences.setValue('StringList', key, allTestValues['flutter.StringList']!); await preferences.remove(key); final Map values = await preferences.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), @@ -592,26 +386,10 @@ void main() { }); testWidgets('clear', (WidgetTester _) async { - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -662,8 +440,7 @@ void main() { const testList = ['foo', 'bar']; Future getPreferences() async { - final SharedPreferencesAsyncPlatform preferences = - SharedPreferencesAsyncPlatform.instance!; + final SharedPreferencesAsyncPlatform preferences = SharedPreferencesAsyncPlatform.instance!; await preferences.clear( const ClearPreferencesParameters(filter: PreferencesFilters()), emptyOptions, @@ -714,10 +491,7 @@ void main() { final SharedPreferencesAsyncPlatform preferences = await getPreferences(); await preferences.setStringList(listKey, testList, emptyOptions); - final List? list = await preferences.getStringList( - listKey, - emptyOptions, - ); + final List? list = await preferences.getStringList(listKey, emptyOptions); list?.add('value'); expect(list?.length, testList.length + 1); }); @@ -755,17 +529,15 @@ void main() { preferences.setStringList(listKey, testList, optionsWithSuiteName), ]); - final Map preferencesWithEmptyOptions = await preferences - .getPreferences( - const GetPreferencesParameters(filter: PreferencesFilters()), - emptyOptions, - ); - - final Map preferencesWithSuiteName = await preferences - .getPreferences( - const GetPreferencesParameters(filter: PreferencesFilters()), - optionsWithSuiteName, - ); + final Map preferencesWithEmptyOptions = await preferences.getPreferences( + const GetPreferencesParameters(filter: PreferencesFilters()), + emptyOptions, + ); + + final Map preferencesWithSuiteName = await preferences.getPreferences( + const GetPreferencesParameters(filter: PreferencesFilters()), + optionsWithSuiteName, + ); expect(preferencesWithEmptyOptions.length, 2); expect(preferencesWithSuiteName.length, 3); diff --git a/packages/shared_preferences/shared_preferences_foundation/example/lib/main.dart b/packages/shared_preferences/shared_preferences_foundation/example/lib/main.dart index c6aaf8e98936..3ae5cfb50fe7 100644 --- a/packages/shared_preferences/shared_preferences_foundation/example/lib/main.dart +++ b/packages/shared_preferences/shared_preferences_foundation/example/lib/main.dart @@ -17,10 +17,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'SharedPreferences Demo', - home: SharedPreferencesDemo(), - ); + return const MaterialApp(title: 'SharedPreferences Demo', home: SharedPreferencesDemo()); } } @@ -32,10 +29,8 @@ class SharedPreferencesDemo extends StatefulWidget { } class SharedPreferencesDemoState extends State { - final SharedPreferencesAsyncPlatform? _prefs = - SharedPreferencesAsyncPlatform.instance; - SharedPreferencesAsyncFoundationOptions options = - SharedPreferencesAsyncFoundationOptions(); + final SharedPreferencesAsyncPlatform? _prefs = SharedPreferencesAsyncPlatform.instance; + SharedPreferencesAsyncFoundationOptions options = SharedPreferencesAsyncFoundationOptions(); static const String _counterKey = 'counter'; late Future _counter; diff --git a/packages/shared_preferences/shared_preferences_foundation/lib/src/messages.g.dart b/packages/shared_preferences/shared_preferences_foundation/lib/src/messages.g.dart index 2f2c98620604..738e6db5a152 100644 --- a/packages/shared_preferences/shared_preferences_foundation/lib/src/messages.g.dart +++ b/packages/shared_preferences/shared_preferences_foundation/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -57,8 +55,7 @@ class SharedPreferencesPigeonOptions { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! SharedPreferencesPigeonOptions || - other.runtimeType != runtimeType) { + if (other is! SharedPreferencesPigeonOptions || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -102,13 +99,11 @@ class LegacyUserDefaultsApi { /// Constructor for [LegacyUserDefaultsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - LegacyUserDefaultsApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + LegacyUserDefaultsApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -118,17 +113,13 @@ class LegacyUserDefaultsApi { Future remove(String key) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.LegacyUserDefaultsApi.remove$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -145,17 +136,13 @@ class LegacyUserDefaultsApi { Future setBool(String key, bool value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.LegacyUserDefaultsApi.setBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -172,17 +159,13 @@ class LegacyUserDefaultsApi { Future setDouble(String key, double value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.LegacyUserDefaultsApi.setDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -199,17 +182,13 @@ class LegacyUserDefaultsApi { Future setValue(String key, Object value) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.LegacyUserDefaultsApi.setValue$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, value]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -223,23 +202,19 @@ class LegacyUserDefaultsApi { } } - Future> getAll( - String prefix, - List? allowList, - ) async { + Future> getAll(String prefix, List? allowList) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.LegacyUserDefaultsApi.getAll$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [prefix, allowList], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + prefix, + allowList, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -254,25 +229,23 @@ class LegacyUserDefaultsApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as Map?)! - .cast(); + return (pigeonVar_replyList[0] as Map?)!.cast(); } } Future clear(String prefix, List? allowList) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.LegacyUserDefaultsApi.clear$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [prefix, allowList], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + prefix, + allowList, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -296,13 +269,11 @@ class UserDefaultsApi { /// Constructor for [UserDefaultsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UserDefaultsApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + UserDefaultsApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -310,24 +281,20 @@ class UserDefaultsApi { final String pigeonVar_messageChannelSuffix; /// Adds property to shared preferences data set of type String. - Future set( - String key, - Object value, - SharedPreferencesPigeonOptions options, - ) async { + Future set(String key, Object value, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.set$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, value, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + key, + value, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -342,23 +309,19 @@ class UserDefaultsApi { } /// Removes all properties from shared preferences data set with matching prefix. - Future clear( - List? allowList, - SharedPreferencesPigeonOptions options, - ) async { + Future clear(List? allowList, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.clear$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [allowList, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + allowList, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -379,17 +342,16 @@ class UserDefaultsApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getAll$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [allowList, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + allowList, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -404,29 +366,21 @@ class UserDefaultsApi { message: 'Host platform returned null value for non-null return value.', ); } else { - return (pigeonVar_replyList[0] as Map?)! - .cast(); + return (pigeonVar_replyList[0] as Map?)!.cast(); } } /// Gets individual value stored with [key], if any. - Future getValue( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getValue(String key, SharedPreferencesPigeonOptions options) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getValue$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [key, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([key, options]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -447,17 +401,16 @@ class UserDefaultsApi { ) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getKeys$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [allowList, options], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + allowList, + options, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_async_foundation.dart b/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_async_foundation.dart index ea63c70ee409..45bf5e98febc 100644 --- a/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_async_foundation.dart +++ b/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_async_foundation.dart @@ -14,8 +14,7 @@ import './messages.g.dart'; const String _argumentErrorCode = 'Argument Error'; /// iOS and macOS implementation of shared_preferences. -base class SharedPreferencesAsyncFoundation - extends SharedPreferencesAsyncPlatform { +base class SharedPreferencesAsyncFoundation extends SharedPreferencesAsyncPlatform { /// Creates a new plugin implementation instance. SharedPreferencesAsyncFoundation({@visibleForTesting UserDefaultsApi? api}) : _api = api ?? UserDefaultsApi(); @@ -24,14 +23,11 @@ base class SharedPreferencesAsyncFoundation /// Registers this class as the default instance of [SharedPreferencesAsyncPlatform]. static void registerWith() { - SharedPreferencesAsyncPlatform.instance = - SharedPreferencesAsyncFoundation(); + SharedPreferencesAsyncPlatform.instance = SharedPreferencesAsyncFoundation(); } /// Returns a SharedPreferencesPigeonOptions for sending to platform. - SharedPreferencesPigeonOptions _convertOptionsToPigeonOptions( - SharedPreferencesOptions options, - ) { + SharedPreferencesPigeonOptions _convertOptionsToPigeonOptions(SharedPreferencesOptions options) { if (options is SharedPreferencesAsyncFoundationOptions) { final String? suiteName = options.suiteName; return SharedPreferencesPigeonOptions(suiteName: suiteName); @@ -46,38 +42,23 @@ base class SharedPreferencesAsyncFoundation ) async { final PreferencesFilters filter = parameters.filter; return (await _convertKnownExceptions>( - () async => _api.getKeys( - filter.allowList?.toList(), - _convertOptionsToPigeonOptions(options), - ), + () async => _api.getKeys(filter.allowList?.toList(), _convertOptionsToPigeonOptions(options)), ))!.toSet(); } - Future _setValue( - String key, - Object value, - SharedPreferencesOptions options, - ) async { + Future _setValue(String key, Object value, SharedPreferencesOptions options) async { return _convertKnownExceptions( () async => _api.set(key, value, _convertOptionsToPigeonOptions(options)), ); } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) async { + Future setString(String key, String value, SharedPreferencesOptions options) async { await _setValue(key, value, options); } @override - Future setInt( - String key, - int value, - SharedPreferencesOptions options, - ) async { + Future setInt(String key, int value, SharedPreferencesOptions options) async { await _setValue(key, value, options); } @@ -91,76 +72,50 @@ base class SharedPreferencesAsyncFoundation } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) async { + Future setBool(String key, bool value, SharedPreferencesOptions options) async { await _api.set(key, value, _convertOptionsToPigeonOptions(options)); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) async { + Future setDouble(String key, double value, SharedPreferencesOptions options) async { await _api.set(key, value, _convertOptionsToPigeonOptions(options)); } @override - Future getString( - String key, - SharedPreferencesOptions options, - ) async { + Future getString(String key, SharedPreferencesOptions options) async { return _convertKnownExceptions( - () async => - (await _api.getValue(key, _convertOptionsToPigeonOptions(options))) - as String?, + () async => (await _api.getValue(key, _convertOptionsToPigeonOptions(options))) as String?, ); } @override Future getBool(String key, SharedPreferencesOptions options) async { return _convertKnownExceptions( - () async => - await _api.getValue(key, _convertOptionsToPigeonOptions(options)) - as bool?, + () async => await _api.getValue(key, _convertOptionsToPigeonOptions(options)) as bool?, ); } @override - Future getDouble( - String key, - SharedPreferencesOptions options, - ) async { + Future getDouble(String key, SharedPreferencesOptions options) async { return _convertKnownExceptions( - () async => - await _api.getValue(key, _convertOptionsToPigeonOptions(options)) - as double?, + () async => await _api.getValue(key, _convertOptionsToPigeonOptions(options)) as double?, ); } @override Future getInt(String key, SharedPreferencesOptions options) async { return _convertKnownExceptions( - () async => - await _api.getValue(key, _convertOptionsToPigeonOptions(options)) - as int?, + () async => await _api.getValue(key, _convertOptionsToPigeonOptions(options)) as int?, ); } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) async { + Future?> getStringList(String key, SharedPreferencesOptions options) async { // Since `getValue` is not strongly typed, the array type won't be set // during deserialization, and needs to be manually cast. return _convertKnownExceptions>( () async => - ((await _api.getValue(key, _convertOptionsToPigeonOptions(options))) - as List?) + ((await _api.getValue(key, _convertOptionsToPigeonOptions(options))) as List?) ?.cast() .toList(), ); @@ -173,10 +128,7 @@ base class SharedPreferencesAsyncFoundation ) async { final PreferencesFilters filter = parameters.filter; return _convertKnownExceptions( - () async => _api.clear( - filter.allowList?.toList(), - _convertOptionsToPigeonOptions(options), - ), + () async => _api.clear(filter.allowList?.toList(), _convertOptionsToPigeonOptions(options)), ); } @@ -187,10 +139,7 @@ base class SharedPreferencesAsyncFoundation ) async { final PreferencesFilters filter = parameters.filter; return (await _convertKnownExceptions>( - () async => _api.getAll( - filter.allowList?.toList(), - _convertOptionsToPigeonOptions(options), - ), + () async => _api.getAll(filter.allowList?.toList(), _convertOptionsToPigeonOptions(options)), ))!; } @@ -200,9 +149,7 @@ base class SharedPreferencesAsyncFoundation return value; } on PlatformException catch (e) { if (e.code == _argumentErrorCode) { - throw ArgumentError( - 'shared_preferences_foundation argument error ${e.message ?? ''}', - ); + throw ArgumentError('shared_preferences_foundation argument error ${e.message ?? ''}'); } else { rethrow; } diff --git a/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_foundation.dart b/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_foundation.dart index b550e443baad..6e5b775db751 100644 --- a/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_foundation.dart +++ b/packages/shared_preferences/shared_preferences_foundation/lib/src/shared_preferences_foundation.dart @@ -49,16 +49,12 @@ class SharedPreferencesFoundation extends SharedPreferencesStorePlatform { @override Future clear() async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix))); } @override Future clearWithPrefix(String prefix) async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override @@ -76,15 +72,11 @@ class SharedPreferencesFoundation extends SharedPreferencesStorePlatform { @override Future> getAllWithPrefix(String prefix) async { - return getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return getAllWithParameters(GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) async { + Future> getAllWithParameters(GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; return _api.getAll(filter.prefix, filter.allowList?.toList()); } diff --git a/packages/shared_preferences/shared_preferences_foundation/pigeons/messages.dart b/packages/shared_preferences/shared_preferences_foundation/pigeons/messages.dart index 9db1151f0f3c..4a7923fae91d 100644 --- a/packages/shared_preferences/shared_preferences_foundation/pigeons/messages.dart +++ b/packages/shared_preferences/shared_preferences_foundation/pigeons/messages.dart @@ -37,17 +37,11 @@ abstract class UserDefaultsApi { void clear(List? allowList, SharedPreferencesPigeonOptions options); /// Gets all properties from shared preferences data set with matching prefix. - Map getAll( - List? allowList, - SharedPreferencesPigeonOptions options, - ); + Map getAll(List? allowList, SharedPreferencesPigeonOptions options); /// Gets individual value stored with [key], if any. Object? getValue(String key, SharedPreferencesPigeonOptions options); /// Gets all properties from shared preferences data set with matching prefix. - List getKeys( - List? allowList, - SharedPreferencesPigeonOptions options, - ); + List getKeys(List? allowList, SharedPreferencesPigeonOptions options); } diff --git a/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_async_foundation_test.dart b/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_async_foundation_test.dart index 05383cfc3ed5..70f8cf16f5e2 100644 --- a/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_async_foundation_test.dart +++ b/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_async_foundation_test.dart @@ -204,10 +204,7 @@ class _FakeSharedPreferencesApi implements UserDefaultsApi { final Map items = {}; @override - Future clear( - List? allowList, - SharedPreferencesPigeonOptions options, - ) async { + Future clear(List? allowList, SharedPreferencesPigeonOptions options) async { if (allowList != null) { items.removeWhere((String key, _) => allowList.contains(key)); } else { @@ -242,19 +239,12 @@ class _FakeSharedPreferencesApi implements UserDefaultsApi { } @override - Future set( - String key, - Object value, - SharedPreferencesPigeonOptions options, - ) async { + Future set(String key, Object value, SharedPreferencesPigeonOptions options) async { items[key] = value; } @override - Future getValue( - String key, - SharedPreferencesPigeonOptions options, - ) async { + Future getValue(String key, SharedPreferencesPigeonOptions options) async { return items[key]; } diff --git a/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart b/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart index 7a8a2481dbb8..ed3ba4bb10c3 100644 --- a/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart +++ b/packages/shared_preferences/shared_preferences_foundation/test/shared_preferences_foundation_test.dart @@ -13,18 +13,14 @@ class _MockSharedPreferencesApi implements LegacyUserDefaultsApi { final Map items = {}; @override - Future> getAll( - String prefix, - List? allowList, - ) async { + Future> getAll(String prefix, List? allowList) async { Set? allowSet; if (allowList != null) { allowSet = Set.from(allowList); } return { for (final MapEntry entry in items.entries) - if (entry.key.startsWith(prefix) && - (allowSet == null || allowSet.contains(entry.key))) + if (entry.key.startsWith(prefix) && (allowSet == null || allowSet.contains(entry.key))) entry.key: entry.value, }; } @@ -52,8 +48,7 @@ class _MockSharedPreferencesApi implements LegacyUserDefaultsApi { @override Future clear(String prefix, List? allowList) async { items.keys.toList().forEach((String key) { - if (key.startsWith(prefix) && - (allowList == null || allowList.contains(key))) { + if (key.startsWith(prefix) && (allowList == null || allowList.contains(key))) { items.remove(key); } }); @@ -109,10 +104,7 @@ void main() { test('registerWith', () async { SharedPreferencesFoundation.registerWith(); - expect( - SharedPreferencesStorePlatform.instance, - isA(), - ); + expect(SharedPreferencesStorePlatform.instance, isA()); }); test('remove', () async { @@ -154,9 +146,7 @@ void main() { GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), ); expect(all.length, 5); - await plugin.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + await plugin.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: 'prefix.'))); all = await plugin.getAll(); expect(all.length, 5); all = await plugin.getAllWithParameters( @@ -177,10 +167,7 @@ void main() { expect(all.length, 5); await plugin.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.String'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.String'}), ), ); all = await plugin.getAll(); @@ -230,10 +217,7 @@ void main() { } final Map all = await plugin.getAllWithParameters( GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.Bool'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.Bool'}), ), ); expect(all.length, 1); @@ -250,10 +234,7 @@ void main() { expect(api.items['flutter.Int'], 12); expect(await plugin.setValue('String', 'flutter.String', 'hi'), isTrue); expect(api.items['flutter.String'], 'hi'); - expect( - await plugin.setValue('StringList', 'flutter.StringList', ['hi']), - isTrue, - ); + expect(await plugin.setValue('StringList', 'flutter.StringList', ['hi']), isTrue); expect(api.items['flutter.StringList'], ['hi']); }); @@ -309,9 +290,7 @@ void main() { GetAllParameters(filter: PreferencesFilter(prefix: '')), ); expect(all.length, 15); - await plugin.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await plugin.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); all = await plugin.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), ); diff --git a/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart index 59e8095176b3..2e5a8651a2c9 100644 --- a/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences_linux/example/integration_test/shared_preferences_test.dart @@ -49,56 +49,20 @@ void main() { await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); await preferences.setValue('Double', 'Double', allTestValues['Double']!); - await preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ); - await preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ); - await preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ); - await preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ); - await preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ); + await preferences.setValue('StringList', 'StringList', allTestValues['StringList']!); + await preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!); + await preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); + await preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!); + await preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ); - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -112,9 +76,7 @@ void main() { }); tearDown(() async { - await preferences.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await preferences.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); }); testWidgets('getAll', (WidgetTester _) async { @@ -130,9 +92,7 @@ void main() { testWidgets('remove', (WidgetTester _) async { const key = 'flutter.String'; await preferences.remove(key); - final Map values = await preferences.getAllWithPrefix( - '', - ); + final Map values = await preferences.getAllWithPrefix(''); expect(values[key], isNull); }); @@ -147,9 +107,7 @@ void main() { }); testWidgets('get all with prefix', (WidgetTester _) async { - final Map values = await preferences.getAllWithPrefix( - 'prefix.', - ); + final Map values = await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -158,9 +116,7 @@ void main() { }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { - final Map values = await preferences.getAllWithPrefix( - '', - ); + final Map values = await preferences.getAllWithPrefix(''); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -170,17 +126,12 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithPrefix', (WidgetTester _) async { await preferences.clearWithPrefix('prefix.'); - Map values = await preferences.getAllWithPrefix( - 'prefix.', - ); + Map values = await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -191,17 +142,12 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithPrefix(''); - final Map values = await preferences.getAllWithPrefix( - '', - ); + final Map values = await preferences.getAllWithPrefix(''); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); @@ -219,10 +165,9 @@ void main() { testWidgets('remove', (WidgetTester _) async { const key = 'flutter.String'; await preferences.remove(key); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values[key], isNull); }); @@ -237,10 +182,9 @@ void main() { }); testWidgets('get all with prefix', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -249,15 +193,11 @@ void main() { }); testWidgets('get all with allow list', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.String'}, - ), - ), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters( + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.String'}), + ), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -266,10 +206,9 @@ void main() { }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -279,10 +218,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters', (WidgetTester _) async { @@ -304,22 +240,14 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); - testWidgets('clearWithParameters with allow list', ( - WidgetTester _, - ) async { + testWidgets('clearWithParameters with allow list', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.StringList'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.StringList'}), ), ); Map values = await preferences.getAllWithParameters( @@ -337,20 +265,16 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: '')), ); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); @@ -380,11 +304,8 @@ void main() { const testDouble = 3.14159; const testList = ['foo', 'bar']; - Future getPreferences({ - bool clear = true, - }) async { - final SharedPreferencesAsyncPlatform preferences = - SharedPreferencesAsyncPlatform.instance!; + Future getPreferences({bool clear = true}) async { + final SharedPreferencesAsyncPlatform preferences = SharedPreferencesAsyncPlatform.instance!; if (clear) { await preferences.clear( const ClearPreferencesParameters(filter: PreferencesFilters()), @@ -428,9 +349,7 @@ void main() { await preferences.setStringList(listKey, testList, emptyOptions); expect(await preferences.getStringList(listKey, emptyOptions), testList); }); - testWidgets('getStringList does not throw cast error', ( - WidgetTester _, - ) async { + testWidgets('getStringList does not throw cast error', (WidgetTester _) async { final SharedPreferencesAsyncPlatform preferences = await getPreferences(); await preferences.setStringList(listKey, testList, emptyOptions); @@ -442,10 +361,7 @@ void main() { final SharedPreferencesAsyncPlatform preferences = await getPreferences(); await preferences.setStringList(listKey, testList, emptyOptions); - final List? list = await preferences.getStringList( - listKey, - emptyOptions, - ); + final List? list = await preferences.getStringList(listKey, emptyOptions); list?.add('value'); expect(list?.length, testList.length + 1); }); diff --git a/packages/shared_preferences/shared_preferences_linux/example/lib/main.dart b/packages/shared_preferences/shared_preferences_linux/example/lib/main.dart index 243729e73d87..032bc3f22d9c 100644 --- a/packages/shared_preferences/shared_preferences_linux/example/lib/main.dart +++ b/packages/shared_preferences/shared_preferences_linux/example/lib/main.dart @@ -17,10 +17,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'SharedPreferences Demo', - home: SharedPreferencesDemo(), - ); + return const MaterialApp(title: 'SharedPreferences Demo', home: SharedPreferencesDemo()); } } @@ -32,10 +29,8 @@ class SharedPreferencesDemo extends StatefulWidget { } class SharedPreferencesDemoState extends State { - final SharedPreferencesAsyncPlatform? _prefs = - SharedPreferencesAsyncPlatform.instance; - final SharedPreferencesLinuxOptions options = - const SharedPreferencesLinuxOptions(); + final SharedPreferencesAsyncPlatform? _prefs = SharedPreferencesAsyncPlatform.instance; + final SharedPreferencesLinuxOptions options = const SharedPreferencesLinuxOptions(); static const String _counterKey = 'counter'; late Future _counter; diff --git a/packages/shared_preferences/shared_preferences_linux/lib/shared_preferences_linux.dart b/packages/shared_preferences/shared_preferences_linux/lib/shared_preferences_linux.dart index 7cc16fbdb4b7..760e259a9ba2 100644 --- a/packages/shared_preferences/shared_preferences_linux/lib/shared_preferences_linux.dart +++ b/packages/shared_preferences/shared_preferences_linux/lib/shared_preferences_linux.dart @@ -48,26 +48,18 @@ class SharedPreferencesLinux extends SharedPreferencesStorePlatform { /// Checks for cached preferences and returns them or loads preferences from /// file and returns and caches them. Future> _readPreferences() async { - _cachedPreferences ??= await _reload( - _defaultFileName, - fs: fs, - pathProvider: pathProvider, - ); + _cachedPreferences ??= await _reload(_defaultFileName, fs: fs, pathProvider: pathProvider); return _cachedPreferences!; } @override Future clear() async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix))); } @override Future clearWithPrefix(String prefix) async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override @@ -80,12 +72,7 @@ class SharedPreferencesLinux extends SharedPreferencesStorePlatform { key.startsWith(filter.prefix) && (filter.allowList == null || filter.allowList!.contains(key)), ); - return _writePreferences( - preferences, - _defaultFileName, - fs: fs, - pathProvider: pathProvider, - ); + return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); } @override @@ -97,21 +84,16 @@ class SharedPreferencesLinux extends SharedPreferencesStorePlatform { @override Future> getAllWithPrefix(String prefix) async { - return getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return getAllWithParameters(GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) async { + Future> getAllWithParameters(GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final withPrefix = Map.from(await _readPreferences()); withPrefix.removeWhere( (String key, _) => - !(key.startsWith(filter.prefix) && - (filter.allowList?.contains(key) ?? true)), + !(key.startsWith(filter.prefix) && (filter.allowList?.contains(key) ?? true)), ); return withPrefix; } @@ -120,24 +102,14 @@ class SharedPreferencesLinux extends SharedPreferencesStorePlatform { Future remove(String key) async { final Map preferences = await _readPreferences(); preferences.remove(key); - return _writePreferences( - preferences, - _defaultFileName, - fs: fs, - pathProvider: pathProvider, - ); + return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); } @override Future setValue(String valueType, String key, Object value) async { final Map preferences = await _readPreferences(); preferences[key] = value; - return _writePreferences( - preferences, - _defaultFileName, - fs: fs, - pathProvider: pathProvider, - ); + return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); } } @@ -170,29 +142,17 @@ base class SharedPreferencesAsyncLinux extends SharedPreferencesAsyncPlatform { } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) { + Future setString(String key, String value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) { + Future setBool(String key, bool value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) { + Future setDouble(String key, double value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @@ -202,19 +162,12 @@ base class SharedPreferencesAsyncLinux extends SharedPreferencesAsyncPlatform { } @override - Future setStringList( - String key, - List value, - SharedPreferencesOptions options, - ) { + Future setStringList(String key, List value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future getString( - String key, - SharedPreferencesOptions options, - ) async { + Future getString(String key, SharedPreferencesOptions options) async { final Map data = await _readAll({key}, options); return data[key] as String?; } @@ -226,10 +179,7 @@ base class SharedPreferencesAsyncLinux extends SharedPreferencesAsyncPlatform { } @override - Future getDouble( - String key, - SharedPreferencesOptions options, - ) async { + Future getDouble(String key, SharedPreferencesOptions options) async { final Map data = await _readAll({key}, options); return data[key] as double?; } @@ -241,10 +191,7 @@ base class SharedPreferencesAsyncLinux extends SharedPreferencesAsyncPlatform { } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) async { + Future?> getStringList(String key, SharedPreferencesOptions options) async { final Map data = await _readAll({key}, options); return (data[key] as List?)?.cast().toList(); } @@ -257,19 +204,11 @@ base class SharedPreferencesAsyncLinux extends SharedPreferencesAsyncPlatform { final SharedPreferencesLinuxOptions linuxOptions = SharedPreferencesLinuxOptions.fromSharedPreferencesOptions(options); final PreferencesFilters filter = parameters.filter; - final Map preferences = await _readPreferences( - linuxOptions.fileName, - ); + final Map preferences = await _readPreferences(linuxOptions.fileName); preferences.removeWhere( - (String key, _) => - filter.allowList == null || filter.allowList!.contains(key), - ); - await _writePreferences( - preferences, - linuxOptions.fileName, - fs: fs, - pathProvider: pathProvider, + (String key, _) => filter.allowList == null || filter.allowList!.contains(key), ); + await _writePreferences(preferences, linuxOptions.fileName, fs: fs, pathProvider: pathProvider); } @override @@ -292,40 +231,23 @@ base class SharedPreferencesAsyncLinux extends SharedPreferencesAsyncPlatform { ) async { final SharedPreferencesLinuxOptions linuxOptions = SharedPreferencesLinuxOptions.fromSharedPreferencesOptions(options); - final prefs = Map.from( - await _readPreferences(linuxOptions.fileName), - ); + final prefs = Map.from(await _readPreferences(linuxOptions.fileName)); prefs.removeWhere((String key, _) => !(allowList?.contains(key) ?? true)); return prefs; } - Future _setValue( - String key, - Object value, - SharedPreferencesOptions options, - ) async { + Future _setValue(String key, Object value, SharedPreferencesOptions options) async { final SharedPreferencesLinuxOptions linuxOptions = SharedPreferencesLinuxOptions.fromSharedPreferencesOptions(options); - final Map preferences = await _readPreferences( - linuxOptions.fileName, - ); + final Map preferences = await _readPreferences(linuxOptions.fileName); preferences[key] = value; - await _writePreferences( - preferences, - linuxOptions.fileName, - fs: fs, - pathProvider: pathProvider, - ); + await _writePreferences(preferences, linuxOptions.fileName, fs: fs, pathProvider: pathProvider); } /// Checks for cached preferences and returns them or loads preferences from /// file and returns and caches them. Future> _readPreferences(String fileName) async { - _cachedPreferences ??= await _reload( - fileName, - fs: fs, - pathProvider: pathProvider, - ); + _cachedPreferences ??= await _reload(fileName, fs: fs, pathProvider: pathProvider); return _cachedPreferences!; } } @@ -352,11 +274,7 @@ Future> _reload( PathProviderLinux? pathProvider, }) async { var preferences = {}; - final File? localDataFile = await _getLocalDataFile( - fileName, - fs: fs, - pathProvider: pathProvider, - ); + final File? localDataFile = await _getLocalDataFile(fileName, fs: fs, pathProvider: pathProvider); if (localDataFile != null && localDataFile.existsSync()) { final String stringMap = localDataFile.readAsStringSync(); if (stringMap.isNotEmpty) { diff --git a/packages/shared_preferences/shared_preferences_linux/test/fake_path_provider_linux.dart b/packages/shared_preferences/shared_preferences_linux/test/fake_path_provider_linux.dart index 06cc8b58ed62..30964b223ef4 100644 --- a/packages/shared_preferences/shared_preferences_linux/test/fake_path_provider_linux.dart +++ b/packages/shared_preferences/shared_preferences_linux/test/fake_path_provider_linux.dart @@ -10,8 +10,7 @@ import 'package:path_provider_platform_interface/path_provider_platform_interfac /// /// Note that this should only be used with an in-memory filesystem, as the /// path it returns is a root path that does not actually exist on Linux. -class FakePathProviderLinux extends PathProviderPlatform - implements PathProviderLinux { +class FakePathProviderLinux extends PathProviderPlatform implements PathProviderLinux { @override Future getApplicationSupportPath() async => r'/appsupport'; diff --git a/packages/shared_preferences/shared_preferences_linux/test/legacy_shared_preferences_linux_test.dart b/packages/shared_preferences/shared_preferences_linux/test/legacy_shared_preferences_linux_test.dart index 08e303bd371c..3bc2259f2ecd 100644 --- a/packages/shared_preferences/shared_preferences_linux/test/legacy_shared_preferences_linux_test.dart +++ b/packages/shared_preferences/shared_preferences_linux/test/legacy_shared_preferences_linux_test.dart @@ -78,10 +78,7 @@ void main() { test('registered instance', () async { SharedPreferencesLinux.registerWith(); - expect( - SharedPreferencesStorePlatform.instance, - isA(), - ); + expect(SharedPreferencesStorePlatform.instance, isA()); }); test('getAll', () async { @@ -119,10 +116,7 @@ void main() { final Map all = await prefs.getAllWithParameters( GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.Bool'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.Bool'}), ), ); expect(all.length, 1); @@ -161,9 +155,7 @@ void main() { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); await prefs.clearWithPrefix('prefix.'); - final Map noValues = await prefs.getAllWithPrefix( - 'prefix.', - ); + final Map noValues = await prefs.getAllWithPrefix('prefix.'); expect(noValues, hasLength(0)); final Map values = await prefs.getAll(); @@ -191,9 +183,7 @@ void main() { test('clearWithParameters', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); - await prefs.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + await prefs.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: 'prefix.'))); final Map noValues = await prefs.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), ); @@ -209,10 +199,7 @@ void main() { final SharedPreferencesLinux prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.StringList'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.StringList'}), ), ); final Map someValues = await prefs.getAllWithParameters( @@ -235,9 +222,7 @@ void main() { test('clearWithNoPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesLinux prefs = getPreferences(); - await prefs.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await prefs.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); final Map noValues = await prefs.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), ); diff --git a/packages/shared_preferences/shared_preferences_platform_interface/lib/in_memory_shared_preferences_async.dart b/packages/shared_preferences/shared_preferences_platform_interface/lib/in_memory_shared_preferences_async.dart index 54ae0c66331f..4377a149aab9 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/lib/in_memory_shared_preferences_async.dart +++ b/packages/shared_preferences/shared_preferences_platform_interface/lib/in_memory_shared_preferences_async.dart @@ -10,8 +10,7 @@ import 'types.dart'; /// Stores data in memory. /// /// Data does not persist across application restarts. This is useful in unit tests. -base class InMemorySharedPreferencesAsync - extends SharedPreferencesAsyncPlatform { +base class InMemorySharedPreferencesAsync extends SharedPreferencesAsyncPlatform { /// Instantiates an empty in-memory preferences store. InMemorySharedPreferencesAsync.empty() : _data = {}; @@ -43,54 +42,33 @@ base class InMemorySharedPreferencesAsync final PreferencesFilters filter = parameters.filter; final preferences = Map.from(_data); preferences.removeWhere( - (String key, _) => - filter.allowList != null && !filter.allowList!.contains(key), + (String key, _) => filter.allowList != null && !filter.allowList!.contains(key), ); return preferences; } - Future _setValue( - String key, - Object value, - SharedPreferencesOptions options, - ) async { + Future _setValue(String key, Object value, SharedPreferencesOptions options) async { _data[key] = value; return true; } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) async { + Future setString(String key, String value, SharedPreferencesOptions options) async { return _setValue(key, value, options); } @override - Future setInt( - String key, - int value, - SharedPreferencesOptions options, - ) async { + Future setInt(String key, int value, SharedPreferencesOptions options) async { return _setValue(key, value, options); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) async { + Future setDouble(String key, double value, SharedPreferencesOptions options) async { return _setValue(key, value, options); } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) async { + Future setBool(String key, bool value, SharedPreferencesOptions options) async { return _setValue(key, value, options); } @@ -104,10 +82,7 @@ base class InMemorySharedPreferencesAsync } @override - Future getString( - String key, - SharedPreferencesOptions options, - ) async { + Future getString(String key, SharedPreferencesOptions options) async { return _data[key] as String?; } @@ -117,10 +92,7 @@ base class InMemorySharedPreferencesAsync } @override - Future getDouble( - String key, - SharedPreferencesOptions options, - ) async { + Future getDouble(String key, SharedPreferencesOptions options) async { return _data[key] as double?; } @@ -130,10 +102,7 @@ base class InMemorySharedPreferencesAsync } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) async { + Future?> getStringList(String key, SharedPreferencesOptions options) async { final data = _data[key] as List?; return data?.cast(); } @@ -145,9 +114,7 @@ base class InMemorySharedPreferencesAsync ) async { final Set keys = _data.keys.toSet(); if (parameters.filter.allowList != null) { - keys.retainWhere( - (String element) => parameters.filter.allowList!.contains(element), - ); + keys.retainWhere((String element) => parameters.filter.allowList!.contains(element)); } return keys; diff --git a/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart b/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart index 882557e2d363..d6d8e825eaad 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart +++ b/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart @@ -9,29 +9,24 @@ import 'package:flutter/services.dart'; import 'shared_preferences_platform_interface.dart'; import 'types.dart'; -const MethodChannel _kChannel = MethodChannel( - 'plugins.flutter.io/shared_preferences', -); +const MethodChannel _kChannel = MethodChannel('plugins.flutter.io/shared_preferences'); /// Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing /// a persistent store for simple data. /// /// Data is persisted to disk asynchronously. -class MethodChannelSharedPreferencesStore - extends SharedPreferencesStorePlatform { +class MethodChannelSharedPreferencesStore extends SharedPreferencesStorePlatform { @override Future remove(String key) async { - return (await _kChannel.invokeMethod('remove', { - 'key': key, - }))!; + return (await _kChannel.invokeMethod('remove', {'key': key}))!; } @override Future setValue(String valueType, String key, Object value) async { - return (await _kChannel.invokeMethod( - 'set$valueType', - {'key': key, 'value': value}, - ))!; + return (await _kChannel.invokeMethod('set$valueType', { + 'key': key, + 'value': value, + }))!; } @override @@ -42,52 +37,36 @@ class MethodChannelSharedPreferencesStore @override @Deprecated('Use clearWithParameters instead') Future clearWithPrefix(String prefix) async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override Future clearWithParameters(ClearParameters parameters) async { final PreferencesFilter filter = parameters.filter; - return (await _kChannel.invokeMethod( - 'clearWithParameters', - { - 'prefix': filter.prefix, - 'allowList': filter.allowList?.toList(), - }, - ))!; + return (await _kChannel.invokeMethod('clearWithParameters', { + 'prefix': filter.prefix, + 'allowList': filter.allowList?.toList(), + }))!; } @override Future> getAll() async { - return await _kChannel.invokeMapMethod('getAll') ?? - {}; + return await _kChannel.invokeMapMethod('getAll') ?? {}; } @override @Deprecated('Use getAllWithParameters instead') - Future> getAllWithPrefix( - String prefix, { - Set? allowList, - }) async { - return getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: prefix)), - ); + Future> getAllWithPrefix(String prefix, {Set? allowList}) async { + return getAllWithParameters(GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) async { + Future> getAllWithParameters(GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final List? allowListAsList = filter.allowList?.toList(); return await _kChannel.invokeMapMethod( 'getAllWithParameters', - { - 'prefix': filter.prefix, - 'allowList': allowListAsList, - }, + {'prefix': filter.prefix, 'allowList': allowListAsList}, ) ?? {}; } diff --git a/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_async_platform_interface.dart b/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_async_platform_interface.dart index 77dec7f04d10..0f8104f25e95 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_async_platform_interface.dart +++ b/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_async_platform_interface.dart @@ -15,35 +15,19 @@ abstract base class SharedPreferencesAsyncPlatform { static SharedPreferencesAsyncPlatform? instance; /// Stores the String [value] associated with the [key]. - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ); + Future setString(String key, String value, SharedPreferencesOptions options); /// Stores the bool [value] associated with the [key]. - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ); + Future setBool(String key, bool value, SharedPreferencesOptions options); /// Stores the double [value] associated with the [key]. - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ); + Future setDouble(String key, double value, SharedPreferencesOptions options); /// Stores the int [value] associated with the [key]. Future setInt(String key, int value, SharedPreferencesOptions options); /// Stores the `List` [value] associated with the [key]. - Future setStringList( - String key, - List value, - SharedPreferencesOptions options, - ); + Future setStringList(String key, List value, SharedPreferencesOptions options); /// Retrieves the `String` [value] associated with the [key], if any. /// @@ -73,16 +57,10 @@ abstract base class SharedPreferencesAsyncPlatform { /// /// Throws a [TypeError] if the returned type is not a `List`. /// May return null for unsupported types. - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ); + Future?> getStringList(String key, SharedPreferencesOptions options); /// Removes all keys and values in the store that match the given [parameters]. - Future clear( - ClearPreferencesParameters parameters, - SharedPreferencesOptions options, - ); + Future clear(ClearPreferencesParameters parameters, SharedPreferencesOptions options); /// Returns all key/value pairs persisting in this store that match the given [parameters]. /// diff --git a/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_platform_interface.dart b/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_platform_interface.dart index c5b86042b6f8..1f64d5e585d6 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_platform_interface.dart +++ b/packages/shared_preferences/shared_preferences_platform_interface/lib/shared_preferences_platform_interface.dart @@ -37,8 +37,7 @@ abstract class SharedPreferencesStorePlatform extends PlatformInterface { _instance = instance; } - static SharedPreferencesStorePlatform _instance = - MethodChannelSharedPreferencesStore(); + static SharedPreferencesStorePlatform _instance = MethodChannelSharedPreferencesStore(); /// Only mock implementations should set this to true. /// @@ -95,9 +94,7 @@ abstract class SharedPreferencesStorePlatform extends PlatformInterface { } /// Returns all key/value pairs persisting in this store that match [options]. - Future> getAllWithParameters( - GetAllParameters parameters, - ) { + Future> getAllWithParameters(GetAllParameters parameters) { throw UnimplementedError('getAllWithParameters is not implemented.'); } } @@ -118,16 +115,12 @@ class InMemorySharedPreferencesStore extends SharedPreferencesStorePlatform { @override Future clear() async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix))); } @override Future clearWithPrefix(String prefix) async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override @@ -135,8 +128,7 @@ class InMemorySharedPreferencesStore extends SharedPreferencesStorePlatform { final PreferencesFilter filter = parameters.filter; if (filter.allowList != null) { _data.removeWhere( - (String key, _) => - key.startsWith(filter.prefix) && filter.allowList!.contains(key), + (String key, _) => key.startsWith(filter.prefix) && filter.allowList!.contains(key), ); } else { _data.removeWhere((String key, _) => key.startsWith(filter.prefix)); @@ -153,15 +145,11 @@ class InMemorySharedPreferencesStore extends SharedPreferencesStorePlatform { @override Future> getAllWithPrefix(String prefix) async { - return getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return getAllWithParameters(GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) async { + Future> getAllWithParameters(GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final preferences = Map.from(_data); preferences.removeWhere( diff --git a/packages/shared_preferences/shared_preferences_platform_interface/test/deprecated_method_channel_shared_preferences_test.dart b/packages/shared_preferences/shared_preferences_platform_interface/test/deprecated_method_channel_shared_preferences_test.dart index bbb662a5148d..705a1f75e981 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/test/deprecated_method_channel_shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences_platform_interface/test/deprecated_method_channel_shared_preferences_test.dart @@ -53,83 +53,70 @@ void main() { testData = InMemorySharedPreferencesStore.empty(); Map getArgumentDictionary(MethodCall call) { - return (call.arguments as Map) - .cast(); + return (call.arguments as Map).cast(); } - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (MethodCall methodCall) async { - log.add(methodCall); - if (methodCall.method == 'getAll') { - return testData.getAll(); - } - if (methodCall.method == 'getAllWithParameters') { - final Map arguments = getArgumentDictionary( - methodCall, - ); - final prefix = arguments['prefix']! as String; - Set? allowSet; - final allowList = arguments['allowList'] as List?; - if (allowList != null) { - allowSet = {}; - for (final Object? key in allowList) { - allowSet.add(key! as String); - } + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (MethodCall methodCall) async { + log.add(methodCall); + if (methodCall.method == 'getAll') { + return testData.getAll(); + } + if (methodCall.method == 'getAllWithParameters') { + final Map arguments = getArgumentDictionary(methodCall); + final prefix = arguments['prefix']! as String; + Set? allowSet; + final allowList = arguments['allowList'] as List?; + if (allowList != null) { + allowSet = {}; + for (final Object? key in allowList) { + allowSet.add(key! as String); } - return testData.getAllWithParameters( - GetAllParameters( - filter: PreferencesFilter( - prefix: prefix, - allowList: allowSet, - ), - ), - ); - } - if (methodCall.method == 'remove') { - final Map arguments = getArgumentDictionary( - methodCall, - ); - final key = arguments['key']! as String; - return testData.remove(key); } - if (methodCall.method == 'clear') { - return testData.clear(); - } - if (methodCall.method == 'clearWithParameters') { - final Map arguments = getArgumentDictionary( - methodCall, - ); - final prefix = arguments['prefix']! as String; - Set? allowSet; - final allowList = arguments['allowList'] as List?; - if (allowList != null) { - allowSet = {}; - for (final Object? key in allowList) { - allowSet.add(key! as String); - } + return testData.getAllWithParameters( + GetAllParameters( + filter: PreferencesFilter(prefix: prefix, allowList: allowSet), + ), + ); + } + if (methodCall.method == 'remove') { + final Map arguments = getArgumentDictionary(methodCall); + final key = arguments['key']! as String; + return testData.remove(key); + } + if (methodCall.method == 'clear') { + return testData.clear(); + } + if (methodCall.method == 'clearWithParameters') { + final Map arguments = getArgumentDictionary(methodCall); + final prefix = arguments['prefix']! as String; + Set? allowSet; + final allowList = arguments['allowList'] as List?; + if (allowList != null) { + allowSet = {}; + for (final Object? key in allowList) { + allowSet.add(key! as String); } - return testData.clearWithParameters( - ClearParameters( - filter: PreferencesFilter( - prefix: prefix, - allowList: allowSet, - ), - ), - ); - } - final setterRegExp = RegExp(r'set(.*)'); - final Match? match = setterRegExp.matchAsPrefix(methodCall.method); - if (match?.groupCount == 1) { - final String valueType = match!.group(1)!; - final Map arguments = getArgumentDictionary( - methodCall, - ); - final key = arguments['key']! as String; - final Object value = arguments['value']!; - return testData.setValue(valueType, key, value); } - fail('Unexpected method call: ${methodCall.method}'); - }); + return testData.clearWithParameters( + ClearParameters( + filter: PreferencesFilter(prefix: prefix, allowList: allowSet), + ), + ); + } + final setterRegExp = RegExp(r'set(.*)'); + final Match? match = setterRegExp.matchAsPrefix(methodCall.method); + if (match?.groupCount == 1) { + final String valueType = match!.group(1)!; + final Map arguments = getArgumentDictionary(methodCall); + final key = arguments['key']! as String; + final Object value = arguments['value']!; + return testData.setValue(valueType, key, value); + } + fail('Unexpected method call: ${methodCall.method}'); + }, + ); store = MethodChannelSharedPreferencesStore(); log.clear(); }); @@ -159,10 +146,7 @@ void main() { testData = InMemorySharedPreferencesStore.withData(allTestValues); final Map data = await store.getAllWithParameters( GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.Bool'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.Bool'}), ), ); expect(data.length, 1); @@ -254,9 +238,7 @@ void main() { isNotEmpty, ); expect( - await store.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ), + await store.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))), true, ); expect( @@ -279,10 +261,7 @@ void main() { expect( await store.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.String'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.String'}), ), ), true, diff --git a/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart b/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart index 3cff51643963..a68f79b96509 100644 --- a/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart +++ b/packages/shared_preferences/shared_preferences_platform_interface/test/shared_preferences_platform_interface_test.dart @@ -70,9 +70,7 @@ class IllegalImplementation implements SharedPreferencesStorePlatform { } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) { + Future> getAllWithParameters(GetAllParameters parameters) { throw UnimplementedError(); } @@ -117,9 +115,7 @@ class LegacyIsMockImplementation implements SharedPreferencesStorePlatform { } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) { + Future> getAllWithParameters(GetAllParameters parameters) { throw UnimplementedError(); } @@ -166,9 +162,7 @@ class ModernMockImplementation } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) { + Future> getAllWithParameters(GetAllParameters parameters) { throw UnimplementedError(); } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/main.dart b/packages/shared_preferences/shared_preferences_tool/lib/main.dart index 7c12788eaac3..72a0490d68de 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/main.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/main.dart @@ -35,12 +35,9 @@ class _ConnectionManagerState extends State<_ConnectionManager> { super.initState(); // Used to move the application back to the loading state on the simulated // environment when the developer disconnects the app. - serviceManager.registerLifecycleCallback( - ServiceManagerLifecycle.afterCloseVmService, - (_) { - setState(() {}); - }, - ); + serviceManager.registerLifecycleCallback(ServiceManagerLifecycle.afterCloseVmService, (_) { + setState(() {}); + }); } @override @@ -52,9 +49,7 @@ class _ConnectionManagerState extends State<_ConnectionManager> { return const Center(child: CircularProgressIndicator()); } - return const SharedPreferencesStateProvider( - child: SharedPreferencesBody(), - ); + return const SharedPreferencesStateProvider(child: SharedPreferencesBody()); }, ); } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/async_state.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/async_state.dart index 0d6692359930..21ed69506561 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/async_state.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/async_state.dart @@ -22,8 +22,7 @@ sealed class AsyncState { const factory AsyncState.data(T data) = AsyncStateData._; - const factory AsyncState.error(Object error, StackTrace? stackTrace) = - AsyncStateError._; + const factory AsyncState.error(Object error, StackTrace? stackTrace) = AsyncStateError._; /// Returns a [AsyncState] with the same type `T` but with the data transformed by the `onData` function. /// If the current state is not [AsyncStateData], it returns the current state. @@ -55,10 +54,7 @@ sealed class AsyncState { AsyncState flatMapWhenData(AsyncState Function(T data) onData) { return switch (this) { AsyncStateData(data: final T data) => onData(data), - AsyncStateError( - error: final Object error, - stackTrace: final StackTrace? stackTrace, - ) => + AsyncStateError(error: final Object error, stackTrace: final StackTrace? stackTrace) => AsyncState.error(error, stackTrace), AsyncState() => AsyncState.loading(), }; @@ -77,15 +73,9 @@ sealed class AsyncState { return identical(this, other) || switch (this) { AsyncStateLoading() => other is AsyncStateLoading, - AsyncStateData(data: final T data) => - other is AsyncStateData && other.data == data, - AsyncStateError( - error: final Object error, - stackTrace: final StackTrace? stackTrace, - ) => - other is AsyncStateError && - other.error == error && - other.stackTrace == stackTrace, + AsyncStateData(data: final T data) => other is AsyncStateData && other.data == data, + AsyncStateError(error: final Object error, stackTrace: final StackTrace? stackTrace) => + other is AsyncStateError && other.error == error && other.stackTrace == stackTrace, }; } @@ -93,10 +83,7 @@ sealed class AsyncState { int get hashCode => switch (this) { AsyncStateLoading() => 0, AsyncStateData(data: final T data) => data.hashCode, - AsyncStateError( - error: final Object error, - stackTrace: final StackTrace? stackTrace, - ) => + AsyncStateError(error: final Object error, stackTrace: final StackTrace? stackTrace) => error.hashCode ^ stackTrace.hashCode, }; @@ -105,10 +92,7 @@ sealed class AsyncState { return switch (this) { AsyncStateLoading() => 'AsyncState.loading()', AsyncStateData(data: final T data) => 'AsyncState.data($data)', - AsyncStateError( - error: final Object error, - stackTrace: final StackTrace? stackTrace, - ) => + AsyncStateError(error: final Object error, stackTrace: final StackTrace? stackTrace) => 'AsyncState.error($error, $stackTrace)', }; } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart index 1b2b00f6cb0f..06e49b4884b1 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state.dart @@ -50,16 +50,12 @@ class SharedPreferencesState { Object legacyApi = _undefined, }) { return SharedPreferencesState( - allKeys: allKeys == _undefined - ? this.allKeys - : allKeys as AsyncState>, + allKeys: allKeys == _undefined ? this.allKeys : allKeys as AsyncState>, selectedKey: selectedKey == _undefined ? this.selectedKey : selectedKey as SelectedSharedPreferencesKey?, editing: editing == _undefined ? this.editing : editing as bool, - legacyApi: legacyApi == _undefined - ? this.legacyApi - : legacyApi as bool, + legacyApi: legacyApi == _undefined ? this.legacyApi : legacyApi as bool, ); }; @@ -99,9 +95,7 @@ class SelectedSharedPreferencesKey { @override bool operator ==(Object other) { return identical(this, other) || - (other is SelectedSharedPreferencesKey && - other.key == key && - other.value == value); + (other is SelectedSharedPreferencesKey && other.key == key && other.value == value); } @override @@ -126,18 +120,15 @@ sealed class SharedPreferencesData implements _SharedPreferencesData { const factory SharedPreferencesData.string({required String value}) = SharedPreferencesDataString._; - const factory SharedPreferencesData.int({required int value}) = - SharedPreferencesDataInt._; + const factory SharedPreferencesData.int({required int value}) = SharedPreferencesDataInt._; const factory SharedPreferencesData.double({required double value}) = SharedPreferencesDataDouble._; - const factory SharedPreferencesData.bool({required bool value}) = - SharedPreferencesDataBool._; + const factory SharedPreferencesData.bool({required bool value}) = SharedPreferencesDataBool._; - const factory SharedPreferencesData.stringList({ - required List value, - }) = SharedPreferencesDataStringList._; + const factory SharedPreferencesData.stringList({required List value}) = + SharedPreferencesDataStringList._; /// The string representation of the value. String get valueAsString { @@ -165,18 +156,10 @@ sealed class SharedPreferencesData implements _SharedPreferencesData { /// preference value. SharedPreferencesData changeValue(String newValue) { return switch (this) { - SharedPreferencesDataString() => SharedPreferencesData.string( - value: newValue, - ), - SharedPreferencesDataInt() => SharedPreferencesData.int( - value: int.parse(newValue), - ), - SharedPreferencesDataDouble() => SharedPreferencesData.double( - value: double.parse(newValue), - ), - SharedPreferencesDataBool() => SharedPreferencesData.bool( - value: bool.parse(newValue), - ), + SharedPreferencesDataString() => SharedPreferencesData.string(value: newValue), + SharedPreferencesDataInt() => SharedPreferencesData.int(value: int.parse(newValue)), + SharedPreferencesDataDouble() => SharedPreferencesData.double(value: double.parse(newValue)), + SharedPreferencesDataBool() => SharedPreferencesData.bool(value: bool.parse(newValue)), SharedPreferencesDataStringList() => SharedPreferencesData.stringList( value: (jsonDecode(newValue) as List).cast(), ), @@ -189,8 +172,7 @@ sealed class SharedPreferencesData implements _SharedPreferencesData { (other is SharedPreferencesData && switch (this) { final SharedPreferencesDataStringList data => - other is SharedPreferencesDataStringList && - listEquals(other.value, data.value), + other is SharedPreferencesDataStringList && listEquals(other.value, data.value), _ => other.value == value, }); } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_notifier.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_notifier.dart index bc1f166cb4d2..4bb2b1e8a699 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_notifier.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_notifier.dart @@ -10,13 +10,11 @@ import 'shared_preferences_state.dart'; import 'shared_preferences_tool_eval.dart'; /// A [ValueNotifier] that manages the state of the shared preferences tool. -class SharedPreferencesStateNotifier - extends ValueNotifier { +class SharedPreferencesStateNotifier extends ValueNotifier { /// Default constructor that takes an instance of [SharedPreferencesToolEval]. /// /// You don't need to call this constructor directly. Use [SharedPreferencesStateNotifierProvider] instead. - SharedPreferencesStateNotifier(this._eval) - : super(const SharedPreferencesState()); + SharedPreferencesStateNotifier(this._eval) : super(const SharedPreferencesState()); final SharedPreferencesToolEval _eval; @@ -31,10 +29,7 @@ class SharedPreferencesStateNotifier /// /// If this is called when data already exists, it will update the list of keys. Future fetchAllKeys() async { - value = value.copyWith( - selectedKey: null, - allKeys: const AsyncState>.loading(), - ); + value = value.copyWith(selectedKey: null, allKeys: const AsyncState>.loading()); try { final KeysResult allKeys = await _eval.fetchAllKeys(); @@ -49,13 +44,9 @@ class SharedPreferencesStateNotifier key, ]; - value = value.copyWith( - allKeys: AsyncState>.data(_keysForSelectedApi), - ); + value = value.copyWith(allKeys: AsyncState>.data(_keysForSelectedApi)); } catch (error, stackTrace) { - value = value.copyWith( - allKeys: AsyncState>.error(error, stackTrace), - ); + value = value.copyWith(allKeys: AsyncState>.error(error, stackTrace)); } } @@ -71,10 +62,7 @@ class SharedPreferencesStateNotifier ); try { - final SharedPreferencesData keyValue = await _eval.fetchValue( - key, - _legacyApi, - ); + final SharedPreferencesData keyValue = await _eval.fetchValue(key, _legacyApi); value = value.copyWith( selectedKey: SelectedSharedPreferencesKey( key: key, @@ -149,9 +137,7 @@ class SharedPreferencesStateNotifier void selectApi({required bool legacyApi}) { value = value.copyWith( legacyApi: legacyApi, - allKeys: AsyncState>.data( - legacyApi ? _legacyKeys : _asyncKeys, - ), + allKeys: AsyncState>.data(legacyApi ? _legacyKeys : _asyncKeys), ); } } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_provider.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_provider.dart index 206a37a20a76..191b1dd89563 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_provider.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_state_provider.dart @@ -28,32 +28,20 @@ class _StateInheritedWidget extends InheritedWidget { } } -enum _StateInheritedModelAspect { - keysList, - selectedKey, - selectedKeyData, - editing, - legacyApi, -} +enum _StateInheritedModelAspect { keysList, selectedKey, selectedKeyData, editing, legacyApi } /// An inherited model that provides a [SharedPreferencesState] to its descendants. /// /// Notifies the descendants depending on the aspect of the state that changed. /// This is meant to prevent unnecessary rebuilds. /// For more info check [InheritedModel] and [MediaQuery]. -class _SharedPreferencesStateInheritedModel - extends InheritedModel<_StateInheritedModelAspect> { - const _SharedPreferencesStateInheritedModel({ - required super.child, - required this.state, - }); +class _SharedPreferencesStateInheritedModel extends InheritedModel<_StateInheritedModelAspect> { + const _SharedPreferencesStateInheritedModel({required super.child, required this.state}); final SharedPreferencesState state; @override - bool updateShouldNotify( - covariant _SharedPreferencesStateInheritedModel oldWidget, - ) { + bool updateShouldNotify(covariant _SharedPreferencesStateInheritedModel oldWidget) { return oldWidget.state != state; } @@ -64,16 +52,12 @@ class _SharedPreferencesStateInheritedModel ) { return dependencies.any( (_StateInheritedModelAspect aspect) => switch (aspect) { - _StateInheritedModelAspect.keysList => - state.allKeys != oldWidget.state.allKeys, - _StateInheritedModelAspect.selectedKey => - state.selectedKey != oldWidget.state.selectedKey, + _StateInheritedModelAspect.keysList => state.allKeys != oldWidget.state.allKeys, + _StateInheritedModelAspect.selectedKey => state.selectedKey != oldWidget.state.selectedKey, _StateInheritedModelAspect.selectedKeyData => state.selectedKey?.value != oldWidget.state.selectedKey?.value, - _StateInheritedModelAspect.editing => - state.editing != oldWidget.state.editing, - _StateInheritedModelAspect.legacyApi => - state.legacyApi != oldWidget.state.legacyApi, + _StateInheritedModelAspect.editing => state.editing != oldWidget.state.editing, + _StateInheritedModelAspect.legacyApi => state.legacyApi != oldWidget.state.legacyApi, }, ); } @@ -104,10 +88,7 @@ class InnerSharedPreferencesStateProvider extends StatelessWidget { child: ValueListenableBuilder( valueListenable: notifier, builder: (BuildContext context, SharedPreferencesState value, _) { - return _SharedPreferencesStateInheritedModel( - state: value, - child: child, - ); + return _SharedPreferencesStateInheritedModel(state: value, child: child); }, ), ); @@ -127,9 +108,9 @@ class SharedPreferencesStateProvider extends StatefulWidget { /// This will not cause a rebuild when any other part of the state changes. static AsyncState> keysListStateOf(BuildContext context) { return context - .dependOnInheritedWidgetOfExactType< - _SharedPreferencesStateInheritedModel - >(aspect: _StateInheritedModelAspect.keysList)! + .dependOnInheritedWidgetOfExactType<_SharedPreferencesStateInheritedModel>( + aspect: _StateInheritedModelAspect.keysList, + )! .state .allKeys; } @@ -142,9 +123,9 @@ class SharedPreferencesStateProvider extends StatefulWidget { /// This will not cause a rebuild when any other part of the state changes. static SelectedSharedPreferencesKey? selectedKeyOf(BuildContext context) { return context - .dependOnInheritedWidgetOfExactType< - _SharedPreferencesStateInheritedModel - >(aspect: _StateInheritedModelAspect.selectedKey)! + .dependOnInheritedWidgetOfExactType<_SharedPreferencesStateInheritedModel>( + aspect: _StateInheritedModelAspect.selectedKey, + )! .state .selectedKey; } @@ -153,9 +134,7 @@ class SharedPreferencesStateProvider extends StatefulWidget { /// [_SharedPreferencesStateInheritedModel] ancestor. /// /// Throws an error if the selected key is null. - static SelectedSharedPreferencesKey requireSelectedKeyOf( - BuildContext context, - ) { + static SelectedSharedPreferencesKey requireSelectedKeyOf(BuildContext context) { return selectedKeyOf(context)!; } @@ -164,13 +143,11 @@ class SharedPreferencesStateProvider extends StatefulWidget { /// Use of this method will cause the given [context] to rebuild whenever the /// selected key data changes, including loading and error states. /// This will not cause a rebuild when any other part of the state changes. - static AsyncState? selectedKeyDataOf( - BuildContext context, - ) { + static AsyncState? selectedKeyDataOf(BuildContext context) { return context - .dependOnInheritedWidgetOfExactType< - _SharedPreferencesStateInheritedModel - >(aspect: _StateInheritedModelAspect.selectedKeyData)! + .dependOnInheritedWidgetOfExactType<_SharedPreferencesStateInheritedModel>( + aspect: _StateInheritedModelAspect.selectedKeyData, + )! .state .selectedKey ?.value; @@ -183,9 +160,9 @@ class SharedPreferencesStateProvider extends StatefulWidget { /// This will not cause a rebuild when any other part of the state changes. static bool editingOf(BuildContext context) { return context - .dependOnInheritedWidgetOfExactType< - _SharedPreferencesStateInheritedModel - >(aspect: _StateInheritedModelAspect.editing)! + .dependOnInheritedWidgetOfExactType<_SharedPreferencesStateInheritedModel>( + aspect: _StateInheritedModelAspect.editing, + )! .state .editing; } @@ -197,9 +174,9 @@ class SharedPreferencesStateProvider extends StatefulWidget { /// This will not cause a rebuild when any other part of the state changes. static bool legacyApiOf(BuildContext context) { return context - .dependOnInheritedWidgetOfExactType< - _SharedPreferencesStateInheritedModel - >(aspect: _StateInheritedModelAspect.legacyApi)! + .dependOnInheritedWidgetOfExactType<_SharedPreferencesStateInheritedModel>( + aspect: _StateInheritedModelAspect.legacyApi, + )! .state .legacyApi; } @@ -208,12 +185,10 @@ class SharedPreferencesStateProvider extends StatefulWidget { final Widget child; @override - State createState() => - _SharedPreferencesStateProviderState(); + State createState() => _SharedPreferencesStateProviderState(); } -class _SharedPreferencesStateProviderState - extends State { +class _SharedPreferencesStateProviderState extends State { late final SharedPreferencesStateNotifier _notifier; @override @@ -238,10 +213,7 @@ class _SharedPreferencesStateProviderState @override Widget build(BuildContext context) { - return InnerSharedPreferencesStateProvider( - notifier: _notifier, - child: widget.child, - ); + return InnerSharedPreferencesStateProvider(notifier: _notifier, child: widget.child); } } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_tool_eval.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_tool_eval.dart index deffd31a22f0..f48db6bbf7c7 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_tool_eval.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/shared_preferences_tool_eval.dart @@ -48,10 +48,7 @@ class SharedPreferencesToolEval { return (data[key]! as List).cast(); } - return ( - asyncKeys: castList('asyncKeys'), - legacyKeys: castList('legacyKeys'), - ); + return (asyncKeys: castList('asyncKeys'), legacyKeys: castList('legacyKeys')); } Future> _evalMethod({ @@ -71,10 +68,7 @@ class SharedPreferencesToolEval { } }); - await _eval.eval( - 'SharedPreferencesDevToolsExtensionData().$method', - isAlive: isAlive, - ); + await _eval.eval('SharedPreferencesDevToolsExtensionData().$method', isAlive: isAlive); return completer.future; } @@ -112,19 +106,14 @@ class SharedPreferencesToolEval { /// Changes the value of the key in the shared preferences of the target debug /// session. - Future changeValue( - String key, - SharedPreferencesData value, - bool legacy, - ) async { + Future changeValue(String key, SharedPreferencesData value, bool legacy) async { _changeValueDisposable?.dispose(); _changeValueDisposable = Disposable(); final String serializedValue = jsonEncode(value.value); final String kind = value.kind; await _evalMethod( - method: - "requestValueChange('$key', '$serializedValue', '$kind', $legacy)", + method: "requestValueChange('$key', '$serializedValue', '$kind', $legacy)", eventKind: 'change_value', isAlive: _changeValueDisposable, ); diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/api_switch.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/api_switch.dart index 8224ceda994c..97e4cbefa2b5 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/api_switch.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/api_switch.dart @@ -25,19 +25,11 @@ class ApiSwitch extends StatelessWidget { child: DevToolsToggleButtonGroup( selectedStates: [legacyApi, !legacyApi], onPressed: (int index) { - context.sharedPreferencesStateNotifier.selectApi( - legacyApi: index == 0, - ); + context.sharedPreferencesStateNotifier.selectApi(legacyApi: index == 0); }, children: const [ - Padding( - padding: EdgeInsets.all(densePadding), - child: Text('Legacy API'), - ), - Padding( - padding: EdgeInsets.all(densePadding), - child: Text('Async API'), - ), + Padding(padding: EdgeInsets.all(densePadding), child: Text('Legacy API')), + Padding(padding: EdgeInsets.all(densePadding), child: Text('Async API')), ], ), ), diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart index 24f45dfb0da3..bb619f47137b 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/data_panel.dart @@ -48,17 +48,14 @@ class _DataPanelState extends State { error: value.error, stackTrace: value.stackTrace, ), - AsyncStateData( - data: final SharedPreferencesData data, - ) => - Column( - children: [ - _Header(currentValue: currentValue, data: data), - Expanded( - child: _Content(data: data, setCurrentValue: _setCurrentValue), - ), - ], - ), + AsyncStateData(data: final SharedPreferencesData data) => Column( + children: [ + _Header(currentValue: currentValue, data: data), + Expanded( + child: _Content(data: data, setCurrentValue: _setCurrentValue), + ), + ], + ), }, ); } @@ -75,8 +72,7 @@ class _Header extends StatelessWidget { final bool editing = SharedPreferencesStateProvider.editingOf(context); // it is safe to assume that the selected key is not null // because the header is only shown when a key is selected - final String selectedKey = - SharedPreferencesStateProvider.requireSelectedKeyOf(context).key; + final String selectedKey = SharedPreferencesStateProvider.requireSelectedKeyOf(context).key; return AreaPaneHeader( roundedTopBorder: false, @@ -93,8 +89,7 @@ class _Header extends StatelessWidget { ), if (currentValue case final String currentValue? when currentValue != data.valueAsString && - (data is SharedPreferencesDataString || - currentValue.isNotEmpty)) ...[ + (data is SharedPreferencesDataString || currentValue.isNotEmpty)) ...[ const SizedBox(width: denseRowSpacing), DevToolsButton( onPressed: () async { @@ -120,18 +115,15 @@ class _Header extends StatelessWidget { context.sharedPreferencesStateNotifier; showDialog( context: context, - builder: (BuildContext context) => _ConfirmRemoveDialog( - selectedKey: selectedKey, - notifier: notifier, - ), + builder: (BuildContext context) => + _ConfirmRemoveDialog(selectedKey: selectedKey, notifier: notifier), ); }, label: 'Remove', ), const SizedBox(width: denseRowSpacing), DevToolsButton( - onPressed: () => - context.sharedPreferencesStateNotifier.startEditing(), + onPressed: () => context.sharedPreferencesStateNotifier.startEditing(), label: 'Edit', ), ], @@ -141,10 +133,7 @@ class _Header extends StatelessWidget { } class _ConfirmRemoveDialog extends StatelessWidget { - const _ConfirmRemoveDialog({ - required this.selectedKey, - required this.notifier, - }); + const _ConfirmRemoveDialog({required this.selectedKey, required this.notifier}); final String selectedKey; final SharedPreferencesStateNotifier notifier; @@ -201,11 +190,10 @@ class _Content extends StatelessWidget { initialValue: state.value, setCurrentValue: setCurrentValue, ), - final SharedPreferencesDataStringList state => - _EditStringList( - initialData: state.value, - onChanged: setCurrentValue, - ), + final SharedPreferencesDataStringList state => _EditStringList( + initialData: state.value, + onChanged: setCurrentValue, + ), _ => TextFormField( autofocus: true, initialValue: data.valueAsString, @@ -214,9 +202,7 @@ class _Content extends StatelessWidget { FilteringTextInputFormatter.allow(RegExp(r'^-?\d*')), ], SharedPreferencesDataDouble() => [ - FilteringTextInputFormatter.allow( - RegExp(r'^-?\d*\.?\d*'), - ), + FilteringTextInputFormatter.allow(RegExp(r'^-?\d*\.?\d*')), ], _ => [], }, @@ -233,10 +219,7 @@ class _Content extends StatelessWidget { } class _EditBoolean extends StatelessWidget { - const _EditBoolean({ - required this.setCurrentValue, - required this.initialValue, - }); + const _EditBoolean({required this.setCurrentValue, required this.initialValue}); final ValueChanged setCurrentValue; final bool initialValue; @@ -278,9 +261,7 @@ class _EditStringListState extends State<_EditStringList> { } void _updateValue() { - widget.onChanged( - jsonEncode([for (final (_, String value) in _currentList) value]), - ); + widget.onChanged(jsonEncode([for (final (_, String value) in _currentList) value])); } @override @@ -297,8 +278,7 @@ class _EditStringListState extends State<_EditStringList> { crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ - for (final (int index, (int keyValue, String str)) - in _currentList.indexed) ...[ + for (final (int index, (int keyValue, String str)) in _currentList.indexed) ...[ if (index > 0) const SizedBox(height: largeSpacing), _AddListElement(onPressed: () => _addElementAt(index)), Padding( diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/error_panel.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/error_panel.dart index 5c2228748d5d..ec127af0431f 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/error_panel.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/error_panel.dart @@ -21,10 +21,7 @@ class ErrorPanel extends StatelessWidget { Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(densePadding), - child: Text( - 'Error:\n$error\n\n$stackTrace', - style: Theme.of(context).errorTextStyle, - ), + child: Text('Error:\n$error\n\n$stackTrace', style: Theme.of(context).errorTextStyle), ); } } diff --git a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart index bf9ef5b5b431..710bbaa86c5c 100644 --- a/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart +++ b/packages/shared_preferences/shared_preferences_tool/lib/src/ui/keys_panel.dart @@ -56,10 +56,7 @@ class _KeysPanelState extends State { tall: true, title: Row( children: [ - Text( - 'Stored Keys', - style: Theme.of(context).textTheme.titleSmall, - ), + Text('Stored Keys', style: Theme.of(context).textTheme.titleSmall), if (searching) ...[ const SizedBox(width: denseSpacing), Expanded( @@ -98,11 +95,7 @@ class _KeysPanelState extends State { // TODO(adsonpleal): replace this with `ToolbarAction` once it's available in `devtools_app_shared`, https://github.com/flutter/devtools/issues/7793. class _ToolbarAction extends StatelessWidget { - const _ToolbarAction({ - required this.tooltipMessage, - required this.icon, - required this.onPressed, - }); + const _ToolbarAction({required this.tooltipMessage, required this.icon, required this.onPressed}); final String tooltipMessage; final IconData icon; @@ -118,21 +111,14 @@ class _ToolbarAction extends StatelessWidget { tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: onPressed, - child: Icon( - icon, - size: actionsIconSize, - color: Theme.of(context).colorScheme.onSurface, - ), + child: Icon(icon, size: actionsIconSize, color: Theme.of(context).colorScheme.onSurface), ), ); } } class _SearchField extends StatelessWidget { - const _SearchField({ - required this.searchFocusNode, - required this.stopSearching, - }); + const _SearchField({required this.searchFocusNode, required this.stopSearching}); final FocusNode searchFocusNode; final VoidCallback stopSearching; @@ -177,9 +163,7 @@ class _StateMapper extends StatelessWidget { error: value.error, stackTrace: value.stackTrace, ), - AsyncStateLoading>() => const Center( - child: CircularProgressIndicator(), - ), + AsyncStateLoading>() => const Center(child: CircularProgressIndicator()), }; } } @@ -208,9 +192,7 @@ class _KeysListState extends State<_KeysList> { controller: scrollController, child: ListView( controller: scrollController, - children: [ - for (final String keyName in widget.keys) _KeyItem(keyName: keyName), - ], + children: [for (final String keyName in widget.keys) _KeyItem(keyName: keyName)], ), ); } @@ -223,13 +205,12 @@ class _KeyItem extends StatelessWidget { @override Widget build(BuildContext context) { - final SelectedSharedPreferencesKey? selectedKey = - SharedPreferencesStateProvider.selectedKeyOf(context); + final SelectedSharedPreferencesKey? selectedKey = SharedPreferencesStateProvider.selectedKeyOf( + context, + ); final isSelected = selectedKey?.key == keyName; final ColorScheme colorScheme = Theme.of(context).colorScheme; - final Color? backgroundColor = isSelected - ? colorScheme.selectedRowBackgroundColor - : null; + final Color? backgroundColor = isSelected ? colorScheme.selectedRowBackgroundColor : null; return InkWell( onTap: () { diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.dart index 25f11b5276ef..e66bd56a0e25 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.dart @@ -62,12 +62,10 @@ void main() { test('should select key', () async { const keys = ['key1', 'key2']; const keyValue = SharedPreferencesData.string(value: 'value'); - when(evalMock.fetchAllKeys()).thenAnswer( - (_) async => (asyncKeys: keys, legacyKeys: const []), - ); when( - evalMock.fetchValue('key1', false), - ).thenAnswer((_) async => keyValue); + evalMock.fetchAllKeys(), + ).thenAnswer((_) async => (asyncKeys: keys, legacyKeys: const [])); + when(evalMock.fetchValue('key1', false)).thenAnswer((_) async => keyValue); await notifier.fetchAllKeys(); await notifier.selectKey('key1'); @@ -86,9 +84,9 @@ void main() { test('should select key for legacy api', () async { const keys = ['key1', 'key2']; const keyValue = SharedPreferencesData.string(value: 'value'); - when(evalMock.fetchAllKeys()).thenAnswer( - (_) async => (asyncKeys: const [], legacyKeys: keys), - ); + when( + evalMock.fetchAllKeys(), + ).thenAnswer((_) async => (asyncKeys: const [], legacyKeys: keys)); when(evalMock.fetchValue('key1', true)).thenAnswer((_) async => keyValue); await notifier.fetchAllKeys(); notifier.selectApi(legacyApi: true); @@ -150,9 +148,7 @@ void main() { evalMock.fetchAllKeys(), ).thenAnswer((_) async => (asyncKeys: asyncKeys, legacyKeys: legacyKeys)); const keyValue = SharedPreferencesData.string(value: 'value'); - when( - evalMock.fetchValue('key1', false), - ).thenAnswer((_) async => keyValue); + when(evalMock.fetchValue('key1', false)).thenAnswer((_) async => keyValue); await notifier.fetchAllKeys(); await notifier.selectKey('key1'); @@ -168,22 +164,14 @@ void main() { evalMock.fetchAllKeys(), ).thenAnswer((_) async => (asyncKeys: asyncKeys, legacyKeys: legacyKeys)); const keyValue = SharedPreferencesData.string(value: 'value'); - when( - evalMock.fetchValue('key1', false), - ).thenAnswer((_) async => keyValue); + when(evalMock.fetchValue('key1', false)).thenAnswer((_) async => keyValue); await notifier.fetchAllKeys(); await notifier.selectKey('key1'); - await notifier.changeValue( - const SharedPreferencesData.string(value: 'newValue'), - ); + await notifier.changeValue(const SharedPreferencesData.string(value: 'newValue')); verify( - evalMock.changeValue( - 'key1', - const SharedPreferencesData.string(value: 'newValue'), - false, - ), + evalMock.changeValue('key1', const SharedPreferencesData.string(value: 'newValue'), false), ).called(1); }); diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart index 89fb66be1f07..31f07288e224 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_notifier_test.mocks.dart @@ -8,10 +8,8 @@ import 'dart:async' as _i2; import 'package:devtools_app_shared/service.dart' as _i6; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i5; -import 'package:shared_preferences_tool/src/shared_preferences_state.dart' - as _i4; -import 'package:shared_preferences_tool/src/shared_preferences_tool_eval.dart' - as _i3; +import 'package:shared_preferences_tool/src/shared_preferences_state.dart' as _i4; +import 'package:shared_preferences_tool/src/shared_preferences_tool_eval.dart' as _i3; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -27,78 +25,64 @@ import 'package:shared_preferences_tool/src/shared_preferences_tool_eval.dart' // ignore_for_file: subtype_of_sealed_class class _FakeCompleter_0 extends _i1.SmartFake implements _i2.Completer { - _FakeCompleter_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); + _FakeCompleter_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } /// A class which mocks [SharedPreferencesToolEval]. /// /// See the documentation for Mockito's code generation for more information. -class MockSharedPreferencesToolEval extends _i1.Mock - implements _i3.SharedPreferencesToolEval { +class MockSharedPreferencesToolEval extends _i1.Mock implements _i3.SharedPreferencesToolEval { @override - _i2.Future<({List asyncKeys, List legacyKeys})> - fetchAllKeys() => + _i2.Future<({List asyncKeys, List legacyKeys})> fetchAllKeys() => (super.noSuchMethod( - Invocation.method(#fetchAllKeys, []), - returnValue: - _i2.Future< - ({List asyncKeys, List legacyKeys}) - >.value((asyncKeys: [], legacyKeys: [])), - returnValueForMissingStub: - _i2.Future< - ({List asyncKeys, List legacyKeys}) - >.value((asyncKeys: [], legacyKeys: [])), - ) - as _i2.Future<({List asyncKeys, List legacyKeys})>); + Invocation.method(#fetchAllKeys, []), + returnValue: _i2.Future<({List asyncKeys, List legacyKeys})>.value(( + asyncKeys: [], + legacyKeys: [], + )), + returnValueForMissingStub: + _i2.Future<({List asyncKeys, List legacyKeys})>.value(( + asyncKeys: [], + legacyKeys: [], + )), + ) as _i2.Future<({List asyncKeys, List legacyKeys})>); @override _i2.Future<_i4.SharedPreferencesData> fetchValue(String? key, bool? legacy) => (super.noSuchMethod( + Invocation.method(#fetchValue, [key, legacy]), + returnValue: _i2.Future<_i4.SharedPreferencesData>.value( + _i5.dummyValue<_i4.SharedPreferencesData>( + this, Invocation.method(#fetchValue, [key, legacy]), - returnValue: _i2.Future<_i4.SharedPreferencesData>.value( - _i5.dummyValue<_i4.SharedPreferencesData>( - this, - Invocation.method(#fetchValue, [key, legacy]), - ), - ), - returnValueForMissingStub: - _i2.Future<_i4.SharedPreferencesData>.value( - _i5.dummyValue<_i4.SharedPreferencesData>( - this, - Invocation.method(#fetchValue, [key, legacy]), - ), - ), - ) - as _i2.Future<_i4.SharedPreferencesData>); - - @override - _i2.Future changeValue( - String? key, - _i4.SharedPreferencesData? value, - bool? legacy, - ) => - (super.noSuchMethod( - Invocation.method(#changeValue, [key, value, legacy]), - returnValue: _i2.Future.value(), - returnValueForMissingStub: _i2.Future.value(), - ) - as _i2.Future); + ), + ), + returnValueForMissingStub: _i2.Future<_i4.SharedPreferencesData>.value( + _i5.dummyValue<_i4.SharedPreferencesData>( + this, + Invocation.method(#fetchValue, [key, legacy]), + ), + ), + ) as _i2.Future<_i4.SharedPreferencesData>); @override - _i2.Future deleteKey(String? key, bool? legacy) => + _i2.Future changeValue(String? key, _i4.SharedPreferencesData? value, bool? legacy) => (super.noSuchMethod( - Invocation.method(#deleteKey, [key, legacy]), - returnValue: _i2.Future.value(), - returnValueForMissingStub: _i2.Future.value(), - ) - as _i2.Future); + Invocation.method(#changeValue, [key, value, legacy]), + returnValue: _i2.Future.value(), + returnValueForMissingStub: _i2.Future.value(), + ) as _i2.Future); @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); + _i2.Future deleteKey(String? key, bool? legacy) => (super.noSuchMethod( + Invocation.method(#deleteKey, [key, legacy]), + returnValue: _i2.Future.value(), + returnValueForMissingStub: _i2.Future.value(), + ) as _i2.Future); + + @override + void dispose() => + super.noSuchMethod(Invocation.method(#dispose, []), returnValueForMissingStub: null); } /// A class which mocks [ConnectedApp]. @@ -106,19 +90,11 @@ class MockSharedPreferencesToolEval extends _i1.Mock /// See the documentation for Mockito's code generation for more information. class MockConnectedApp extends _i1.Mock implements _i6.ConnectedApp { @override - _i2.Completer get initialized => - (super.noSuchMethod( - Invocation.getter(#initialized), - returnValue: _FakeCompleter_0( - this, - Invocation.getter(#initialized), - ), - returnValueForMissingStub: _FakeCompleter_0( - this, - Invocation.getter(#initialized), - ), - ) - as _i2.Completer); + _i2.Completer get initialized => (super.noSuchMethod( + Invocation.getter(#initialized), + returnValue: _FakeCompleter_0(this, Invocation.getter(#initialized)), + returnValueForMissingStub: _FakeCompleter_0(this, Invocation.getter(#initialized)), + ) as _i2.Completer); @override set initialized(_i2.Completer? _initialized) => super.noSuchMethod( @@ -127,116 +103,86 @@ class MockConnectedApp extends _i1.Mock implements _i6.ConnectedApp { ); @override - bool get connectedAppInitialized => - (super.noSuchMethod( - Invocation.getter(#connectedAppInitialized), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get connectedAppInitialized => (super.noSuchMethod( + Invocation.getter(#connectedAppInitialized), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - String get operatingSystem => - (super.noSuchMethod( - Invocation.getter(#operatingSystem), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#operatingSystem), - ), - returnValueForMissingStub: _i5.dummyValue( - this, - Invocation.getter(#operatingSystem), - ), - ) - as String); - - @override - _i2.Future get isFlutterApp => - (super.noSuchMethod( - Invocation.getter(#isFlutterApp), - returnValue: _i2.Future.value(false), - returnValueForMissingStub: _i2.Future.value(false), - ) - as _i2.Future); + String get operatingSystem => (super.noSuchMethod( + Invocation.getter(#operatingSystem), + returnValue: _i5.dummyValue(this, Invocation.getter(#operatingSystem)), + returnValueForMissingStub: _i5.dummyValue(this, Invocation.getter(#operatingSystem)), + ) as String); @override - _i2.Future get isProfileBuild => - (super.noSuchMethod( - Invocation.getter(#isProfileBuild), - returnValue: _i2.Future.value(false), - returnValueForMissingStub: _i2.Future.value(false), - ) - as _i2.Future); + _i2.Future get isFlutterApp => (super.noSuchMethod( + Invocation.getter(#isFlutterApp), + returnValue: _i2.Future.value(false), + returnValueForMissingStub: _i2.Future.value(false), + ) as _i2.Future); @override - _i2.Future get isDartWebApp => - (super.noSuchMethod( - Invocation.getter(#isDartWebApp), - returnValue: _i2.Future.value(false), - returnValueForMissingStub: _i2.Future.value(false), - ) - as _i2.Future); + _i2.Future get isProfileBuild => (super.noSuchMethod( + Invocation.getter(#isProfileBuild), + returnValue: _i2.Future.value(false), + returnValueForMissingStub: _i2.Future.value(false), + ) as _i2.Future); @override - bool get isFlutterWebAppNow => - (super.noSuchMethod( - Invocation.getter(#isFlutterWebAppNow), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + _i2.Future get isDartWebApp => (super.noSuchMethod( + Invocation.getter(#isDartWebApp), + returnValue: _i2.Future.value(false), + returnValueForMissingStub: _i2.Future.value(false), + ) as _i2.Future); @override - bool get isFlutterNativeAppNow => - (super.noSuchMethod( - Invocation.getter(#isFlutterNativeAppNow), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isFlutterWebAppNow => (super.noSuchMethod( + Invocation.getter(#isFlutterWebAppNow), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - bool get isDebugFlutterAppNow => - (super.noSuchMethod( - Invocation.getter(#isDebugFlutterAppNow), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get isFlutterNativeAppNow => (super.noSuchMethod( + Invocation.getter(#isFlutterNativeAppNow), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i2.Future get isDartCliApp => - (super.noSuchMethod( - Invocation.getter(#isDartCliApp), - returnValue: _i2.Future.value(false), - returnValueForMissingStub: _i2.Future.value(false), - ) - as _i2.Future); + bool get isDebugFlutterAppNow => (super.noSuchMethod( + Invocation.getter(#isDebugFlutterAppNow), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - bool get isDartCliAppNow => - (super.noSuchMethod( - Invocation.getter(#isDartCliAppNow), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + _i2.Future get isDartCliApp => (super.noSuchMethod( + Invocation.getter(#isDartCliApp), + returnValue: _i2.Future.value(false), + returnValueForMissingStub: _i2.Future.value(false), + ) as _i2.Future); @override - _i2.Future initializeValues({void Function()? onComplete}) => - (super.noSuchMethod( - Invocation.method(#initializeValues, [], {#onComplete: onComplete}), - returnValue: _i2.Future.value(), - returnValueForMissingStub: _i2.Future.value(), - ) - as _i2.Future); + bool get isDartCliAppNow => (super.noSuchMethod( + Invocation.getter(#isDartCliAppNow), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - Map toJson() => - (super.noSuchMethod( - Invocation.method(#toJson, []), - returnValue: {}, - returnValueForMissingStub: {}, - ) - as Map); + _i2.Future initializeValues({void Function()? onComplete}) => (super.noSuchMethod( + Invocation.method(#initializeValues, [], {#onComplete: onComplete}), + returnValue: _i2.Future.value(), + returnValueForMissingStub: _i2.Future.value(), + ) as _i2.Future); + + @override + Map toJson() => (super.noSuchMethod( + Invocation.method(#toJson, []), + returnValue: {}, + returnValueForMissingStub: {}, + ) as Map); } diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_test.dart index 600613e5495e..bcd827ab28de 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_state_test.dart @@ -16,10 +16,7 @@ void main() { ), ); - expect( - state.copyWith(selectedKey: null), - equals(const SharedPreferencesState()), - ); + expect(state.copyWith(selectedKey: null), equals(const SharedPreferencesState())); }); }); @@ -37,9 +34,7 @@ void main() { const boolData = SharedPreferencesData.bool(value: true); expect(boolData.valueAsString, 'true'); - const stringListData = SharedPreferencesData.stringList( - value: ['value1', 'value2'], - ); + const stringListData = SharedPreferencesData.stringList(value: ['value1', 'value2']); expect(stringListData.valueAsString, '\n0 -> value1\n1 -> value2'); }); }); @@ -57,9 +52,7 @@ void main() { const boolData = SharedPreferencesData.bool(value: true); expect(boolData.kind, 'bool'); - const stringListData = SharedPreferencesData.stringList( - value: ['value1', 'value2'], - ); + const stringListData = SharedPreferencesData.stringList(value: ['value1', 'value2']); expect(stringListData.kind, 'List'); }); @@ -108,9 +101,7 @@ void main() { ), ); - const stringListData = SharedPreferencesData.stringList( - value: ['value1', 'value2'], - ); + const stringListData = SharedPreferencesData.stringList(value: ['value1', 'value2']); const newStringListValue = '["newValue1", "newValue2"]'; expect( stringListData.changeValue(newStringListValue), diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_tool_eval_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_tool_eval_test.dart index ed3dfb74c9b3..a658843235a8 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_tool_eval_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/shared_preferences_tool_eval_test.dart @@ -16,11 +16,7 @@ typedef _Event = (String eventKind, Map eventData); // ignore: subtype_of_sealed_class class _FakeEvalOnDartLibrary extends EvalOnDartLibrary { _FakeEvalOnDartLibrary(VmService vmService) - : super( - 'fake_library', - vmService, - serviceManager: ServiceManager(), - ); + : super('fake_library', vmService, serviceManager: ServiceManager()); final List<_Event> eventLog = <_Event>[]; @@ -104,13 +100,9 @@ void main() { response: {'value': expectedValue, 'kind': 'int'}, ); - final SharedPreferencesData data = await sharedPreferencesToolEval - .fetchValue(key, false); + final SharedPreferencesData data = await sharedPreferencesToolEval.fetchValue(key, false); - expect( - data, - equals(const SharedPreferencesData.int(value: expectedValue)), - ); + expect(data, equals(const SharedPreferencesData.int(value: expectedValue))); }); test('should fetch bool value', () async { @@ -122,13 +114,9 @@ void main() { response: {'value': expectedValue, 'kind': 'bool'}, ); - final SharedPreferencesData data = await sharedPreferencesToolEval - .fetchValue(key, false); + final SharedPreferencesData data = await sharedPreferencesToolEval.fetchValue(key, false); - expect( - data, - equals(const SharedPreferencesData.bool(value: expectedValue)), - ); + expect(data, equals(const SharedPreferencesData.bool(value: expectedValue))); }); test('should fetch double value', () async { @@ -140,13 +128,9 @@ void main() { response: {'value': expectedValue, 'kind': 'double'}, ); - final SharedPreferencesData data = await sharedPreferencesToolEval - .fetchValue(key, false); + final SharedPreferencesData data = await sharedPreferencesToolEval.fetchValue(key, false); - expect( - data, - equals(const SharedPreferencesData.double(value: expectedValue)), - ); + expect(data, equals(const SharedPreferencesData.double(value: expectedValue))); }); test('should fetch string value', () async { @@ -158,13 +142,9 @@ void main() { response: {'value': expectedValue, 'kind': 'String'}, ); - final SharedPreferencesData data = await sharedPreferencesToolEval - .fetchValue(key, false); + final SharedPreferencesData data = await sharedPreferencesToolEval.fetchValue(key, false); - expect( - data, - equals(const SharedPreferencesData.string(value: expectedValue)), - ); + expect(data, equals(const SharedPreferencesData.string(value: expectedValue))); }); test('should fetch string list value', () async { @@ -173,19 +153,12 @@ void main() { stubEvalMethod( eventKind: 'value', method: "requestValue('$key', true)", - response: { - 'value': expectedValue, - 'kind': 'List', - }, + response: {'value': expectedValue, 'kind': 'List'}, ); - final SharedPreferencesData data = await sharedPreferencesToolEval - .fetchValue(key, true); + final SharedPreferencesData data = await sharedPreferencesToolEval.fetchValue(key, true); - expect( - data, - equals(const SharedPreferencesData.stringList(value: expectedValue)), - ); + expect(data, equals(const SharedPreferencesData.stringList(value: expectedValue))); }); test('should throw error on unsupported value', () { @@ -196,20 +169,13 @@ void main() { response: {'value': 'error', 'kind': 'SomeClass'}, ); - expect( - () => sharedPreferencesToolEval.fetchValue(key, true), - throwsUnsupportedError, - ); + expect(() => sharedPreferencesToolEval.fetchValue(key, true), throwsUnsupportedError); }); test('should change value', () async { const key = 'testKey'; const method = "requestValueChange('$key', 'true', 'bool', false)"; - stubEvalMethod( - eventKind: 'change_value', - method: method, - response: {}, - ); + stubEvalMethod(eventKind: 'change_value', method: method, response: {}); await sharedPreferencesToolEval.changeValue( key, @@ -218,25 +184,18 @@ void main() { ); expect(eval.eventLog.length, equals(1)); - final (String eventKind, Map eventData) = - eval.eventLog.first; + final (String eventKind, Map eventData) = eval.eventLog.first; expect(eventKind, equals('eval')); expect( eventData, - equals({ - 'expression': 'SharedPreferencesDevToolsExtensionData().$method', - }), + equals({'expression': 'SharedPreferencesDevToolsExtensionData().$method'}), ); }); test('should delete key', () async { const key = 'testKey'; const method = "requestRemoveKey('$key', false)"; - stubEvalMethod( - eventKind: 'remove', - method: method, - response: {}, - ); + stubEvalMethod(eventKind: 'remove', method: method, response: {}); await sharedPreferencesToolEval.deleteKey(key, false); diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart index 76b4ae549d23..eba361162daa 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/ui/data_panel_test.dart @@ -40,10 +40,7 @@ void main() { ); } - void stubAsyncState( - AsyncState? state, { - bool editing = false, - }) { + void stubAsyncState(AsyncState? state, {bool editing = false}) { const selectedKey = 'selectedTestKey'; when(notifierMock.value).thenReturn( SharedPreferencesState( @@ -57,10 +54,7 @@ void main() { } void stubDataState(SharedPreferencesData state, {bool editing = false}) { - stubAsyncState( - AsyncState.data(state), - editing: editing, - ); + stubAsyncState(AsyncState.data(state), editing: editing); } testWidgets('should show select key state', (WidgetTester tester) async { @@ -78,12 +72,7 @@ void main() { }); testWidgets('should show error state', (WidgetTester tester) async { - stubAsyncState( - const AsyncState.error( - 'error', - StackTrace.empty, - ), - ); + stubAsyncState(const AsyncState.error('error', StackTrace.empty)); await pumpDataPanel(tester); expect(find.byType(ErrorPanel), findsOneWidget); @@ -126,11 +115,7 @@ void main() { }); testWidgets('should show string list value', (WidgetTester tester) async { - stubDataState( - const SharedPreferencesData.stringList( - value: ['value1', 'value2'], - ), - ); + stubDataState(const SharedPreferencesData.stringList(value: ['value1', 'value2'])); await pumpDataPanel(tester); expect(find.text('Type: List'), findsOneWidget); @@ -154,26 +139,19 @@ void main() { verify(notifierMock.startEditing()).called(1); }); - testWidgets('on remove should show confirmation modal', ( - WidgetTester tester, - ) async { + testWidgets('on remove should show confirmation modal', (WidgetTester tester) async { stubDataState(const SharedPreferencesData.string(value: 'value')); await pumpDataPanel(tester); await tester.tap(find.text('Remove')); await tester.pumpAndSettle(); - expect( - find.text('Are you sure you want to remove selectedTestKey?'), - findsOneWidget, - ); + expect(find.text('Are you sure you want to remove selectedTestKey?'), findsOneWidget); expect(find.text('CANCEL'), findsOneWidget); expect(find.text('REMOVE'), findsOneWidget); }); - testWidgets('on removed confirmed should remove key', ( - WidgetTester tester, - ) async { + testWidgets('on removed confirmed should remove key', (WidgetTester tester) async { const value = SharedPreferencesData.string(value: 'value'); stubDataState(value); await pumpDataPanel(tester); @@ -185,9 +163,7 @@ void main() { verify(notifierMock.deleteSelectedKey()).called(1); }); - testWidgets('on remove canceled should cancel remove', ( - WidgetTester tester, - ) async { + testWidgets('on remove canceled should cancel remove', (WidgetTester tester) async { stubDataState(const SharedPreferencesData.string(value: 'value')); await pumpDataPanel(tester); await tester.tap(find.text('Remove')); @@ -196,30 +172,19 @@ void main() { await tester.tap(find.text('CANCEL')); await tester.pumpAndSettle(); - expect( - find.text('Are you sure you want to remove selectedTestKey?'), - findsNothing, - ); + expect(find.text('Are you sure you want to remove selectedTestKey?'), findsNothing); }); testWidgets('should show editing state', (WidgetTester tester) async { - stubDataState( - const SharedPreferencesData.string(value: 'value'), - editing: true, - ); + stubDataState(const SharedPreferencesData.string(value: 'value'), editing: true); await pumpDataPanel(tester); expect(find.text('Cancel'), findsOneWidget); }); - testWidgets('should show string editing state', ( - WidgetTester tester, - ) async { + testWidgets('should show string editing state', (WidgetTester tester) async { const value = 'value'; - stubDataState( - const SharedPreferencesData.string(value: value), - editing: true, - ); + stubDataState(const SharedPreferencesData.string(value: value), editing: true); await pumpDataPanel(tester); expect(find.text('Type: String'), findsOneWidget); @@ -230,50 +195,31 @@ void main() { testWidgets('should show int editing state', (WidgetTester tester) async { const value = 42; - stubDataState( - const SharedPreferencesData.int(value: value), - editing: true, - ); + stubDataState(const SharedPreferencesData.int(value: value), editing: true); await pumpDataPanel(tester); expect(find.text('Type: int'), findsOneWidget); expect(find.text('Value:'), findsOneWidget); expect(find.text('$value'), findsOneWidget); expect(find.byType(TextField), findsOneWidget); - expect( - tester.textInputFormatterPattern, - equals(RegExp(r'^-?\d*').toString()), - ); + expect(tester.textInputFormatterPattern, equals(RegExp(r'^-?\d*').toString())); }); - testWidgets('should show double editing state', ( - WidgetTester tester, - ) async { + testWidgets('should show double editing state', (WidgetTester tester) async { const value = 42.0; - stubDataState( - const SharedPreferencesData.double(value: value), - editing: true, - ); + stubDataState(const SharedPreferencesData.double(value: value), editing: true); await pumpDataPanel(tester); expect(find.text('Type: double'), findsOneWidget); expect(find.text('Value:'), findsOneWidget); expect(find.text('$value'), findsOneWidget); expect(find.byType(TextField), findsOneWidget); - expect( - tester.textInputFormatterPattern, - equals(RegExp(r'^-?\d*\.?\d*').toString()), - ); + expect(tester.textInputFormatterPattern, equals(RegExp(r'^-?\d*\.?\d*').toString())); }); - testWidgets('should show boolean editing state', ( - WidgetTester tester, - ) async { + testWidgets('should show boolean editing state', (WidgetTester tester) async { const value = true; - stubDataState( - const SharedPreferencesData.bool(value: value), - editing: true, - ); + stubDataState(const SharedPreferencesData.bool(value: value), editing: true); await pumpDataPanel(tester); expect(find.text('Type: bool'), findsOneWidget); @@ -281,13 +227,9 @@ void main() { expect(find.byType(DropdownMenu), findsOneWidget); }); - testWidgets('should show string list editing state', ( - WidgetTester tester, - ) async { + testWidgets('should show string list editing state', (WidgetTester tester) async { stubDataState( - const SharedPreferencesData.stringList( - value: ['value1', 'value2'], - ), + const SharedPreferencesData.stringList(value: ['value1', 'value2']), editing: true, ); await pumpDataPanel(tester); @@ -306,13 +248,8 @@ void main() { expect(find.byIcon(Icons.add), findsNWidgets(3)); }); - testWidgets('should show apply changes button on value changed', ( - WidgetTester tester, - ) async { - stubDataState( - const SharedPreferencesData.string(value: 'value'), - editing: true, - ); + testWidgets('should show apply changes button on value changed', (WidgetTester tester) async { + stubDataState(const SharedPreferencesData.string(value: 'value'), editing: true); await pumpDataPanel(tester); await tester.enterText(find.byType(TextField), 'newValue'); @@ -324,9 +261,7 @@ void main() { testWidgets('pressing an add button on the string list editing state ' 'should add element in the right index', (WidgetTester tester) async { stubDataState( - const SharedPreferencesData.stringList( - value: ['value1', 'value2'], - ), + const SharedPreferencesData.stringList(value: ['value1', 'value2']), editing: true, ); await pumpDataPanel(tester); @@ -342,14 +277,10 @@ void main() { verifyInOrder(>[ notifierMock.changeValue( - const SharedPreferencesData.stringList( - value: ['0', 'value1', 'value2'], - ), + const SharedPreferencesData.stringList(value: ['0', 'value1', 'value2']), ), notifierMock.changeValue( - const SharedPreferencesData.stringList( - value: ['0', '1', 'value1', 'value2'], - ), + const SharedPreferencesData.stringList(value: ['0', '1', 'value1', 'value2']), ), notifierMock.changeValue( const SharedPreferencesData.stringList( @@ -364,8 +295,7 @@ void main() { extension on WidgetTester { Pattern get textInputFormatterPattern { final TextField textField = widget(find.byType(TextField)); - return (textField.inputFormatters!.first as FilteringTextInputFormatter) - .filterPattern + return (textField.inputFormatters!.first as FilteringTextInputFormatter).filterPattern .toString(); } } diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/ui/error_panel_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/ui/error_panel_test.dart index 285585572390..650a40bb0826 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/ui/error_panel_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/ui/error_panel_test.dart @@ -12,9 +12,7 @@ import 'package:shared_preferences_tool/src/ui/error_panel.dart'; void main() { group('ErrorPanel', () { - testWidgets('should show error and stacktrace', ( - WidgetTester tester, - ) async { + testWidgets('should show error and stacktrace', (WidgetTester tester) async { const error = 'error'; final StackTrace stackTrace = StackTrace.current; diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart index 6da48a540cc1..4e469fbe15bc 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/ui/keys_panel_test.dart @@ -41,18 +41,12 @@ void main() { } void stubDataState({ - AsyncState> allKeys = const AsyncState>.data( - [], - ), + AsyncState> allKeys = const AsyncState>.data([]), SelectedSharedPreferencesKey? selectedKey, bool editing = false, }) { when(notifierMock.value).thenReturn( - SharedPreferencesState( - allKeys: allKeys, - selectedKey: selectedKey, - editing: editing, - ), + SharedPreferencesState(allKeys: allKeys, selectedKey: selectedKey, editing: editing), ); } @@ -64,20 +58,13 @@ void main() { }); testWidgets('should show error state', (WidgetTester tester) async { - stubDataState( - allKeys: const AsyncState>.error( - 'error', - StackTrace.empty, - ), - ); + stubDataState(allKeys: const AsyncState>.error('error', StackTrace.empty)); await pumpKeysPanel(tester); expect(find.byType(ErrorPanel), findsOneWidget); }); - testWidgets('should show keys list with all keys', ( - WidgetTester tester, - ) async { + testWidgets('should show keys list with all keys', (WidgetTester tester) async { const allKeys = ['key1', 'key2']; stubDataState(allKeys: const AsyncState>.data(allKeys)); @@ -88,9 +75,7 @@ void main() { } }); - testWidgets('only selected key should be highlighted', ( - WidgetTester tester, - ) async { + testWidgets('only selected key should be highlighted', (WidgetTester tester) async { const selectedKey = 'selectedKey'; const keys = ['key1', selectedKey, 'key2']; @@ -115,15 +100,9 @@ void main() { } for (final key in [...keys]..remove(selectedKey)) { - expect( - bgColorFor(key), - isNot(equals(colorScheme.selectedRowBackgroundColor)), - ); + expect(bgColorFor(key), isNot(equals(colorScheme.selectedRowBackgroundColor))); } - expect( - bgColorFor(selectedKey), - equals(colorScheme.selectedRowBackgroundColor), - ); + expect(bgColorFor(selectedKey), equals(colorScheme.selectedRowBackgroundColor)); }); testWidgets('should start searching when clicking the search icon', ( @@ -138,9 +117,7 @@ void main() { expect(find.byType(TextField), findsOneWidget); }); - testWidgets('should stop searching when clicking the close icon', ( - WidgetTester tester, - ) async { + testWidgets('should stop searching when clicking the close icon', (WidgetTester tester) async { stubDataState(); await pumpKeysPanel(tester); await tester.tap(find.byIcon(Icons.search)); @@ -152,9 +129,7 @@ void main() { expect(find.byType(TextField), findsNothing); }); - testWidgets('should filter keys when searching', ( - WidgetTester tester, - ) async { + testWidgets('should filter keys when searching', (WidgetTester tester) async { stubDataState(); await pumpKeysPanel(tester); await tester.tap(find.byIcon(Icons.search)); @@ -165,9 +140,7 @@ void main() { verify(notifierMock.filter('key2')).called(1); }); - testWidgets('should refresh on refresh icon clicked', ( - WidgetTester tester, - ) async { + testWidgets('should refresh on refresh icon clicked', (WidgetTester tester) async { stubDataState(); await pumpKeysPanel(tester); @@ -177,13 +150,9 @@ void main() { verify(notifierMock.fetchAllKeys()).called(1); }); - testWidgets('should select key on key clicked', ( - WidgetTester tester, - ) async { + testWidgets('should select key on key clicked', (WidgetTester tester) async { const keyToSelect = 'keyToSelect'; - stubDataState( - allKeys: const AsyncState>.data([keyToSelect]), - ); + stubDataState(allKeys: const AsyncState>.data([keyToSelect])); await pumpKeysPanel(tester); await tester.tap(find.text(keyToSelect)); diff --git a/packages/shared_preferences/shared_preferences_tool/test/src/ui/shared_preferences_body_test.dart b/packages/shared_preferences/shared_preferences_tool/test/src/ui/shared_preferences_body_test.dart index bf1c06f47a5d..97f505498b63 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/src/ui/shared_preferences_body_test.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/src/ui/shared_preferences_body_test.dart @@ -21,9 +21,7 @@ void main() { group('group name', () { setupDummies(); - testWidgets('should show keys and data panels', ( - WidgetTester tester, - ) async { + testWidgets('should show keys and data panels', (WidgetTester tester) async { final notifier = MockSharedPreferencesStateNotifier(); when(notifier.value).thenReturn(const SharedPreferencesState()); diff --git a/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.dart b/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.dart index c2ea2ec644ba..1ae6d745debf 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.dart @@ -9,21 +9,15 @@ import 'package:shared_preferences_tool/src/async_state.dart'; import 'package:shared_preferences_tool/src/shared_preferences_state.dart'; import 'package:shared_preferences_tool/src/shared_preferences_state_notifier.dart'; -@GenerateNiceMocks(>[ - MockSpec(), -]) +@GenerateNiceMocks(>[MockSpec()]) // ignore: unused_import import 'notifier_mocking_helpers.mocks.dart'; void setupDummies() { setUpAll(() { provideDummy( - const AsyncState.data( - SharedPreferencesData.int(value: 42), - ), - ); - provideDummy( - const AsyncState.data(SharedPreferencesState()), + const AsyncState.data(SharedPreferencesData.int(value: 42)), ); + provideDummy(const AsyncState.data(SharedPreferencesState())); }); } diff --git a/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.mocks.dart b/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.mocks.dart index 23a8c13db0a1..4d6961e16a40 100644 --- a/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.mocks.dart +++ b/packages/shared_preferences/shared_preferences_tool/test/test_helpers/notifier_mocking_helpers.mocks.dart @@ -7,10 +7,8 @@ import 'dart:async' as _i4; import 'dart:ui' as _i5; import 'package:mockito/mockito.dart' as _i1; -import 'package:shared_preferences_tool/src/shared_preferences_state.dart' - as _i2; -import 'package:shared_preferences_tool/src/shared_preferences_state_notifier.dart' - as _i3; +import 'package:shared_preferences_tool/src/shared_preferences_state.dart' as _i2; +import 'package:shared_preferences_tool/src/shared_preferences_state_notifier.dart' as _i3; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -25,8 +23,7 @@ import 'package:shared_preferences_tool/src/shared_preferences_state_notifier.da // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class -class _FakeSharedPreferencesState_0 extends _i1.SmartFake - implements _i2.SharedPreferencesState { +class _FakeSharedPreferencesState_0 extends _i1.SmartFake implements _i2.SharedPreferencesState { _FakeSharedPreferencesState_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -37,88 +34,62 @@ class _FakeSharedPreferencesState_0 extends _i1.SmartFake class MockSharedPreferencesStateNotifier extends _i1.Mock implements _i3.SharedPreferencesStateNotifier { @override - _i2.SharedPreferencesState get value => - (super.noSuchMethod( - Invocation.getter(#value), - returnValue: _FakeSharedPreferencesState_0( - this, - Invocation.getter(#value), - ), - returnValueForMissingStub: _FakeSharedPreferencesState_0( - this, - Invocation.getter(#value), - ), - ) - as _i2.SharedPreferencesState); + _i2.SharedPreferencesState get value => (super.noSuchMethod( + Invocation.getter(#value), + returnValue: _FakeSharedPreferencesState_0(this, Invocation.getter(#value)), + returnValueForMissingStub: _FakeSharedPreferencesState_0(this, Invocation.getter(#value)), + ) as _i2.SharedPreferencesState); @override - set value(_i2.SharedPreferencesState? newValue) => super.noSuchMethod( - Invocation.setter(#value, newValue), - returnValueForMissingStub: null, - ); + set value(_i2.SharedPreferencesState? newValue) => + super.noSuchMethod(Invocation.setter(#value, newValue), returnValueForMissingStub: null); @override - bool get hasListeners => - (super.noSuchMethod( - Invocation.getter(#hasListeners), - returnValue: false, - returnValueForMissingStub: false, - ) - as bool); + bool get hasListeners => (super.noSuchMethod( + Invocation.getter(#hasListeners), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i4.Future fetchAllKeys() => - (super.noSuchMethod( - Invocation.method(#fetchAllKeys, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future fetchAllKeys() => (super.noSuchMethod( + Invocation.method(#fetchAllKeys, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future selectKey(String? key) => - (super.noSuchMethod( - Invocation.method(#selectKey, [key]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future selectKey(String? key) => (super.noSuchMethod( + Invocation.method(#selectKey, [key]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - void filter(String? token) => super.noSuchMethod( - Invocation.method(#filter, [token]), - returnValueForMissingStub: null, - ); + void filter(String? token) => + super.noSuchMethod(Invocation.method(#filter, [token]), returnValueForMissingStub: null); @override - _i4.Future changeValue(_i2.SharedPreferencesData? newValue) => - (super.noSuchMethod( - Invocation.method(#changeValue, [newValue]), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future changeValue(_i2.SharedPreferencesData? newValue) => (super.noSuchMethod( + Invocation.method(#changeValue, [newValue]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - _i4.Future deleteSelectedKey() => - (super.noSuchMethod( - Invocation.method(#deleteSelectedKey, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future deleteSelectedKey() => (super.noSuchMethod( + Invocation.method(#deleteSelectedKey, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); @override - void startEditing() => super.noSuchMethod( - Invocation.method(#startEditing, []), - returnValueForMissingStub: null, - ); + void startEditing() => + super.noSuchMethod(Invocation.method(#startEditing, []), returnValueForMissingStub: null); @override - void stopEditing() => super.noSuchMethod( - Invocation.method(#stopEditing, []), - returnValueForMissingStub: null, - ); + void stopEditing() => + super.noSuchMethod(Invocation.method(#stopEditing, []), returnValueForMissingStub: null); @override void selectApi({required bool? legacyApi}) => super.noSuchMethod( @@ -139,14 +110,10 @@ class MockSharedPreferencesStateNotifier extends _i1.Mock ); @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); + void dispose() => + super.noSuchMethod(Invocation.method(#dispose, []), returnValueForMissingStub: null); @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); + void notifyListeners() => + super.noSuchMethod(Invocation.method(#notifyListeners, []), returnValueForMissingStub: null); } diff --git a/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart b/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart index 0a89c4dd52d3..ceee6c0a9a76 100644 --- a/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart +++ b/packages/shared_preferences/shared_preferences_web/example/integration_test/shared_preferences_web_test.dart @@ -20,17 +20,10 @@ void main() { }); group('shared_preferences_web', () { testWidgets('registers itself', (WidgetTester tester) async { - SharedPreferencesStorePlatform.instance = - MethodChannelSharedPreferencesStore(); - expect( - SharedPreferencesStorePlatform.instance, - isNot(isA()), - ); + SharedPreferencesStorePlatform.instance = MethodChannelSharedPreferencesStore(); + expect(SharedPreferencesStorePlatform.instance, isNot(isA())); SharedPreferencesPlugin.registerWith(null); - expect( - SharedPreferencesStorePlatform.instance, - isA(), - ); + expect(SharedPreferencesStorePlatform.instance, isA()); }); const flutterTestValues = { @@ -70,9 +63,7 @@ void main() { }); tearDown(() async { - await preferences.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await preferences.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); }); testWidgets('reading', (WidgetTester _) async { @@ -85,56 +76,20 @@ void main() { await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); await preferences.setValue('Double', 'Double', allTestValues['Double']!); - await preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ); - await preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ); - await preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ); - await preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ); - await preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ); + await preferences.setValue('StringList', 'StringList', allTestValues['StringList']!); + await preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!); + await preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); + await preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!); + await preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ); - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -200,10 +155,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithPrefix', (WidgetTester _) async { @@ -223,10 +175,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { @@ -256,18 +205,16 @@ void main() { testWidgets('remove', (WidgetTester _) async { const key = 'flutter.String'; await preferences.remove(key); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values[key], isNull); }); testWidgets('get all with prefix', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -276,15 +223,11 @@ void main() { }); testWidgets('get all with allow list', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.String'}, - ), - ), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters( + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.String'}), + ), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -293,10 +236,9 @@ void main() { }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -306,10 +248,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters', (WidgetTester _) async { @@ -331,22 +270,14 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); - testWidgets('clearWithParameters with allow list', ( - WidgetTester _, - ) async { + testWidgets('clearWithParameters with allow list', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.StringList'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.StringList'}), ), ); Map values = await preferences.getAllWithParameters( @@ -364,20 +295,16 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: '')), ); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); @@ -440,8 +367,7 @@ void main() { const testList = ['foo', 'bar']; Future getPreferences() async { - final SharedPreferencesAsyncPlatform preferences = - SharedPreferencesAsyncPlatform.instance!; + final SharedPreferencesAsyncPlatform preferences = SharedPreferencesAsyncPlatform.instance!; await preferences.clear( const ClearPreferencesParameters(filter: PreferencesFilters()), emptyOptions, @@ -488,17 +414,12 @@ void main() { final SharedPreferencesAsyncPlatform preferences = await getPreferences(); await preferences.setStringList(listKey, testList, emptyOptions); - final List? list = await preferences.getStringList( - listKey, - emptyOptions, - ); + final List? list = await preferences.getStringList(listKey, emptyOptions); list?.add('value'); expect(list?.length, testList.length + 1); }); - testWidgets('returns null when reading invalid JSON value', ( - WidgetTester _, - ) async { + testWidgets('returns null when reading invalid JSON value', (WidgetTester _) async { const value = 'value'; const invalidJsonDataKey = 'invalidJsonData'; const validJsonDataKey = 'validJsonData'; @@ -507,14 +428,8 @@ void main() { html.window.localStorage.setItem(invalidJsonDataKey, value); html.window.localStorage.setItem(validJsonDataKey, '"$value"'); - expect( - await preferences.getString(invalidJsonDataKey, emptyOptions), - isNull, - ); - expect( - await preferences.getString(validJsonDataKey, emptyOptions), - equals(value), - ); + expect(await preferences.getString(invalidJsonDataKey, emptyOptions), isNull); + expect(await preferences.getString(validJsonDataKey, emptyOptions), equals(value)); }); testWidgets('getPreferences', (WidgetTester _) async { diff --git a/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart b/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart index 87446fbf210f..90080b7a31f7 100644 --- a/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart +++ b/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart @@ -27,16 +27,12 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { @override Future clear() async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix))); } @override Future clearWithPrefix(String prefix) async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override @@ -45,10 +41,7 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { // IMPORTANT: Do not use html.window.localStorage.clear() as that will // remove _all_ local data, not just the keys prefixed with // _prefix - _getPrefixedKeys( - filter.prefix, - allowList: filter.allowList, - ).forEach(remove); + _getPrefixedKeys(filter.prefix, allowList: filter.allowList).forEach(remove); return true; } @@ -61,24 +54,15 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { @override Future> getAllWithPrefix(String prefix) async { - return getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return getAllWithParameters(GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) async { + Future> getAllWithParameters(GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final allData = {}; - for (final String key in _getPrefixedKeys( - filter.prefix, - allowList: filter.allowList, - )) { - final Object? value = _decodeValue( - html.window.localStorage.getItem(key)!, - ); + for (final String key in _getPrefixedKeys(filter.prefix, allowList: filter.allowList)) { + final Object? value = _decodeValue(html.window.localStorage.getItem(key)!); if (value != null) { allData[key] = value; } @@ -99,9 +83,7 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { } Iterable _getPrefixedKeys(String prefix, {Set? allowList}) { - return _getAllowedKeys( - allowList: allowList, - ).where((String key) => key.startsWith(prefix)); + return _getAllowedKeys(allowList: allowList).where((String key) => key.startsWith(prefix)); } } @@ -139,9 +121,7 @@ base class SharedPreferencesAsyncWeb extends SharedPreferencesAsyncPlatform { ) async { final allData = {}; for (final String key in _getAllowedKeys(allowList: allowList)) { - final Object? value = _decodeValue( - html.window.localStorage.getItem(key)!, - ); + final Object? value = _decodeValue(html.window.localStorage.getItem(key)!); if (value != null) { allData[key] = value; } @@ -158,29 +138,17 @@ base class SharedPreferencesAsyncWeb extends SharedPreferencesAsyncPlatform { } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) { + Future setString(String key, String value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) { + Future setBool(String key, bool value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) { + Future setDouble(String key, double value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @@ -190,76 +158,47 @@ base class SharedPreferencesAsyncWeb extends SharedPreferencesAsyncPlatform { } @override - Future setStringList( - String key, - List value, - SharedPreferencesOptions options, - ) { + Future setStringList(String key, List value, SharedPreferencesOptions options) { return _setValue(key, value, options); } - Future _setValue( - String key, - Object? value, - SharedPreferencesOptions options, - ) async { + Future _setValue(String key, Object? value, SharedPreferencesOptions options) async { html.window.localStorage.setItem(key, _encodeValue(value)); } @override - Future getString( - String key, - SharedPreferencesOptions options, - ) async { - final Map data = await _readAllFromLocalStorage({ - key, - }, options); + Future getString(String key, SharedPreferencesOptions options) async { + final Map data = await _readAllFromLocalStorage({key}, options); return data[key] as String?; } @override Future getBool(String key, SharedPreferencesOptions options) async { - final Map data = await _readAllFromLocalStorage({ - key, - }, options); + final Map data = await _readAllFromLocalStorage({key}, options); return data[key] as bool?; } @override - Future getDouble( - String key, - SharedPreferencesOptions options, - ) async { - final Map data = await _readAllFromLocalStorage({ - key, - }, options); + Future getDouble(String key, SharedPreferencesOptions options) async { + final Map data = await _readAllFromLocalStorage({key}, options); return data[key] as double?; } @override Future getInt(String key, SharedPreferencesOptions options) async { - final Map data = await _readAllFromLocalStorage({ - key, - }, options); + final Map data = await _readAllFromLocalStorage({key}, options); return data[key] as int?; } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) async { - final Map data = await _readAllFromLocalStorage({ - key, - }, options); + Future?> getStringList(String key, SharedPreferencesOptions options) async { + final Map data = await _readAllFromLocalStorage({key}, options); return (data[key] as List?)?.toList(); } } Iterable _getAllowedKeys({Set? allowList}) { - return html.window.localStorage.keys.where( - (String key) => allowList?.contains(key) ?? true, - ); + return html.window.localStorage.keys.where((String key) => allowList?.contains(key) ?? true); } String _encodeValue(Object? value) { diff --git a/packages/shared_preferences/shared_preferences_windows/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences_windows/example/integration_test/shared_preferences_test.dart index 456098c5563c..643daff6a54d 100644 --- a/packages/shared_preferences/shared_preferences_windows/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences_windows/example/integration_test/shared_preferences_test.dart @@ -49,56 +49,20 @@ void main() { await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); await preferences.setValue('Double', 'Double', allTestValues['Double']!); - await preferences.setValue( - 'StringList', - 'StringList', - allTestValues['StringList']!, - ); - await preferences.setValue( - 'String', - 'prefix.String', - allTestValues['prefix.String']!, - ); - await preferences.setValue( - 'Bool', - 'prefix.Bool', - allTestValues['prefix.Bool']!, - ); - await preferences.setValue( - 'Int', - 'prefix.Int', - allTestValues['prefix.Int']!, - ); - await preferences.setValue( - 'Double', - 'prefix.Double', - allTestValues['prefix.Double']!, - ); + await preferences.setValue('StringList', 'StringList', allTestValues['StringList']!); + await preferences.setValue('String', 'prefix.String', allTestValues['prefix.String']!); + await preferences.setValue('Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); + await preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!); + await preferences.setValue('Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue( 'StringList', 'prefix.StringList', allTestValues['prefix.StringList']!, ); - await preferences.setValue( - 'String', - 'flutter.String', - allTestValues['flutter.String']!, - ); - await preferences.setValue( - 'Bool', - 'flutter.Bool', - allTestValues['flutter.Bool']!, - ); - await preferences.setValue( - 'Int', - 'flutter.Int', - allTestValues['flutter.Int']!, - ); - await preferences.setValue( - 'Double', - 'flutter.Double', - allTestValues['flutter.Double']!, - ); + await preferences.setValue('String', 'flutter.String', allTestValues['flutter.String']!); + await preferences.setValue('Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); + await preferences.setValue('Int', 'flutter.Int', allTestValues['flutter.Int']!); + await preferences.setValue('Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', 'flutter.StringList', @@ -112,9 +76,7 @@ void main() { }); tearDown(() async { - await preferences.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await preferences.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); }); testWidgets('getAll', (WidgetTester _) async { @@ -130,9 +92,7 @@ void main() { testWidgets('remove', (WidgetTester _) async { const key = 'flutter.String'; await preferences.remove(key); - final Map values = await preferences.getAllWithPrefix( - '', - ); + final Map values = await preferences.getAllWithPrefix(''); expect(values[key], isNull); }); @@ -147,9 +107,7 @@ void main() { }); testWidgets('get all with prefix', (WidgetTester _) async { - final Map values = await preferences.getAllWithPrefix( - 'prefix.', - ); + final Map values = await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -158,9 +116,7 @@ void main() { }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { - final Map values = await preferences.getAllWithPrefix( - '', - ); + final Map values = await preferences.getAllWithPrefix(''); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -170,17 +126,12 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithPrefix', (WidgetTester _) async { await preferences.clearWithPrefix('prefix.'); - Map values = await preferences.getAllWithPrefix( - 'prefix.', - ); + Map values = await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -191,17 +142,12 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithPrefix(''); - final Map values = await preferences.getAllWithPrefix( - '', - ); + final Map values = await preferences.getAllWithPrefix(''); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); @@ -219,10 +165,9 @@ void main() { testWidgets('remove', (WidgetTester _) async { const key = 'flutter.String'; await preferences.remove(key); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values[key], isNull); }); @@ -237,10 +182,9 @@ void main() { }); testWidgets('get all with prefix', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); @@ -249,15 +193,11 @@ void main() { }); testWidgets('get all with allow list', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.String'}, - ), - ), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters( + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.String'}), + ), + ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); @@ -266,10 +206,9 @@ void main() { }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); @@ -279,10 +218,7 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters', (WidgetTester _) async { @@ -304,22 +240,14 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); - testWidgets('clearWithParameters with allow list', ( - WidgetTester _, - ) async { + testWidgets('clearWithParameters with allow list', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.StringList'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.StringList'}), ), ); Map values = await preferences.getAllWithParameters( @@ -337,20 +265,16 @@ void main() { expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); - expect( - values['flutter.StringList'], - allTestValues['flutter.StringList'], - ); + expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await preferences.clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: '')), ); - final Map values = await preferences - .getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: '')), - ); + final Map values = await preferences.getAllWithParameters( + GetAllParameters(filter: PreferencesFilter(prefix: '')), + ); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); @@ -380,11 +304,8 @@ void main() { const testDouble = 3.14159; const testList = ['foo', 'bar']; - Future getPreferences({ - bool clear = true, - }) async { - final SharedPreferencesAsyncPlatform preferences = - SharedPreferencesAsyncPlatform.instance!; + Future getPreferences({bool clear = true}) async { + final SharedPreferencesAsyncPlatform preferences = SharedPreferencesAsyncPlatform.instance!; if (clear) { await preferences.clear( const ClearPreferencesParameters(filter: PreferencesFilters()), @@ -429,9 +350,7 @@ void main() { expect(await preferences.getStringList(listKey, emptyOptions), testList); }); - testWidgets('getStringList does not throw cast error', ( - WidgetTester _, - ) async { + testWidgets('getStringList does not throw cast error', (WidgetTester _) async { final SharedPreferencesAsyncPlatform preferences = await getPreferences(); await preferences.setStringList(listKey, testList, emptyOptions); @@ -443,10 +362,7 @@ void main() { final SharedPreferencesAsyncPlatform preferences = await getPreferences(); await preferences.setStringList(listKey, testList, emptyOptions); - final List? list = await preferences.getStringList( - listKey, - emptyOptions, - ); + final List? list = await preferences.getStringList(listKey, emptyOptions); list?.add('value'); expect(list?.length, testList.length + 1); }); diff --git a/packages/shared_preferences/shared_preferences_windows/example/lib/main.dart b/packages/shared_preferences/shared_preferences_windows/example/lib/main.dart index 0742fdbb6e21..2d777fdf7d9e 100644 --- a/packages/shared_preferences/shared_preferences_windows/example/lib/main.dart +++ b/packages/shared_preferences/shared_preferences_windows/example/lib/main.dart @@ -17,10 +17,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'SharedPreferences Demo', - home: SharedPreferencesDemo(), - ); + return const MaterialApp(title: 'SharedPreferences Demo', home: SharedPreferencesDemo()); } } @@ -32,10 +29,8 @@ class SharedPreferencesDemo extends StatefulWidget { } class SharedPreferencesDemoState extends State { - final SharedPreferencesAsyncPlatform? _prefs = - SharedPreferencesAsyncPlatform.instance; - final SharedPreferencesWindowsOptions options = - const SharedPreferencesWindowsOptions(); + final SharedPreferencesAsyncPlatform? _prefs = SharedPreferencesAsyncPlatform.instance; + final SharedPreferencesWindowsOptions options = const SharedPreferencesWindowsOptions(); static const String _counterKey = 'counter'; late Future _counter; diff --git a/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart b/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart index c340b6dd7d6a..16d213904db9 100644 --- a/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart +++ b/packages/shared_preferences/shared_preferences_windows/lib/shared_preferences_windows.dart @@ -58,16 +58,12 @@ class SharedPreferencesWindows extends SharedPreferencesStorePlatform { @override Future clear() async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: _defaultPrefix))); } @override Future clearWithPrefix(String prefix) async { - return clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override @@ -80,12 +76,7 @@ class SharedPreferencesWindows extends SharedPreferencesStorePlatform { key.startsWith(filter.prefix) && (filter.allowList == null || filter.allowList!.contains(key)), ); - return _writePreferences( - preferences, - _defaultFileName, - fs: fs, - pathProvider: pathProvider, - ); + return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); } @override @@ -97,21 +88,16 @@ class SharedPreferencesWindows extends SharedPreferencesStorePlatform { @override Future> getAllWithPrefix(String prefix) async { - return getAllWithParameters( - GetAllParameters(filter: PreferencesFilter(prefix: prefix)), - ); + return getAllWithParameters(GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override - Future> getAllWithParameters( - GetAllParameters parameters, - ) async { + Future> getAllWithParameters(GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final withPrefix = Map.from(await _readPreferences()); withPrefix.removeWhere( (String key, _) => - !(key.startsWith(filter.prefix) && - (filter.allowList?.contains(key) ?? true)), + !(key.startsWith(filter.prefix) && (filter.allowList?.contains(key) ?? true)), ); return withPrefix; } @@ -120,32 +106,21 @@ class SharedPreferencesWindows extends SharedPreferencesStorePlatform { Future remove(String key) async { final Map preferences = await _readPreferences(); preferences.remove(key); - return _writePreferences( - preferences, - _defaultFileName, - fs: fs, - pathProvider: pathProvider, - ); + return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); } @override Future setValue(String valueType, String key, Object value) async { final Map preferences = await _readPreferences(); preferences[key] = value; - return _writePreferences( - preferences, - _defaultFileName, - fs: fs, - pathProvider: pathProvider, - ); + return _writePreferences(preferences, _defaultFileName, fs: fs, pathProvider: pathProvider); } } /// The Windows implementation of [SharedPreferencesAsyncPlatform]. /// /// This class implements the `package:shared_preferences` functionality for Windows. -base class SharedPreferencesAsyncWindows - extends SharedPreferencesAsyncPlatform { +base class SharedPreferencesAsyncWindows extends SharedPreferencesAsyncPlatform { /// Registers the Windows implementation. static void registerWith() { SharedPreferencesAsyncPlatform.instance = SharedPreferencesAsyncWindows(); @@ -171,29 +146,17 @@ base class SharedPreferencesAsyncWindows } @override - Future setString( - String key, - String value, - SharedPreferencesOptions options, - ) { + Future setString(String key, String value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future setBool( - String key, - bool value, - SharedPreferencesOptions options, - ) { + Future setBool(String key, bool value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future setDouble( - String key, - double value, - SharedPreferencesOptions options, - ) { + Future setDouble(String key, double value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @@ -203,19 +166,12 @@ base class SharedPreferencesAsyncWindows } @override - Future setStringList( - String key, - List value, - SharedPreferencesOptions options, - ) { + Future setStringList(String key, List value, SharedPreferencesOptions options) { return _setValue(key, value, options); } @override - Future getString( - String key, - SharedPreferencesOptions options, - ) async { + Future getString(String key, SharedPreferencesOptions options) async { final Map data = await _readAll({key}, options); return data[key] as String?; } @@ -227,10 +183,7 @@ base class SharedPreferencesAsyncWindows } @override - Future getDouble( - String key, - SharedPreferencesOptions options, - ) async { + Future getDouble(String key, SharedPreferencesOptions options) async { final Map data = await _readAll({key}, options); return data[key] as double?; } @@ -242,10 +195,7 @@ base class SharedPreferencesAsyncWindows } @override - Future?> getStringList( - String key, - SharedPreferencesOptions options, - ) async { + Future?> getStringList(String key, SharedPreferencesOptions options) async { final Map data = await _readAll({key}, options); return (data[key] as List?)?.cast().toList(); } @@ -258,12 +208,9 @@ base class SharedPreferencesAsyncWindows final SharedPreferencesWindowsOptions windowsOptions = SharedPreferencesWindowsOptions.fromSharedPreferencesOptions(options); final PreferencesFilters filter = parameters.filter; - final Map preferences = await _readPreferences( - windowsOptions.fileName, - ); + final Map preferences = await _readPreferences(windowsOptions.fileName); preferences.removeWhere( - (String key, _) => - filter.allowList == null || filter.allowList!.contains(key), + (String key, _) => filter.allowList == null || filter.allowList!.contains(key), ); await _writePreferences( preferences, @@ -293,23 +240,15 @@ base class SharedPreferencesAsyncWindows ) async { final SharedPreferencesWindowsOptions windowsOptions = SharedPreferencesWindowsOptions.fromSharedPreferencesOptions(options); - final prefs = Map.from( - await _readPreferences(windowsOptions.fileName), - ); + final prefs = Map.from(await _readPreferences(windowsOptions.fileName)); prefs.removeWhere((String key, _) => !(allowList?.contains(key) ?? true)); return prefs; } - Future _setValue( - String key, - Object value, - SharedPreferencesOptions options, - ) async { + Future _setValue(String key, Object value, SharedPreferencesOptions options) async { final SharedPreferencesWindowsOptions windowsOptions = SharedPreferencesWindowsOptions.fromSharedPreferencesOptions(options); - final Map preferences = await _readPreferences( - windowsOptions.fileName, - ); + final Map preferences = await _readPreferences(windowsOptions.fileName); preferences[key] = value; await _writePreferences( preferences, @@ -322,11 +261,7 @@ base class SharedPreferencesAsyncWindows /// Checks for cached preferences and returns them or loads preferences from /// file and returns and caches them. Future> _readPreferences(String fileName) async { - _cachedPreferences ??= await _readFromFile( - fileName, - fs: fs, - pathProvider: pathProvider, - ); + _cachedPreferences ??= await _readFromFile(fileName, fs: fs, pathProvider: pathProvider); return _cachedPreferences!; } } @@ -353,11 +288,7 @@ Future> _readFromFile( PathProviderWindows? pathProvider, }) async { var preferences = {}; - final File? localDataFile = await _getLocalDataFile( - fileName, - fs: fs, - pathProvider: pathProvider, - ); + final File? localDataFile = await _getLocalDataFile(fileName, fs: fs, pathProvider: pathProvider); if (localDataFile != null && localDataFile.existsSync()) { final String stringMap = localDataFile.readAsStringSync(); if (stringMap.isNotEmpty) { diff --git a/packages/shared_preferences/shared_preferences_windows/test/fake_path_provider_windows.dart b/packages/shared_preferences/shared_preferences_windows/test/fake_path_provider_windows.dart index 500a5c2b5b2c..a911988ab7e1 100644 --- a/packages/shared_preferences/shared_preferences_windows/test/fake_path_provider_windows.dart +++ b/packages/shared_preferences/shared_preferences_windows/test/fake_path_provider_windows.dart @@ -11,8 +11,7 @@ import 'package:path_provider_windows/path_provider_windows.dart'; /// /// Note that this should only be used with an in-memory filesystem, as the /// path it returns is a root path that does not actually exist on Windows. -class FakePathProviderWindows extends PathProviderPlatform - implements PathProviderWindows { +class FakePathProviderWindows extends PathProviderPlatform implements PathProviderWindows { @override late VersionInfoQuerier versionInfoQuerier; diff --git a/packages/shared_preferences/shared_preferences_windows/test/legacy_shared_preferences_windows_test.dart b/packages/shared_preferences/shared_preferences_windows/test/legacy_shared_preferences_windows_test.dart index ed14c1864e9a..5004debb41d6 100644 --- a/packages/shared_preferences/shared_preferences_windows/test/legacy_shared_preferences_windows_test.dart +++ b/packages/shared_preferences/shared_preferences_windows/test/legacy_shared_preferences_windows_test.dart @@ -79,10 +79,7 @@ void main() { test('registered instance', () async { SharedPreferencesWindows.registerWith(); - expect( - SharedPreferencesStorePlatform.instance, - isA(), - ); + expect(SharedPreferencesStorePlatform.instance, isA()); }); test('getAll', () async { @@ -120,10 +117,7 @@ void main() { final Map all = await prefs.getAllWithParameters( GetAllParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.Bool'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.Bool'}), ), ); expect(all.length, 1); @@ -162,9 +156,7 @@ void main() { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); await prefs.clearWithPrefix('prefix.'); - final Map noValues = await prefs.getAllWithPrefix( - 'prefix.', - ); + final Map noValues = await prefs.getAllWithPrefix('prefix.'); expect(noValues, hasLength(0)); final Map values = await prefs.getAll(); @@ -192,9 +184,7 @@ void main() { test('clearWithParameters with Prefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); - await prefs.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: 'prefix.')), - ); + await prefs.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: 'prefix.'))); final Map noValues = await prefs.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: 'prefix.')), ); @@ -210,10 +200,7 @@ void main() { final SharedPreferencesWindows prefs = getPreferences(); await prefs.clearWithParameters( ClearParameters( - filter: PreferencesFilter( - prefix: 'prefix.', - allowList: {'prefix.StringList'}, - ), + filter: PreferencesFilter(prefix: 'prefix.', allowList: {'prefix.StringList'}), ), ); final Map noValues = await prefs.getAllWithParameters( @@ -236,9 +223,7 @@ void main() { test('clearWithNoPrefix', () async { await writeTestFile(json.encode(flutterTestValues)); final SharedPreferencesWindows prefs = getPreferences(); - await prefs.clearWithParameters( - ClearParameters(filter: PreferencesFilter(prefix: '')), - ); + await prefs.clearWithParameters(ClearParameters(filter: PreferencesFilter(prefix: ''))); final Map noValues = await prefs.getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: '')), ); diff --git a/packages/standard_message_codec/example/lib/readme_excerpts.dart b/packages/standard_message_codec/example/lib/readme_excerpts.dart index 5bf151d065ab..6d6b1e4ce730 100644 --- a/packages/standard_message_codec/example/lib/readme_excerpts.dart +++ b/packages/standard_message_codec/example/lib/readme_excerpts.dart @@ -12,9 +12,10 @@ import 'package:standard_message_codec/standard_message_codec.dart'; // #docregion Encoding void main() { - final ByteData? data = const StandardMessageCodec().encodeMessage( - {'foo': true, 3: 'fizz'}, - ); + final ByteData? data = const StandardMessageCodec().encodeMessage({ + 'foo': true, + 3: 'fizz', + }); print('The encoded message is $data'); } diff --git a/packages/standard_message_codec/lib/src/serialization.dart b/packages/standard_message_codec/lib/src/serialization.dart index 7229ef3c3fff..10a98fdecf76 100644 --- a/packages/standard_message_codec/lib/src/serialization.dart +++ b/packages/standard_message_codec/lib/src/serialization.dart @@ -6,14 +6,7 @@ import 'dart:math' as math; import 'dart:typed_data'; export 'dart:typed_data' - show - ByteData, - Endian, - Float32List, - Float64List, - Int32List, - Int64List, - Uint8List; + show ByteData, Endian, Float32List, Float64List, Int32List, Int64List, Uint8List; /// Write-only buffer for incrementally building a [ByteData] instance. /// @@ -30,11 +23,7 @@ class WriteBuffer { assert(startCapacity > 0); final eightBytes = ByteData(8); final Uint8List eightBytesAsList = eightBytes.buffer.asUint8List(); - return WriteBuffer._( - Uint8List(startCapacity), - eightBytes, - eightBytesAsList, - ); + return WriteBuffer._(Uint8List(startCapacity), eightBytes, eightBytesAsList); } WriteBuffer._(this._buffer, this._eightBytes, this._eightBytesAsList); @@ -168,9 +157,7 @@ class WriteBuffer { /// Finalize and return the written [ByteData]. ByteData done() { if (_isDone) { - throw StateError( - 'done() must not be called more than once on the same $runtimeType.', - ); + throw StateError('done() must not be called more than once on the same $runtimeType.'); } final ByteData result = _buffer.buffer.asByteData(0, _currentSize); _buffer = Uint8List(0); @@ -238,10 +225,7 @@ class ReadBuffer { /// Reads the given number of Uint8s from the buffer. Uint8List getUint8List(int length) { - final Uint8List list = data.buffer.asUint8List( - data.offsetInBytes + _position, - length, - ); + final Uint8List list = data.buffer.asUint8List(data.offsetInBytes + _position, length); _position += length; return list; } @@ -249,10 +233,7 @@ class ReadBuffer { /// Reads the given number of Int32s from the buffer. Int32List getInt32List(int length) { _alignTo(4); - final Int32List list = data.buffer.asInt32List( - data.offsetInBytes + _position, - length, - ); + final Int32List list = data.buffer.asInt32List(data.offsetInBytes + _position, length); _position += 4 * length; return list; } @@ -260,10 +241,7 @@ class ReadBuffer { /// Reads the given number of Int64s from the buffer. Int64List getInt64List(int length) { _alignTo(8); - final Int64List list = data.buffer.asInt64List( - data.offsetInBytes + _position, - length, - ); + final Int64List list = data.buffer.asInt64List(data.offsetInBytes + _position, length); _position += 8 * length; return list; } @@ -271,10 +249,7 @@ class ReadBuffer { /// Reads the given number of Float32s from the buffer Float32List getFloat32List(int length) { _alignTo(4); - final Float32List list = data.buffer.asFloat32List( - data.offsetInBytes + _position, - length, - ); + final Float32List list = data.buffer.asFloat32List(data.offsetInBytes + _position, length); _position += 4 * length; return list; } @@ -282,10 +257,7 @@ class ReadBuffer { /// Reads the given number of Float64s from the buffer. Float64List getFloat64List(int length) { _alignTo(8); - final Float64List list = data.buffer.asFloat64List( - data.offsetInBytes + _position, - length, - ); + final Float64List list = data.buffer.asFloat64List(data.offsetInBytes + _position, length); _position += 8 * length; return list; } diff --git a/packages/standard_message_codec/test/standard_message_codec_test.dart b/packages/standard_message_codec/test/standard_message_codec_test.dart index 273b3b918974..470ae5ce5a1f 100644 --- a/packages/standard_message_codec/test/standard_message_codec_test.dart +++ b/packages/standard_message_codec/test/standard_message_codec_test.dart @@ -12,15 +12,9 @@ const StandardMessageCodec messageCodec = StandardMessageCodec(); void main() { group('Standard method codec', () { test('Should encode and decode objects produced from codec', () { - final ByteData? data = messageCodec.encodeMessage({ - 'foo': true, - 3: 'fizz', - }); - - expect(messageCodec.decodeMessage(data), { - 'foo': true, - 3: 'fizz', - }); + final ByteData? data = messageCodec.encodeMessage({'foo': true, 3: 'fizz'}); + + expect(messageCodec.decodeMessage(data), {'foo': true, 3: 'fizz'}); }); }); @@ -68,18 +62,14 @@ void main() { expect(read.getInt64(), equals(-9000000000000)); }, testOn: 'vm' /* Int64 isn't supported on web */); - test( - 'of 64-bit integer in big endian', - () { - final write = WriteBuffer(); - write.putInt64(-9000000000000, endian: Endian.big); - final ByteData written = write.done(); - expect(written.lengthInBytes, equals(8)); - final read = ReadBuffer(written); - expect(read.getInt64(endian: Endian.big), equals(-9000000000000)); - }, - testOn: 'vm' /* Int64 isn't supported on web */, - ); + test('of 64-bit integer in big endian', () { + final write = WriteBuffer(); + write.putInt64(-9000000000000, endian: Endian.big); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(8)); + final read = ReadBuffer(written); + expect(read.getInt64(endian: Endian.big), equals(-9000000000000)); + }, testOn: 'vm' /* Int64 isn't supported on web */); test('of double', () { final write = WriteBuffer(); @@ -109,21 +99,17 @@ void main() { expect(read.getInt32List(3), equals(integers)); }); - test( - 'of 64-bit int list when unaligned', - () { - final integers = Int64List.fromList([-99, 2, 99]); - final write = WriteBuffer(); - write.putUint8(9); - write.putInt64List(integers); - final ByteData written = write.done(); - expect(written.lengthInBytes, equals(32)); - final read = ReadBuffer(written); - read.getUint8(); - expect(read.getInt64List(3), equals(integers)); - }, - testOn: 'vm' /* Int64 isn't supported on web */, - ); + test('of 64-bit int list when unaligned', () { + final integers = Int64List.fromList([-99, 2, 99]); + final write = WriteBuffer(); + write.putUint8(9); + write.putInt64List(integers); + final ByteData written = write.done(); + expect(written.lengthInBytes, equals(32)); + final read = ReadBuffer(written); + read.getUint8(); + expect(read.getInt64List(3), equals(integers)); + }, testOn: 'vm' /* Int64 isn't supported on web */); test('of float list when unaligned', () { final floats = Float32List.fromList([3.14, double.nan]); @@ -160,10 +146,7 @@ void main() { }); test('empty WriteBuffer', () { - expect( - () => WriteBuffer(startCapacity: 0), - throwsA(isA()), - ); + expect(() => WriteBuffer(startCapacity: 0), throwsA(isA())); }); test('size 1', () { diff --git a/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart b/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart index db412cf71bf8..0fd61b42fd80 100644 --- a/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart +++ b/packages/two_dimensional_scrollables/example/lib/table_view/infinite_table.dart @@ -46,9 +46,7 @@ class _InfiniteExampleState extends State { } }); }, - child: Text( - 'Make columns ${_columnCount == null ? 'fixed' : 'infinite'}', - ), + child: Text('Make columns ${_columnCount == null ? 'fixed' : 'infinite'}'), ), const SizedBox.square(dimension: 10), Text( @@ -72,10 +70,7 @@ class _InfiniteExampleState extends State { } TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) { - final Color boxColor = switch (( - vicinity.row.isEven, - vicinity.column.isEven, - )) { + final Color boxColor = switch ((vicinity.row.isEven, vicinity.column.isEven)) { (true, false) || (false, true) => Colors.white, (false, false) => Colors.indigo[100]!, (true, true) => Colors.indigo[200]!, diff --git a/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart b/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart index bbc49839ddfc..65bb46c5af8d 100644 --- a/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart +++ b/packages/two_dimensional_scrollables/example/lib/table_view/merged_table.dart @@ -20,10 +20,7 @@ class _MergedTableExampleState extends State { final MaterialColor primary = Colors.primaries[colorIndex]; if (vicinity.column == 0) { // Leading primary color - return ( - color: primary[500]!, - name: '${_getPrimaryNameFor(colorIndex)}, 500', - ); + return (color: primary[500]!, name: '${_getPrimaryNameFor(colorIndex)}, 500'); } final int leadingRow = colorIndex * 3; final int middleRow = leadingRow + 1; @@ -99,8 +96,7 @@ class _MergedTableExampleState extends State { TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) { final int colorIndex = (vicinity.row / 3).floor(); final ({String name, Color color}) cell = _getColorForVicinity(vicinity); - final Color textColor = - ThemeData.estimateBrightnessForColor(cell.color) == Brightness.light + final Color textColor = ThemeData.estimateBrightnessForColor(cell.color) == Brightness.light ? Colors.black : Colors.white; final style = TextStyle( @@ -123,9 +119,7 @@ class _MergedTableExampleState extends State { extent: FixedTableSpanExtent(index == 0 ? 220 : 180), foregroundDecoration: index == 0 ? const TableSpanDecoration( - border: TableSpanBorder( - trailing: BorderSide(width: 5, color: Colors.white), - ), + border: TableSpanBorder(trailing: BorderSide(width: 5, color: Colors.white)), ) : null, ); diff --git a/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart b/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart index 855d35a17fe0..6a3c4d4a8f89 100644 --- a/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart +++ b/packages/two_dimensional_scrollables/example/lib/table_view/simple_table.dart @@ -40,9 +40,7 @@ class _TableExampleState extends State { child: _selectionMode == _TableSelection.multiCell ? SelectionArea( child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: _verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: _verticalController), cellBuilder: _buildCell, columnCount: 20, columnBuilder: _buildColumnSpan, @@ -51,9 +49,7 @@ class _TableExampleState extends State { ), ) : TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: _verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: _verticalController), cellBuilder: _buildCell, columnCount: 20, columnBuilder: _buildColumnSpan, @@ -110,9 +106,7 @@ class _TableExampleState extends State { ), TextButton( onPressed: () { - _verticalController.jumpTo( - _verticalController.position.maxScrollExtent, - ); + _verticalController.jumpTo(_verticalController.position.maxScrollExtent); }, child: const Text('Jump to Bottom'), ), @@ -133,9 +127,7 @@ class _TableExampleState extends State { } TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) { - Widget result = Center( - child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}'), - ); + Widget result = Center(child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}')); if (_selectionMode == _TableSelection.singleCell) { result = SelectionArea(child: result); } @@ -143,9 +135,7 @@ class _TableExampleState extends State { } TableSpan _buildColumnSpan(int index) { - const decoration = TableSpanDecoration( - border: TableSpanBorder(trailing: BorderSide()), - ); + const decoration = TableSpanDecoration(border: TableSpanBorder(trailing: BorderSide())); switch (index % 5) { case 0: @@ -154,12 +144,10 @@ class _TableExampleState extends State { extent: const FixedTableSpanExtent(100), onEnter: (_) => print('Entered column $index'), recognizerFactories: { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => - t.onTap = () => print('Tap column $index'), - ), + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () => print('Tap column $index'), + ), }, ); case 1: @@ -206,12 +194,10 @@ class _TableExampleState extends State { backgroundDecoration: decoration, extent: const FixedTableSpanExtent(50), recognizerFactories: { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => - t.onTap = () => print('Tap row $index'), - ), + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () => print('Tap row $index'), + ), }, ); case 1: diff --git a/packages/two_dimensional_scrollables/example/lib/table_view/table_explorer.dart b/packages/two_dimensional_scrollables/example/lib/table_view/table_explorer.dart index 5b551d318e8f..1b903dad4679 100644 --- a/packages/two_dimensional_scrollables/example/lib/table_view/table_explorer.dart +++ b/packages/two_dimensional_scrollables/example/lib/table_view/table_explorer.dart @@ -90,10 +90,7 @@ class _TableExplorerState extends State { title: Text(_getTitle()), bottom: PreferredSize( preferredSize: const Size.fromHeight(50), - child: Padding( - padding: const EdgeInsets.all(8.0), - child: _getRadioRow(), - ), + child: Padding(padding: const EdgeInsets.all(8.0), child: _getRadioRow()), ), ), body: _getTable(), diff --git a/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart b/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart index 2754c2eb9131..a08abc72a5a2 100644 --- a/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart +++ b/packages/two_dimensional_scrollables/example/lib/tree_view/custom_tree.dart @@ -41,9 +41,7 @@ class CustomTreeExampleState extends State { children: >[ TreeViewNode( 'common', - children: >[ - TreeViewNode('span.dart'), - ], + children: >[TreeViewNode('span.dart')], ), TreeViewNode( 'table_view', @@ -76,9 +74,7 @@ class CustomTreeExampleState extends State { children: >[ TreeViewNode( 'common', - children: >[ - TreeViewNode('span_test.dart'), - ], + children: >[TreeViewNode('span_test.dart')], ), TreeViewNode( 'table_view', @@ -120,9 +116,7 @@ class CustomTreeExampleState extends State { SizedBox(width: 10.0 * node.depth! + 8.0), DecoratedBox( decoration: BoxDecoration( - border: node.parent != null - ? Border(left: border, bottom: border) - : null, + border: node.parent != null ? Border(left: border, bottom: border) : null, ), child: const SizedBox(height: 50.0, width: 20.0), ), @@ -143,22 +137,19 @@ class CustomTreeExampleState extends State { ); } - Map _getTapRecognizer( - TreeViewNode node, - ) { + Map _getTapRecognizer(TreeViewNode node) { return { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () { - setState(() { - // Toggling the node here instead means any tap on the row can - // toggle parent nodes opened and closed. - treeController.toggleNode(node); - _selectedNode = node; - }); - }, - ), + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () { + setState(() { + // Toggling the node here instead means any tap on the row can + // toggle parent nodes opened and closed. + treeController.toggleNode(node); + _selectedNode = node; + }); + }, + ), }; } @@ -173,12 +164,8 @@ class CustomTreeExampleState extends State { thumbVisibility: true, child: TreeView( controller: treeController, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: _horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: _horizontalController), tree: _tree, onNodeToggle: (TreeViewNode node) { setState(() { @@ -189,22 +176,16 @@ class CustomTreeExampleState extends State { treeRowBuilder: (TreeViewNode node) { if (_selectedNode == node) { return TreeRow( - extent: FixedTreeRowExtent( - node.children.isNotEmpty ? 60.0 : 50.0, - ), + extent: FixedTreeRowExtent(node.children.isNotEmpty ? 60.0 : 50.0), recognizerFactories: _getTapRecognizer(node), - backgroundDecoration: TreeRowDecoration( - color: Colors.amber[100], - ), + backgroundDecoration: TreeRowDecoration(color: Colors.amber[100]), foregroundDecoration: const TreeRowDecoration( border: TreeRowBorder.all(BorderSide()), ), ); } return TreeRow( - extent: FixedTreeRowExtent( - node.children.isNotEmpty ? 60.0 : 50.0, - ), + extent: FixedTreeRowExtent(node.children.isNotEmpty ? 60.0 : 50.0), recognizerFactories: _getTapRecognizer(node), ); }, @@ -232,11 +213,7 @@ class CustomTreeExampleState extends State { if (_selectedNode != null) { selectedChildren.addAll([ const Spacer(), - Icon( - _selectedNode!.children.isEmpty - ? Icons.file_open_outlined - : Icons.folder_outlined, - ), + Icon(_selectedNode!.children.isEmpty ? Icons.file_open_outlined : Icons.folder_outlined), const SizedBox(height: 25.0), Text(_selectedNode!.content), const Spacer(), diff --git a/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart b/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart index cdcbf15a6aa2..c15c30b4847a 100644 --- a/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart +++ b/packages/two_dimensional_scrollables/example/lib/tree_view/simple_tree.dart @@ -33,12 +33,8 @@ class TreeExampleState extends State { TreeViewNode( "It's supercalifragilisticexpialidocious", children: >[ - TreeViewNode( - 'Even though the sound of it is something quite atrocious', - ), - TreeViewNode( - "If you say it loud enough you'll always sound precocious", - ), + TreeViewNode('Even though the sound of it is something quite atrocious'), + TreeViewNode("If you say it loud enough you'll always sound precocious"), ], ), TreeViewNode( @@ -64,19 +60,16 @@ class TreeExampleState extends State { ), ]; - Map _getTapRecognizer( - TreeViewNode node, - ) { + Map _getTapRecognizer(TreeViewNode node) { return { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () { - setState(() { - _selectedNode = node; - }); - }, - ), + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () { + setState(() { + _selectedNode = node; + }); + }, + ), }; } @@ -91,12 +84,8 @@ class TreeExampleState extends State { thumbVisibility: true, child: TreeView( controller: treeController, - verticalDetails: ScrollableDetails.vertical( - controller: _verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: _verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), tree: _tree, onNodeToggle: (TreeViewNode node) { setState(() { @@ -107,9 +96,7 @@ class TreeExampleState extends State { if (_selectedNode == node) { return TreeView.defaultTreeRowBuilder(node).copyWith( recognizerFactories: _getTapRecognizer(node), - backgroundDecoration: TreeRowDecoration( - color: Colors.purple[100], - ), + backgroundDecoration: TreeRowDecoration(color: Colors.purple[100]), ); } return TreeView.defaultTreeRowBuilder( @@ -138,10 +125,7 @@ class TreeExampleState extends State { body: ScrollConfiguration( behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), child: Padding( - padding: EdgeInsets.symmetric( - horizontal: screenSize.width * 0.25, - vertical: 25.0, - ), + padding: EdgeInsets.symmetric(horizontal: screenSize.width * 0.25, vertical: 25.0), child: _getTree(), ), ), diff --git a/packages/two_dimensional_scrollables/example/lib/tree_view/tree_explorer.dart b/packages/two_dimensional_scrollables/example/lib/tree_view/tree_explorer.dart index 0b631819bfba..8078c6f1da47 100644 --- a/packages/two_dimensional_scrollables/example/lib/tree_view/tree_explorer.dart +++ b/packages/two_dimensional_scrollables/example/lib/tree_view/tree_explorer.dart @@ -81,10 +81,7 @@ class _TreeExplorerState extends State { title: Text(_getTitle()), bottom: PreferredSize( preferredSize: const Size.fromHeight(50), - child: Padding( - padding: const EdgeInsets.all(8.0), - child: _getRadioRow(), - ), + child: Padding(padding: const EdgeInsets.all(8.0), child: _getRadioRow()), ), ), body: _getTree(), diff --git a/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart b/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart index 9b14cd4da32a..29f26a90e9ec 100644 --- a/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart +++ b/packages/two_dimensional_scrollables/example/test/table_view/simple_table_test.dart @@ -23,8 +23,7 @@ void main() { } return false; }); - final ScrollPosition position = - (tester.state(scrollable) as ScrollableState).position; + final ScrollPosition position = (tester.state(scrollable) as ScrollableState).position; expect(position.axis, Axis.vertical); expect(position.pixels, 0.0); position.jumpTo(10); @@ -42,8 +41,7 @@ void main() { } return false; }); - final ScrollPosition position = - (tester.state(scrollable) as ScrollableState).position; + final ScrollPosition position = (tester.state(scrollable) as ScrollableState).position; expect(position.maxScrollExtent, greaterThan(750)); await tester.tap(find.text('Add 10 Rows')); @@ -57,9 +55,7 @@ void main() { expect(position.pixels, 0.0); }); - testWidgets('Selection SegmentedButton control works', ( - WidgetTester tester, - ) async { + testWidgets('Selection SegmentedButton control works', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: TableExample())); await tester.pump(); diff --git a/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart b/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart index 4b026e773dcf..7bcae26be108 100644 --- a/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart +++ b/packages/two_dimensional_scrollables/example/test/table_view/table_explorer_test.dart @@ -10,9 +10,7 @@ import 'package:two_dimensional_examples/table_view/simple_table.dart'; import 'package:two_dimensional_examples/table_view/table_explorer.dart'; void main() { - testWidgets('Table explorer switches between samples', ( - WidgetTester tester, - ) async { + testWidgets('Table explorer switches between samples', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: TableExplorer())); await tester.pumpAndSettle(); // The first example diff --git a/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart b/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart index 946c40165cff..641c8abb6698 100644 --- a/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart +++ b/packages/two_dimensional_scrollables/example/test/tree_view/custom_tree_test.dart @@ -7,9 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_examples/tree_view/custom_tree.dart'; void main() { - testWidgets('Example builds and can be interacted with', ( - WidgetTester tester, - ) async { + testWidgets('Example builds and can be interacted with', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: CustomTreeExample())); await tester.pumpAndSettle(); expect(find.text('README.md'), findsOneWidget); @@ -35,28 +33,24 @@ void main() { expect(verticalPosition.maxScrollExtent, 0.0); expect(verticalPosition.pixels, 0.0); - final state = - tester.state(find.byType(CustomTreeExample)) as CustomTreeExampleState; + final state = tester.state(find.byType(CustomTreeExample)) as CustomTreeExampleState; state.treeController.toggleNode(state.treeController.getNodeFor('lib')!); await tester.pumpAndSettle(); - verticalPosition = - (tester.state(verticalScrollable) as ScrollableState).position; + verticalPosition = (tester.state(verticalScrollable) as ScrollableState).position; expect(verticalPosition.maxScrollExtent, 0.0); expect(verticalPosition.pixels, 0.0); state.treeController.toggleNode(state.treeController.getNodeFor('test')!); await tester.pumpAndSettle(); - verticalPosition = - (tester.state(verticalScrollable) as ScrollableState).position; + verticalPosition = (tester.state(verticalScrollable) as ScrollableState).position; expect(verticalPosition.maxScrollExtent, 10.0); expect(verticalPosition.pixels, 0.0); state.treeController.toggleNode(state.treeController.getNodeFor('src')!); await tester.pumpAndSettle(); - verticalPosition = - (tester.state(verticalScrollable) as ScrollableState).position; + verticalPosition = (tester.state(verticalScrollable) as ScrollableState).position; // Enough nodes expanded to allow us to scroll expect(verticalPosition.maxScrollExtent, 190.0); diff --git a/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart b/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart index 83e79d9902a7..bc2d37ff4b29 100644 --- a/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart +++ b/packages/two_dimensional_scrollables/example/test/tree_view/simple_tree_test.dart @@ -7,15 +7,10 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:two_dimensional_examples/tree_view/simple_tree.dart'; void main() { - testWidgets('Example builds and can be interacted with', ( - WidgetTester tester, - ) async { + testWidgets('Example builds and can be interacted with', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: TreeExample())); await tester.pumpAndSettle(); - expect( - find.text("It's supercalifragilisticexpialidocious"), - findsOneWidget, - ); + expect(find.text("It's supercalifragilisticexpialidocious"), findsOneWidget); expect(find.text('Um-dittle-ittl-um-dittle-I'), findsNothing); await tester.tap(find.byType(Icon).last); await tester.pumpAndSettle(); @@ -40,8 +35,7 @@ void main() { state.treeController.expandAll(); await tester.pumpAndSettle(); - horizontalPosition = - (tester.state(horizontalScrollable) as ScrollableState).position; + horizontalPosition = (tester.state(horizontalScrollable) as ScrollableState).position; // Expanding all of the node increased the max extent. expect(horizontalPosition.maxScrollExtent, 502.0); expect(horizontalPosition.pixels, 0.0); diff --git a/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart b/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart index 355ca33952dc..fd20804b5235 100644 --- a/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart +++ b/packages/two_dimensional_scrollables/example/test/tree_view/tree_explorer_test.dart @@ -9,9 +9,7 @@ import 'package:two_dimensional_examples/tree_view/simple_tree.dart'; import 'package:two_dimensional_examples/tree_view/tree_explorer.dart'; void main() { - testWidgets('Tree explorer switches between samples', ( - WidgetTester tester, - ) async { + testWidgets('Tree explorer switches between samples', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: TreeExplorer())); await tester.pumpAndSettle(); // The first example diff --git a/packages/two_dimensional_scrollables/lib/src/common/span.dart b/packages/two_dimensional_scrollables/lib/src/common/span.dart index 84d6f64da9ed..d7910a7cd4da 100644 --- a/packages/two_dimensional_scrollables/lib/src/common/span.dart +++ b/packages/two_dimensional_scrollables/lib/src/common/span.dart @@ -167,10 +167,7 @@ class SpanExtentDelegate { /// Creates a [SpanExtentDelegate]. /// /// Usually, only [TableView]s need to create instances of this class. - const SpanExtentDelegate({ - required this.viewportExtent, - required this.precedingExtent, - }); + const SpanExtentDelegate({required this.viewportExtent, required this.precedingExtent}); /// The size of the viewport in the axis-direction of the span. /// @@ -233,8 +230,7 @@ class FractionalSpanExtent extends SpanExtent { final double fraction; @override - double calculateExtent(SpanExtentDelegate delegate) => - delegate.viewportExtent * fraction; + double calculateExtent(SpanExtentDelegate delegate) => delegate.viewportExtent * fraction; } /// Specifies that the span should occupy the remaining space in the viewport. @@ -280,25 +276,20 @@ class CombiningSpanExtent extends SpanExtent { @override double calculateExtent(SpanExtentDelegate delegate) { - return _combiner( - _extent1.calculateExtent(delegate), - _extent2.calculateExtent(delegate), - ); + return _combiner(_extent1.calculateExtent(delegate), _extent2.calculateExtent(delegate)); } } /// Returns the larger pixel extent of the two provided [SpanExtent]. class MaxSpanExtent extends CombiningSpanExtent { /// Creates a [MaxSpanExtent]. - const MaxSpanExtent(SpanExtent extent1, SpanExtent extent2) - : super(extent1, extent2, math.max); + const MaxSpanExtent(SpanExtent extent1, SpanExtent extent2) : super(extent1, extent2, math.max); } /// Returns the smaller pixel extent of the two provided [SpanExtent]. class MinSpanExtent extends CombiningSpanExtent { /// Creates a [MinSpanExtent]. - const MinSpanExtent(SpanExtent extent1, SpanExtent extent2) - : super(extent1, extent2, math.min); + const MinSpanExtent(SpanExtent extent1, SpanExtent extent2) : super(extent1, extent2, math.min); } /// A decoration for a [Span]. @@ -401,10 +392,7 @@ class SpanDecoration { /// Describes the border for a [Span]. class SpanBorder { /// Creates a [SpanBorder]. - const SpanBorder({ - this.trailing = BorderSide.none, - this.leading = BorderSide.none, - }); + const SpanBorder({this.trailing = BorderSide.none, this.leading = BorderSide.none}); /// The border to draw on the trailing side of the span, based on the /// [AxisDirection]. @@ -443,8 +431,7 @@ class SpanBorder { switch (axisDirectionToAxis(axisDirection)) { case Axis.horizontal: final bool isLeadingTop = - crossAxisDirection == null || - crossAxisDirection == AxisDirection.down; + crossAxisDirection == null || crossAxisDirection == AxisDirection.down; final border = Border( top: isLeadingTop ? leading : trailing, bottom: isLeadingTop ? trailing : leading, @@ -452,8 +439,7 @@ class SpanBorder { border.paint(details.canvas, details.rect, borderRadius: borderRadius); case Axis.vertical: final bool isLeadingLeft = - crossAxisDirection == null || - crossAxisDirection == AxisDirection.right; + crossAxisDirection == null || crossAxisDirection == AxisDirection.right; final border = Border( left: isLeadingLeft ? leading : trailing, right: isLeadingLeft ? trailing : leading, diff --git a/packages/two_dimensional_scrollables/lib/src/table_view/table.dart b/packages/two_dimensional_scrollables/lib/src/table_view/table.dart index dc46613574f0..dab40443d8ea 100644 --- a/packages/two_dimensional_scrollables/lib/src/table_view/table.dart +++ b/packages/two_dimensional_scrollables/lib/src/table_view/table.dart @@ -170,17 +170,11 @@ class TableView extends TwoDimensionalScrollView { }) : assert(pinnedRowCount >= 0), assert(trailingPinnedRowCount >= 0), assert(rowCount == null || rowCount >= 0), - assert( - rowCount == null || - rowCount >= pinnedRowCount + trailingPinnedRowCount, - ), + assert(rowCount == null || rowCount >= pinnedRowCount + trailingPinnedRowCount), assert(columnCount == null || columnCount >= 0), assert(pinnedColumnCount >= 0), assert(trailingPinnedColumnCount >= 0), - assert( - columnCount == null || - columnCount >= pinnedColumnCount + trailingPinnedColumnCount, - ), + assert(columnCount == null || columnCount >= pinnedColumnCount + trailingPinnedColumnCount), super( delegate: TableCellBuilderDelegate( columnCount: columnCount, @@ -304,10 +298,7 @@ class TableViewport extends TwoDimensionalViewport { } @override - void updateRenderObject( - BuildContext context, - RenderTableViewport renderObject, - ) { + void updateRenderObject(BuildContext context, RenderTableViewport renderObject) { renderObject ..horizontalOffset = horizontalOffset ..horizontalAxisDirection = horizontalAxisDirection @@ -348,8 +339,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { _textDirection = textDirection; @override - TableCellDelegateMixin get delegate => - super.delegate as TableCellDelegateMixin; + TableCellDelegateMixin get delegate => super.delegate as TableCellDelegateMixin; @override set delegate(TableCellDelegateMixin value) { super.delegate = value; @@ -385,8 +375,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // vicinities. // The key represents a skipped vicinity, the value is the resolved vicinity // of the merged child. - final Map _mergedVicinities = - {}; + final Map _mergedVicinities = {}; // These contain the indexes of rows/columns that contain merged cells to // optimize decoration drawing for rows/columns that don't contain merged // cells. @@ -406,8 +395,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // Where column layout begins, potentially outside of the visible area. double get _targetLeadingColumnPixel { return clampDouble( - horizontalOffset.pixels - - math.max(_leadingPinnedColumnsExtent, cacheExtent), + horizontalOffset.pixels - math.max(_leadingPinnedColumnsExtent, cacheExtent), 0, double.infinity, ); @@ -415,10 +403,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // How far columns should be laid out in a given frame. double get _targetTrailingColumnPixel { - return cacheExtent + - horizontalOffset.pixels + - viewportDimension.width - - _pinnedColumnsExtent; + return cacheExtent + horizontalOffset.pixels + viewportDimension.width - _pinnedColumnsExtent; } int? _rowNullTerminatedIndex; @@ -434,34 +419,24 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // How far rows should be laid out in a given frame. double get _targetTrailingRowPixel { - return cacheExtent + - verticalOffset.pixels + - viewportDimension.height - - _pinnedRowsExtent; + return cacheExtent + verticalOffset.pixels + viewportDimension.height - _pinnedRowsExtent; } TableVicinity? get _firstNonPinnedCell { if (_firstNonPinnedRow == null || _firstNonPinnedColumn == null) { return null; } - return TableVicinity( - column: _firstNonPinnedColumn!, - row: _firstNonPinnedRow!, - ); + return TableVicinity(column: _firstNonPinnedColumn!, row: _firstNonPinnedRow!); } TableVicinity? get _lastNonPinnedCell { if (_lastNonPinnedRow == null || _lastNonPinnedColumn == null) { return null; } - return TableVicinity( - column: _lastNonPinnedColumn!, - row: _lastNonPinnedRow!, - ); + return TableVicinity(column: _lastNonPinnedColumn!, row: _lastNonPinnedRow!); } - int? get _lastPinnedRow => - delegate.pinnedRowCount > 0 ? delegate.pinnedRowCount - 1 : null; + int? get _lastPinnedRow => delegate.pinnedRowCount > 0 ? delegate.pinnedRowCount - 1 : null; int? get _lastPinnedColumn => delegate.pinnedColumnCount > 0 ? delegate.pinnedColumnCount - 1 : null; @@ -474,9 +449,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ? delegate.columnCount! - delegate.trailingPinnedColumnCount : null; - double get _leadingPinnedRowsExtent => delegate.pinnedRowCount > 0 - ? _rowMetrics[delegate.pinnedRowCount - 1]!.trailingOffset - : 0.0; + double get _leadingPinnedRowsExtent => + delegate.pinnedRowCount > 0 ? _rowMetrics[delegate.pinnedRowCount - 1]!.trailingOffset : 0.0; double get _leadingPinnedColumnsExtent => delegate.pinnedColumnCount > 0 ? _columnMetrics[delegate.pinnedColumnCount - 1]!.trailingOffset @@ -508,11 +482,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { return lastSpan.trailingOffset - firstSpan.leadingOffset; } - double get _pinnedRowsExtent => - _leadingPinnedRowsExtent + _trailingPinnedRowsExtent; + double get _pinnedRowsExtent => _leadingPinnedRowsExtent + _trailingPinnedRowsExtent; - double get _pinnedColumnsExtent => - _leadingPinnedColumnsExtent + _trailingPinnedColumnsExtent; + double get _pinnedColumnsExtent => _leadingPinnedColumnsExtent + _trailingPinnedColumnsExtent; void _debugCheckPinnedExtent() { assert(() { @@ -526,8 +498,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { } else if (_pinnedColumnsExtent == viewportDimension.width) { final bool hasUnpinnedColumns = delegate.columnCount == null || - delegate.columnCount! > - delegate.pinnedColumnCount + delegate.trailingPinnedColumnCount; + delegate.columnCount! > delegate.pinnedColumnCount + delegate.trailingPinnedColumnCount; if (hasUnpinnedColumns) { debugPrint( 'TableView has pinned columns that fully consume the viewport width. ' @@ -546,8 +517,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { } else if (_pinnedRowsExtent == viewportDimension.height) { final bool hasUnpinnedRows = delegate.rowCount == null || - delegate.rowCount! > - delegate.pinnedRowCount + delegate.trailingPinnedRowCount; + delegate.rowCount! > delegate.pinnedRowCount + delegate.trailingPinnedRowCount; if (hasUnpinnedRows) { debugPrint( 'TableView has pinned rows that fully consume the viewport height. ' @@ -593,24 +563,12 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { switch (mainAxis) { case Axis.vertical: // Row major order, rows go first. - result.add( - HitTestEntry(_rowMetrics[cellParentData.tableVicinity.row]!), - ); - result.add( - HitTestEntry( - _columnMetrics[cellParentData.tableVicinity.column]!, - ), - ); + result.add(HitTestEntry(_rowMetrics[cellParentData.tableVicinity.row]!)); + result.add(HitTestEntry(_columnMetrics[cellParentData.tableVicinity.column]!)); case Axis.horizontal: // Column major order, columns go first. - result.add( - HitTestEntry( - _columnMetrics[cellParentData.tableVicinity.column]!, - ), - ); - result.add( - HitTestEntry(_rowMetrics[cellParentData.tableVicinity.row]!), - ); + result.add(HitTestEntry(_columnMetrics[cellParentData.tableVicinity.column]!)); + result.add(HitTestEntry(_rowMetrics[cellParentData.tableVicinity.row]!)); } return true; } @@ -644,16 +602,12 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // columns we already know about. assert(_columnsAreInfinite); assert(_columnMetrics.isNotEmpty); - startOfPinnedColumn = - _columnMetrics[_firstNonPinnedColumn]?.trailingOffset ?? 0.0; - startOfRegularColumn = - _columnMetrics[_lastNonPinnedColumn]?.trailingOffset ?? 0.0; + startOfPinnedColumn = _columnMetrics[_firstNonPinnedColumn]?.trailingOffset ?? 0.0; + startOfRegularColumn = _columnMetrics[_lastNonPinnedColumn]?.trailingOffset ?? 0.0; } // If we are computing up to a specific index, we are getting info for a // merged cell, do not change the visible cells. - _firstNonPinnedColumn = toColumnIndex == null - ? null - : _firstNonPinnedColumn; + _firstNonPinnedColumn = toColumnIndex == null ? null : _firstNonPinnedColumn; _lastNonPinnedColumn = toColumnIndex == null ? null : _lastNonPinnedColumn; int column = appendColumns ? _columnMetrics.length : 0; @@ -668,8 +622,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // There are infinite columns, and no target index, compute metrics // up to what is visible and in the cache extent, or the index that null // terminates. - return _lastNonPinnedColumn != null || - _columnNullTerminatedIndex != null; + return _lastNonPinnedColumn != null || _columnNullTerminatedIndex != null; } // Compute all the metrics if the columns are finite. return column == delegate.columnCount!; @@ -679,8 +632,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { final bool isPinned = column < delegate.pinnedColumnCount || (delegate.columnCount != null && - column >= - delegate.columnCount! - delegate.trailingPinnedColumnCount); + column >= delegate.columnCount! - delegate.trailingPinnedColumnCount); final leadingOffset = isPinned ? (column < delegate.pinnedColumnCount ? startOfPinnedColumn @@ -722,12 +674,10 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ); _columnMetrics[column] = span; if (!isPinned) { - if (span.trailingOffset >= _targetLeadingColumnPixel && - _firstNonPinnedColumn == null) { + if (span.trailingOffset >= _targetLeadingColumnPixel && _firstNonPinnedColumn == null) { _firstNonPinnedColumn = column; } - if (span.trailingOffset >= _targetTrailingColumnPixel && - _lastNonPinnedColumn == null) { + if (span.trailingOffset >= _targetTrailingColumnPixel && _lastNonPinnedColumn == null) { _lastNonPinnedColumn = column; } startOfRegularColumn = span.trailingOffset; @@ -810,9 +760,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { (delegate.rowCount != null && row >= delegate.rowCount! - delegate.trailingPinnedRowCount); final leadingOffset = isPinned - ? (row < delegate.pinnedRowCount - ? startOfPinnedRow - : startOfTrailingPinnedRow) + ? (row < delegate.pinnedRowCount ? startOfPinnedRow : startOfTrailingPinnedRow) : startOfRegularRow; _Span? span = _rowMetrics.remove(row); final TableSpan? configuration = (needsDelegateRebuild || span == null) @@ -851,12 +799,10 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ); _rowMetrics[row] = span; if (!isPinned) { - if (span.trailingOffset >= _targetLeadingRowPixel && - _firstNonPinnedRow == null) { + if (span.trailingOffset >= _targetLeadingRowPixel && _firstNonPinnedRow == null) { _firstNonPinnedRow = row; } - if (span.trailingOffset >= _targetTrailingRowPixel && - _lastNonPinnedRow == null) { + if (span.trailingOffset >= _targetTrailingRowPixel && _lastNonPinnedRow == null) { _lastNonPinnedRow = row; } startOfRegularRow = span.trailingOffset; @@ -905,8 +851,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { } void _updateScrollBounds() { - final bool acceptedDimension = - _updateHorizontalScrollBounds() && _updateVerticalScrollBounds(); + final bool acceptedDimension = _updateHorizontalScrollBounds() && _updateVerticalScrollBounds(); if (!acceptedDimension) { _updateFirstAndLastVisibleCell(); } @@ -917,8 +862,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_columnsAreInfinite && _columnNullTerminatedIndex == null) { maxHorizontalScrollExtent = double.infinity; } else if (!_columnsAreInfinite && - _columnMetrics.length <= - delegate.pinnedColumnCount + delegate.trailingPinnedColumnCount) { + _columnMetrics.length <= delegate.pinnedColumnCount + delegate.trailingPinnedColumnCount) { assert(_firstNonPinnedColumn == null && _lastNonPinnedColumn == null); maxHorizontalScrollExtent = 0.0; } else { @@ -934,10 +878,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ); } } - return horizontalOffset.applyContentDimensions( - 0.0, - maxHorizontalScrollExtent, - ); + return horizontalOffset.applyContentDimensions(0.0, maxHorizontalScrollExtent); } bool _updateVerticalScrollBounds() { @@ -945,8 +886,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_rowsAreInfinite && _rowNullTerminatedIndex == null) { maxVerticalScrollExtent = double.infinity; } else if (!_rowsAreInfinite && - _rowMetrics.length <= - delegate.pinnedRowCount + delegate.trailingPinnedRowCount) { + _rowMetrics.length <= delegate.pinnedRowCount + delegate.trailingPinnedRowCount) { assert(_firstNonPinnedRow == null && _lastNonPinnedRow == null); maxVerticalScrollExtent = 0.0; } else { @@ -956,9 +896,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { } else { maxVerticalScrollExtent = math.max( 0.0, - _rowMetrics[lastRow]!.trailingOffset - - viewportDimension.height + - _pinnedRowsExtent, + _rowMetrics[lastRow]!.trailingOffset - viewportDimension.height + _pinnedRowsExtent, ); } } @@ -968,10 +906,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { /// Binary search to find the first index with [_Span] matching the condition. /// [map]: Index-[_Span] map, [condition]: Match rule /// Returns the first matched index or null if not found. - int? _binarySearchFirstFromMap( - Map map, - bool Function(_Span) condition, - ) { + int? _binarySearchFirstFromMap(Map map, bool Function(_Span) condition) { if (map.isEmpty) { return null; } @@ -998,8 +933,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { void _updateFirstAndLastVisibleCell() { if (_columnMetrics.isNotEmpty) { _Span lastKnownColumn = _columnMetrics[_columnMetrics.length - 1]!; - if (_columnsAreInfinite && - lastKnownColumn.trailingOffset < _targetTrailingColumnPixel) { + if (_columnsAreInfinite && lastKnownColumn.trailingOffset < _targetTrailingColumnPixel) { // This will add the column metrics we do not know about up to the // _targetColumnPixel, while keeping the ones we already know about. _updateColumnMetrics(appendColumns: true); @@ -1016,13 +950,11 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // Binary search replaces for-loop to reduce computation. _firstNonPinnedColumn = _binarySearchFirstFromMap( _columnMetrics, - (span) => - !span.isPinned && span.trailingOffset >= _targetLeadingColumnPixel, + (span) => !span.isPinned && span.trailingOffset >= _targetLeadingColumnPixel, ); _lastNonPinnedColumn = _binarySearchFirstFromMap( _columnMetrics, - (span) => - !span.isPinned && span.trailingOffset >= _targetTrailingColumnPixel, + (span) => !span.isPinned && span.trailingOffset >= _targetTrailingColumnPixel, ); if (_firstNonPinnedColumn != null) { _lastNonPinnedColumn ??= _columnMetrics.length - 1; @@ -1030,8 +962,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_rowMetrics.isNotEmpty) { _Span lastKnownRow = _rowMetrics[_rowMetrics.length - 1]!; - if (_rowsAreInfinite && - lastKnownRow.trailingOffset < _targetTrailingRowPixel) { + if (_rowsAreInfinite && lastKnownRow.trailingOffset < _targetTrailingRowPixel) { // This will add the row metrics we do not know about up to the // _targetRowPixel, while keeping the ones we already know about. _updateRowMetrics(appendRows: true); @@ -1052,8 +983,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ); _lastNonPinnedRow = _binarySearchFirstFromMap( _rowMetrics, - (span) => - !span.isPinned && span.trailingOffset >= _targetTrailingRowPixel, + (span) => !span.isPinned && span.trailingOffset >= _targetTrailingRowPixel, ); if (_firstNonPinnedRow != null) { _lastNonPinnedRow ??= _rowMetrics.length - 1; @@ -1086,26 +1016,20 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { _hAlignmentOffset = 0.0; if (!_columnsAreInfinite && _columnMetrics.isNotEmpty) { final double totalWidth = - _pinnedColumnsExtent + - _columnMetrics[delegate.columnCount! - 1]!.trailingOffset; + _pinnedColumnsExtent + _columnMetrics[delegate.columnCount! - 1]!.trailingOffset; if (totalWidth < viewportDimension.width) { _hAlignmentOffset = - (viewportDimension.width - totalWidth) * - (resolvedAlignment.x + 1.0) / - 2.0; + (viewportDimension.width - totalWidth) * (resolvedAlignment.x + 1.0) / 2.0; } } _vAlignmentOffset = 0.0; if (!_rowsAreInfinite && _rowMetrics.isNotEmpty) { final double totalHeight = - _pinnedRowsExtent + - _rowMetrics[delegate.rowCount! - 1]!.trailingOffset; + _pinnedRowsExtent + _rowMetrics[delegate.rowCount! - 1]!.trailingOffset; if (totalHeight < viewportDimension.height) { _vAlignmentOffset = - (viewportDimension.height - totalHeight) * - (resolvedAlignment.y + 1.0) / - 2.0; + (viewportDimension.height - totalHeight) * (resolvedAlignment.y + 1.0) / 2.0; } } @@ -1154,10 +1078,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { assert(offsetIntoColumn != null); _layoutCells( start: TableVicinity(column: _firstNonPinnedColumn!, row: 0), - end: TableVicinity( - column: _lastNonPinnedColumn!, - row: _lastPinnedRow!, - ), + end: TableVicinity(column: _lastNonPinnedColumn!, row: _lastPinnedRow!), offset: Offset(offsetIntoColumn!, -_vAlignmentOffset), ); } @@ -1165,10 +1086,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_firstTrailingPinnedColumn != null) { _layoutCells( start: TableVicinity(column: _firstTrailingPinnedColumn!, row: 0), - end: TableVicinity( - column: delegate.columnCount! - 1, - row: _lastPinnedRow!, - ), + end: TableVicinity(column: delegate.columnCount! - 1, row: _lastPinnedRow!), offset: Offset(trailingPinnedColumnOffset, -_vAlignmentOffset), ); } @@ -1182,10 +1100,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_lastPinnedColumn != null) { _layoutCells( start: TableVicinity(column: 0, row: _firstNonPinnedRow!), - end: TableVicinity( - column: _lastPinnedColumn!, - row: _lastNonPinnedRow!, - ), + end: TableVicinity(column: _lastPinnedColumn!, row: _lastNonPinnedRow!), offset: Offset(-_hAlignmentOffset, offsetIntoRow!), ); } @@ -1194,28 +1109,16 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { assert(_lastNonPinnedColumn != null); assert(offsetIntoColumn != null); _layoutCells( - start: TableVicinity( - column: _firstNonPinnedColumn!, - row: _firstNonPinnedRow!, - ), - end: TableVicinity( - column: _lastNonPinnedColumn!, - row: _lastNonPinnedRow!, - ), + start: TableVicinity(column: _firstNonPinnedColumn!, row: _firstNonPinnedRow!), + end: TableVicinity(column: _lastNonPinnedColumn!, row: _lastNonPinnedRow!), offset: Offset(offsetIntoColumn!, offsetIntoRow!), ); } // (N, T) if (_firstTrailingPinnedColumn != null) { _layoutCells( - start: TableVicinity( - column: _firstTrailingPinnedColumn!, - row: _firstNonPinnedRow!, - ), - end: TableVicinity( - column: delegate.columnCount! - 1, - row: _lastNonPinnedRow!, - ), + start: TableVicinity(column: _firstTrailingPinnedColumn!, row: _firstNonPinnedRow!), + end: TableVicinity(column: delegate.columnCount! - 1, row: _lastNonPinnedRow!), offset: Offset(trailingPinnedColumnOffset, offsetIntoRow!), ); } @@ -1227,10 +1130,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_lastPinnedColumn != null) { _layoutCells( start: TableVicinity(column: 0, row: _firstTrailingPinnedRow!), - end: TableVicinity( - column: _lastPinnedColumn!, - row: delegate.rowCount! - 1, - ), + end: TableVicinity(column: _lastPinnedColumn!, row: delegate.rowCount! - 1), offset: Offset(-_hAlignmentOffset, trailingPinnedRowOffset), ); } @@ -1239,28 +1139,16 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { assert(_lastNonPinnedColumn != null); assert(offsetIntoColumn != null); _layoutCells( - start: TableVicinity( - column: _firstNonPinnedColumn!, - row: _firstTrailingPinnedRow!, - ), - end: TableVicinity( - column: _lastNonPinnedColumn!, - row: delegate.rowCount! - 1, - ), + start: TableVicinity(column: _firstNonPinnedColumn!, row: _firstTrailingPinnedRow!), + end: TableVicinity(column: _lastNonPinnedColumn!, row: delegate.rowCount! - 1), offset: Offset(offsetIntoColumn!, trailingPinnedRowOffset), ); } // (T, T) if (_firstTrailingPinnedColumn != null) { _layoutCells( - start: TableVicinity( - column: _firstTrailingPinnedColumn!, - row: _firstTrailingPinnedRow!, - ), - end: TableVicinity( - column: delegate.columnCount! - 1, - row: delegate.rowCount! - 1, - ), + start: TableVicinity(column: _firstTrailingPinnedColumn!, row: _firstTrailingPinnedRow!), + end: TableVicinity(column: delegate.columnCount! - 1, row: delegate.rowCount! - 1), offset: Offset(trailingPinnedColumnOffset, trailingPinnedRowOffset), ); } @@ -1305,8 +1193,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { '$lowerSpanOrientation ${pinnedSpanCount - 1}.', ); } - if (spanCount != null && - spanMergeEnd >= spanCount - trailingPinnedSpanCount) { + if (spanCount != null && spanMergeEnd >= spanCount - trailingPinnedSpanCount) { // Merged cells cannot span trailing pinned and unpinned cells. assert( spanMergeStart >= spanCount - trailingPinnedSpanCount, @@ -1352,8 +1239,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { final TableViewParentData cellParentData = parentDataOf(cell); // Merged cell handling - if (cellParentData.rowMergeStart != null || - cellParentData.columnMergeStart != null) { + if (cellParentData.rowMergeStart != null || cellParentData.columnMergeStart != null) { final int firstRow = cellParentData.rowMergeStart ?? row; final int lastRow = cellParentData.rowMergeStart == null ? row @@ -1400,27 +1286,20 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // Compute height and layout offset for merged rows. final bool rowIsInPinnedColumn = - (_lastPinnedColumn != null && - vicinity.column <= _lastPinnedColumn!) || + (_lastPinnedColumn != null && vicinity.column <= _lastPinnedColumn!) || (_firstTrailingPinnedColumn != null && vicinity.column >= _firstTrailingPinnedColumn!); final bool rowIsPinned = (_lastPinnedRow != null && firstRow <= _lastPinnedRow!) || - (_firstTrailingPinnedRow != null && - firstRow >= _firstTrailingPinnedRow!); - final double baseRowOffset = switch (( - rowIsInPinnedColumn, - rowIsPinned, - )) { + (_firstTrailingPinnedRow != null && firstRow >= _firstTrailingPinnedRow!); + final double baseRowOffset = switch ((rowIsInPinnedColumn, rowIsPinned)) { // Both row and column are pinned at this cell, or just pinned row. (true, true) || (false, true) => - _firstTrailingPinnedRow != null && - firstRow >= _firstTrailingPinnedRow! + _firstTrailingPinnedRow != null && firstRow >= _firstTrailingPinnedRow! ? viewportDimension.height - _trailingPinnedRowsExtent : 0.0, // Cell is within a pinned column, or no pinned area at all. - (true, false) || (false, false) => - _leadingPinnedRowsExtent - verticalOffset.pixels, + (true, false) || (false, false) => _leadingPinnedRowsExtent - verticalOffset.pixels, }; mergedRowOffset = baseRowOffset + @@ -1447,26 +1326,19 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // Compute width and layout offset for merged columns. final bool columnIsInPinnedRow = (_lastPinnedRow != null && vicinity.row <= _lastPinnedRow!) || - (_firstTrailingPinnedRow != null && - vicinity.row >= _firstTrailingPinnedRow!); + (_firstTrailingPinnedRow != null && vicinity.row >= _firstTrailingPinnedRow!); final bool columnIsPinned = - (_lastPinnedColumn != null && - firstColumn <= _lastPinnedColumn!) || - (_firstTrailingPinnedColumn != null && - firstColumn >= _firstTrailingPinnedColumn!); - final double baseColumnOffset = switch (( - columnIsInPinnedRow, - columnIsPinned, - )) { + (_lastPinnedColumn != null && firstColumn <= _lastPinnedColumn!) || + (_firstTrailingPinnedColumn != null && firstColumn >= _firstTrailingPinnedColumn!); + final double baseColumnOffset = switch ((columnIsInPinnedRow, columnIsPinned)) { // Both row and column are pinned at this cell, or just pinned column. (true, true) || (false, true) => - _firstTrailingPinnedColumn != null && - firstColumn >= _firstTrailingPinnedColumn! + _firstTrailingPinnedColumn != null && firstColumn >= _firstTrailingPinnedColumn! ? viewportDimension.width - _trailingPinnedColumnsExtent : 0.0, // Cell is within a pinned row, or no pinned area at all. - (true, false) || (false, false) => - _leadingPinnedColumnsExtent - horizontalOffset.pixels, + (true, false) || + (false, false) => _leadingPinnedColumnsExtent - horizontalOffset.pixels, }; mergedColumnOffset = baseColumnOffset + @@ -1477,10 +1349,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // The number of columns is infinite, and we have not calculated // the metrics to the full extent of the merged cell. Update the // metrics so we have all the information for the merged area. - _updateColumnMetrics( - appendColumns: true, - toColumnIndex: lastColumn, - ); + _updateColumnMetrics(appendColumns: true, toColumnIndex: lastColumn); } assert( _columnMetrics[lastColumn] != null, @@ -1506,10 +1375,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (cellParentData.columnMergeStart != null) { _mergedColumns.add(currentColumn); } - final key = TableVicinity( - row: currentRow, - column: currentColumn, - ); + final key = TableVicinity(row: currentRow, column: currentColumn); _mergedVicinities[key] = vicinity; currentColumn++; } @@ -1532,24 +1398,17 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { mergedColumnWidth = null; } columnOffset += - standardColumnWidth + - _columnMetrics[column]!.configuration.padding.trailing; + standardColumnWidth + _columnMetrics[column]!.configuration.padding.trailing; } - rowOffset += - standardRowHeight + _rowMetrics[row]!.configuration.padding.trailing; + rowOffset += standardRowHeight + _rowMetrics[row]!.configuration.padding.trailing; } } - final LayerHandle _clipPinnedRowsHandle = - LayerHandle(); - final LayerHandle _clipPinnedColumnsHandle = - LayerHandle(); - final LayerHandle _clipTrailingPinnedRowsHandle = - LayerHandle(); - final LayerHandle _clipTrailingPinnedColumnsHandle = - LayerHandle(); - final LayerHandle _clipCellsHandle = - LayerHandle(); + final LayerHandle _clipPinnedRowsHandle = LayerHandle(); + final LayerHandle _clipPinnedColumnsHandle = LayerHandle(); + final LayerHandle _clipTrailingPinnedRowsHandle = LayerHandle(); + final LayerHandle _clipTrailingPinnedColumnsHandle = LayerHandle(); + final LayerHandle _clipCellsHandle = LayerHandle(); @override void paint(PaintingContext context, Offset offset) { @@ -1572,9 +1431,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { needsCompositing, offset, Rect.fromLTWH( - (reversedH - ? _trailingPinnedColumnsExtent - : _leadingPinnedColumnsExtent) + + (reversedH ? _trailingPinnedColumnsExtent : _leadingPinnedColumnsExtent) + (reversedH ? -_hAlignmentOffset : _hAlignmentOffset), (reversedV ? _trailingPinnedRowsExtent : _leadingPinnedRowsExtent) + (reversedV ? -_vAlignmentOffset : _vAlignmentOffset), @@ -1604,9 +1461,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { offset, Rect.fromLTWH( reversedH - ? viewportDimension.width - - _leadingPinnedColumnsExtent - - _hAlignmentOffset + ? viewportDimension.width - _leadingPinnedColumnsExtent - _hAlignmentOffset : _hAlignmentOffset, (reversedV ? _trailingPinnedRowsExtent : _leadingPinnedRowsExtent) + (reversedV ? -_vAlignmentOffset : _vAlignmentOffset), @@ -1618,10 +1473,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { context: context, offset: offset, leadingVicinity: TableVicinity(column: 0, row: _firstNonPinnedRow!), - trailingVicinity: TableVicinity( - column: _lastPinnedColumn!, - row: _lastNonPinnedRow!, - ), + trailingVicinity: TableVicinity(column: _lastPinnedColumn!, row: _lastNonPinnedRow!), ); }, clipBehavior: clipBehavior, @@ -1640,9 +1492,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { Rect.fromLTWH( reversedH ? _hAlignmentOffset - : viewportDimension.width - - _trailingPinnedColumnsExtent - - _hAlignmentOffset, + : viewportDimension.width - _trailingPinnedColumnsExtent - _hAlignmentOffset, (reversedV ? _trailingPinnedRowsExtent : _leadingPinnedRowsExtent) + (reversedV ? -_vAlignmentOffset : _vAlignmentOffset), _trailingPinnedColumnsExtent, @@ -1676,14 +1526,10 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { needsCompositing, offset, Rect.fromLTWH( - (reversedH - ? _trailingPinnedColumnsExtent - : _leadingPinnedColumnsExtent) + + (reversedH ? _trailingPinnedColumnsExtent : _leadingPinnedColumnsExtent) + (reversedH ? -_hAlignmentOffset : _hAlignmentOffset), reversedV - ? viewportDimension.height - - _leadingPinnedRowsExtent - - _vAlignmentOffset + ? viewportDimension.height - _leadingPinnedRowsExtent - _vAlignmentOffset : _vAlignmentOffset, viewportDimension.width - _pinnedColumnsExtent, _leadingPinnedRowsExtent, @@ -1692,14 +1538,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { _paintCells( context: context, offset: offset, - leadingVicinity: TableVicinity( - column: _firstNonPinnedColumn!, - row: 0, - ), - trailingVicinity: TableVicinity( - column: _lastNonPinnedColumn!, - row: _lastPinnedRow!, - ), + leadingVicinity: TableVicinity(column: _firstNonPinnedColumn!, row: 0), + trailingVicinity: TableVicinity(column: _lastNonPinnedColumn!, row: _lastPinnedRow!), ); }, clipBehavior: clipBehavior, @@ -1716,15 +1556,11 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { needsCompositing, offset, Rect.fromLTWH( - (reversedH - ? _trailingPinnedColumnsExtent - : _leadingPinnedColumnsExtent) + + (reversedH ? _trailingPinnedColumnsExtent : _leadingPinnedColumnsExtent) + (reversedH ? -_hAlignmentOffset : _hAlignmentOffset), reversedV ? _vAlignmentOffset - : viewportDimension.height - - _trailingPinnedRowsExtent - - _vAlignmentOffset, + : viewportDimension.height - _trailingPinnedRowsExtent - _vAlignmentOffset, viewportDimension.width - _pinnedColumnsExtent, _trailingPinnedRowsExtent, ), @@ -1756,24 +1592,15 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { context: context, offset: offset, leadingVicinity: TableVicinity.zero, - trailingVicinity: TableVicinity( - column: _lastPinnedColumn!, - row: _lastPinnedRow!, - ), + trailingVicinity: TableVicinity(column: _lastPinnedColumn!, row: _lastPinnedRow!), ); } if (_firstTrailingPinnedColumn != null) { _paintCells( context: context, offset: offset, - leadingVicinity: TableVicinity( - column: _firstTrailingPinnedColumn!, - row: 0, - ), - trailingVicinity: TableVicinity( - column: delegate.columnCount! - 1, - row: _lastPinnedRow!, - ), + leadingVicinity: TableVicinity(column: _firstTrailingPinnedColumn!, row: 0), + trailingVicinity: TableVicinity(column: delegate.columnCount! - 1, row: _lastPinnedRow!), ); } } @@ -1782,14 +1609,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { _paintCells( context: context, offset: offset, - leadingVicinity: TableVicinity( - column: 0, - row: _firstTrailingPinnedRow!, - ), - trailingVicinity: TableVicinity( - column: _lastPinnedColumn!, - row: delegate.rowCount! - 1, - ), + leadingVicinity: TableVicinity(column: 0, row: _firstTrailingPinnedRow!), + trailingVicinity: TableVicinity(column: _lastPinnedColumn!, row: delegate.rowCount! - 1), ); } if (_firstTrailingPinnedColumn != null) { @@ -1816,14 +1637,9 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // This is relevant for scenarios like painting, where we only want to paint // one merged cell. @override - RenderBox? getChildFor( - ChildVicinity vicinity, { - bool mapMergedVicinityToCanonicalChild = true, - }) { + RenderBox? getChildFor(ChildVicinity vicinity, {bool mapMergedVicinityToCanonicalChild = true}) { return super.getChildFor(vicinity) ?? - (mapMergedVicinityToCanonicalChild - ? _getMergedChildFor(vicinity as TableVicinity) - : null); + (mapMergedVicinityToCanonicalChild ? _getMergedChildFor(vicinity as TableVicinity) : null); } RenderBox _getMergedChildFor(TableVicinity vicinity) { @@ -1836,10 +1652,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { ); final TableVicinity mergedVicinity = _mergedVicinities[vicinity]!; // This vicinity must resolve to a child, unless something has gone wrong! - return getChildFor( - mergedVicinity, - mapMergedVicinityToCanonicalChild: false, - )!; + return getChildFor(mergedVicinity, mapMergedVicinityToCanonicalChild: false)!; } void _paintCells({ @@ -1852,11 +1665,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { final foregroundColumns = {}; final backgroundColumns = {}; - for ( - int column = leadingVicinity.column; - column <= trailingVicinity.column; - column++ - ) { + for (int column = leadingVicinity.column; column <= trailingVicinity.column; column++) { TableSpan columnSpan = _columnMetrics[column]!.configuration; if (columnSpan.backgroundDecoration != null || columnSpan.foregroundDecoration != null || @@ -1865,12 +1674,8 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (_mergedColumns.isEmpty || !_mergedColumns.contains(column)) { // One decoration across the whole column. decorationCells.add(( - leading: getChildFor( - TableVicinity(column: column, row: leadingVicinity.row), - )!, - trailing: getChildFor( - TableVicinity(column: column, row: trailingVicinity.row), - )!, + leading: getChildFor(TableVicinity(column: column, row: leadingVicinity.row))!, + trailing: getChildFor(TableVicinity(column: column, row: trailingVicinity.row))!, )); } else { // Walk through the rows to separate merged cells for decorating. A @@ -1894,10 +1699,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (parentDataOf(leadingCell).columnMergeStart != null) { // Merged portion decorated individually since it exceeds the // single column width. - decorationCells.add(( - leading: leadingCell, - trailing: leadingCell, - )); + decorationCells.add((leading: leadingCell, trailing: leadingCell)); currentRow++; continue; } @@ -1905,21 +1707,16 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // up to, or following after, the merged cell so we can decorate // efficiently with as few rects as possible. RenderBox? nextCell = leadingCell; - while (nextCell != null && - parentDataOf(nextCell).columnMergeStart == null) { + while (nextCell != null && parentDataOf(nextCell).columnMergeStart == null) { final TableViewParentData parentData = parentDataOf(nextCell); if (parentData.rowMergeStart != null) { - currentRow = - parentData.rowMergeStart! + parentData.rowMergeSpan!; + currentRow = parentData.rowMergeStart! + parentData.rowMergeSpan!; } else { currentRow += 1; } trailingCell = nextCell; vicinity = vicinity.copyWith(row: currentRow); - nextCell = getChildFor( - vicinity, - mapMergedVicinityToCanonicalChild: false, - ); + nextCell = getChildFor(vicinity, mapMergedVicinityToCanonicalChild: false); } decorationCells.add((leading: leadingCell, trailing: trailingCell)); } @@ -1930,26 +1727,18 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { required RenderBox trailingCell, required bool consumePadding, }) { - final bool reversedH = axisDirectionIsReversed( - horizontalAxisDirection, - ); + final bool reversedH = axisDirectionIsReversed(horizontalAxisDirection); final bool reversedV = axisDirectionIsReversed(verticalAxisDirection); final TableSpan leadingRowSpan = - _rowMetrics[parentDataOf(leadingCell).tableVicinity.row]! - .configuration; + _rowMetrics[parentDataOf(leadingCell).tableVicinity.row]!.configuration; final TableSpan trailingRowSpan = - _rowMetrics[parentDataOf(trailingCell).tableVicinity.row]! - .configuration; + _rowMetrics[parentDataOf(trailingCell).tableVicinity.row]!.configuration; final double leftExpansion = consumePadding - ? (reversedH - ? columnSpan.padding.trailing - : columnSpan.padding.leading) + ? (reversedH ? columnSpan.padding.trailing : columnSpan.padding.leading) : 0.0; final double rightExpansion = consumePadding - ? (reversedH - ? columnSpan.padding.leading - : columnSpan.padding.trailing) + ? (reversedH ? columnSpan.padding.leading : columnSpan.padding.trailing) : 0.0; final double topExpansion = reversedV ? trailingRowSpan.padding.trailing @@ -1983,8 +1772,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { final Rect rect = getColumnRect( leadingCell: cell.leading, trailingCell: cell.trailing, - consumePadding: - columnSpan.backgroundDecoration!.consumeSpanPadding, + consumePadding: columnSpan.backgroundDecoration!.consumeSpanPadding, ); backgroundColumns[rect] = columnSpan.backgroundDecoration!; } @@ -1992,8 +1780,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { final Rect rect = getColumnRect( leadingCell: cell.leading, trailingCell: cell.trailing, - consumePadding: - columnSpan.foregroundDecoration!.consumeSpanPadding, + consumePadding: columnSpan.foregroundDecoration!.consumeSpanPadding, ); foregroundColumns[rect] = columnSpan.foregroundDecoration!; } @@ -2042,10 +1829,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { if (parentDataOf(leadingCell).rowMergeStart != null) { // Merged portion decorated individually since it exceeds the // single row height. - decorationCells.add(( - leading: leadingCell, - trailing: leadingCell, - )); + decorationCells.add((leading: leadingCell, trailing: leadingCell)); currentColumn++; continue; } @@ -2053,21 +1837,16 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { // up to, or following after, the merged cell so we can decorate // efficiently with as few rects as possible. RenderBox? nextCell = leadingCell; - while (nextCell != null && - parentDataOf(nextCell).rowMergeStart == null) { + while (nextCell != null && parentDataOf(nextCell).rowMergeStart == null) { final TableViewParentData parentData = parentDataOf(nextCell); if (parentData.columnMergeStart != null) { - currentColumn = - parentData.columnMergeStart! + parentData.columnMergeSpan!; + currentColumn = parentData.columnMergeStart! + parentData.columnMergeSpan!; } else { currentColumn += 1; } trailingCell = nextCell; vicinity = vicinity.copyWith(column: currentColumn); - nextCell = getChildFor( - vicinity, - mapMergedVicinityToCanonicalChild: false, - ); + nextCell = getChildFor(vicinity, mapMergedVicinityToCanonicalChild: false); } decorationCells.add((leading: leadingCell, trailing: trailingCell)); } @@ -2078,16 +1857,12 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { required RenderBox trailingCell, required bool consumePadding, }) { - final bool reversedH = axisDirectionIsReversed( - horizontalAxisDirection, - ); + final bool reversedH = axisDirectionIsReversed(horizontalAxisDirection); final bool reversedV = axisDirectionIsReversed(verticalAxisDirection); final TableSpan leadingColSpan = - _columnMetrics[parentDataOf(leadingCell).tableVicinity.column]! - .configuration; + _columnMetrics[parentDataOf(leadingCell).tableVicinity.column]!.configuration; final TableSpan trailingColSpan = - _columnMetrics[parentDataOf(trailingCell).tableVicinity.column]! - .configuration; + _columnMetrics[parentDataOf(trailingCell).tableVicinity.column]!.configuration; final double leftExpansion = reversedH ? trailingColSpan.padding.trailing @@ -2193,17 +1968,10 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { } // Cells - for ( - int column = leadingVicinity.column; - column <= trailingVicinity.column; - column++ - ) { + for (int column = leadingVicinity.column; column <= trailingVicinity.column; column++) { for (int row = leadingVicinity.row; row <= trailingVicinity.row; row++) { final vicinity = TableVicinity(column: column, row: row); - final RenderBox? cell = getChildFor( - vicinity, - mapMergedVicinityToCanonicalChild: false, - ); + final RenderBox? cell = getChildFor(vicinity, mapMergedVicinityToCanonicalChild: false); if (cell == null) { // Covered by a merged cell assert( @@ -2284,9 +2052,7 @@ class RenderTableViewport extends RenderTwoDimensionalViewport { } } -class _Span - with Diagnosticable - implements HitTestTarget, MouseTrackerAnnotation { +class _Span with Diagnosticable implements HitTestTarget, MouseTrackerAnnotation { double get leadingOffset => _leadingOffset; late double _leadingOffset; @@ -2300,10 +2066,7 @@ class _Span late bool _isPinned; double get trailingOffset { - return leadingOffset + - extent + - configuration.padding.leading + - configuration.padding.trailing; + return leadingOffset + extent + configuration.padding.leading + configuration.padding.trailing; } // ---- Span Management ---- @@ -2344,8 +2107,7 @@ class _Span for (final Type type in configuration.recognizerFactories.keys) { assert(!newRecognizers.containsKey(type)); newRecognizers[type] = - _recognizers?.remove(type) ?? - configuration.recognizerFactories[type]!.constructor(); + _recognizers?.remove(type) ?? configuration.recognizerFactories[type]!.constructor(); assert( newRecognizers[type].runtimeType == type, 'GestureRecognizerFactory of type $type created a GestureRecognizer of ' @@ -2353,9 +2115,7 @@ class _Span 'GestureRecognizerFactory must be specialized with the type of the ' 'class that it returns from its constructor method.', ); - configuration.recognizerFactories[type]!.initializer( - newRecognizers[type]!, - ); + configuration.recognizerFactories[type]!.initializer(newRecognizers[type]!); } _disposeRecognizers(); // only disposes the ones that where not re-used above. _recognizers = newRecognizers; @@ -2374,8 +2134,7 @@ class _Span @override void handleEvent(PointerEvent event, HitTestEntry entry) { - if (event is PointerDownEvent && - configuration.recognizerFactories.isNotEmpty) { + if (event is PointerDownEvent && configuration.recognizerFactories.isNotEmpty) { if (_recognizers == null) { _syncRecognizers(); } diff --git a/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart b/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart index 4e13b2971a79..d5e882b9d638 100644 --- a/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart +++ b/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart @@ -17,8 +17,7 @@ import 'table.dart'; class TableVicinity extends ChildVicinity { /// Creates a reference to a child in a [TableView], with the [xIndex] and /// [yIndex] converted to terms of [row] and [column]. - const TableVicinity({required int row, required int column}) - : super(xIndex: column, yIndex: row); + const TableVicinity({required int row, required int column}) : super(xIndex: column, yIndex: row); /// The row index of the child in the [TableView]. /// diff --git a/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart b/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart index b99cccf62183..775096aaae94 100644 --- a/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart +++ b/packages/two_dimensional_scrollables/lib/src/table_view/table_delegate.dart @@ -24,8 +24,7 @@ typedef TableSpanBuilder = TableSpan? Function(int index); /// /// Used by [TableCellBuilderDelegate.builder] to build cells on demand for the /// table. -typedef TableViewCellBuilder = - TableViewCell Function(BuildContext context, TableVicinity vicinity); +typedef TableViewCellBuilder = TableViewCell Function(BuildContext context, TableVicinity vicinity); /// A mixin that defines the model for a [TwoDimensionalChildDelegate] to be /// used with a [TableView]. @@ -198,14 +197,8 @@ class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate assert(trailingPinnedRowCount >= 0), assert(rowCount == null || rowCount >= 0), assert(columnCount == null || columnCount >= 0), - assert( - columnCount == null || - pinnedColumnCount + trailingPinnedColumnCount <= columnCount, - ), - assert( - rowCount == null || - pinnedRowCount + trailingPinnedRowCount <= rowCount, - ), + assert(columnCount == null || pinnedColumnCount + trailingPinnedColumnCount <= columnCount), + assert(rowCount == null || pinnedRowCount + trailingPinnedRowCount <= rowCount), _rowBuilder = rowBuilder, _columnBuilder = columnBuilder, _pinnedColumnCount = pinnedColumnCount, @@ -225,9 +218,7 @@ class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate int? get columnCount => maxXIndex == null ? null : maxXIndex! + 1; set columnCount(int? value) { - assert( - value == null || pinnedColumnCount + trailingPinnedColumnCount <= value, - ); + assert(value == null || pinnedColumnCount + trailingPinnedColumnCount <= value); maxXIndex = value == null ? null : value - 1; } @@ -246,9 +237,7 @@ class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate int _pinnedColumnCount; set pinnedColumnCount(int value) { assert(value >= 0); - assert( - columnCount == null || value + trailingPinnedColumnCount <= columnCount!, - ); + assert(columnCount == null || value + trailingPinnedColumnCount <= columnCount!); if (pinnedColumnCount == value) { return; } @@ -324,8 +313,7 @@ class TableCellBuilderDelegate extends TwoDimensionalChildBuilderDelegate /// Unlike the base [TwoDimensionalChildBuilderDelegate] this delegate does not /// automatically insert repaint boundaries. Instead, repaint boundaries are /// controlled by [TableViewCell.addRepaintBoundaries]. -class TableCellListDelegate extends TwoDimensionalChildListDelegate - with TableCellDelegateMixin { +class TableCellListDelegate extends TwoDimensionalChildListDelegate with TableCellDelegateMixin { /// Creates a delegate that supplies children for a [TableView]. TableCellListDelegate({ int pinnedColumnCount = 0, diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart index 10eb1ac3646a..f5befabcaf36 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/render_tree.dart @@ -155,10 +155,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { // Updates the cache at the start of eah layout pass. void _updateAnimationCache() { _animationLeadingIndices.clear(); - _activeAnimations.forEach(( - UniqueKey key, - TreeViewNodesAnimation animation, - ) { + _activeAnimations.forEach((UniqueKey key, TreeViewNodesAnimation animation) { _animationLeadingIndices[animation.fromIndex] = key; }); // Remove any stored offsets or clip layers that are no longer actively @@ -166,10 +163,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { _animationOffsets.removeWhere((UniqueKey key, _) { return !_activeAnimations.keys.contains(key); }); - _clipHandles.removeWhere(( - UniqueKey key, - LayerHandle handle, - ) { + _clipHandles.removeWhere((UniqueKey key, LayerHandle handle) { if (!_activeAnimations.keys.contains(key)) { handle.layer = null; return true; @@ -188,9 +182,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { row = childAfter(row); continue; } - final Rect rowRect = - parentData.paintOffset! & - Size(viewportDimension.width, row.size.height); + final Rect rowRect = parentData.paintOffset! & Size(viewportDimension.width, row.size.height); if (rowRect.contains(position)) { result.addWithPaintOffset( offset: parentData.paintOffset, @@ -210,10 +202,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { @override void dispose() { - _clipHandles.removeWhere(( - UniqueKey key, - LayerHandle handle, - ) { + _clipHandles.removeWhere((UniqueKey key, LayerHandle handle) { handle.layer = null; return true; }); @@ -238,16 +227,11 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { _Span? span = _rowMetrics.remove(currentIndex); assert(needsDelegateRebuild || span != null); final TreeRow configuration = needsDelegateRebuild - ? delegate.buildRow( - TreeVicinity(depth: _rowDepths[currentIndex]!, row: currentIndex), - ) + ? delegate.buildRow(TreeVicinity(depth: _rowDepths[currentIndex]!, row: currentIndex)) : span!.configuration; span ??= _Span(); final double extent = configuration.extent.calculateExtent( - TreeRowExtentDelegate( - viewportExtent: viewportDimension.height, - precedingExtent: position, - ), + TreeRowExtentDelegate(viewportExtent: viewportDimension.height, precedingExtent: position), ); totalAnimatingOffset += extent; currentPosition += extent; @@ -292,8 +276,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { } // We add the offset accounting for the animation value. totalAnimationOffset += - _animationOffsets[animationKey]! * - (1 - _activeAnimations[animationKey]!.value); + _animationOffsets[animationKey]! * (1 - _activeAnimations[animationKey]!.value); } span.update( configuration: configuration, @@ -305,8 +288,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { if (span.trailingOffset >= verticalOffset.pixels && _firstRow == null) { _firstRow = row; } - if (span.trailingOffset - totalAnimationOffset >= _targetRowPixel && - _lastRow == null) { + if (span.trailingOffset - totalAnimationOffset >= _targetRowPixel && _lastRow == null) { _lastRow = row; } startOfRow = span.trailingOffset; @@ -379,13 +361,10 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { final Alignment resolvedAlignment = alignment.resolve(textDirection); _vAlignmentOffset = 0.0; if (_rowMetrics.isNotEmpty) { - final double totalHeight = - _rowMetrics[_rowMetrics.length - 1]!.trailingOffset; + final double totalHeight = _rowMetrics[_rowMetrics.length - 1]!.trailingOffset; if (totalHeight < viewportDimension.height) { _vAlignmentOffset = - (viewportDimension.height - totalHeight) * - (resolvedAlignment.y + 1.0) / - 2.0; + (viewportDimension.height - totalHeight) * (resolvedAlignment.y + 1.0) / 2.0; } } @@ -397,9 +376,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { _Span rowSpan; double rowOffset = - -verticalOffset.pixels + - _rowMetrics[_firstRow!]!.leadingOffset + - _vAlignmentOffset; + -verticalOffset.pixels + _rowMetrics[_firstRow!]!.leadingOffset + _vAlignmentOffset; for (int row = _firstRow!; row <= _lastRow!; row++) { rowSpan = _rowMetrics[row]!; final double rowHeight = rowSpan.extent; @@ -457,24 +434,14 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { offset, Offset.zero & size, (PaintingContext context, Offset offset) { - _paintRows( - context, - offset, - leadingRow: _firstRow!, - trailingRow: _lastRow!, - ); + _paintRows(context, offset, leadingRow: _firstRow!, trailingRow: _lastRow!); }, clipBehavior: clipBehavior, oldLayer: _clipHandles[_viewportClipKey]!.layer, ); } else { _clipHandles[_viewportClipKey]?.layer = null; - _paintRows( - context, - offset, - leadingRow: _firstRow!, - trailingRow: _lastRow!, - ); + _paintRows(context, offset, leadingRow: _firstRow!, trailingRow: _lastRow!); } return; } @@ -482,15 +449,11 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { // We are animating. // Separate animating segments to clip for any overlap. int leadingIndex = _firstRow!; - final List animationIndices = _animationLeadingIndices.keys.toList() - ..sort(); + final List animationIndices = _animationLeadingIndices.keys.toList()..sort(); final paintSegments = <_PaintSegment>[]; while (animationIndices.isNotEmpty) { final int trailingIndex = animationIndices.removeAt(0); - paintSegments.add(( - leadingIndex: leadingIndex, - trailingIndex: trailingIndex - 1, - )); + paintSegments.add((leadingIndex: leadingIndex, trailingIndex: trailingIndex - 1)); leadingIndex = trailingIndex; } paintSegments.add((leadingIndex: leadingIndex, trailingIndex: _lastRow!)); @@ -529,8 +492,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { final _PaintSegment segment = paintSegments.removeAt(0); final int parentIndex = segment.leadingIndex - 1; final double leadingOffset = _rowMetrics[parentIndex]!.trailingOffset; - final double trailingOffset = - _rowMetrics[segment.trailingIndex]!.trailingOffset; + final double trailingOffset = _rowMetrics[segment.trailingIndex]!.trailingOffset; final rect = Rect.fromPoints( Offset(0.0, leadingOffset - verticalOffset.pixels + _vAlignmentOffset), Offset( @@ -545,20 +507,17 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { // this is the odd man out segment. final UniqueKey key = _animationLeadingIndices[leadingIndex]!; _clipHandles[key] ??= LayerHandle(); - _clipHandles[key]!.layer = context.pushClipRect( - needsCompositing, - offset, - rect, - (PaintingContext context, Offset offset) { - _paintRows( - context, - offset, - leadingRow: segment.leadingIndex, - trailingRow: segment.trailingIndex, - ); - }, - oldLayer: _clipHandles[key]!.layer, - ); + _clipHandles[key]!.layer = context.pushClipRect(needsCompositing, offset, rect, ( + PaintingContext context, + Offset offset, + ) { + _paintRows( + context, + offset, + leadingRow: segment.leadingIndex, + trailingRow: segment.trailingIndex, + ); + }, oldLayer: _clipHandles[key]!.layer); } } @@ -583,9 +542,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { )!; Rect getRowRect(bool consumePadding) { - final TwoDimensionalViewportParentData parentData = parentDataOf( - child, - ); + final TwoDimensionalViewportParentData parentData = parentDataOf(child); // Decoration rects cover the whole row from the left and right // edge of the viewport. return Rect.fromLTRB( @@ -600,15 +557,11 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { } if (configuration.backgroundDecoration != null) { - final Rect rect = getRowRect( - configuration.backgroundDecoration!.consumeSpanPadding, - ); + final Rect rect = getRowRect(configuration.backgroundDecoration!.consumeSpanPadding); backgroundRows[rect] = configuration.backgroundDecoration!; } if (configuration.foregroundDecoration != null) { - final Rect rect = getRowRect( - configuration.foregroundDecoration!.consumeSpanPadding, - ); + final Rect rect = getRowRect(configuration.foregroundDecoration!.consumeSpanPadding); foregroundRows[rect] = configuration.foregroundDecoration!; } } @@ -628,12 +581,8 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { }); // Child nodes. for (var row = leadingRow; row <= trailingRow; row++) { - final RenderBox child = getChildFor( - TreeVicinity(depth: _rowDepths[row]!, row: row), - )!; - final TwoDimensionalViewportParentData rowParentData = parentDataOf( - child, - ); + final RenderBox child = getChildFor(TreeVicinity(depth: _rowDepths[row]!, row: row))!; + final TwoDimensionalViewportParentData rowParentData = parentDataOf(child); if (rowParentData.isVisible) { context.paintChild(child, offset + rowParentData.paintOffset!); } @@ -651,9 +600,7 @@ class RenderTreeViewport extends RenderTwoDimensionalViewport { } } -class _Span - with Diagnosticable - implements HitTestTarget, MouseTrackerAnnotation { +class _Span with Diagnosticable implements HitTestTarget, MouseTrackerAnnotation { double get leadingOffset => _leadingOffset; late double _leadingOffset; @@ -667,10 +614,7 @@ class _Span late double _animationOffset; double get trailingOffset { - return leadingOffset + - extent + - configuration.padding.leading + - configuration.padding.trailing; + return leadingOffset + extent + configuration.padding.leading + configuration.padding.trailing; } // ---- Span Management ---- @@ -711,8 +655,7 @@ class _Span for (final Type type in configuration.recognizerFactories.keys) { assert(!newRecognizers.containsKey(type)); newRecognizers[type] = - _recognizers?.remove(type) ?? - configuration.recognizerFactories[type]!.constructor(); + _recognizers?.remove(type) ?? configuration.recognizerFactories[type]!.constructor(); assert( newRecognizers[type].runtimeType == type, 'GestureRecognizerFactory of type $type created a GestureRecognizer of ' @@ -720,9 +663,7 @@ class _Span 'GestureRecognizerFactory must be specialized with the type of the ' 'class that it returns from its constructor method.', ); - configuration.recognizerFactories[type]!.initializer( - newRecognizers[type]!, - ); + configuration.recognizerFactories[type]!.initializer(newRecognizers[type]!); } _disposeRecognizers(); // only disposes the ones that where not re-used above. _recognizers = newRecognizers; @@ -741,8 +682,7 @@ class _Span @override void handleEvent(PointerEvent event, HitTestEntry entry) { - if (event is PointerDownEvent && - configuration.recognizerFactories.isNotEmpty) { + if (event is PointerDownEvent && configuration.recognizerFactories.isNotEmpty) { if (_recognizers == null) { _syncRecognizers(); } diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart index 6819c9424018..79ee107a9a8d 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree.dart @@ -30,13 +30,10 @@ const double _kDefaultRowExtent = 40.0; /// [TreeView]'s state. class TreeViewNode { /// Creates a [TreeViewNode] instance for use in a [TreeView]. - TreeViewNode( - T content, { - List>? children, - bool expanded = false, - }) : _expanded = children != null && children.isNotEmpty && expanded, - _content = content, - _children = children ?? >[]; + TreeViewNode(T content, {List>? children, bool expanded = false}) + : _expanded = children != null && children.isNotEmpty && expanded, + _content = content, + _children = children ?? >[]; /// The subject matter of the node. /// @@ -264,9 +261,7 @@ class TreeViewController { /// encloses the given context. Also includes some sample code in its /// documentation. static TreeViewController? maybeOf(BuildContext context) { - return context - .findAncestorStateOfType<_TreeViewState>() - ?.controller; + return context.findAncestorStateOfType<_TreeViewState>()?.controller; } } @@ -576,8 +571,7 @@ class TreeView extends StatefulWidget { ) { final Duration animationDuration = toggleAnimationStyle.duration ?? TreeView.defaultAnimationDuration; - final Curve animationCurve = - toggleAnimationStyle.curve ?? TreeView.defaultAnimationCurve; + final Curve animationCurve = toggleAnimationStyle.curve ?? TreeView.defaultAnimationCurve; final int index = TreeViewController.of(context).getActiveIndexFor(node)!; return Padding( padding: const EdgeInsets.all(8.0), @@ -643,11 +637,7 @@ class _TreeViewState extends State> } // Flattens the tree, omitting nodes that are not active. - void _unpackActiveNodes({ - int depth = 0, - List>? nodes, - TreeViewNode? parent, - }) { + void _unpackActiveNodes({int depth = 0, List>? nodes, TreeViewNode? parent}) { if (nodes == null) { _activeNodes.clear(); _rowDepths.clear(); @@ -659,11 +649,7 @@ class _TreeViewState extends State> _activeNodes.add(node); _rowDepths[_activeNodes.length - 1] = depth; if (_shouldUnpackNode(node)) { - _unpackActiveNodes( - depth: depth + 1, - nodes: node.children, - parent: node, - ); + _unpackActiveNodes(depth: depth + 1, nodes: node.children, parent: node); } } } @@ -814,10 +800,7 @@ class _TreeViewState extends State> activeNodesToExpand.reversed.forEach(toggleNode); } - void _expandAll( - List> tree, - List> activeNodesToExpand, - ) { + void _expandAll(List> tree, List> activeNodesToExpand) { for (final node in tree) { if (node.children.isNotEmpty) { // This is a parent node. @@ -846,10 +829,7 @@ class _TreeViewState extends State> activeNodesToCollapse.reversed.forEach(toggleNode); } - void _collapseAll( - List> tree, - List> activeNodesToCollapse, - ) { + void _collapseAll(List> tree, List> activeNodesToCollapse) { for (final node in tree) { if (node.children.isNotEmpty) { // This is a parent node. @@ -877,8 +857,7 @@ class _TreeViewState extends State> // animations keys each time we build with an updated active node list. _activeAnimations.clear(); for (final TreeViewNode node in _currentAnimationForParent.keys) { - final _AnimationRecord animationRecord = - _currentAnimationForParent[node]!; + final _AnimationRecord animationRecord = _currentAnimationForParent[node]!; final int leadingChildIndex = _activeNodes.indexOf(node) + 1; final TreeViewNodesAnimation animatingChildren = ( fromIndex: leadingChildIndex, @@ -915,9 +894,7 @@ class _TreeViewState extends State> AnimationController( value: node._expanded ? 0.0 : 1.0, vsync: this, - duration: - widget.toggleAnimationStyle?.duration ?? - TreeView.defaultAnimationDuration, + duration: widget.toggleAnimationStyle?.duration ?? TreeView.defaultAnimationDuration, ); controller ..addStatusListener((AnimationStatus status) { @@ -954,9 +931,7 @@ class _TreeViewState extends State> final newAnimation = CurvedAnimation( parent: controller, - curve: - widget.toggleAnimationStyle?.curve ?? - TreeView.defaultAnimationCurve, + curve: widget.toggleAnimationStyle?.curve ?? TreeView.defaultAnimationCurve, ); _currentAnimationForParent[node] = ( controller: controller, @@ -1100,10 +1075,7 @@ class TreeViewport extends TwoDimensionalViewport { } @override - void updateRenderObject( - BuildContext context, - RenderTreeViewport renderObject, - ) { + void updateRenderObject(BuildContext context, RenderTreeViewport renderObject) { renderObject ..activeAnimations = activeAnimations ..rowDepths = rowDepths diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart index 7eb971afacf7..fad5b0507c72 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_core.dart @@ -113,8 +113,7 @@ class TreeViewIndentationType { /// The default indentation of child [TreeViewNode]s in a [TreeView]. /// /// Child nodes will be offset by 10 pixels for each level in the tree. - static const TreeViewIndentationType standard = - TreeViewIndentationType._internal(10.0); + static const TreeViewIndentationType standard = TreeViewIndentationType._internal(10.0); /// Configures no offsetting of child nodes in a [TreeView]. /// @@ -122,9 +121,7 @@ class TreeViewIndentationType { /// [TreeView.treeNodeBuilder] instead for more customization options. /// /// Child nodes will not be offset in the tree. - static const TreeViewIndentationType none = TreeViewIndentationType._internal( - 0.0, - ); + static const TreeViewIndentationType none = TreeViewIndentationType._internal(0.0); /// Configures a custom offset for indenting child nodes in a [TreeView]. /// diff --git a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart index a1c5c5fa4bdd..4949743e5c1a 100644 --- a/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart +++ b/packages/two_dimensional_scrollables/lib/src/tree_view/tree_delegate.dart @@ -19,12 +19,11 @@ typedef TreeViewRowBuilder = TreeRow Function(TreeViewNode node); /// /// Used by [TreeView.treeRowBuilder] to build rows on demand for the /// tree. -typedef TreeViewNodeBuilder = - Widget Function( - BuildContext context, - TreeViewNode node, - AnimationStyle toggleAnimationStyle, - ); +typedef TreeViewNodeBuilder = Widget Function( + BuildContext context, + TreeViewNode node, + AnimationStyle toggleAnimationStyle, +); /// The position of a [TreeRow] in a [TreeViewport] in relation /// to other children of the viewport. @@ -36,8 +35,7 @@ typedef TreeViewNodeBuilder = class TreeVicinity extends ChildVicinity { /// Creates a reference to a [TreeRow] in a [TreeView], with the [xIndex] and /// [yIndex] converted to terms of [depth] and [row], respectively. - const TreeVicinity({required int depth, required int row}) - : super(xIndex: depth, yIndex: row); + const TreeVicinity({required int depth, required int row}) : super(xIndex: depth, yIndex: row); /// The row index of the [TreeRow] in the [TreeView]. /// @@ -90,8 +88,7 @@ typedef TreeVicinityToRowBuilder = TreeRow Function(TreeVicinity); /// /// The [rowCount] is determined by the number of active nodes in the /// [TreeView]. -class TreeRowBuilderDelegate extends TwoDimensionalChildBuilderDelegate - with TreeRowDelegateMixin { +class TreeRowBuilderDelegate extends TwoDimensionalChildBuilderDelegate with TreeRowDelegateMixin { /// Creates a lazy building delegate to use with a [TreeView]. TreeRowBuilderDelegate({ required int rowCount, diff --git a/packages/two_dimensional_scrollables/test/common/span_test.dart b/packages/two_dimensional_scrollables/test/common/span_test.dart index eb3fbe18fdab..63485f227229 100644 --- a/packages/two_dimensional_scrollables/test/common/span_test.dart +++ b/packages/two_dimensional_scrollables/test/common/span_test.dart @@ -12,9 +12,7 @@ void main() { test('FixedSpanExtent', () { var extent = const FixedSpanExtent(150); expect( - extent.calculateExtent( - const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 150, ); expect( @@ -41,9 +39,7 @@ void main() { test('FractionalSpanExtent', () { var extent = const FractionalSpanExtent(0.5); expect( - extent.calculateExtent( - const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 0.0, ); expect( @@ -70,9 +66,7 @@ void main() { test('RemainingSpanExtent', () { const extent = RemainingSpanExtent(); expect( - extent.calculateExtent( - const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 0.0, ); expect( @@ -84,17 +78,14 @@ void main() { }); test('CombiningSpanExtent', () { - final extent = CombiningSpanExtent( - const FixedSpanExtent(100), - const RemainingSpanExtent(), - (double a, double b) { - return a + b; - }, - ); + final extent = CombiningSpanExtent(const FixedSpanExtent(100), const RemainingSpanExtent(), ( + double a, + double b, + ) { + return a + b; + }); expect( - extent.calculateExtent( - const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 100, ); expect( @@ -108,9 +99,7 @@ void main() { test('MaxSpanExtent', () { const extent = MaxSpanExtent(FixedSpanExtent(100), RemainingSpanExtent()); expect( - extent.calculateExtent( - const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 100, ); expect( @@ -124,9 +113,7 @@ void main() { test('MinSpanExtent', () { const extent = MinSpanExtent(FixedSpanExtent(100), RemainingSpanExtent()); expect( - extent.calculateExtent( - const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const SpanExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 0, ); expect( diff --git a/packages/two_dimensional_scrollables/test/table_view/alignment_test.dart b/packages/two_dimensional_scrollables/test/table_view/alignment_test.dart index 2f87360f6278..b62fd6f324ee 100644 --- a/packages/two_dimensional_scrollables/test/table_view/alignment_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/alignment_test.dart @@ -23,16 +23,12 @@ void main() { child: TableView.builder( columnCount: 1, rowCount: 1, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -67,16 +63,12 @@ void main() { columnCount: 3, rowCount: 1, alignment: Alignment.topCenter, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -90,16 +82,10 @@ void main() { final Offset tableTopLeft = tester.getTopLeft(find.byType(TableView)); // Table is 300 wide, viewport is 600 wide. Centered means 150 offset. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(150.0, 0.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(150.0, 0.0)); final Finder cell20 = find.byKey(const ValueKey('cell 2:0')); - expect( - tester.getTopLeft(cell20) - tableTopLeft, - const Offset(350.0, 0.0), - ); + expect(tester.getTopLeft(cell20) - tableTopLeft, const Offset(350.0, 0.0)); }); testWidgets('Horizontal alignment - end', (WidgetTester tester) async { @@ -120,16 +106,12 @@ void main() { columnCount: 3, rowCount: 1, alignment: Alignment.topRight, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -143,10 +125,7 @@ void main() { final Offset tableTopLeft = tester.getTopLeft(find.byType(TableView)); // Table is 300 wide, viewport is 600 wide. End means 300 offset. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(300.0, 0.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(300.0, 0.0)); }); testWidgets('Vertical alignment - center', (WidgetTester tester) async { @@ -167,16 +146,12 @@ void main() { columnCount: 1, rowCount: 2, alignment: Alignment.centerLeft, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -190,16 +165,10 @@ void main() { final Offset tableTopLeft = tester.getTopLeft(find.byType(TableView)); // Table is 200 high, viewport is 600 high. Centered means 200 offset. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(0.0, 200.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(0.0, 200.0)); final Finder cell01 = find.byKey(const ValueKey('cell 0:1')); - expect( - tester.getTopLeft(cell01) - tableTopLeft, - const Offset(0.0, 300.0), - ); + expect(tester.getTopLeft(cell01) - tableTopLeft, const Offset(0.0, 300.0)); }); testWidgets('Combined alignment', (WidgetTester tester) async { @@ -218,16 +187,12 @@ void main() { columnCount: 1, rowCount: 1, alignment: Alignment.center, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -241,10 +206,7 @@ void main() { final Offset tableTopLeft = tester.getTopLeft(find.byType(TableView)); // Table is 100x100, viewport is 600x600. Centered means 250, 250 offset. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(250.0, 250.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(250.0, 250.0)); }); testWidgets('Alignment with pinned columns', (WidgetTester tester) async { @@ -264,16 +226,12 @@ void main() { rowCount: 1, pinnedColumnCount: 1, alignment: Alignment.topCenter, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -288,17 +246,11 @@ void main() { // Total width 300 (1 pinned, 2 unpinned). Viewport 600. Offset 150. // Pinned column 0 should be at 150. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(150.0, 0.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(150.0, 0.0)); // Unpinned column 1 should be at 250. final Finder cell10 = find.byKey(const ValueKey('cell 1:0')); - expect( - tester.getTopLeft(cell10) - tableTopLeft, - const Offset(250.0, 0.0), - ); + expect(tester.getTopLeft(cell10) - tableTopLeft, const Offset(250.0, 0.0)); }); testWidgets('Alignment with pinned rows', (WidgetTester tester) async { @@ -318,16 +270,12 @@ void main() { rowCount: 3, pinnedRowCount: 1, alignment: Alignment.centerLeft, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -342,22 +290,14 @@ void main() { // Total height 300 (1 pinned, 2 unpinned). Viewport 600. Offset 150. // Pinned row 0 should be at 150. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(0.0, 150.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(0.0, 150.0)); // Unpinned row 1 should be at 250. final Finder cell01 = find.byKey(const ValueKey('cell 0:1')); - expect( - tester.getTopLeft(cell01) - tableTopLeft, - const Offset(0.0, 250.0), - ); + expect(tester.getTopLeft(cell01) - tableTopLeft, const Offset(0.0, 250.0)); }); - testWidgets('Alignment with reversed horizontal axis', ( - WidgetTester tester, - ) async { + testWidgets('Alignment with reversed horizontal axis', (WidgetTester tester) async { await tester.pumpWidget( WidgetsApp( color: const Color(0xFFFFFFFF), @@ -373,19 +313,13 @@ void main() { columnCount: 1, rowCount: 1, alignment: Alignment.topCenter, - horizontalDetails: const ScrollableDetails.horizontal( - reverse: true, - ), - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -400,15 +334,10 @@ void main() { // Reversed horizontal. Start is on the right (600). // Center should still be at 250. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(250.0, 0.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(250.0, 0.0)); }); - testWidgets('Alignment with reversed vertical axis', ( - WidgetTester tester, - ) async { + testWidgets('Alignment with reversed vertical axis', (WidgetTester tester) async { await tester.pumpWidget( WidgetsApp( color: const Color(0xFFFFFFFF), @@ -424,19 +353,13 @@ void main() { columnCount: 1, rowCount: 1, alignment: Alignment.centerLeft, - verticalDetails: const ScrollableDetails.vertical( - reverse: true, - ), - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + verticalDetails: const ScrollableDetails.vertical(reverse: true), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -450,15 +373,10 @@ void main() { final Offset tableTopLeft = tester.getTopLeft(find.byType(TableView)); // Reversed vertical. Center should still be at 250. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(0.0, 250.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(0.0, 250.0)); }); - testWidgets('Alignment with both axes reversed', ( - WidgetTester tester, - ) async { + testWidgets('Alignment with both axes reversed', (WidgetTester tester) async { await tester.pumpWidget( WidgetsApp( color: const Color(0xFFFFFFFF), @@ -474,22 +392,14 @@ void main() { columnCount: 1, rowCount: 1, alignment: Alignment.center, - horizontalDetails: const ScrollableDetails.horizontal( - reverse: true, - ), - verticalDetails: const ScrollableDetails.vertical( - reverse: true, - ), - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + verticalDetails: const ScrollableDetails.vertical(reverse: true), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -503,10 +413,7 @@ void main() { final Offset tableTopLeft = tester.getTopLeft(find.byType(TableView)); // Both reversed. Center should still be at (250, 250). final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(250.0, 250.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(250.0, 250.0)); }); testWidgets('AlignmentDirectional with RTL', (WidgetTester tester) async { @@ -525,16 +432,12 @@ void main() { columnCount: 1, rowCount: 1, alignment: AlignmentDirectional.centerEnd, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -575,16 +478,12 @@ void main() { columnCount: 3, // 300 wide rowCount: 1, alignment: Alignment.center, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -599,15 +498,10 @@ void main() { // Table (300) > Viewport (200). Horizontal alignment should be ignored (start). // Viewport (400) > Table (100) Row. Vertical alignment should be center (150). final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(0.0, 150.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(0.0, 150.0)); }); - testWidgets('Alignment with trailing pinned columns', ( - WidgetTester tester, - ) async { + testWidgets('Alignment with trailing pinned columns', (WidgetTester tester) async { const viewportWidth = 600.0; await tester.pumpWidget( @@ -626,16 +520,12 @@ void main() { rowCount: 1, trailingPinnedColumnCount: 1, alignment: Alignment.topCenter, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -652,27 +542,16 @@ void main() { // If it sticks to table flow, it should be at 350. // If it sticks to viewport edge, it should be at 500. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(200.0, 0.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(200.0, 0.0)); final Finder cell10 = find.byKey(const ValueKey('cell 1:0')); - expect( - tester.getTopLeft(cell10) - tableTopLeft, - const Offset(300.0, 0.0), - ); + expect(tester.getTopLeft(cell10) - tableTopLeft, const Offset(300.0, 0.0)); final Finder cell20 = find.byKey(const ValueKey('cell 2:0')); - expect( - tester.getTopLeft(cell20) - tableTopLeft, - const Offset(500.0, 0.0), - ); + expect(tester.getTopLeft(cell20) - tableTopLeft, const Offset(500.0, 0.0)); }); - testWidgets('Alignment with trailing pinned rows', ( - WidgetTester tester, - ) async { + testWidgets('Alignment with trailing pinned rows', (WidgetTester tester) async { const viewportHeight = 600.0; await tester.pumpWidget( @@ -691,16 +570,12 @@ void main() { rowCount: 3, trailingPinnedRowCount: 1, alignment: Alignment.centerLeft, - columnBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (context, vicinity) { return TableViewCell( child: SizedBox( - key: ValueKey( - 'cell ${vicinity.column}:${vicinity.row}', - ), + key: ValueKey('cell ${vicinity.column}:${vicinity.row}'), ), ); }, @@ -716,22 +591,13 @@ void main() { // Rows 0 and 1 are unpinned. Row 2 is trailing pinned. // If it sticks to table flow, it should be at 350. final Finder cell00 = find.byKey(const ValueKey('cell 0:0')); - expect( - tester.getTopLeft(cell00) - tableTopLeft, - const Offset(0.0, 200.0), - ); + expect(tester.getTopLeft(cell00) - tableTopLeft, const Offset(0.0, 200.0)); final Finder cell01 = find.byKey(const ValueKey('cell 0:1')); - expect( - tester.getTopLeft(cell01) - tableTopLeft, - const Offset(0.0, 300.0), - ); + expect(tester.getTopLeft(cell01) - tableTopLeft, const Offset(0.0, 300.0)); final Finder cell02 = find.byKey(const ValueKey('cell 0:2')); - expect( - tester.getTopLeft(cell02) - tableTopLeft, - const Offset(0.0, 500.0), - ); + expect(tester.getTopLeft(cell02) - tableTopLeft, const Offset(0.0, 500.0)); }); }); } diff --git a/packages/two_dimensional_scrollables/test/table_view/pinned_extent_warning_test.dart b/packages/two_dimensional_scrollables/test/table_view/pinned_extent_warning_test.dart index af0d6625b6e8..799fa471f09b 100644 --- a/packages/two_dimensional_scrollables/test/table_view/pinned_extent_warning_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/pinned_extent_warning_test.dart @@ -9,9 +9,7 @@ import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart'; void main() { group('TableView pinned extent warnings', () { - testWidgets('Warns when pinned columns exceed viewport width', ( - WidgetTester tester, - ) async { + testWidgets('Warns when pinned columns exceed viewport width', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/136833 final log = []; final DebugPrintCallback oldDebugPrint = debugPrint; @@ -29,10 +27,8 @@ void main() { columnCount: 5, rowCount: 5, pinnedColumnCount: 3, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (BuildContext context, TableVicinity vicinity) => const TableViewCell(child: SizedBox.shrink()), ), @@ -55,9 +51,7 @@ void main() { debugPrint = oldDebugPrint; }); - testWidgets('Warns when pinned rows exceed viewport height', ( - WidgetTester tester, - ) async { + testWidgets('Warns when pinned rows exceed viewport height', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/136833 final log = []; final DebugPrintCallback oldDebugPrint = debugPrint; @@ -75,10 +69,8 @@ void main() { columnCount: 5, rowCount: 5, pinnedRowCount: 3, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (BuildContext context, TableVicinity vicinity) => const TableViewCell(child: SizedBox.shrink()), ), @@ -121,10 +113,8 @@ void main() { columnCount: 3, rowCount: 5, pinnedColumnCount: 2, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (BuildContext context, TableVicinity vicinity) => const TableViewCell(child: SizedBox.shrink()), ), @@ -147,95 +137,86 @@ void main() { }, ); - testWidgets( - 'Warns when pinned rows fully consume viewport height and there are unpinned rows', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/136833 - final log = []; - final DebugPrintCallback oldDebugPrint = debugPrint; - debugPrint = (String? message, {int? wrapWidth}) { - log.add(message!); - }; + testWidgets('Warns when pinned rows fully consume viewport height and there are unpinned rows', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/136833 + final log = []; + final DebugPrintCallback oldDebugPrint = debugPrint; + debugPrint = (String? message, {int? wrapWidth}) { + log.add(message!); + }; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: SizedBox( - width: 400, - height: 200, - child: TableView.builder( - columnCount: 5, - rowCount: 3, - pinnedRowCount: 2, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - cellBuilder: (BuildContext context, TableVicinity vicinity) => - const TableViewCell(child: SizedBox.shrink()), - ), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 400, + height: 200, + child: TableView.builder( + columnCount: 5, + rowCount: 3, + pinnedRowCount: 2, + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + cellBuilder: (BuildContext context, TableVicinity vicinity) => + const TableViewCell(child: SizedBox.shrink()), ), ), ), - ); + ), + ); - // Pinned rows extent = 200 (2 * 100), viewport height = 200. - // There is 1 unpinned row (rowCount: 3, pinnedRowCount: 2). - // Since the pinned rows take up the entire viewport height, the - // unpinned row will never be visible during scrolling. - expect( - log, - contains( - 'TableView has pinned rows that fully consume the viewport height. Unpinned rows will not be visible.', - ), - ); - debugPrint = oldDebugPrint; - }, - ); + // Pinned rows extent = 200 (2 * 100), viewport height = 200. + // There is 1 unpinned row (rowCount: 3, pinnedRowCount: 2). + // Since the pinned rows take up the entire viewport height, the + // unpinned row will never be visible during scrolling. + expect( + log, + contains( + 'TableView has pinned rows that fully consume the viewport height. Unpinned rows will not be visible.', + ), + ); + debugPrint = oldDebugPrint; + }); - testWidgets( - 'Does not warn when all columns are pinned even if they consume viewport', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/136833 - final log = []; - final DebugPrintCallback oldDebugPrint = debugPrint; - debugPrint = (String? message, {int? wrapWidth}) { - log.add(message!); - }; + testWidgets('Does not warn when all columns are pinned even if they consume viewport', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/136833 + final log = []; + final DebugPrintCallback oldDebugPrint = debugPrint; + debugPrint = (String? message, {int? wrapWidth}) { + log.add(message!); + }; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: SizedBox( - width: 200, - height: 400, - child: TableView.builder( - columnCount: 2, - rowCount: 5, - pinnedColumnCount: 2, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - cellBuilder: (BuildContext context, TableVicinity vicinity) => - const TableViewCell(child: SizedBox.shrink()), - ), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 200, + height: 400, + child: TableView.builder( + columnCount: 2, + rowCount: 5, + pinnedColumnCount: 2, + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + cellBuilder: (BuildContext context, TableVicinity vicinity) => + const TableViewCell(child: SizedBox.shrink()), ), ), ), - ); + ), + ); - // Pinned columns extent = 200 (2 * 100), viewport width = 200. - // Although the pinned columns fully consume the viewport width, - // ALL columns are pinned (columnCount: 2, pinnedColumnCount: 2). - // Since there are no unpinned columns, no warning is issued about - // unpinned columns being hidden. - expect( - log, - isNot(contains(contains('Unpinned columns will not be visible'))), - ); - debugPrint = oldDebugPrint; - }, - ); + // Pinned columns extent = 200 (2 * 100), viewport width = 200. + // Although the pinned columns fully consume the viewport width, + // ALL columns are pinned (columnCount: 2, pinnedColumnCount: 2). + // Since there are no unpinned columns, no warning is issued about + // unpinned columns being hidden. + expect(log, isNot(contains(contains('Unpinned columns will not be visible')))); + debugPrint = oldDebugPrint; + }); }); } diff --git a/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart index 8313dc5c48b0..e357271a62c2 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_cell_test.dart @@ -57,9 +57,7 @@ void main() { isA().having( (AssertionError error) => error.toString(), 'description', - contains( - 'Row merge start and span must both be set, or both unset.', - ), + contains('Row merge start and span must both be set, or both unset.'), ), ), ); @@ -71,19 +69,13 @@ void main() { isA().having( (AssertionError error) => error.toString(), 'description', - contains( - 'Row merge start and span must both be set, or both unset.', - ), + contains('Row merge start and span must both be set, or both unset.'), ), ), ); expect( () { - cell = TableViewCell( - rowMergeStart: -1, - rowMergeSpan: 2, - child: child, - ); + cell = TableViewCell(rowMergeStart: -1, rowMergeSpan: 2, child: child); }, throwsA( isA().having( @@ -95,11 +87,7 @@ void main() { ); expect( () { - cell = TableViewCell( - rowMergeStart: 0, - rowMergeSpan: 0, - child: child, - ); + cell = TableViewCell(rowMergeStart: 0, rowMergeSpan: 0, child: child); }, throwsA( isA().having( @@ -117,9 +105,7 @@ void main() { isA().having( (AssertionError error) => error.toString(), 'description', - contains( - 'Column merge start and span must both be set, or both unset.', - ), + contains('Column merge start and span must both be set, or both unset.'), ), ), ); @@ -131,19 +117,13 @@ void main() { isA().having( (AssertionError error) => error.toString(), 'description', - contains( - 'Column merge start and span must both be set, or both unset.', - ), + contains('Column merge start and span must both be set, or both unset.'), ), ), ); expect( () { - cell = TableViewCell( - columnMergeStart: -1, - columnMergeSpan: 2, - child: child, - ); + cell = TableViewCell(columnMergeStart: -1, columnMergeSpan: 2, child: child); }, throwsA( isA().having( @@ -155,11 +135,7 @@ void main() { ); expect( () { - cell = TableViewCell( - columnMergeStart: 0, - columnMergeSpan: 0, - child: child, - ); + cell = TableViewCell(columnMergeStart: 0, columnMergeSpan: 0, child: child); }, throwsA( isA().having( @@ -172,9 +148,7 @@ void main() { expect(cell, isNull); }); - testWidgets('Merge start cannot exceed current index', ( - WidgetTester tester, - ) async { + testWidgets('Merge start cannot exceed current index', (WidgetTester tester) async { // Merge span start is greater than given index, ex: column 10 has merge // start at 20. final exceptions = []; @@ -194,11 +168,7 @@ void main() { // | | // +---------+ // This cell should only be built for (0, 1) and (0, 2), not (0,0). - var cell = const TableViewCell( - rowMergeStart: 1, - rowMergeSpan: 2, - child: SizedBox.shrink(), - ); + var cell = const TableViewCell(rowMergeStart: 1, rowMergeSpan: 2, child: SizedBox.shrink()); await tester.pumpWidget( TableView.builder( cellBuilder: (_, __) => cell, @@ -210,10 +180,7 @@ void main() { ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); - expect( - exceptions.first.toString(), - contains('spanMergeStart <= currentSpan'), - ); + expect(exceptions.first.toString(), contains('spanMergeStart <= currentSpan')); await tester.pumpWidget(Container()); exceptions.clear(); @@ -242,15 +209,10 @@ void main() { ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); - expect( - exceptions.first.toString(), - contains('spanMergeStart <= currentSpan'), - ); + expect(exceptions.first.toString(), contains('spanMergeStart <= currentSpan')); }); - testWidgets('Merge cannot exceed table contents', ( - WidgetTester tester, - ) async { + testWidgets('Merge cannot exceed table contents', (WidgetTester tester) async { // Merge exceeds table content, ex: at column 10, cell spans 4 columns, // but table only has 12 columns. final exceptions = []; @@ -275,10 +237,7 @@ void main() { ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); - expect( - exceptions.first.toString(), - contains('spanMergeEnd < spanCount'), - ); + expect(exceptions.first.toString(), contains('spanMergeEnd < spanCount')); await tester.pumpWidget(Container()); exceptions.clear(); @@ -302,15 +261,10 @@ void main() { ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); - expect( - exceptions.first.toString(), - contains('spanMergeEnd < spanCount'), - ); + expect(exceptions.first.toString(), contains('spanMergeEnd < spanCount')); }); - testWidgets('Merge cannot contain pinned and unpinned cells', ( - WidgetTester tester, - ) async { + testWidgets('Merge cannot contain pinned and unpinned cells', (WidgetTester tester) async { // Merge spans pinned and unpinned cells, ex: column 0 is pinned, 0-2 // expected merge. final exceptions = []; @@ -319,11 +273,7 @@ void main() { exceptions.add(details.exception); }; // Row - var cell = const TableViewCell( - rowMergeStart: 0, - rowMergeSpan: 3, - child: SizedBox.shrink(), - ); + var cell = const TableViewCell(rowMergeStart: 0, rowMergeSpan: 3, child: SizedBox.shrink()); await tester.pumpWidget( TableView.builder( cellBuilder: (_, __) => cell, @@ -336,10 +286,7 @@ void main() { ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); - expect( - exceptions.first.toString(), - contains('spanMergeEnd < pinnedSpanCount'), - ); + expect(exceptions.first.toString(), contains('spanMergeEnd < pinnedSpanCount')); await tester.pumpWidget(Container()); exceptions.clear(); @@ -364,10 +311,7 @@ void main() { ); FlutterError.onError = oldHandler; expect(exceptions.length, 2); - expect( - exceptions.first.toString(), - contains('spanMergeEnd < pinnedSpanCount'), - ); + expect(exceptions.first.toString(), contains('spanMergeEnd < pinnedSpanCount')); }); }); @@ -415,8 +359,7 @@ void main() { }; TableViewCell cellBuilder(BuildContext context, TableVicinity vicinity) { - if (mergedColumns.keys.contains(vicinity) || - mergedRows.keys.contains(vicinity)) { + if (mergedColumns.keys.contains(vicinity) || mergedRows.keys.contains(vicinity)) { return TableViewCell( rowMergeStart: mergedRows[vicinity]?.$1, rowMergeSpan: mergedRows[vicinity]?.$2, @@ -433,9 +376,7 @@ void main() { ), ); } - return TableViewCell( - child: Text('M(${vicinity.row},${vicinity.column})'), - ); + return TableViewCell(child: Text('M(${vicinity.row},${vicinity.column})')); } setUp(() { @@ -449,19 +390,13 @@ void main() { horizontalController.dispose(); }); - testWidgets('vertical main axis and natural scroll directions', ( - WidgetTester tester, - ) async { + testWidgets('vertical main axis and natural scroll directions', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, @@ -474,32 +409,17 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); expect(tester.getTopLeft(find.text('M(0,0)')), Offset.zero); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); @@ -508,30 +428,21 @@ void main() { BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(100.0, 0.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 0.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(100.0, 100.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 100.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(0.0, 200.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 200.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -541,73 +452,44 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(-30.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, -25.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(70.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, -25.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(70.0, 75.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 75.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(-30.0, 175.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 175.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('vertical main axis, reversed vertical', ( - WidgetTester tester, - ) async { + testWidgets('vertical main axis, reversed vertical', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -616,9 +498,7 @@ void main() { controller: verticalController, reverse: true, ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, @@ -631,67 +511,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(0.0, 400.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(0.0, 400.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(100.0, 500.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 500.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(100.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 300.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(0.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 300.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -701,80 +554,49 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(-30.0, 425.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, 425.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(70.0, 525.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, 525.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(70.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 325.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(-30.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 325.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('vertical main axis, reversed horizontal', ( - WidgetTester tester, - ) async { + testWidgets('vertical main axis, reversed horizontal', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, @@ -791,67 +613,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(700.0, 0.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 0.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(500.0, 0.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 0.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(500.0, 100.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 100.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(700.0, 200.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 200.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -861,73 +656,44 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(730.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, -25.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(530.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, -25.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(530.0, 75.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 75.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(730.0, 175.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 175.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('vertical main axis, both axes reversed', ( - WidgetTester tester, - ) async { + testWidgets('vertical main axis, both axes reversed', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -952,67 +718,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(700.0, 400.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 400.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(500.0, 500.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 500.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(500.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 300.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(700.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 300.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -1022,67 +761,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(730.0, 425.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, 425.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(530.0, 525.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, 525.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(530.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 325.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(730.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 325.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); @@ -1094,12 +806,8 @@ void main() { textDirection: TextDirection.ltr, child: TableView.builder( mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, @@ -1112,32 +820,17 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); expect(tester.getTopLeft(find.text('M(0,0)')), Offset.zero); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); @@ -1146,30 +839,21 @@ void main() { BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(100.0, 0.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 0.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(100.0, 100.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 100.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(0.0, 200.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 200.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -1179,73 +863,44 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(-30.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, -25.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(70.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, -25.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(70.0, 75.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 75.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(-30.0, 175.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 175.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('horizontal main axis, reversed vertical', ( - WidgetTester tester, - ) async { + testWidgets('horizontal main axis, reversed vertical', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -1255,9 +910,7 @@ void main() { controller: verticalController, reverse: true, ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), cellBuilder: cellBuilder, columnBuilder: (_) => span, rowBuilder: (_) => span, @@ -1270,67 +923,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(0.0, 400.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(0.0, 400.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(100.0, 500.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(100.0, 500.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(100.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(100.0, 300.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(0.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(0.0, 300.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -1340,81 +966,50 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(-30.0, 425.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(-30.0, 425.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(70.0, 525.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(70.0, 525.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(70.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(70.0, 325.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(-30.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(-30.0, 325.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('horizontal main axis, reversed horizontal', ( - WidgetTester tester, - ) async { + testWidgets('horizontal main axis, reversed horizontal', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TableView.builder( mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, @@ -1431,67 +1026,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(700.0, 0.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 0.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(500.0, 0.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 0.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(500.0, 100.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 100.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(700.0, 200.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 200.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -1501,73 +1069,44 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(730.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, -25.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(530.0, -25.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, -25.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(530.0, 75.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 75.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(730.0, 175.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 175.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); - testWidgets('horizontal main axis, both axes reversed', ( - WidgetTester tester, - ) async { + testWidgets('horizontal main axis, both axes reversed', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -1593,67 +1132,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(700.0, 400.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(700.0, 400.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(500.0, 500.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(500.0, 500.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(500.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(500.0, 300.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(700.0, 300.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(700.0, 300.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); // Let's scroll a bit and check the layout @@ -1663,67 +1175,40 @@ void main() { expect(find.text('M(0,0)'), findsOneWidget); expect(find.text('M(0,1)'), findsOneWidget); expect(find.text('M(0,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 0, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 0, column: 2)], isNull); expect(find.text('M(1,0)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 0)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 0)], isNull); expect(find.text('M(1,1)'), findsOneWidget); expect(find.text('M(1,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 1, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 1, column: 2)], isNull); expect(find.text('M(2,0)'), findsOneWidget); expect(find.text('M(2,1)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 1)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 1)], isNull); expect(find.text('M(2,2)'), findsNothing); // Merged - expect( - layoutConstraints[const TableVicinity(row: 2, column: 2)], - isNull, - ); + expect(layoutConstraints[const TableVicinity(row: 2, column: 2)], isNull); - expect( - tester.getTopLeft(find.text('M(0,0)')), - const Offset(730.0, 425.0), - ); + expect(tester.getTopLeft(find.text('M(0,0)')), const Offset(730.0, 425.0)); expect(tester.getSize(find.text('M(0,0)')), const Size(100.0, 200.0)); expect( layoutConstraints[TableVicinity.zero], BoxConstraints.tight(const Size(100.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(0,1)')), - const Offset(530.0, 525.0), - ); + expect(tester.getTopLeft(find.text('M(0,1)')), const Offset(530.0, 525.0)); expect(tester.getSize(find.text('M(0,1)')), const Size(200.0, 100.0)); expect( layoutConstraints[const TableVicinity(row: 0, column: 1)], BoxConstraints.tight(const Size(200.0, 100.0)), ); - expect( - tester.getTopLeft(find.text('M(1,1)')), - const Offset(530.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(1,1)')), const Offset(530.0, 325.0)); expect(tester.getSize(find.text('M(1,1)')), const Size(200.0, 200.0)); expect( layoutConstraints[const TableVicinity(row: 1, column: 1)], BoxConstraints.tight(const Size(200.0, 200.0)), ); - expect( - tester.getTopLeft(find.text('M(2,0)')), - const Offset(730.0, 325.0), - ); + expect(tester.getTopLeft(find.text('M(2,0)')), const Offset(730.0, 325.0)); expect(tester.getSize(find.text('M(2,0)')), const Size(100.0, 100.0)); }); }); diff --git a/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart index e94918238df0..3bb419f712f5 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_delegate_test.dart @@ -118,9 +118,7 @@ void main() { isA().having( (AssertionError error) => error.toString(), 'description', - contains( - 'pinnedColumnCount + trailingPinnedColumnCount <= columnCount', - ), + contains('pinnedColumnCount + trailingPinnedColumnCount <= columnCount'), ), ), ); @@ -329,9 +327,7 @@ void main() { isA().having( (AssertionError error) => error.toString(), 'description', - contains( - 'Each list of Widgets within cells must be of the same length.', - ), + contains('Each list of Widgets within cells must be of the same length.'), ), ), ); @@ -386,8 +382,7 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(150)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), rowBuilder: spanBuilder, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -400,8 +395,7 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(150)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), rowBuilder: spanBuilder, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -414,10 +408,8 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: (int index) => - const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => const TableSpan(extent: RemainingTableSpanExtent()), ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -429,10 +421,8 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: (int index) => - const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => const TableSpan(extent: RemainingTableSpanExtent()), pinnedRowCount: 2, ); expect(delegate.shouldRebuild(oldDelegate), isTrue); @@ -445,10 +435,8 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: (int index) => - const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => const TableSpan(extent: RemainingTableSpanExtent()), pinnedColumnCount: 2, pinnedRowCount: 2, ); @@ -465,10 +453,8 @@ void main() { [cell, cell, cell], [cell, cell, cell], ], - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(150)), - rowBuilder: (int index) => - const TableSpan(extent: RemainingTableSpanExtent()), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(150)), + rowBuilder: (int index) => const TableSpan(extent: RemainingTableSpanExtent()), pinnedColumnCount: 2, pinnedRowCount: 2, ); diff --git a/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart index ad3a9b8dca44..e3a124a03274 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_span_test.dart @@ -18,10 +18,7 @@ void main() { ); expect( extent.calculateExtent( - const TableSpanExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TableSpanExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 150, ); @@ -50,10 +47,7 @@ void main() { ); expect( extent.calculateExtent( - const TableSpanExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TableSpanExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 500, ); @@ -82,10 +76,7 @@ void main() { ); expect( extent.calculateExtent( - const TableSpanExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TableSpanExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 900, ); @@ -107,20 +98,14 @@ void main() { ); expect( extent.calculateExtent( - const TableSpanExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TableSpanExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 1000, ); }); test('MaxTableSpanExtent', () { - const extent = MaxTableSpanExtent( - FixedTableSpanExtent(100), - RemainingTableSpanExtent(), - ); + const extent = MaxTableSpanExtent(FixedTableSpanExtent(100), RemainingTableSpanExtent()); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), @@ -129,20 +114,14 @@ void main() { ); expect( extent.calculateExtent( - const TableSpanExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TableSpanExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 900, ); }); test('MinTableSpanExtent', () { - const extent = MinTableSpanExtent( - FixedTableSpanExtent(100), - RemainingTableSpanExtent(), - ); + const extent = MinTableSpanExtent(FixedTableSpanExtent(100), RemainingTableSpanExtent()); expect( extent.calculateExtent( const TableSpanExtentDelegate(precedingExtent: 0, viewportExtent: 0), @@ -151,10 +130,7 @@ void main() { ); expect( extent.calculateExtent( - const TableSpanExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TableSpanExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 100, ); @@ -209,26 +185,17 @@ void main() { ); } - testWidgets('Vertical main axis, vertical reversed', ( - WidgetTester tester, - ) async { + testWidgets('Vertical main axis, vertical reversed', (WidgetTester tester) async { final table = TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController, reverse: true), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget( - Directionality(textDirection: TextDirection.ltr, child: table), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: table)); await tester.pumpAndSettle(); expect( @@ -255,10 +222,7 @@ void main() { rect: const Rect.fromLTRB(0.0, 100.0, 1000.0, 200.0), color: const Color(0xffbbdefb), ) - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 1000.0, 100.0), - color: const Color(0xffbbdefb), - ) + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 1000.0, 100.0), color: const Color(0xffbbdefb)) ..rect( rect: const Rect.fromLTRB(0.0, -100.0, 1000.0, 0.0), color: const Color(0xffbbdefb), @@ -315,13 +279,9 @@ void main() { ); }); - testWidgets('Vertical main axis, horizontal reversed', ( - WidgetTester tester, - ) async { + testWidgets('Vertical main axis, horizontal reversed', (WidgetTester tester) async { final table = TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, @@ -332,9 +292,7 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget( - Directionality(textDirection: TextDirection.ltr, child: table), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: table)); await tester.pumpAndSettle(); expect( @@ -406,14 +364,8 @@ void main() { rect: const Rect.fromLTRB(100.0, 0.0, 200.0, 900.0), color: const Color(0xffe1bee7), ) - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 900.0), - color: const Color(0xffe1bee7), - ) - ..rect( - rect: const Rect.fromLTRB(-100.0, 0.0, 0.0, 900.0), - color: const Color(0xffe1bee7), - ) + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 900.0), color: const Color(0xffe1bee7)) + ..rect(rect: const Rect.fromLTRB(-100.0, 0.0, 0.0, 900.0), color: const Color(0xffe1bee7)) ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, -100.0, 900.0), color: const Color(0xffe1bee7), @@ -421,14 +373,9 @@ void main() { ); }); - testWidgets('Vertical main axis, both reversed', ( - WidgetTester tester, - ) async { + testWidgets('Vertical main axis, both reversed', (WidgetTester tester) async { final table = TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController, reverse: true), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, @@ -439,9 +386,7 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget( - Directionality(textDirection: TextDirection.ltr, child: table), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: table)); await tester.pumpAndSettle(); expect( @@ -528,27 +473,18 @@ void main() { ); }); - testWidgets('Horizontal main axis, vertical reversed', ( - WidgetTester tester, - ) async { + testWidgets('Horizontal main axis, vertical reversed', (WidgetTester tester) async { final table = TableView.builder( mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController, reverse: true), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), rowCount: 10, columnCount: 10, rowBuilder: (_) => buildSpan(false), columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget( - Directionality(textDirection: TextDirection.ltr, child: table), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: table)); await tester.pumpAndSettle(); expect( @@ -616,10 +552,7 @@ void main() { rect: const Rect.fromLTRB(0.0, 100.0, 1000.0, 200.0), color: const Color(0xffbbdefb), ) - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 1000.0, 100.0), - color: const Color(0xffbbdefb), - ) + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 1000.0, 100.0), color: const Color(0xffbbdefb)) ..rect( rect: const Rect.fromLTRB(0.0, -100.0, 1000.0, 0.0), color: const Color(0xffbbdefb), @@ -635,14 +568,10 @@ void main() { ); }); - testWidgets('Horizontal main axis, horizontal reversed', ( - WidgetTester tester, - ) async { + testWidgets('Horizontal main axis, horizontal reversed', (WidgetTester tester) async { final table = TableView.builder( mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, @@ -653,9 +582,7 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget( - Directionality(textDirection: TextDirection.ltr, child: table), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: table)); await tester.pumpAndSettle(); expect( @@ -690,14 +617,8 @@ void main() { rect: const Rect.fromLTRB(100.0, 0.0, 200.0, 900.0), color: const Color(0xffe1bee7), ) - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 900.0), - color: const Color(0xffe1bee7), - ) - ..rect( - rect: const Rect.fromLTRB(-100.0, 0.0, 0.0, 900.0), - color: const Color(0xffe1bee7), - ) + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 900.0), color: const Color(0xffe1bee7)) + ..rect(rect: const Rect.fromLTRB(-100.0, 0.0, 0.0, 900.0), color: const Color(0xffe1bee7)) ..rect( rect: const Rect.fromLTRB(-200.0, 0.0, -100.0, 900.0), color: const Color(0xffe1bee7), @@ -742,15 +663,10 @@ void main() { ); }); - testWidgets('Horizontal main axis, both reversed', ( - WidgetTester tester, - ) async { + testWidgets('Horizontal main axis, both reversed', (WidgetTester tester) async { final table = TableView.builder( mainAxis: Axis.horizontal, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - reverse: true, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController, reverse: true), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, reverse: true, @@ -761,9 +677,7 @@ void main() { columnBuilder: (_) => buildSpan(true), cellBuilder: buildCell, ); - await tester.pumpWidget( - Directionality(textDirection: TextDirection.ltr, child: table), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: table)); await tester.pumpAndSettle(); expect( @@ -850,109 +764,87 @@ void main() { ); }); - testWidgets( - 'paints borders correctly when cross axis is reversed (TableView)', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/177117 - final tableView = TableView.builder( - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - rowCount: 1, - columnCount: 1, - columnBuilder: (int index) => const TableSpan( - extent: FixedTableSpanExtent(200.0), - foregroundDecoration: TableSpanDecoration( - border: TableSpanBorder( - leading: BorderSide(color: Colors.orange, width: 3), - ), - ), + testWidgets('paints borders correctly when cross axis is reversed (TableView)', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/177117 + final tableView = TableView.builder( + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + rowCount: 1, + columnCount: 1, + columnBuilder: (int index) => const TableSpan( + extent: FixedTableSpanExtent(200.0), + foregroundDecoration: TableSpanDecoration( + border: TableSpanBorder(leading: BorderSide(color: Colors.orange, width: 3)), ), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(200.0)), - cellBuilder: (_, TableVicinity vicinity) { - return TableViewCell( - child: Container( - height: 200, - width: 200, - color: Colors.grey.withValues(alpha: 0.5), - ), - ); - }, - ); + ), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), + cellBuilder: (_, TableVicinity vicinity) { + return TableViewCell( + child: Container(height: 200, width: 200, color: Colors.grey.withValues(alpha: 0.5)), + ); + }, + ); - tester.view.physicalSize = const Size(400, 400); - tester.view.devicePixelRatio = 1.0; - addTearDown(() { - tester.view.resetPhysicalSize(); - tester.view.resetDevicePixelRatio(); - }); + tester.view.physicalSize = const Size(400, 400); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); - await tester.pumpWidget(MaterialApp(home: Scaffold(body: tableView))); - await tester.pumpAndSettle(); + await tester.pumpWidget(MaterialApp(home: Scaffold(body: tableView))); + await tester.pumpAndSettle(); - expect( - find.byType(TableViewport), - paints..path( - includes: [ - const Offset(400.0, 0.0), - const Offset(400.0, 200.0), - ], - color: const Color(0xffff9800), - ), - ); - }, - ); + expect( + find.byType(TableViewport), + paints..path( + includes: [const Offset(400.0, 0.0), const Offset(400.0, 200.0)], + color: const Color(0xffff9800), + ), + ); + }); - testWidgets( - 'paints borders correctly when vertical scrolling is reversed (TableView)', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/177117 - final tableView = TableView.builder( - verticalDetails: const ScrollableDetails.vertical(reverse: true), - rowCount: 1, - columnCount: 1, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(200.0)), - rowBuilder: (int index) => const TableSpan( - extent: FixedTableSpanExtent(200.0), - foregroundDecoration: TableSpanDecoration( - border: TableSpanBorder( - leading: BorderSide(color: Colors.orange, width: 3), - ), - ), + testWidgets('paints borders correctly when vertical scrolling is reversed (TableView)', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/177117 + final tableView = TableView.builder( + verticalDetails: const ScrollableDetails.vertical(reverse: true), + rowCount: 1, + columnCount: 1, + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), + rowBuilder: (int index) => const TableSpan( + extent: FixedTableSpanExtent(200.0), + foregroundDecoration: TableSpanDecoration( + border: TableSpanBorder(leading: BorderSide(color: Colors.orange, width: 3)), ), - cellBuilder: (_, TableVicinity vicinity) { - return TableViewCell( - child: Container( - height: 200, - width: 200, - color: Colors.grey.withValues(alpha: 0.5), - ), - ); - }, - ); + ), + cellBuilder: (_, TableVicinity vicinity) { + return TableViewCell( + child: Container(height: 200, width: 200, color: Colors.grey.withValues(alpha: 0.5)), + ); + }, + ); - tester.view.physicalSize = const Size(400, 400); - tester.view.devicePixelRatio = 1.0; - addTearDown(() { - tester.view.resetPhysicalSize(); - tester.view.resetDevicePixelRatio(); - }); + tester.view.physicalSize = const Size(400, 400); + tester.view.devicePixelRatio = 1.0; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); - await tester.pumpWidget(MaterialApp(home: Scaffold(body: tableView))); - await tester.pumpAndSettle(); + await tester.pumpWidget(MaterialApp(home: Scaffold(body: tableView))); + await tester.pumpAndSettle(); - expect( - find.byType(TableViewport), - paints..path( - includes: [ - const Offset(0.0, 400.0), - const Offset(200.0, 400.0), - ], - color: const Color(0xffff9800), - ), - ); - }, - ); + expect( + find.byType(TableViewport), + paints..path( + includes: [const Offset(0.0, 400.0), const Offset(200.0, 400.0)], + color: const Color(0xffff9800), + ), + ); + }); testWidgets( 'TableView row decoration rect is correct when vertical axis is reversed and padding is used', @@ -962,17 +854,14 @@ void main() { verticalDetails: const ScrollableDetails.vertical(reverse: true), rowCount: 1, columnCount: 1, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(200.0)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), rowBuilder: (int index) => const TableSpan( extent: FixedTableSpanExtent(200.0), padding: TableSpanPadding(leading: 10.0, trailing: 20.0), backgroundDecoration: TableSpanDecoration(color: Colors.red), ), cellBuilder: (_, TableVicinity vicinity) { - return TableViewCell( - child: Container(width: 200, height: 200, color: Colors.blue), - ); + return TableViewCell(child: Container(width: 200, height: 200, color: Colors.blue)); }, ); @@ -992,10 +881,7 @@ void main() { // Content covers from y=190 to y=390. expect( find.byType(TableViewport), - paints..rect( - rect: const Rect.fromLTRB(0.0, 170.0, 200.0, 400.0), - color: Colors.red, - ), + paints..rect(rect: const Rect.fromLTRB(0.0, 170.0, 200.0, 400.0), color: Colors.red), ); }, ); @@ -1037,15 +923,10 @@ void main() { const TableVicinity(row: 3, column: 2): (2, 2), }; - TableView buildScenario1({ - bool reverseVertical = false, - bool reverseHorizontal = false, - }) { + TableView buildScenario1({bool reverseVertical = false, bool reverseHorizontal = false}) { return TableView.builder( verticalDetails: ScrollableDetails.vertical(reverse: reverseVertical), - horizontalDetails: ScrollableDetails.horizontal( - reverse: reverseHorizontal, - ), + horizontalDetails: ScrollableDetails.horizontal(reverse: reverseHorizontal), columnCount: 3, rowCount: 4, cellBuilder: (_, TableVicinity vicinity) { @@ -1068,9 +949,7 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: color == null - ? null - : TableSpanDecoration(color: color), + backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, ); @@ -1099,15 +978,10 @@ void main() { const TableVicinity(row: 2, column: 3): (2, 2), }; - TableView buildScenario2({ - bool reverseVertical = false, - bool reverseHorizontal = false, - }) { + TableView buildScenario2({bool reverseVertical = false, bool reverseHorizontal = false}) { return TableView.builder( verticalDetails: ScrollableDetails.vertical(reverse: reverseVertical), - horizontalDetails: ScrollableDetails.horizontal( - reverse: reverseHorizontal, - ), + horizontalDetails: ScrollableDetails.horizontal(reverse: reverseHorizontal), columnCount: 4, rowCount: 3, cellBuilder: (_, TableVicinity vicinity) { @@ -1130,9 +1004,7 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: color == null - ? null - : TableSpanDecoration(color: color), + backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, ); @@ -1184,9 +1056,7 @@ void main() { return TableView.builder( mainAxis: mainAxis, verticalDetails: ScrollableDetails.vertical(reverse: reverseVertical), - horizontalDetails: ScrollableDetails.horizontal( - reverse: reverseHorizontal, - ), + horizontalDetails: ScrollableDetails.horizontal(reverse: reverseHorizontal), columnCount: 4, rowCount: 3, cellBuilder: (_, TableVicinity vicinity) { @@ -1206,9 +1076,7 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: color == null - ? null - : TableSpanDecoration(color: color), + backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, columnBuilder: (int index) { @@ -1220,17 +1088,13 @@ void main() { } return TableSpan( extent: const FixedTableSpanExtent(100.0), - backgroundDecoration: color == null - ? null - : TableSpanDecoration(color: color), + backgroundDecoration: color == null ? null : TableSpanDecoration(color: color), ); }, ); } - testWidgets('Vertical main axis, natural scroll directions', ( - WidgetTester tester, - ) async { + testWidgets('Vertical main axis, natural scroll directions', (WidgetTester tester) async { // Scenario 1 await tester.pumpWidget(buildScenario1()); expect( @@ -1312,9 +1176,7 @@ void main() { ); }); - testWidgets('Vertical main axis, vertical reversed', ( - WidgetTester tester, - ) async { + testWidgets('Vertical main axis, vertical reversed', (WidgetTester tester) async { // Scenario 1 await tester.pumpWidget(buildScenario1(reverseVertical: true)); expect( @@ -1390,20 +1252,13 @@ void main() { color: const Color(0xff4caf50), ) ..rect( - rect: const Rect.fromLTRB( - 300.0, - 500.0, - 400.0, - 600.0, - ), // Last column + rect: const Rect.fromLTRB(300.0, 500.0, 400.0, 600.0), // Last column color: const Color(0xff4caf50), ), ); }); - testWidgets('Vertical main axis, horizontal reversed', ( - WidgetTester tester, - ) async { + testWidgets('Vertical main axis, horizontal reversed', (WidgetTester tester) async { // Scenario 1 await tester.pumpWidget(buildScenario1(reverseHorizontal: true)); expect( @@ -1485,13 +1340,9 @@ void main() { ); }); - testWidgets('Vertical main axis, both reversed', ( - WidgetTester tester, - ) async { + testWidgets('Vertical main axis, both reversed', (WidgetTester tester) async { // Scenario 1 - await tester.pumpWidget( - buildScenario1(reverseHorizontal: true, reverseVertical: true), - ); + await tester.pumpWidget(buildScenario1(reverseHorizontal: true, reverseVertical: true)); expect( find.byType(TableViewport), paints @@ -1513,9 +1364,7 @@ void main() { ); // Scenario 2 - await tester.pumpWidget( - buildScenario2(reverseHorizontal: true, reverseVertical: true), - ); + await tester.pumpWidget(buildScenario2(reverseHorizontal: true, reverseVertical: true)); expect( find.byType(TableViewport), paints @@ -1542,9 +1391,7 @@ void main() { ); // Scenario 3 - await tester.pumpWidget( - buildScenario3(reverseHorizontal: true, reverseVertical: true), - ); + await tester.pumpWidget(buildScenario3(reverseHorizontal: true, reverseVertical: true)); expect( find.byType(TableViewport), paints @@ -1576,9 +1423,7 @@ void main() { ); }); - testWidgets('Horizontal main axis, natural scroll directions', ( - WidgetTester tester, - ) async { + testWidgets('Horizontal main axis, natural scroll directions', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. @@ -1614,16 +1459,12 @@ void main() { ); }); - testWidgets('Horizontal main axis, vertical reversed', ( - WidgetTester tester, - ) async { + testWidgets('Horizontal main axis, vertical reversed', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 - await tester.pumpWidget( - buildScenario3(reverseVertical: true, mainAxis: Axis.horizontal), - ); + await tester.pumpWidget(buildScenario3(reverseVertical: true, mainAxis: Axis.horizontal)); expect( find.byType(TableViewport), paints @@ -1655,16 +1496,12 @@ void main() { ); }); - testWidgets('Horizontal main axis, horizontal reversed', ( - WidgetTester tester, - ) async { + testWidgets('Horizontal main axis, horizontal reversed', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 - await tester.pumpWidget( - buildScenario3(reverseHorizontal: true, mainAxis: Axis.horizontal), - ); + await tester.pumpWidget(buildScenario3(reverseHorizontal: true, mainAxis: Axis.horizontal)); expect( find.byType(TableViewport), paints @@ -1695,19 +1532,13 @@ void main() { ); }); - testWidgets('Horizontal main axis, both reversed', ( - WidgetTester tester, - ) async { + testWidgets('Horizontal main axis, both reversed', (WidgetTester tester) async { // Scenarios 1 & 2 do not mix column and row decorations, so main axis // does not affect them. // Scenario 3 await tester.pumpWidget( - buildScenario3( - reverseHorizontal: true, - reverseVertical: true, - mainAxis: Axis.horizontal, - ), + buildScenario3(reverseHorizontal: true, reverseVertical: true, mainAxis: Axis.horizontal), ); expect( find.byType(TableViewport), @@ -1723,12 +1554,7 @@ void main() { color: const Color(0xff4caf50), ) ..rect( - rect: const Rect.fromLTRB( - 400.0, - 500.0, - 500.0, - 600.0, - ), // Last column + rect: const Rect.fromLTRB(400.0, 500.0, 500.0, 600.0), // Last column color: const Color(0xff4caf50), ) // Row decorations @@ -1745,9 +1571,7 @@ void main() { }); }); - testWidgets('merged cells account for row/column padding', ( - WidgetTester tester, - ) async { + testWidgets('merged cells account for row/column padding', (WidgetTester tester) async { // Leading padding on the leading cell, and trailing padding on the // trailing cell should be excluded. Interim leading/trailing // paddings are consumed by the merged cell. @@ -1766,14 +1590,9 @@ void main() { rowCount: 2, columnCount: 1, cellBuilder: (_, __) { - return const TableViewCell( - rowMergeStart: 0, - rowMergeSpan: 2, - child: Text('M(0,0)'), - ); + return const TableViewCell(rowMergeStart: 0, rowMergeSpan: 2, child: Text('M(0,0)')); }, - columnBuilder: (_) => - const TableSpan(extent: FixedTableSpanExtent(100.0)), + columnBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100.0)), rowBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), @@ -1801,8 +1620,7 @@ void main() { child: Text('M(0,0)'), ); }, - rowBuilder: (_) => - const TableSpan(extent: FixedTableSpanExtent(100.0)), + rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100.0)), columnBuilder: (_) { return const TableSpan( extent: FixedTableSpanExtent(100.0), diff --git a/packages/two_dimensional_scrollables/test/table_view/table_test.dart b/packages/two_dimensional_scrollables/test/table_view/table_test.dart index a89029c843b4..63b8189b6aaf 100644 --- a/packages/two_dimensional_scrollables/test/table_view/table_test.dart +++ b/packages/two_dimensional_scrollables/test/table_view/table_test.dart @@ -17,11 +17,10 @@ TableSpan getTappableSpan(int index, VoidCallback callback) { return TableSpan( extent: const FixedTableSpanExtent(100), recognizerFactories: { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () => callback(), - ), + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () => callback(), + ), }, ); } @@ -201,12 +200,8 @@ void main() { int pinnedRowCount = 0, }) { return TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), columnCount: columnCount, pinnedColumnCount: pinnedColumnCount, columnBuilder: columnBuilder ?? (_) => largeSpan, @@ -216,30 +211,21 @@ void main() { cellBuilder: cellBuilder ?? (_, TableVicinity vicinity) { - return TableViewCell( - child: Text('R${vicinity.row}:C${vicinity.column}'), - ); + return TableViewCell(child: Text('R${vicinity.row}:C${vicinity.column}')); }, ); } - testWidgets('infinite rows, columns are finite', ( - WidgetTester tester, - ) async { + testWidgets('infinite rows, columns are finite', (WidgetTester tester) async { // Nothing pinned --- - await tester.pumpWidget( - MaterialApp(home: getTableView(columnCount: 10)), - ); + await tester.pumpWidget(MaterialApp(home: getTableView(columnCount: 10))); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -255,10 +241,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C4'), findsOneWidget); expect( tester.getRect(find.text('R9:C4')), @@ -272,9 +255,7 @@ void main() { // Pinned columns --- await tester.pumpWidget( - MaterialApp( - home: getTableView(columnCount: 10, pinnedColumnCount: 1), - ), + MaterialApp(home: getTableView(columnCount: 10, pinnedColumnCount: 1)), ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); @@ -282,10 +263,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -301,10 +279,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C4'), findsOneWidget); expect( tester.getRect(find.text('R9:C4')), @@ -326,10 +301,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -345,10 +317,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C4'), findsOneWidget); expect( tester.getRect(find.text('R9:C4')), @@ -364,13 +333,7 @@ void main() { // Pinned columns and rows --- await tester.pumpWidget( - MaterialApp( - home: getTableView( - columnCount: 10, - pinnedColumnCount: 1, - pinnedRowCount: 1, - ), - ), + MaterialApp(home: getTableView(columnCount: 10, pinnedColumnCount: 1, pinnedRowCount: 1)), ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); @@ -378,10 +341,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -397,10 +357,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C4'), findsOneWidget); expect( tester.getRect(find.text('R9:C4')), @@ -413,9 +370,7 @@ void main() { expect(find.text('R10:C0'), findsNothing); }); - testWidgets('infinite columns, rows are finite', ( - WidgetTester tester, - ) async { + testWidgets('infinite columns, rows are finite', (WidgetTester tester) async { // Nothing pinned --- await tester.pumpWidget(MaterialApp(home: getTableView(rowCount: 10))); await tester.pumpAndSettle(); @@ -424,10 +379,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -444,10 +396,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C11'), findsOneWidget); expect( tester.getRect(find.text('R4:C11')), @@ -471,10 +420,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -491,10 +437,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C11'), findsOneWidget); expect( tester.getRect(find.text('R4:C11')), @@ -509,19 +452,14 @@ void main() { await tester.pumpWidget(Container()); // Pinned rows --- - await tester.pumpWidget( - MaterialApp(home: getTableView(rowCount: 10, pinnedRowCount: 1)), - ); + await tester.pumpWidget(MaterialApp(home: getTableView(rowCount: 10, pinnedRowCount: 1))); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -538,10 +476,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C11'), findsOneWidget); expect( tester.getRect(find.text('R4:C11')), @@ -557,13 +492,7 @@ void main() { // Pinned columns and rows --- await tester.pumpWidget( - MaterialApp( - home: getTableView( - rowCount: 10, - pinnedRowCount: 1, - pinnedColumnCount: 1, - ), - ), + MaterialApp(home: getTableView(rowCount: 10, pinnedRowCount: 1, pinnedColumnCount: 1)), ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); @@ -571,10 +500,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -591,10 +517,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C11'), findsOneWidget); expect( tester.getRect(find.text('R4:C11')), @@ -616,10 +539,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -638,10 +558,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C11'), findsOneWidget); expect( tester.getRect(find.text('R9:C11')), @@ -663,19 +580,14 @@ void main() { await tester.pumpWidget(Container()); // Pinned columns --- - await tester.pumpWidget( - MaterialApp(home: getTableView(pinnedColumnCount: 1)), - ); + await tester.pumpWidget(MaterialApp(home: getTableView(pinnedColumnCount: 1))); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -694,10 +606,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C11'), findsOneWidget); expect( tester.getRect(find.text('R9:C11')), @@ -721,19 +630,14 @@ void main() { await tester.pumpWidget(Container()); // Pinned Rows --- - await tester.pumpWidget( - MaterialApp(home: getTableView(pinnedRowCount: 1)), - ); + await tester.pumpWidget(MaterialApp(home: getTableView(pinnedRowCount: 1))); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -752,10 +656,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C11'), findsOneWidget); expect( tester.getRect(find.text('R9:C11')), @@ -780,9 +681,7 @@ void main() { // Pinned columns and rows --- await tester.pumpWidget( - MaterialApp( - home: getTableView(pinnedRowCount: 1, pinnedColumnCount: 1), - ), + MaterialApp(home: getTableView(pinnedRowCount: 1, pinnedColumnCount: 1)), ); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 0.0); @@ -790,10 +689,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -812,10 +708,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R9:C11'), findsOneWidget); expect( tester.getRect(find.text('R9:C11')), @@ -833,9 +726,7 @@ void main() { expect(find.text('R10:C6'), findsNothing); }); - testWidgets('infinite rows can null terminate', ( - WidgetTester tester, - ) async { + testWidgets('infinite rows can null terminate', (WidgetTester tester) async { // Nothing pinned --- var calledOutOfBounds = false; await tester.pumpWidget( @@ -861,10 +752,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -887,10 +775,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C4'), findsOneWidget); expect( tester.getRect(find.text('R7:C4')), @@ -924,10 +809,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -948,10 +830,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C4'), findsOneWidget); expect( tester.getRect(find.text('R7:C4')), @@ -985,10 +864,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -1009,10 +885,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C4'), findsOneWidget); expect( tester.getRect(find.text('R7:C4')), @@ -1049,10 +922,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -1073,10 +943,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C4'), findsOneWidget); expect( tester.getRect(find.text('R7:C4')), @@ -1089,9 +956,7 @@ void main() { expect(find.text('R8:C0'), findsNothing); }); - testWidgets('Null terminated rows will update', ( - WidgetTester tester, - ) async { + testWidgets('Null terminated rows will update', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: getTableView( @@ -1120,10 +985,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C4'), findsOneWidget); expect( tester.getRect(find.text('R7:C4')), @@ -1159,10 +1021,7 @@ void main() { expect(horizontalController.position.maxScrollExtent, 1200.0); // The layout should not have changed. expect(find.text('R5:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C4'), findsOneWidget); expect( tester.getRect(find.text('R7:C4')), @@ -1208,10 +1067,7 @@ void main() { expect(horizontalController.position.maxScrollExtent, 1200.0); // The layout updated. expect(find.text('R2:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -1221,9 +1077,7 @@ void main() { expect(find.text('R5:C0'), findsNothing); }); - testWidgets('Null terminated columns will update', ( - WidgetTester tester, - ) async { + testWidgets('Null terminated columns will update', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: getTableView( @@ -1252,10 +1106,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, 800.0); expect(find.text('R0:C5'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C5')), - const Rect.fromLTRB(200.0, 0.0, 400.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C5')), const Rect.fromLTRB(200.0, 0.0, 400.0, 200.0)); expect(find.text('R4:C7'), findsOneWidget); expect( tester.getRect(find.text('R4:C7')), @@ -1298,10 +1149,7 @@ void main() { expect(horizontalController.position.maxScrollExtent, double.infinity); // The layout should not have changed. expect(find.text('R0:C5'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C5')), - const Rect.fromLTRB(200.0, 0.0, 400.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C5')), const Rect.fromLTRB(200.0, 0.0, 400.0, 200.0)); expect(find.text('R4:C7'), findsOneWidget); expect( tester.getRect(find.text('R4:C7')), @@ -1353,10 +1201,7 @@ void main() { expect(horizontalController.position.maxScrollExtent, 200.0); // The layout updated. expect(find.text('R0:C2'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTRB(200.0, 0.0, 400.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTRB(200.0, 0.0, 400.0, 200.0)); expect(find.text('R4:C4'), findsOneWidget); expect( tester.getRect(find.text('R4:C4')), @@ -1366,9 +1211,7 @@ void main() { expect(find.text('R0:C5'), findsNothing); }); - testWidgets('infinite columns can null terminate', ( - WidgetTester tester, - ) async { + testWidgets('infinite columns can null terminate', (WidgetTester tester) async { // Nothing pinned --- var calledOutOfBounds = false; await tester.pumpWidget( @@ -1394,10 +1237,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.00); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1420,10 +1260,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C9'), findsOneWidget); expect( tester.getRect(find.text('R4:C9')), @@ -1464,10 +1301,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.00); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1488,10 +1322,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C9'), findsOneWidget); expect( tester.getRect(find.text('R4:C9')), @@ -1527,10 +1358,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.00); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1551,10 +1379,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C9'), findsOneWidget); expect( tester.getRect(find.text('R4:C9')), @@ -1596,10 +1421,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.00); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1620,10 +1442,7 @@ void main() { expect(verticalController.position.maxScrollExtent, 1400.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R0:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C9'), findsOneWidget); expect( tester.getRect(find.text('R4:C9')), @@ -1635,9 +1454,7 @@ void main() { expect(find.text('R0:C4'), findsNothing); expect(find.text('R0:C10'), findsNothing); }); - testWidgets('infinite rows & columns can null terminate', ( - WidgetTester tester, - ) async { + testWidgets('infinite rows & columns can null terminate', (WidgetTester tester) async { // Nothing pinned --- var calledRowOutOfBounds = false; var calledColumnOutOfBounds = false; @@ -1673,10 +1490,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1704,15 +1518,9 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C9'), findsOneWidget); - expect( - tester.getRect(find.text('R7:C9')), - const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), - ); + expect(tester.getRect(find.text('R7:C9')), const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0)); // No Columns laid out before/after cache extent. expect(find.text('R3:C0'), findsNothing); expect(find.text('R7:C3'), findsNothing); @@ -1756,10 +1564,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1784,15 +1589,9 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C9'), findsOneWidget); - expect( - tester.getRect(find.text('R7:C9')), - const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), - ); + expect(tester.getRect(find.text('R7:C9')), const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0)); // No Columns laid out before/after cache extent. expect(find.text('R3:C1'), findsNothing); expect(find.text('R3:C2'), findsNothing); @@ -1836,10 +1635,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1864,15 +1660,9 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C9'), findsOneWidget); - expect( - tester.getRect(find.text('R7:C9')), - const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), - ); + expect(tester.getRect(find.text('R7:C9')), const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0)); // First pinned row. expect(find.text('R0:C6'), findsOneWidget); // No Columns laid out before/after cache extent. @@ -1919,10 +1709,7 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R4:C5'), findsOneWidget); expect( tester.getRect(find.text('R4:C5')), @@ -1947,15 +1734,9 @@ void main() { expect(verticalController.position.maxScrollExtent, 1000.0); expect(horizontalController.position.maxScrollExtent, 1200.0); expect(find.text('R5:C6'), findsOneWidget); - expect( - tester.getRect(find.text('R5:C6')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - ); + expect(tester.getRect(find.text('R5:C6')), const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0)); expect(find.text('R7:C9'), findsOneWidget); - expect( - tester.getRect(find.text('R7:C9')), - const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0), - ); + expect(tester.getRect(find.text('R7:C9')), const Rect.fromLTRB(600.0, 400.0, 800.0, 600.0)); // No columns laid out before column 5, or after column 9, except for //the first pinned column. expect(find.text('R5:C0'), findsOneWidget); @@ -1967,9 +1748,7 @@ void main() { expect(find.text('R3:C6'), findsNothing); expect(find.text('R8:C6'), findsNothing); }); - testWidgets('merged cells work with lazy layout computation', ( - WidgetTester tester, - ) async { + testWidgets('merged cells work with lazy layout computation', (WidgetTester tester) async { // When columns and rows are finite, the layout is eagerly computed and // the children are lazily laid out. This makes computing merged cell // layouts easy. In an infinite world, the layout is also lazily @@ -1993,17 +1772,14 @@ void main() { ); } // Merged column - if (mergedColumns.contains(vicinity.column) && - vicinity.row == 0) { + if (mergedColumns.contains(vicinity.column) && vicinity.row == 0) { return TableViewCell( columnMergeStart: columnConfig.start, columnMergeSpan: columnConfig.span, child: const Text('R0:C1'), ); } - return TableViewCell( - child: Text('R${vicinity.row}:C${vicinity.column}'), - ); + return TableViewCell(child: Text('R${vicinity.row}:C${vicinity.column}')); }, ), ), @@ -2014,25 +1790,14 @@ void main() { expect(verticalController.position.maxScrollExtent, double.infinity); expect(horizontalController.position.maxScrollExtent, double.infinity); expect(find.text('R0:C0'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTRB(0.0, 0.0, 200.0, 2000.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTRB(0.0, 0.0, 200.0, 2000.0)); expect(find.text('R0:C1'), findsOneWidget); - expect( - tester.getRect(find.text('R0:C1')), - const Rect.fromLTRB(200.0, 0.0, 2200.0, 200.0), - ); + expect(tester.getRect(find.text('R0:C1')), const Rect.fromLTRB(200.0, 0.0, 2200.0, 200.0)); expect(find.text('R1:C1'), findsOneWidget); - expect( - tester.getRect(find.text('R1:C1')), - const Rect.fromLTRB(200.0, 200.0, 400.0, 400.0), - ); + expect(tester.getRect(find.text('R1:C1')), const Rect.fromLTRB(200.0, 200.0, 400.0, 400.0)); }); - testWidgets('merged column that exceeds metrics will assert', ( - WidgetTester tester, - ) async { + testWidgets('merged column that exceeds metrics will assert', (WidgetTester tester) async { final exceptions = []; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { @@ -2052,17 +1817,14 @@ void main() { }, cellBuilder: (_, TableVicinity vicinity) { // Merged column - if (mergedColumns.contains(vicinity.column) && - vicinity.row == 0) { + if (mergedColumns.contains(vicinity.column) && vicinity.row == 0) { return TableViewCell( columnMergeStart: columnConfig.start, columnMergeSpan: columnConfig.span, child: const Text('R0:C1'), ); } - return TableViewCell( - child: Text('R${vicinity.row}:C${vicinity.column}'), - ); + return TableViewCell(child: Text('R${vicinity.row}:C${vicinity.column}')); }, ), ), @@ -2081,9 +1843,7 @@ void main() { ); }); - testWidgets('merged row that exceeds metrics will assert', ( - WidgetTester tester, - ) async { + testWidgets('merged row that exceeds metrics will assert', (WidgetTester tester) async { final exceptions = []; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { @@ -2110,9 +1870,7 @@ void main() { child: const Text('R0:C0'), ); } - return TableViewCell( - child: Text('R${vicinity.row}:C${vicinity.column}'), - ); + return TableViewCell(child: Text('R${vicinity.row}:C${vicinity.column}')); }, ), ), @@ -2227,9 +1985,7 @@ void main() { }); group('RenderTableViewport', () { - testWidgets('parent data and table vicinities', ( - WidgetTester tester, - ) async { + testWidgets('parent data and table vicinities', (WidgetTester tester) async { final childKeys = {}; const span = TableSpan(extent: FixedTableSpanExtent(200)); final tableView = TableView.builder( @@ -2239,9 +1995,7 @@ void main() { rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); - return TableViewCell( - child: SizedBox.square(key: childKeys[vicinity], dimension: 200), - ); + return TableViewCell(child: SizedBox.square(key: childKeys[vicinity], dimension: 200)); }, ); TableViewParentData parentDataOf(RenderBox child) { @@ -2250,10 +2004,7 @@ void main() { await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); - final RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKeys.values.first, - ); + final RenderTwoDimensionalViewport viewport = getViewport(tester, childKeys.values.first); expect(viewport.mainAxis, Axis.vertical); // first child TableVicinity vicinity = TableVicinity.zero; @@ -2304,9 +2055,7 @@ void main() { rowBuilder: (_) => rowSpan, cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); - return TableViewCell( - child: SizedBox.square(key: childKeys[vicinity], dimension: 200), - ); + return TableViewCell(child: SizedBox.square(key: childKeys[vicinity], dimension: 200)); }, ); TableViewParentData parentDataOf(RenderBox child) { @@ -2315,10 +2064,7 @@ void main() { await tester.pumpWidget(MaterialApp(home: tableView)); await tester.pumpAndSettle(); - RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKeys.values.first, - ); + RenderTwoDimensionalViewport viewport = getViewport(tester, childKeys.values.first); // first child TableVicinity vicinity = TableVicinity.zero; TableViewParentData parentData = parentDataOf(viewport.firstChild!); @@ -2365,9 +2111,7 @@ void main() { rowBuilder: (_) => rowSpan, cellBuilder: (_, TableVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); - return TableViewCell( - child: SizedBox.square(key: childKeys[vicinity], dimension: 200), - ); + return TableViewCell(child: SizedBox.square(key: childKeys[vicinity], dimension: 200)); }, ); @@ -2401,8 +2145,7 @@ void main() { rowCount: 50, columnCount: 50, columnBuilder: (_) => span, - rowBuilder: (int index) => - index.isEven ? getTappableSpan(index, () => tapCounter++) : span, + rowBuilder: (int index) => index.isEven ? getTappableSpan(index, () => tapCounter++) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -2487,9 +2230,8 @@ void main() { columnCount: 50, rowBuilder: (int index) => index.isEven ? getTappableSpan(index, () => rowTapCounter++) : span, - columnBuilder: (int index) => index.isEven - ? getTappableSpan(index, () => columnTapCounter++) - : span, + columnBuilder: (int index) => + index.isEven ? getTappableSpan(index, () => columnTapCounter++) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -2539,9 +2281,8 @@ void main() { columnCount: 50, rowBuilder: (int index) => index.isEven ? getTappableSpan(index, () => rowTapCounter++) : span, - columnBuilder: (int index) => index.isEven - ? getTappableSpan(index, () => columnTapCounter++) - : span, + columnBuilder: (int index) => + index.isEven ? getTappableSpan(index, () => columnTapCounter++) : span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( child: SizedBox.square( @@ -2566,9 +2307,7 @@ void main() { expect(rowTapCounter, 0); }); - testWidgets('provides correct details in TableSpanExtentDelegate', ( - WidgetTester tester, - ) async { + testWidgets('provides correct details in TableSpanExtentDelegate', (WidgetTester tester) async { final columnExtent = TestTableSpanExtent(); final rowExtent = TestTableSpanExtent(); final verticalController = ScrollController(); @@ -2581,12 +2320,8 @@ void main() { cellBuilder: (_, TableVicinity vicinity) { return const TableViewCell(child: SizedBox.square(dimension: 100)); }, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ); await tester.pumpWidget(MaterialApp(home: tableView)); @@ -2620,9 +2355,7 @@ void main() { expect(rowExtent.delegate.viewportExtent, 600.0); }); - testWidgets('First row/column layout based on padding', ( - WidgetTester tester, - ) async { + testWidgets('First row/column layout based on padding', (WidgetTester tester) async { // Huge padding, first span layout // Column-wise var tableView = TableView.builder( @@ -2691,16 +2424,13 @@ void main() { expect(find.text('Row: 2 Column: 1'), findsNothing); }); - testWidgets('lazy layout accounts for gradually accrued padding', ( - WidgetTester tester, - ) async { + testWidgets('lazy layout accounts for gradually accrued padding', (WidgetTester tester) async { // Check with gradually accrued paddings // Column-wise var tableView = TableView.builder( rowCount: 50, columnCount: 50, - columnBuilder: (_) => - const TableSpan(extent: FixedTableSpanExtent(200)), + columnBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(200)), rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( @@ -2831,12 +2561,8 @@ void main() { ), ); }, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ); await tester.pumpWidget(MaterialApp(home: tableView)); @@ -2911,12 +2637,8 @@ void main() { ), ); }, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ); await tester.pumpWidget(MaterialApp(home: tableView)); @@ -2991,12 +2713,8 @@ void main() { ), ); }, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ); await tester.pumpWidget(MaterialApp(home: tableView)); @@ -3072,12 +2790,8 @@ void main() { ), ); }, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ); await tester.pumpWidget(MaterialApp(home: tableView)); @@ -3152,12 +2866,8 @@ void main() { ), ); }, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), ); await tester.pumpWidget(MaterialApp(home: tableView)); @@ -3178,10 +2888,7 @@ void main() { expect(cellNeedsPaint('Row: 0 Column: 8'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 0 Column: 9'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 0 Column: 10'), isTrue); // cacheExtent - expect( - find.text('Row: 0 Column: 11'), - findsNothing, - ); // outside of cacheExtent + expect(find.text('Row: 0 Column: 11'), findsNothing); // outside of cacheExtent expect(cellNeedsPaint('Row: 1 Column: 0'), isFalse); expect(cellNeedsPaint('Row: 2 Column: 0'), isFalse); @@ -3191,10 +2898,7 @@ void main() { expect(cellNeedsPaint('Row: 6 Column: 0'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 7 Column: 0'), isTrue); // cacheExtent expect(cellNeedsPaint('Row: 8 Column: 0'), isTrue); // cacheExtent - expect( - find.text('Row: 9 Column: 0'), - findsNothing, - ); // outside of cacheExtent + expect(find.text('Row: 9 Column: 0'), findsNothing); // outside of cacheExtent // Check a couple other cells expect(cellNeedsPaint('Row: 5 Column: 7'), isFalse); // last visible cell @@ -3203,9 +2907,7 @@ void main() { expect(cellNeedsPaint('Row: 6 Column: 8'), isTrue); // also in cacheExtent }); - testWidgets('paints decorations in correct order', ( - WidgetTester tester, - ) async { + testWidgets('paints decorations in correct order', (WidgetTester tester) async { var tableView = TableView.builder( rowCount: 2, columnCount: 2, @@ -3215,9 +2917,7 @@ void main() { foregroundDecoration: TableSpanDecoration( consumeSpanPadding: false, borderRadius: BorderRadius.circular(10.0), - border: const TableSpanBorder( - trailing: BorderSide(color: Colors.orange, width: 3), - ), + border: const TableSpanBorder(trailing: BorderSide(color: Colors.orange, width: 3)), ), backgroundDecoration: TableSpanDecoration( // consumePadding true by default @@ -3231,9 +2931,7 @@ void main() { foregroundDecoration: TableSpanDecoration( // consumePadding true by default borderRadius: BorderRadius.circular(30.0), - border: const TableSpanBorder( - leading: BorderSide(color: Colors.green, width: 3), - ), + border: const TableSpanBorder(leading: BorderSide(color: Colors.green, width: 3)), ), backgroundDecoration: TableSpanDecoration( color: index.isOdd ? Colors.blue : null, @@ -3243,11 +2941,7 @@ void main() { ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - child: Container( - height: 200, - width: 200, - color: Colors.grey.withValues(alpha: 0.5), - ), + child: Container(height: 200, width: 200, color: Colors.grey.withValues(alpha: 0.5)), ); }, ); @@ -3274,10 +2968,7 @@ void main() { color: const Color(0xfff44336), ) // child at 0,0 - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - color: const Color(0x809e9e9e), - ) + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), color: const Color(0x809e9e9e)) // child at 0,1 ..rect( rect: const Rect.fromLTRB(0.0, 210.0, 200.0, 410.0), @@ -3375,32 +3066,20 @@ void main() { columnBuilder: (int index) => TableSpan( extent: const FixedTableSpanExtent(200.0), foregroundDecoration: const TableSpanDecoration( - border: TableSpanBorder( - trailing: BorderSide(color: Colors.orange, width: 3), - ), - ), - backgroundDecoration: TableSpanDecoration( - color: index.isEven ? Colors.red : null, + border: TableSpanBorder(trailing: BorderSide(color: Colors.orange, width: 3)), ), + backgroundDecoration: TableSpanDecoration(color: index.isEven ? Colors.red : null), ), rowBuilder: (int index) => TableSpan( extent: const FixedTableSpanExtent(200.0), foregroundDecoration: const TableSpanDecoration( - border: TableSpanBorder( - leading: BorderSide(color: Colors.green, width: 3), - ), - ), - backgroundDecoration: TableSpanDecoration( - color: index.isOdd ? Colors.blue : null, + border: TableSpanBorder(leading: BorderSide(color: Colors.green, width: 3)), ), + backgroundDecoration: TableSpanDecoration(color: index.isOdd ? Colors.blue : null), ), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - child: Container( - height: 200, - width: 200, - color: Colors.grey.withValues(alpha: 0.5), - ), + child: Container(height: 200, width: 200, color: Colors.grey.withValues(alpha: 0.5)), ); }, ); @@ -3411,20 +3090,14 @@ void main() { find.byType(TableViewport), paints // background column goes first this time - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 400.0), - color: const Color(0xfff44336), - ) + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 400.0), color: const Color(0xfff44336)) // background row ..rect( rect: const Rect.fromLTRB(0.0, 200.0, 400.0, 400.0), color: const Color(0xff2196f3), ) // child at 0,0 - ..rect( - rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), - color: const Color(0x809e9e9e), - ) + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 200.0, 200.0), color: const Color(0x809e9e9e)) // child at 1,0 ..rect( rect: const Rect.fromLTRB(0.0, 200.0, 200.0, 400.0), @@ -3460,11 +3133,7 @@ void main() { ) // foreground row border ..path( - includes: [ - Offset.zero, - const Offset(200.0, 0.0), - const Offset(400.0, 0.0), - ], + includes: [Offset.zero, const Offset(200.0, 0.0), const Offset(400.0, 0.0)], color: const Color(0xff4caf50), ) // foreground row border(2) @@ -3490,17 +3159,11 @@ void main() { pinnedRowCount: 1, columnCount: 2, pinnedColumnCount: 1, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(200.0)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(200.0)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - child: Container( - height: 200, - width: 200, - color: Colors.grey.withValues(alpha: 0.5), - ), + child: Container(height: 200, width: 200, color: Colors.grey.withValues(alpha: 0.5)), ); }, ); @@ -3536,17 +3199,11 @@ void main() { pinnedRowCount: 1, columnCount: 2, pinnedColumnCount: 1, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(200.0)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(200.0)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(200.0)), cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - child: Container( - height: 200, - width: 200, - color: Colors.grey.withValues(alpha: 0.5), - ), + child: Container(height: 200, width: 200, color: Colors.grey.withValues(alpha: 0.5)), ); }, ); @@ -3604,9 +3261,7 @@ void main() { // Even rows will respond to mouse, odd will not final Offset evenRow = tester.getCenter(find.text('Row: 2 Column: 2')); final Offset oddRow = tester.getCenter(find.text('Row: 3 Column: 2')); - final TestGesture gesture = await tester.createGesture( - kind: PointerDeviceKind.mouse, - ); + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: oddRow); expect(enterCounter, 0); expect(exitCounter, 0); @@ -3633,70 +3288,63 @@ void main() { await gesture.removePointer(); }); - testWidgets( - 'Calling setState within onEnter does not cause a loop of onExit/onEnter', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/147614 - var enterCounter = 0; - var exitCounter = 0; - - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return TableView.builder( - columnCount: 1, - rowCount: 1, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => TableSpan( - extent: const FixedTableSpanExtent(100), - onEnter: (_) { - enterCounter++; - setState(() {}); - }, - onExit: (_) { - exitCounter++; - }, - ), - cellBuilder: - (BuildContext context, TableVicinity vicinity) { - return const TableViewCell( - child: SizedBox.square(dimension: 100), - ); - }, - ); - }, - ), + testWidgets('Calling setState within onEnter does not cause a loop of onExit/onEnter', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/147614 + var enterCounter = 0; + var exitCounter = 0; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return TableView.builder( + columnCount: 1, + rowCount: 1, + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => TableSpan( + extent: const FixedTableSpanExtent(100), + onEnter: (_) { + enterCounter++; + setState(() {}); + }, + onExit: (_) { + exitCounter++; + }, + ), + cellBuilder: (BuildContext context, TableVicinity vicinity) { + return const TableViewCell(child: SizedBox.square(dimension: 100)); + }, + ); + }, ), ), - ); + ), + ); - // Initial state - expect(enterCounter, 0); - expect(exitCounter, 0); + // Initial state + expect(enterCounter, 0); + expect(exitCounter, 0); - // Move mouse to the center of the first row (0,0) - final TestGesture gesture = await tester.createGesture( - kind: PointerDeviceKind.mouse, - ); - await gesture.addPointer(location: const Offset(50, 50)); - await tester.pump(); + // Move mouse to the center of the first row (0,0) + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(location: const Offset(50, 50)); + await tester.pump(); - // Should have entered once - expect(enterCounter, 1); - expect(exitCounter, 0); + // Should have entered once + expect(enterCounter, 1); + expect(exitCounter, 0); - // Pump again to see if it triggers again - await tester.pump(); + // Pump again to see if it triggers again + await tester.pump(); - expect(exitCounter, 0, reason: 'Should not have exited'); - expect(enterCounter, 1, reason: 'Should not have re-entered'); + expect(exitCounter, 0, reason: 'Should not have exited'); + expect(enterCounter, 1, reason: 'Should not have re-entered'); - await gesture.removePointer(); - }, - ); + await gesture.removePointer(); + }); group('Merged pinned cells layout', () { // Regression tests for https://github.com/flutter/flutter/issues/143526 @@ -3730,12 +3378,8 @@ void main() { final verticalController = ScrollController(); final horizontalController = ScrollController(); final tableView = TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), columnCount: 20, rowCount: 20, pinnedRowCount: 2, @@ -3744,14 +3388,10 @@ void main() { rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - columnMergeStart: - bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, - columnMergeSpan: - bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, - rowMergeStart: - bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, - rowMergeSpan: - bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, + columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, + columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, + rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, + rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', @@ -3764,76 +3404,31 @@ void main() { expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(150.0, 0.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(300.0, 75.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(0.0, 150.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(75.0, 300.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 0.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 75.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 150.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 300.0, 75.0, 225.0)); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(150.0, 0.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(300.0, 75.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(0.0, 140.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(75.0, 290.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 0.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 75.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 140.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 290.0, 75.0, 225.0)); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(140.0, 0.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(290.0, 75.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(0.0, 140.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(75.0, 290.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 0.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(140.0, 0.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(290.0, 75.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 140.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 290.0, 75.0, 225.0)); }); testWidgets('Vertical reversed', (WidgetTester tester) async { @@ -3844,9 +3439,7 @@ void main() { reverse: true, controller: verticalController, ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), columnCount: 20, rowCount: 20, pinnedRowCount: 2, @@ -3855,14 +3448,10 @@ void main() { rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - columnMergeStart: - bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, - columnMergeSpan: - bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, - rowMergeStart: - bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, - rowMergeSpan: - bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, + columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, + columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, + rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, + rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', @@ -3875,85 +3464,38 @@ void main() { expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(150.0, 525.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(300.0, 450.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(0.0, 300.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(75.0, 75.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 525.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 450.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 300.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 75.0, 75.0, 225.0)); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(150.0, 525.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(300.0, 450.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(0.0, 310.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(75.0, 85.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(150.0, 525.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(300.0, 450.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 310.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 85.0, 75.0, 225.0)); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(140.0, 525.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(290.0, 450.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(0.0, 310.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(75.0, 85.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(0.0, 450.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(140.0, 525.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(290.0, 450.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(0.0, 310.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(75.0, 85.0, 75.0, 225.0)); }); testWidgets('Horizontal reversed', (WidgetTester tester) async { final verticalController = ScrollController(); final horizontalController = ScrollController(); final tableView = TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal( reverse: true, controller: horizontalController, @@ -3966,14 +3508,10 @@ void main() { rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - columnMergeStart: - bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, - columnMergeSpan: - bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, - rowMergeStart: - bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, - rowMergeSpan: - bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, + columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, + columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, + rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, + rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', @@ -3986,76 +3524,31 @@ void main() { expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(500.0, 0.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(275.0, 75.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(725.0, 150.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(650.0, 300.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 0.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 75.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 150.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 300.0, 75.0, 225.0)); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(500.0, 0.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(275.0, 75.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(725.0, 140.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(650.0, 290.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 0.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 75.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 140.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 290.0, 75.0, 225.0)); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(510.0, 0.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(285.0, 75.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(725.0, 140.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(650.0, 290.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 0.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(510.0, 0.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(285.0, 75.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 140.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 290.0, 75.0, 225.0)); }); testWidgets('Both reversed', (WidgetTester tester) async { @@ -4078,14 +3571,10 @@ void main() { rowBuilder: (_) => span, cellBuilder: (_, TableVicinity vicinity) { return TableViewCell( - columnMergeStart: - bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, - columnMergeSpan: - bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, - rowMergeStart: - bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, - rowMergeSpan: - bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, + columnMergeStart: bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start, + columnMergeSpan: bothMerged[vicinity]?.span ?? columnMerged[vicinity]?.span, + rowMergeStart: bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start, + rowMergeSpan: bothMerged[vicinity]?.span ?? rowMerged[vicinity]?.span, child: Text( 'R${bothMerged[vicinity]?.start ?? rowMerged[vicinity]?.start ?? vicinity.row}:' 'C${bothMerged[vicinity]?.start ?? columnMerged[vicinity]?.start ?? vicinity.column}', @@ -4098,149 +3587,96 @@ void main() { expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(500.0, 525.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(275.0, 450.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(725.0, 300.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(650.0, 75.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 525.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 450.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 300.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 75.0, 75.0, 225.0)); verticalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(500.0, 525.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(275.0, 450.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(725.0, 310.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(650.0, 85.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(500.0, 525.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(275.0, 450.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 310.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 85.0, 75.0, 225.0)); horizontalController.jumpTo(10.0); await tester.pumpAndSettle(); expect(verticalController.position.pixels, 10.0); expect(horizontalController.position.pixels, 10.0); - expect( - tester.getRect(find.text('R0:C0')), - const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0), - ); - expect( - tester.getRect(find.text('R0:C2')), - const Rect.fromLTWH(510.0, 525.0, 150.0, 75.0), - ); - expect( - tester.getRect(find.text('R1:C4')), - const Rect.fromLTWH(285.0, 450.0, 225.0, 75.0), - ); - expect( - tester.getRect(find.text('R2:C0')), - const Rect.fromLTWH(725.0, 310.0, 75.0, 150.0), - ); - expect( - tester.getRect(find.text('R4:C1')), - const Rect.fromLTWH(650.0, 85.0, 75.0, 225.0), - ); + expect(tester.getRect(find.text('R0:C0')), const Rect.fromLTWH(650.0, 450.0, 150.0, 150.0)); + expect(tester.getRect(find.text('R0:C2')), const Rect.fromLTWH(510.0, 525.0, 150.0, 75.0)); + expect(tester.getRect(find.text('R1:C4')), const Rect.fromLTWH(285.0, 450.0, 225.0, 75.0)); + expect(tester.getRect(find.text('R2:C0')), const Rect.fromLTWH(725.0, 310.0, 75.0, 150.0)); + expect(tester.getRect(find.text('R4:C1')), const Rect.fromLTWH(650.0, 85.0, 75.0, 225.0)); }); }); }); - testWidgets( - 'Merged unpinned cells following pinned cells are laid out correctly', - (WidgetTester tester) async { - final verticalController = ScrollController(); - final horizontalController = ScrollController(); - final mergedCell = { - const TableVicinity(row: 2, column: 2), - const TableVicinity(row: 3, column: 2), - const TableVicinity(row: 2, column: 3), - const TableVicinity(row: 3, column: 3), - }; - final tableView = TableView.builder( - columnCount: 10, - rowCount: 10, - columnBuilder: (_) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), - cellBuilder: (BuildContext context, TableVicinity vicinity) { - if (mergedCell.contains(vicinity)) { - return const TableViewCell( - rowMergeStart: 2, - rowMergeSpan: 2, - columnMergeStart: 2, - columnMergeSpan: 2, - child: Text('Tile c: 2, r: 2'), - ); - } - return TableViewCell( - child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}'), + testWidgets('Merged unpinned cells following pinned cells are laid out correctly', ( + WidgetTester tester, + ) async { + final verticalController = ScrollController(); + final horizontalController = ScrollController(); + final mergedCell = { + const TableVicinity(row: 2, column: 2), + const TableVicinity(row: 3, column: 2), + const TableVicinity(row: 2, column: 3), + const TableVicinity(row: 3, column: 3), + }; + final tableView = TableView.builder( + columnCount: 10, + rowCount: 10, + columnBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (_) => const TableSpan(extent: FixedTableSpanExtent(100)), + cellBuilder: (BuildContext context, TableVicinity vicinity) { + if (mergedCell.contains(vicinity)) { + return const TableViewCell( + rowMergeStart: 2, + rowMergeSpan: 2, + columnMergeStart: 2, + columnMergeSpan: 2, + child: Text('Tile c: 2, r: 2'), ); - }, - pinnedRowCount: 1, - pinnedColumnCount: 1, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), - ); - await tester.pumpWidget(MaterialApp(home: tableView)); - await tester.pumpAndSettle(); - - expect(verticalController.position.pixels, 0.0); - expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('Tile c: 2, r: 2')), - const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0), - ); + } + return TableViewCell(child: Text('Tile c: ${vicinity.column}, r: ${vicinity.row}')); + }, + pinnedRowCount: 1, + pinnedColumnCount: 1, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + ); + await tester.pumpWidget(MaterialApp(home: tableView)); + await tester.pumpAndSettle(); + + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect( + tester.getRect(find.text('Tile c: 2, r: 2')), + const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0), + ); - verticalController.jumpTo(10.0); - await tester.pumpAndSettle(); - expect(verticalController.position.pixels, 10.0); - expect(horizontalController.position.pixels, 0.0); - expect( - tester.getRect(find.text('Tile c: 2, r: 2')), - const Rect.fromLTWH(200.0, 190.0, 200.0, 200.0), - ); + verticalController.jumpTo(10.0); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 10.0); + expect(horizontalController.position.pixels, 0.0); + expect( + tester.getRect(find.text('Tile c: 2, r: 2')), + const Rect.fromLTWH(200.0, 190.0, 200.0, 200.0), + ); - horizontalController.jumpTo(10.0); - await tester.pumpAndSettle(); - expect(verticalController.position.pixels, 10.0); - expect(horizontalController.position.pixels, 10.0); - expect( - tester.getRect(find.text('Tile c: 2, r: 2')), - const Rect.fromLTWH(190.0, 190.0, 200.0, 200.0), - ); - }, - ); + horizontalController.jumpTo(10.0); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 10.0); + expect(horizontalController.position.pixels, 10.0); + expect( + tester.getRect(find.text('Tile c: 2, r: 2')), + const Rect.fromLTWH(190.0, 190.0, 200.0, 200.0), + ); + }); testWidgets( 'Merged cells should not unmerge when the first cell is overlaid by a pinned column', @@ -4257,25 +3693,19 @@ void main() { height: 400, child: TableView.builder( cacheExtent: 0.0, - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), pinnedColumnCount: 1, columnCount: 10, rowCount: 10, - columnBuilder: (int index) => TableSpan( - extent: FixedTableSpanExtent(index == 0 ? 100 : 50), - ), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(50)), + columnBuilder: (int index) => + TableSpan(extent: FixedTableSpanExtent(index == 0 ? 100 : 50)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(50)), cellBuilder: (BuildContext context, TableVicinity vicinity) { final isColumn1 = vicinity.column == 1; return TableViewCell( columnMergeStart: isColumn1 ? 1 : null, columnMergeSpan: isColumn1 ? 3 : null, - child: Center( - child: Text('Cell ${vicinity.column},${vicinity.row}'), - ), + child: Center(child: Text('Cell ${vicinity.column},${vicinity.row}')), ); }, ), @@ -4310,63 +3740,56 @@ void main() { }, ); - testWidgets( - 'Merged cells should not unmerge when the first cell is overlaid by a pinned row', - (WidgetTester tester) async { - final verticalController = ScrollController(); - addTearDown(verticalController.dispose); + testWidgets('Merged cells should not unmerge when the first cell is overlaid by a pinned row', ( + WidgetTester tester, + ) async { + final verticalController = ScrollController(); + addTearDown(verticalController.dispose); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: SizedBox( - width: 400, - height: 400, - child: TableView.builder( - cacheExtent: 0.0, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - pinnedRowCount: 1, - columnCount: 10, - rowCount: 10, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(50)), - rowBuilder: (int index) => TableSpan( - extent: FixedTableSpanExtent(index == 0 ? 100 : 50), - ), - cellBuilder: (BuildContext context, TableVicinity vicinity) { - // Merged cell spanning rows 1, 2, and 3. - final isRow1 = vicinity.row == 1; - return TableViewCell( - rowMergeStart: isRow1 ? 1 : null, - rowMergeSpan: isRow1 ? 3 : null, - child: Center( - child: Text('Cell ${vicinity.column},${vicinity.row}'), - ), - ); - }, - ), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 400, + height: 400, + child: TableView.builder( + cacheExtent: 0.0, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + pinnedRowCount: 1, + columnCount: 10, + rowCount: 10, + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(50)), + rowBuilder: (int index) => + TableSpan(extent: FixedTableSpanExtent(index == 0 ? 100 : 50)), + cellBuilder: (BuildContext context, TableVicinity vicinity) { + // Merged cell spanning rows 1, 2, and 3. + final isRow1 = vicinity.row == 1; + return TableViewCell( + rowMergeStart: isRow1 ? 1 : null, + rowMergeSpan: isRow1 ? 3 : null, + child: Center(child: Text('Cell ${vicinity.column},${vicinity.row}')), + ); + }, ), ), ), - ); + ), + ); - // Initially, row 1 is visible below pinned row 0. - expect(find.text('Cell 0,1'), findsOneWidget); - expect(find.text('Cell 0,2'), findsNothing); - expect(find.text('Cell 0,3'), findsNothing); + // Initially, row 1 is visible below pinned row 0. + expect(find.text('Cell 0,1'), findsOneWidget); + expect(find.text('Cell 0,2'), findsNothing); + expect(find.text('Cell 0,3'), findsNothing); - // Scroll vertically so that row 1 is entirely behind pinned row 0. - verticalController.jumpTo(100); - await tester.pump(); + // Scroll vertically so that row 1 is entirely behind pinned row 0. + verticalController.jumpTo(100); + await tester.pump(); - // Row 1 should still be built, maintaining the merge. - expect(find.text('Cell 0,1'), findsOneWidget); - expect(find.text('Cell 0,2'), findsNothing); - expect(find.text('Cell 0,3'), findsNothing); - }, - ); + // Row 1 should still be built, maintaining the merge. + expect(find.text('Cell 0,1'), findsOneWidget); + expect(find.text('Cell 0,2'), findsNothing); + expect(find.text('Cell 0,3'), findsNothing); + }); testWidgets( 'Table does not crash when focusing outside of the table while focused text field is not in the view', @@ -4387,24 +3810,17 @@ void main() { const TextField(key: Key('outside_textfield')), Expanded( child: TableView.builder( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal( controller: horizontalController, ), - cellBuilder: - (BuildContext context, TableVicinity vicinity) { - return TableViewCell( - child: Center( - child: TextField( - key: Key( - 'cell_${vicinity.row}_${vicinity.column}', - ), - ), - ), - ); - }, + cellBuilder: (BuildContext context, TableVicinity vicinity) { + return TableViewCell( + child: Center( + child: TextField(key: Key('cell_${vicinity.row}_${vicinity.column}')), + ), + ); + }, columnCount: 20, columnBuilder: (int index) { return const TableSpan( @@ -4419,9 +3835,7 @@ void main() { return TableSpan( backgroundDecoration: TableSpanDecoration( color: index.isEven ? Colors.purple[100] : null, - border: const TableSpanBorder( - trailing: BorderSide(width: 3), - ), + border: const TableSpanBorder(trailing: BorderSide(width: 3)), ), extent: const FixedTableSpanExtent(50), ); @@ -4437,9 +3851,7 @@ void main() { // 1. Select a TextField in the table. // Use the vicinity from the original crash report. const vicinity = TableVicinity(row: 5, column: 6); - final Finder cellTextField = find.byKey( - Key('cell_${vicinity.row}_${vicinity.column}'), - ); + final Finder cellTextField = find.byKey(Key('cell_${vicinity.row}_${vicinity.column}')); // Bring it into view. verticalController.jumpTo(250); horizontalController.jumpTo(600); @@ -4454,9 +3866,7 @@ void main() { await tester.pumpAndSettle(); // 3. Select another TextField outside of the table. - final Finder outsideTextField = find.byKey( - const Key('outside_textfield'), - ); + final Finder outsideTextField = find.byKey(const Key('outside_textfield')); await tester.tap(outsideTextField); await tester.pumpAndSettle(); @@ -4467,9 +3877,7 @@ void main() { }, ); - testWidgets('Trailing pinned columns and rows - smoke test', ( - WidgetTester tester, - ) async { + testWidgets('Trailing pinned columns and rows - smoke test', (WidgetTester tester) async { final horizontalController = ScrollController(); final verticalController = ScrollController(); @@ -4489,20 +3897,12 @@ void main() { pinnedRowCount: pinnedRowCount, trailingPinnedColumnCount: trailingPinnedColumnCount, trailingPinnedRowCount: trailingPinnedRowCount, - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (BuildContext context, TableVicinity vicinity) { - return TableViewCell( - child: Text('R${vicinity.row} C${vicinity.column}'), - ); + return TableViewCell(child: Text('R${vicinity.row} C${vicinity.column}')); }, ); } @@ -4513,10 +3913,7 @@ void main() { body: SizedBox( height: 400, width: 400, - child: getTableView( - trailingPinnedColumnCount: 1, - trailingPinnedRowCount: 1, - ), + child: getTableView(trailingPinnedColumnCount: 1, trailingPinnedRowCount: 1), ), ), ), @@ -4544,9 +3941,7 @@ void main() { expect(tester.getRect(find.text('R9 C9')).top, 300); }); - testWidgets('Intersections of leading and trailing pinned', ( - WidgetTester tester, - ) async { + testWidgets('Intersections of leading and trailing pinned', (WidgetTester tester) async { const span = TableSpan(extent: FixedTableSpanExtent(100)); await tester.pumpWidget( MaterialApp( @@ -4564,9 +3959,7 @@ void main() { columnBuilder: (int index) => span, rowBuilder: (int index) => span, cellBuilder: (BuildContext context, TableVicinity vicinity) { - return TableViewCell( - child: Text('R${vicinity.row} C${vicinity.column}'), - ); + return TableViewCell(child: Text('R${vicinity.row} C${vicinity.column}')); }, ), ), @@ -4587,9 +3980,7 @@ void main() { expect(tester.getRect(find.text('R1 C1')).topLeft, const Offset(100, 100)); }); - testWidgets('Trailing pinned - merged cells validation', ( - WidgetTester tester, - ) async { + testWidgets('Trailing pinned - merged cells validation', (WidgetTester tester) async { // Merged cell in trailing pinned row await tester.pumpWidget( MaterialApp( @@ -4602,10 +3993,8 @@ void main() { columnCount: 10, rowCount: 10, trailingPinnedRowCount: 2, - columnBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), - rowBuilder: (int index) => - const TableSpan(extent: FixedTableSpanExtent(100)), + columnBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), + rowBuilder: (int index) => const TableSpan(extent: FixedTableSpanExtent(100)), cellBuilder: (BuildContext context, TableVicinity vicinity) { if (vicinity.row >= 8 && vicinity.column == 0) { return const TableViewCell( @@ -4614,9 +4003,7 @@ void main() { child: Text('Merged R8-9 C0'), ); } - return TableViewCell( - child: Text('R${vicinity.row} C${vicinity.column}'), - ); + return TableViewCell(child: Text('R${vicinity.row} C${vicinity.column}')); }, ), ), diff --git a/packages/two_dimensional_scrollables/test/tree_view/alignment_test.dart b/packages/two_dimensional_scrollables/test/tree_view/alignment_test.dart index 9783e253309e..930cac55e1a7 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/alignment_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/alignment_test.dart @@ -24,14 +24,12 @@ void main() { height: 400, child: TreeView( tree: tree, - treeNodeBuilder: (context, node, toggleAnimationStyle) => - SizedBox( - key: const ValueKey('Root'), - height: 100, - child: Text(node.content), - ), - treeRowBuilder: (node) => - const TreeRow(extent: FixedTreeRowExtent(100)), + treeNodeBuilder: (context, node, toggleAnimationStyle) => SizedBox( + key: const ValueKey('Root'), + height: 100, + child: Text(node.content), + ), + treeRowBuilder: (node) => const TreeRow(extent: FixedTreeRowExtent(100)), ), ), ), @@ -39,9 +37,7 @@ void main() { ), ); - final Offset treeTopLeft = tester.getTopLeft( - find.byType(TreeView), - ); + final Offset treeTopLeft = tester.getTopLeft(find.byType(TreeView)); // Default is Alignment.topLeft (0, 0) final Finder root = find.byKey(const ValueKey('Root')); expect(tester.getTopLeft(root) - treeTopLeft, Offset.zero); @@ -65,14 +61,12 @@ void main() { child: TreeView( tree: tree, alignment: Alignment.center, - treeNodeBuilder: (context, node, toggleAnimationStyle) => - SizedBox( - key: const ValueKey('Root'), - height: 100, - child: Text(node.content), - ), - treeRowBuilder: (node) => - const TreeRow(extent: FixedTreeRowExtent(100)), + treeNodeBuilder: (context, node, toggleAnimationStyle) => SizedBox( + key: const ValueKey('Root'), + height: 100, + child: Text(node.content), + ), + treeRowBuilder: (node) => const TreeRow(extent: FixedTreeRowExtent(100)), ), ), ), @@ -80,9 +74,7 @@ void main() { ), ); - final Offset treeTopLeft = tester.getTopLeft( - find.byType(TreeView), - ); + final Offset treeTopLeft = tester.getTopLeft(find.byType(TreeView)); // Tree is 100 high, viewport is 600 high. Centered means 250 offset. final Finder root = find.byKey(const ValueKey('Root')); expect(tester.getTopLeft(root) - treeTopLeft, const Offset(0.0, 250.0)); diff --git a/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart b/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart index 2dc2a717dba8..3b42861afd4c 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/render_tree_test.dart @@ -15,11 +15,10 @@ TreeRow getTappableRow(TreeViewNode node, VoidCallback callback) { return TreeRow( extent: const FixedTreeRowExtent(100), recognizerFactories: { - TapGestureRecognizer: - GestureRecognizerFactoryWithHandlers( - () => TapGestureRecognizer(), - (TapGestureRecognizer t) => t.onTap = () => callback(), - ), + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => TapGestureRecognizer(), + (TapGestureRecognizer t) => t.onTap = () => callback(), + ), }, ); } @@ -87,8 +86,7 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: (_) => - const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, @@ -114,8 +112,7 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: (_) => - const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, @@ -185,9 +182,7 @@ void main() { // Root row will respond to mouse, child will not final Offset rootRow = tester.getCenter(find.text('Second')); final Offset childRow = tester.getCenter(find.text('gamma')); - final TestGesture gesture = await tester.createGesture( - kind: PointerDeviceKind.mouse, - ); + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: childRow); expect(enterCounter, 0); expect(exitCounter, 0); @@ -213,9 +208,7 @@ void main() { ); }); - testWidgets('Scrolls when there is enough content', ( - WidgetTester tester, - ) async { + testWidgets('Scrolls when there is enough content', (WidgetTester tester) async { final verticalController = ScrollController(); final horizontalController = ScrollController(); final treeController = TreeViewController(); @@ -223,12 +216,8 @@ void main() { addTearDown(horizontalController.dispose); final treeView = TreeView( controller: treeController, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), tree: treeNodes, // Exaggerated to exceed viewport bounds. indentation: TreeViewIndentationType.custom(500), @@ -270,82 +259,43 @@ void main() { await tester.pumpWidget(MaterialApp(home: treeView)); await tester.pump(); expect(find.text('First'), findsOneWidget); - expect( - tester.getRect(find.text('First')), - const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0), - ); + expect(tester.getRect(find.text('First')), const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0)); expect(find.text('Second'), findsOneWidget); - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); expect(find.text('Third'), findsOneWidget); - expect( - tester.getRect(find.text('Third')), - const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0), - ); + expect(tester.getRect(find.text('Third')), const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0)); expect(find.text('gamma'), findsOneWidget); - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0), - ); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0)); expect(find.text('delta'), findsOneWidget); - expect( - tester.getRect(find.text('delta')), - const Rect.fromLTRB(56.0, 168.0, 296.0, 192.0), - ); + expect(tester.getRect(find.text('delta')), const Rect.fromLTRB(56.0, 168.0, 296.0, 192.0)); expect(find.text('epsilon'), findsOneWidget); expect( tester.getRect(find.text('epsilon')), const Rect.fromLTRB(56.0, 208.0, 392.0, 232.0), ); expect(find.text('Fourth'), findsOneWidget); - expect( - tester.getRect(find.text('Fourth')), - const Rect.fromLTRB(46.0, 248.0, 334.0, 272.0), - ); + expect(tester.getRect(find.text('Fourth')), const Rect.fromLTRB(46.0, 248.0, 334.0, 272.0)); - treeView = TreeView( - tree: treeNodes, - indentation: TreeViewIndentationType.none, - ); + treeView = TreeView(tree: treeNodes, indentation: TreeViewIndentationType.none); await tester.pumpWidget(MaterialApp(home: treeView)); await tester.pump(); expect(find.text('First'), findsOneWidget); - expect( - tester.getRect(find.text('First')), - const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0), - ); + expect(tester.getRect(find.text('First')), const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0)); expect(find.text('Second'), findsOneWidget); - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); expect(find.text('Third'), findsOneWidget); - expect( - tester.getRect(find.text('Third')), - const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0), - ); + expect(tester.getRect(find.text('Third')), const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0)); expect(find.text('gamma'), findsOneWidget); - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(46.0, 128.0, 286.0, 152.0), - ); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(46.0, 128.0, 286.0, 152.0)); expect(find.text('delta'), findsOneWidget); - expect( - tester.getRect(find.text('delta')), - const Rect.fromLTRB(46.0, 168.0, 286.0, 192.0), - ); + expect(tester.getRect(find.text('delta')), const Rect.fromLTRB(46.0, 168.0, 286.0, 192.0)); expect(find.text('epsilon'), findsOneWidget); expect( tester.getRect(find.text('epsilon')), const Rect.fromLTRB(46.0, 208.0, 382.0, 232.0), ); expect(find.text('Fourth'), findsOneWidget); - expect( - tester.getRect(find.text('Fourth')), - const Rect.fromLTRB(46.0, 248.0, 334.0, 272.0), - ); + expect(tester.getRect(find.text('Fourth')), const Rect.fromLTRB(46.0, 248.0, 334.0, 272.0)); treeView = TreeView( tree: treeNodes, @@ -354,40 +304,22 @@ void main() { await tester.pumpWidget(MaterialApp(home: treeView)); await tester.pump(); expect(find.text('First'), findsOneWidget); - expect( - tester.getRect(find.text('First')), - const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0), - ); + expect(tester.getRect(find.text('First')), const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0)); expect(find.text('Second'), findsOneWidget); - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); expect(find.text('Third'), findsOneWidget); - expect( - tester.getRect(find.text('Third')), - const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0), - ); + expect(tester.getRect(find.text('Third')), const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0)); expect(find.text('gamma'), findsOneWidget); - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(96.0, 128.0, 336.0, 152.0), - ); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(96.0, 128.0, 336.0, 152.0)); expect(find.text('delta'), findsOneWidget); - expect( - tester.getRect(find.text('delta')), - const Rect.fromLTRB(96.0, 168.0, 336.0, 192.0), - ); + expect(tester.getRect(find.text('delta')), const Rect.fromLTRB(96.0, 168.0, 336.0, 192.0)); expect(find.text('epsilon'), findsOneWidget); expect( tester.getRect(find.text('epsilon')), const Rect.fromLTRB(96.0, 208.0, 432.0, 232.0), ); expect(find.text('Fourth'), findsOneWidget); - expect( - tester.getRect(find.text('Fourth')), - const Rect.fromLTRB(46.0, 248.0, 334.0, 272.0), - ); + expect(tester.getRect(find.text('Fourth')), const Rect.fromLTRB(46.0, 248.0, 334.0, 272.0)); treeView = TreeView( tree: treeNodes, @@ -402,40 +334,22 @@ void main() { await tester.pumpWidget(MaterialApp(home: treeView)); await tester.pump(); expect(find.text('First'), findsOneWidget); - expect( - tester.getRect(find.text('First')), - const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0), - ); + expect(tester.getRect(find.text('First')), const Rect.fromLTRB(46.0, 8.0, 286.0, 32.0)); expect(find.text('Second'), findsOneWidget); - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); expect(find.text('Third'), findsOneWidget); - expect( - tester.getRect(find.text('Third')), - const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0), - ); + expect(tester.getRect(find.text('Third')), const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0)); expect(find.text('gamma'), findsOneWidget); - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(56.0, 146.0, 296.0, 194.0), - ); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(56.0, 146.0, 296.0, 194.0)); expect(find.text('delta'), findsOneWidget); - expect( - tester.getRect(find.text('delta')), - const Rect.fromLTRB(56.0, 246.0, 296.0, 294.0), - ); + expect(tester.getRect(find.text('delta')), const Rect.fromLTRB(56.0, 246.0, 296.0, 294.0)); expect(find.text('epsilon'), findsOneWidget); expect( tester.getRect(find.text('epsilon')), const Rect.fromLTRB(56.0, 346.0, 392.0, 394.0), ); expect(find.text('Fourth'), findsOneWidget); - expect( - tester.getRect(find.text('Fourth')), - const Rect.fromLTRB(46.0, 428.0, 334.0, 452.0), - ); + expect(tester.getRect(find.text('Fourth')), const Rect.fromLTRB(46.0, 428.0, 334.0, 452.0)); }); testWidgets('Animating node segment', (WidgetTester tester) async { @@ -448,20 +362,11 @@ void main() { // It has now been inserted into the tree, along with the other children // of the node. expect(find.text('alpha'), findsOneWidget); - expect( - tester.getRect(find.text('alpha')), - const Rect.fromLTRB(56.0, -32.0, 296.0, -8.0), - ); + expect(tester.getRect(find.text('alpha')), const Rect.fromLTRB(56.0, -32.0, 296.0, -8.0)); expect(find.text('beta'), findsOneWidget); - expect( - tester.getRect(find.text('beta')), - const Rect.fromLTRB(56.0, 8.0, 248.0, 32.0), - ); + expect(tester.getRect(find.text('beta')), const Rect.fromLTRB(56.0, 8.0, 248.0, 32.0)); expect(find.text('kappa'), findsOneWidget); - expect( - tester.getRect(find.text('kappa')), - const Rect.fromLTRB(56.0, 48.0, 296.0, 72.0), - ); + expect(tester.getRect(find.text('kappa')), const Rect.fromLTRB(56.0, 48.0, 296.0, 72.0)); // Progress the animation. await tester.pump(const Duration(milliseconds: 50)); expect(tester.getRect(find.text('alpha')).top.floor(), 8.0); @@ -472,20 +377,11 @@ void main() { // Complete the animation await tester.pumpAndSettle(); expect(find.text('alpha'), findsOneWidget); - expect( - tester.getRect(find.text('alpha')), - const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0), - ); + expect(tester.getRect(find.text('alpha')), const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0)); expect(find.text('beta'), findsOneWidget); - expect( - tester.getRect(find.text('beta')), - const Rect.fromLTRB(56.0, 128.0, 248.0, 152.0), - ); + expect(tester.getRect(find.text('beta')), const Rect.fromLTRB(56.0, 128.0, 248.0, 152.0)); expect(find.text('kappa'), findsOneWidget); - expect( - tester.getRect(find.text('kappa')), - const Rect.fromLTRB(56.0, 168.0, 296.0, 192.0), - ); + expect(tester.getRect(find.text('kappa')), const Rect.fromLTRB(56.0, 168.0, 296.0, 192.0)); // Customize the animation treeView = TreeView( @@ -500,10 +396,7 @@ void main() { await tester.pump(); // Still visible from earlier. expect(find.text('alpha'), findsOneWidget); - expect( - tester.getRect(find.text('alpha')), - const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0), - ); + expect(tester.getRect(find.text('alpha')), const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0)); // Collapse the node now await tester.tap(find.byType(Icon).first); await tester.pump(); @@ -540,25 +433,14 @@ void main() { await tester.pump(); // No animating expect(find.text('alpha'), findsOneWidget); - expect( - tester.getRect(find.text('alpha')), - const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0), - ); + expect(tester.getRect(find.text('alpha')), const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0)); expect(find.text('beta'), findsOneWidget); - expect( - tester.getRect(find.text('beta')), - const Rect.fromLTRB(56.0, 128.0, 248.0, 152.0), - ); + expect(tester.getRect(find.text('beta')), const Rect.fromLTRB(56.0, 128.0, 248.0, 152.0)); expect(find.text('kappa'), findsOneWidget); - expect( - tester.getRect(find.text('kappa')), - const Rect.fromLTRB(56.0, 168.0, 296.0, 192.0), - ); + expect(tester.getRect(find.text('kappa')), const Rect.fromLTRB(56.0, 168.0, 296.0, 192.0)); }); - testWidgets('Multiple animating node segments', ( - WidgetTester tester, - ) async { + testWidgets('Multiple animating node segments', (WidgetTester tester) async { final controller = TreeViewController(); await tester.pumpWidget( MaterialApp( @@ -571,18 +453,9 @@ void main() { expect(find.text('Third'), findsOneWidget); expect(find.text('gamma'), findsOneWidget); // Third is expanded - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); - expect( - tester.getRect(find.text('Third')), - const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0), - ); - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); + expect(tester.getRect(find.text('Third')), const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0)); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0)); // Trigger two animations to run together. // Collapse Third @@ -591,19 +464,10 @@ void main() { await tester.tap(find.byType(Icon).first); await tester.pump(const Duration(milliseconds: 15)); // Third is collapsing - expect( - tester.getRect(find.text('Third')), - const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0), - ); - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0), - ); + expect(tester.getRect(find.text('Third')), const Rect.fromLTRB(46.0, 88.0, 286.0, 112.0)); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0)); // Second is expanding - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); // alpha has been added and is animating into view. expect(tester.getRect(find.text('alpha')).top.floor(), -32.0); await tester.pump(const Duration(milliseconds: 15)); @@ -613,15 +477,9 @@ void main() { // gamma appears to not have moved, this is because it is // intersecting both animations, the positive offset of // Second animation == the negative offset of Third - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0), - ); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0)); // Second is still expanding - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); // alpha is still animating into view. expect(tester.getRect(find.text('alpha')).top.floor(), -20.0); // Progress the animation further @@ -632,34 +490,19 @@ void main() { // gamma appears to not have moved, this is because it is // intersecting both animations, the positive offset of // Second animation == the negative offset of Third - expect( - tester.getRect(find.text('gamma')), - const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0), - ); + expect(tester.getRect(find.text('gamma')), const Rect.fromLTRB(56.0, 128.0, 296.0, 152.0)); // Second is still expanding - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); // alpha is still animating into view. expect(tester.getRect(find.text('alpha')).top.floor(), -8.0); // Complete the animations await tester.pumpAndSettle(); - expect( - tester.getRect(find.text('Third')), - const Rect.fromLTRB(46.0, 208.0, 286.0, 232.0), - ); + expect(tester.getRect(find.text('Third')), const Rect.fromLTRB(46.0, 208.0, 286.0, 232.0)); // gamma has left the building expect(find.text('gamma'), findsNothing); - expect( - tester.getRect(find.text('Second')), - const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0), - ); + expect(tester.getRect(find.text('Second')), const Rect.fromLTRB(46.0, 48.0, 334.0, 72.0)); // alpha is in place. - expect( - tester.getRect(find.text('alpha')), - const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0), - ); + expect(tester.getRect(find.text('alpha')), const Rect.fromLTRB(56.0, 88.0, 296.0, 112.0)); }); }); @@ -674,9 +517,7 @@ void main() { final treeView = TreeView( treeRowBuilder: (_) => const TreeRow(extent: FixedTreeRowExtent(400)), tree: treeNodes, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), ); await tester.pumpWidget(MaterialApp(home: treeView)); @@ -704,12 +545,8 @@ void main() { const foregroundDecoration = TreeRowDecoration(color: Colors.orange); const backgroundDecoration = TreeRowDecoration(color: Colors.green); final treeView = TreeView( - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: horizontalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), tree: treeNodes, treeRowBuilder: (TreeViewNode node) { return row.copyWith( @@ -876,11 +713,7 @@ class TestOffset extends ViewportOffset { bool get allowImplicitScrolling => throw UnimplementedError(); @override - Future animateTo( - double to, { - required Duration duration, - required Curve curve, - }) { + Future animateTo(double to, {required Duration duration, required Curve curve}) { throw UnimplementedError(); } diff --git a/packages/two_dimensional_scrollables/test/tree_view/tree_span_test.dart b/packages/two_dimensional_scrollables/test/tree_view/tree_span_test.dart index ae79dfa3417e..1a7a7882fbb1 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/tree_span_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/tree_span_test.dart @@ -12,17 +12,12 @@ void main() { test('FixedTreeRowExtent', () { var extent = const FixedTreeRowExtent(150); expect( - extent.calculateExtent( - const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 150, ); expect( extent.calculateExtent( - const TreeRowExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TreeRowExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 150, ); @@ -44,17 +39,12 @@ void main() { test('FractionalTreeRowExtent', () { var extent = const FractionalTreeRowExtent(0.5); expect( - extent.calculateExtent( - const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 0.0, ); expect( extent.calculateExtent( - const TreeRowExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TreeRowExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 500, ); @@ -76,17 +66,12 @@ void main() { test('RemainingTreeRowExtent', () { const extent = RemainingTreeRowExtent(); expect( - extent.calculateExtent( - const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 0.0, ); expect( extent.calculateExtent( - const TreeRowExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TreeRowExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 900, ); @@ -101,61 +86,40 @@ void main() { }, ); expect( - extent.calculateExtent( - const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 100, ); expect( extent.calculateExtent( - const TreeRowExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TreeRowExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 1000, ); }); test('MaxTreeRowExtent', () { - const extent = MaxTreeRowExtent( - FixedTreeRowExtent(100), - RemainingTreeRowExtent(), - ); + const extent = MaxTreeRowExtent(FixedTreeRowExtent(100), RemainingTreeRowExtent()); expect( - extent.calculateExtent( - const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 100, ); expect( extent.calculateExtent( - const TreeRowExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TreeRowExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 900, ); }); test('MinTreeRowExtent', () { - const extent = MinTreeRowExtent( - FixedTreeRowExtent(100), - RemainingTreeRowExtent(), - ); + const extent = MinTreeRowExtent(FixedTreeRowExtent(100), RemainingTreeRowExtent()); expect( - extent.calculateExtent( - const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0), - ), + extent.calculateExtent(const TreeRowExtentDelegate(precedingExtent: 0, viewportExtent: 0)), 0, ); expect( extent.calculateExtent( - const TreeRowExtentDelegate( - precedingExtent: 100, - viewportExtent: 1000, - ), + const TreeRowExtentDelegate(precedingExtent: 100, viewportExtent: 1000), ), 100, ); diff --git a/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart b/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart index b9eddafcec6e..af7009d35703 100644 --- a/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart +++ b/packages/two_dimensional_scrollables/test/tree_view/tree_test.dart @@ -31,11 +31,7 @@ void main() { group('TreeViewNode', () { test('getters, toString', () { final children = >[TreeViewNode('child')]; - final node = TreeViewNode( - 'parent', - children: children, - expanded: true, - ); + final node = TreeViewNode('parent', children: children, expanded: true); expect(node.content, 'parent'); expect(node.children, children); expect(node.isExpanded, isTrue); @@ -48,25 +44,13 @@ void main() { expect(node.children.first.depth, isNull); expect(node.children.first.parent, isNull); - expect( - node.toString(), - 'TreeViewNode: parent, depth: null, parent, expanded: true', - ); - expect( - node.children.first.toString(), - 'TreeViewNode: child, depth: null, leaf', - ); + expect(node.toString(), 'TreeViewNode: parent, depth: null, parent, expanded: true'); + expect(node.children.first.toString(), 'TreeViewNode: child, depth: null, leaf'); }); - testWidgets('TreeView sets ups parent and depth properties', ( - WidgetTester tester, - ) async { + testWidgets('TreeView sets ups parent and depth properties', (WidgetTester tester) async { final children = >[TreeViewNode('child')]; - final node = TreeViewNode( - 'parent', - children: children, - expanded: true, - ); + final node = TreeViewNode('parent', children: children, expanded: true); await tester.pumpWidget( MaterialApp(home: TreeView(tree: >[node])), ); @@ -82,14 +66,8 @@ void main() { expect(node.children.first.depth, 1); expect(node.children.first.parent, node); - expect( - node.toString(), - 'TreeViewNode: parent, depth: root, parent, expanded: true', - ); - expect( - node.children.first.toString(), - 'TreeViewNode: child, depth: 1, leaf', - ); + expect(node.toString(), 'TreeViewNode: parent, depth: root, parent, expanded: true'); + expect(node.children.first.toString(), 'TreeViewNode: child, depth: 1, leaf'); }); }); @@ -131,11 +109,7 @@ void main() { AnimationStyle toggleAnimationStyle, ) { returnedController ??= TreeViewController.of(context); - return TreeView.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); + return TreeView.defaultTreeNodeBuilder(context, node, toggleAnimationStyle); }, ), ), @@ -143,9 +117,7 @@ void main() { expect(controller, returnedController); }); - testWidgets('Can get default controller on TreeView', ( - WidgetTester tester, - ) async { + testWidgets('Can get default controller on TreeView', (WidgetTester tester) async { TreeViewController? returnedController; await tester.pumpWidget( MaterialApp( @@ -158,11 +130,7 @@ void main() { AnimationStyle toggleAnimationStyle, ) { returnedController ??= TreeViewController.maybeOf(context); - return TreeView.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); + return TreeView.defaultTreeNodeBuilder(context, node, toggleAnimationStyle); }, ), ), @@ -170,9 +138,7 @@ void main() { expect(returnedController, isNotNull); }); - testWidgets('Can get node for TreeViewNode.content', ( - WidgetTester tester, - ) async { + testWidgets('Can get node for TreeViewNode.content', (WidgetTester tester) async { final controller = TreeViewController(); await tester.pumpWidget( MaterialApp( @@ -208,9 +174,7 @@ void main() { expect(controller.isActive(simpleNodeSet[2].children[0]), isFalse); }); - testWidgets('Can toggleNode, to collapse or expand', ( - WidgetTester tester, - ) async { + testWidgets('Can toggleNode, to collapse or expand', (WidgetTester tester) async { final controller = TreeViewController(); await tester.pumpWidget( MaterialApp( @@ -241,9 +205,7 @@ void main() { expect(controller.isActive(simpleNodeSet[1].children[0]), isFalse); }); - testWidgets('Can expandNode, then collapseAll', ( - WidgetTester tester, - ) async { + testWidgets('Can expandNode, then collapseAll', (WidgetTester tester) async { final controller = TreeViewController(); await tester.pumpWidget( MaterialApp( @@ -274,9 +236,7 @@ void main() { expect(controller.isExpanded(simpleNodeSet[2]), isFalse); }); - testWidgets('Can collapseNode, then expandAll', ( - WidgetTester tester, - ) async { + testWidgets('Can collapseNode, then expandAll', (WidgetTester tester) async { final controller = TreeViewController(); await tester.pumpWidget( MaterialApp( @@ -355,9 +315,7 @@ void main() { () { treeView = TreeView( tree: simpleNodeSet, - horizontalDetails: const ScrollableDetails.horizontal( - reverse: true, - ), + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), ); }, throwsA( @@ -416,11 +374,9 @@ void main() { AnimationStyle toggleAnimationStyle, ) { final Duration animationDuration = - toggleAnimationStyle.duration ?? - TreeView.defaultAnimationDuration; + toggleAnimationStyle.duration ?? TreeView.defaultAnimationDuration; final Curve animationCurve = - toggleAnimationStyle.curve ?? - TreeView.defaultAnimationCurve; + toggleAnimationStyle.curve ?? TreeView.defaultAnimationCurve; // This makes the whole row trigger toggling. return TreeView.wrapChildToToggleNode( node: node, @@ -436,10 +392,7 @@ void main() { turns: node.isExpanded ? 0.25 : 0.0, duration: animationDuration, curve: animationCurve, - child: const Icon( - IconData(0x25BA), - size: 14, - ), + child: const Icon(IconData(0x25BA), size: 14), ) : null, ), @@ -465,9 +418,7 @@ void main() { expect(toggledNode, simpleNodeSet[1]); }); - testWidgets('AnimationStyle is piped through to node builder', ( - WidgetTester tester, - ) async { + testWidgets('AnimationStyle is piped through to node builder', (WidgetTester tester) async { AnimationStyle? style; await tester.pumpWidget( MaterialApp( @@ -552,10 +503,7 @@ void main() { home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( - body: TreeView( - tree: simpleNodeSet, - controller: controller, - ), + body: TreeView(tree: simpleNodeSet, controller: controller), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { @@ -595,75 +543,61 @@ void main() { expect(find.text('Added root'), findsOneWidget); }); - testWidgets( - 'Adding more TreeViewNodes below the root are reflected in the tree', - (WidgetTester tester) async { - final controller = TreeViewController(); - await tester.pumpWidget( - MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return Scaffold( - body: TreeView( - tree: simpleNodeSet, - controller: controller, - ), - floatingActionButton: FloatingActionButton( - onPressed: () { - setState(() { - simpleNodeSet[1].children.add( - TreeViewNode('Added child'), - ); - }); - }, - ), - ); - }, - ), + testWidgets('Adding more TreeViewNodes below the root are reflected in the tree', ( + WidgetTester tester, + ) async { + final controller = TreeViewController(); + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + body: TreeView(tree: simpleNodeSet, controller: controller), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + simpleNodeSet[1].children.add(TreeViewNode('Added child')); + }); + }, + ), + ); + }, ), - ); - await tester.pump(); - - expect(find.text('Root 0'), findsOneWidget); - expect(find.text('Root 1'), findsOneWidget); - expect(find.text('Child 1:0'), findsOneWidget); - expect(find.text('Child 1:1'), findsOneWidget); - expect(find.text('Added child'), findsNothing); - expect(find.text('Root 2'), findsOneWidget); - expect(find.text('Child 2:0'), findsNothing); - expect(find.text('Child 2:1'), findsNothing); - expect(find.text('Root 3'), findsOneWidget); - - await tester.tap(find.byType(FloatingActionButton)); - await tester.pump(); - - expect(find.text('Root 0'), findsOneWidget); - expect(find.text('Root 1'), findsOneWidget); - expect(find.text('Child 1:0'), findsOneWidget); - expect(find.text('Child 1:1'), findsOneWidget); - // Child node was added - expect(find.text('Added child'), findsOneWidget); - expect(find.text('Root 2'), findsOneWidget); - expect(find.text('Child 2:0'), findsNothing); - expect(find.text('Child 2:1'), findsNothing); - expect(find.text('Root 3'), findsOneWidget); - }, - ); + ), + ); + await tester.pump(); + + expect(find.text('Root 0'), findsOneWidget); + expect(find.text('Root 1'), findsOneWidget); + expect(find.text('Child 1:0'), findsOneWidget); + expect(find.text('Child 1:1'), findsOneWidget); + expect(find.text('Added child'), findsNothing); + expect(find.text('Root 2'), findsOneWidget); + expect(find.text('Child 2:0'), findsNothing); + expect(find.text('Child 2:1'), findsNothing); + expect(find.text('Root 3'), findsOneWidget); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pump(); + + expect(find.text('Root 0'), findsOneWidget); + expect(find.text('Root 1'), findsOneWidget); + expect(find.text('Child 1:0'), findsOneWidget); + expect(find.text('Child 1:1'), findsOneWidget); + // Child node was added + expect(find.text('Added child'), findsOneWidget); + expect(find.text('Root 2'), findsOneWidget); + expect(find.text('Child 2:0'), findsNothing); + expect(find.text('Child 2:1'), findsNothing); + expect(find.text('Root 3'), findsOneWidget); + }); test('should use the generic type for callbacks and builders', () { final treeView = TreeView( tree: simpleNodeSet, treeNodeBuilder: - ( - BuildContext context, - TreeViewNode node, - AnimationStyle animationStyle, - ) { - return TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, - ); + (BuildContext context, TreeViewNode node, AnimationStyle animationStyle) { + return TreeView.defaultTreeNodeBuilder(context, node, animationStyle); }, treeRowBuilder: (TreeViewNode node) { return TreeView.defaultTreeRowBuilder(node); @@ -729,11 +663,7 @@ void main() { final Widget child = GestureDetector( behavior: HitTestBehavior.translucent, onTap: () => controller.toggleNode(node), - child: TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, - ), + child: TreeView.defaultTreeNodeBuilder(context, node, animationStyle), ); return child; @@ -820,11 +750,7 @@ void main() { final Widget child = GestureDetector( behavior: HitTestBehavior.translucent, onTap: () => controller.toggleNode(node), - child: TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, - ), + child: TreeView.defaultTreeNodeBuilder(context, node, animationStyle), ); return child; @@ -850,9 +776,7 @@ void main() { }, ); - testWidgets('Expand then collapse with offscreen nodes (top)', ( - WidgetTester tester, - ) async { + testWidgets('Expand then collapse with offscreen nodes (top)', (WidgetTester tester) async { final verticalController = ScrollController(); final controller = TreeViewController(); addTearDown(verticalController.dispose); @@ -898,22 +822,13 @@ void main() { tree: tree, controller: controller, toggleAnimationStyle: AnimationStyle.noAnimation, - verticalDetails: ScrollableDetails.vertical( - controller: verticalController, - ), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), treeNodeBuilder: - ( - BuildContext context, - TreeViewNode node, - AnimationStyle animationStyle, - ) => GestureDetector( - onTap: () => controller.toggleNode(node), - child: TreeView.defaultTreeNodeBuilder( - context, - node, - animationStyle, - ), - ), + (BuildContext context, TreeViewNode node, AnimationStyle animationStyle) => + GestureDetector( + onTap: () => controller.toggleNode(node), + child: TreeView.defaultTreeNodeBuilder(context, node, animationStyle), + ), ), ), ); @@ -957,8 +872,7 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: (_) => - const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, @@ -983,8 +897,7 @@ void main() { delegate: TreeRowBuilderDelegate( rowCount: 0, nodeBuilder: (_, __) => const SizedBox(), - rowBuilder: (_) => - const TreeRow(extent: FixedTreeRowExtent(40.0)), + rowBuilder: (_) => const TreeRow(extent: FixedTreeRowExtent(40.0)), ), activeAnimations: const {}, rowDepths: const {}, @@ -1011,11 +924,7 @@ class TestOffset extends ViewportOffset { bool get allowImplicitScrolling => throw UnimplementedError(); @override - Future animateTo( - double to, { - required Duration duration, - required Curve curve, - }) { + Future animateTo(double to, {required Duration duration, required Curve curve}) { throw UnimplementedError(); } diff --git a/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart b/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart index ab01cd86b5fa..b5bae199bb0b 100644 --- a/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart +++ b/packages/url_launcher/url_launcher/example/integration_test/url_launcher_test.dart @@ -13,10 +13,7 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('canLaunch', (WidgetTester _) async { - expect( - await canLaunchUrl(Uri(scheme: 'randomscheme', path: 'a_path')), - false, - ); + expect(await canLaunchUrl(Uri(scheme: 'randomscheme', path: 'a_path')), false); // Generally all devices should have some default browser. expect(await canLaunchUrl(Uri(scheme: 'http', host: 'flutter.dev')), true); diff --git a/packages/url_launcher/url_launcher/example/lib/basic.dart b/packages/url_launcher/url_launcher/example/lib/basic.dart index f79dd5c3fcbb..4fe3d7b39e07 100644 --- a/packages/url_launcher/url_launcher/example/lib/basic.dart +++ b/packages/url_launcher/url_launcher/example/lib/basic.dart @@ -17,10 +17,7 @@ void main() => runApp( const MaterialApp( home: Material( child: Center( - child: ElevatedButton( - onPressed: _launchUrl, - child: Text('Show Flutter homepage'), - ), + child: ElevatedButton(onPressed: _launchUrl, child: Text('Show Flutter homepage')), ), ), ), diff --git a/packages/url_launcher/url_launcher/example/lib/encoding.dart b/packages/url_launcher/url_launcher/example/lib/encoding.dart index a2f541ebb457..d99249a942d6 100644 --- a/packages/url_launcher/url_launcher/example/lib/encoding.dart +++ b/packages/url_launcher/url_launcher/example/lib/encoding.dart @@ -21,6 +21,7 @@ String? encodeQueryParameters(Map params) { ) .join('&'); } + // #enddocregion encode-query-parameters void main() => runApp( @@ -29,10 +30,7 @@ void main() => runApp( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ - ElevatedButton( - onPressed: _composeMail, - child: Text('Compose an email'), - ), + ElevatedButton(onPressed: _composeMail, child: Text('Compose an email')), ], ), ), diff --git a/packages/url_launcher/url_launcher/example/lib/main.dart b/packages/url_launcher/url_launcher/example/lib/main.dart index 3d5e01c3545c..6edde7af3ca7 100644 --- a/packages/url_launcher/url_launcher/example/lib/main.dart +++ b/packages/url_launcher/url_launcher/example/lib/main.dart @@ -138,11 +138,7 @@ class _MyHomePageState extends State { Widget build(BuildContext context) { // onPressed calls using this URL are not gated on a 'canLaunch' check // because the assumption is that every device can launch a web URL. - final toLaunch = Uri( - scheme: 'https', - host: 'www.cylog.org', - path: 'headers/', - ); + final toLaunch = Uri(scheme: 'https', host: 'www.cylog.org', path: 'headers/'); return Scaffold( appBar: AppBar(title: Text(widget.title)), body: ListView( @@ -154,9 +150,7 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(16.0), child: TextField( onChanged: (String text) => _phone = text, - decoration: const InputDecoration( - hintText: 'Input the phone number to launch', - ), + decoration: const InputDecoration(hintText: 'Input the phone number to launch'), ), ), ElevatedButton( @@ -169,10 +163,7 @@ class _MyHomePageState extends State { ? const Text('Make phone call') : const Text('Calling not supported'), ), - Padding( - padding: const EdgeInsets.all(16.0), - child: Text(toLaunch.toString()), - ), + Padding(padding: const EdgeInsets.all(16.0), child: Text(toLaunch.toString())), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); diff --git a/packages/url_launcher/url_launcher/lib/src/legacy_api.dart b/packages/url_launcher/url_launcher/lib/src/legacy_api.dart index a7adefb58e76..035c04fb61ef 100644 --- a/packages/url_launcher/url_launcher/lib/src/legacy_api.dart +++ b/packages/url_launcher/url_launcher/lib/src/legacy_api.dart @@ -75,8 +75,7 @@ Future launch( String? webOnlyWindowName, }) async { final Uri? url = Uri.tryParse(urlString.trimLeft()); - final bool isWebURL = - url != null && (url.scheme == 'http' || url.scheme == 'https'); + final bool isWebURL = url != null && (url.scheme == 'http' || url.scheme == 'https'); if (((forceSafariVC ?? false) || forceWebView) && !isWebURL) { throw PlatformException( @@ -94,8 +93,7 @@ Future launch( ? _findImplicitRenderView() : null; if (renderViewToAdjust != null) { - previousAutomaticSystemUiAdjustment = - renderViewToAdjust.automaticSystemUiAdjustment; + previousAutomaticSystemUiAdjustment = renderViewToAdjust.automaticSystemUiAdjustment; renderViewToAdjust.automaticSystemUiAdjustment = false; SystemChrome.setSystemUIOverlayStyle( statusBarBrightness == Brightness.light @@ -116,8 +114,7 @@ Future launch( ); if (renderViewToAdjust != null) { - renderViewToAdjust.automaticSystemUiAdjustment = - previousAutomaticSystemUiAdjustment; + renderViewToAdjust.automaticSystemUiAdjustment = previousAutomaticSystemUiAdjustment; } return result; @@ -159,8 +156,7 @@ Future closeWebView() async { /// therefore keeping url_launcher forward-compatible with future versions of /// Flutter for longer). RenderView? _findImplicitRenderView() { - final FlutterView? implicitFlutterView = - WidgetsBinding.instance.platformDispatcher.implicitView; + final FlutterView? implicitFlutterView = WidgetsBinding.instance.platformDispatcher.implicitView; if (implicitFlutterView == null) { return null; } diff --git a/packages/url_launcher/url_launcher/lib/src/link.dart b/packages/url_launcher/url_launcher/lib/src/link.dart index 79c7351d3a6b..b053fd89e5b2 100644 --- a/packages/url_launcher/url_launcher/lib/src/link.dart +++ b/packages/url_launcher/url_launcher/lib/src/link.dart @@ -14,8 +14,7 @@ import 'url_launcher_uri.dart'; /// The function used to push routes to the Flutter framework. @visibleForTesting -Future Function(Object?, String) pushRouteToFrameworkFunction = - pushRouteNameToFramework; +Future Function(Object?, String) pushRouteToFrameworkFunction = pushRouteNameToFramework; /// A widget that renders a real link on the web, and uses WebViews in native /// platforms to open links. @@ -70,8 +69,7 @@ class Link extends StatelessWidget implements LinkInfo { bool get isDisabled => uri == null; LinkDelegate get _effectiveDelegate { - return UrlLauncherPlatform.instance.linkDelegate ?? - DefaultLinkDelegate.create; + return UrlLauncherPlatform.instance.linkDelegate ?? DefaultLinkDelegate.create; } @override @@ -125,9 +123,7 @@ class DefaultLinkDelegate extends StatelessWidget { try { success = await launchUrl( url, - mode: _useWebView - ? LaunchMode.inAppBrowserView - : LaunchMode.externalApplication, + mode: _useWebView ? LaunchMode.inAppBrowserView : LaunchMode.externalApplication, ); } on PlatformException { success = false; @@ -146,9 +142,6 @@ class DefaultLinkDelegate extends StatelessWidget { @override Widget build(BuildContext context) { - return link.builder( - context, - link.isDisabled ? null : () => _followLink(context), - ); + return link.builder(context, link.isDisabled ? null : () => _followLink(context)); } } diff --git a/packages/url_launcher/url_launcher/lib/src/type_conversion.dart b/packages/url_launcher/url_launcher/lib/src/type_conversion.dart index 8f79131958f7..dd03f3960dbf 100644 --- a/packages/url_launcher/url_launcher/lib/src/type_conversion.dart +++ b/packages/url_launcher/url_launcher/lib/src/type_conversion.dart @@ -8,9 +8,7 @@ import 'types.dart'; /// Converts an (app-facing) [WebViewConfiguration] to a (platform interface) /// [InAppWebViewConfiguration]. -InAppWebViewConfiguration convertWebViewConfiguration( - WebViewConfiguration config, -) { +InAppWebViewConfiguration convertWebViewConfiguration(WebViewConfiguration config) { return InAppWebViewConfiguration( enableJavaScript: config.enableJavaScript, enableDomStorage: config.enableDomStorage, @@ -20,9 +18,7 @@ InAppWebViewConfiguration convertWebViewConfiguration( /// Converts an (app-facing) [BrowserConfiguration] to a (platform interface) /// [InAppBrowserConfiguration]. -InAppBrowserConfiguration convertBrowserConfiguration( - BrowserConfiguration config, -) { +InAppBrowserConfiguration convertBrowserConfiguration(BrowserConfiguration config) { return InAppBrowserConfiguration(showTitle: config.showTitle); } diff --git a/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart b/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart index e03cc6136eee..f7a72652c721 100644 --- a/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart +++ b/packages/url_launcher/url_launcher/lib/src/url_launcher_string.dart @@ -26,8 +26,7 @@ Future launchUrlString( BrowserConfiguration browserConfiguration = const BrowserConfiguration(), String? webOnlyWindowName, }) async { - if ((mode == LaunchMode.inAppWebView || - mode == LaunchMode.inAppBrowserView) && + if ((mode == LaunchMode.inAppWebView || mode == LaunchMode.inAppBrowserView) && !(urlString.startsWith('https:') || urlString.startsWith('http:'))) { throw ArgumentError.value( urlString, diff --git a/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart b/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart index 591157e07bcc..86615833bdef 100644 --- a/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart +++ b/packages/url_launcher/url_launcher/lib/src/url_launcher_uri.dart @@ -43,8 +43,7 @@ Future launchUrl( BrowserConfiguration browserConfiguration = const BrowserConfiguration(), String? webOnlyWindowName, }) async { - if ((mode == LaunchMode.inAppWebView || - mode == LaunchMode.inAppBrowserView) && + if ((mode == LaunchMode.inAppWebView || mode == LaunchMode.inAppBrowserView) && !(url.scheme == 'https' || url.scheme == 'http')) { throw ArgumentError.value( url, diff --git a/packages/url_launcher/url_launcher/test/link_test.dart b/packages/url_launcher/url_launcher/test/link_test.dart index d8094b968fef..792b49adbdc3 100644 --- a/packages/url_launcher/url_launcher/test/link_test.dart +++ b/packages/url_launcher/url_launcher/test/link_test.dart @@ -109,9 +109,7 @@ void main() { expect(mock.launchCalled, isTrue); }); - testWidgets('pushes to framework for internal route names', ( - WidgetTester tester, - ) async { + testWidgets('pushes to framework for internal route names', (WidgetTester tester) async { final Uri uri = Uri.parse('/foo/bar'); FollowLink? followLink; diff --git a/packages/url_launcher/url_launcher/test/mocks/mock_url_launcher_platform.dart b/packages/url_launcher/url_launcher/test/mocks/mock_url_launcher_platform.dart index 45a5bf7bd366..51f24efdf4df 100644 --- a/packages/url_launcher/url_launcher/test/mocks/mock_url_launcher_platform.dart +++ b/packages/url_launcher/url_launcher/test/mocks/mock_url_launcher_platform.dart @@ -7,9 +7,7 @@ import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; -class MockUrlLauncher extends Fake - with MockPlatformInterfaceMixin - implements UrlLauncherPlatform { +class MockUrlLauncher extends Fake with MockPlatformInterfaceMixin implements UrlLauncherPlatform { String? url; PreferredLaunchMode? launchMode; bool? useSafariVC; diff --git a/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart b/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart index 49057b706e31..0c8dab65f8d3 100644 --- a/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart +++ b/packages/url_launcher/url_launcher/test/src/legacy_api_test.dart @@ -74,10 +74,7 @@ void main() { ) ..setResponse(true); expect( - await launch( - 'http://flutter.dev/', - headers: {'key': 'value'}, - ), + await launch('http://flutter.dev/', headers: {'key': 'value'}), isTrue, ); }); @@ -114,11 +111,7 @@ void main() { ) ..setResponse(true); expect( - await launch( - 'http://flutter.dev/', - forceSafariVC: false, - universalLinksOnly: true, - ), + await launch('http://flutter.dev/', forceSafariVC: false, universalLinksOnly: true), isTrue, ); }); @@ -155,11 +148,7 @@ void main() { ) ..setResponse(true); expect( - await launch( - 'http://flutter.dev/', - forceWebView: true, - enableJavaScript: true, - ), + await launch('http://flutter.dev/', forceWebView: true, enableJavaScript: true), isTrue, ); }); @@ -179,11 +168,7 @@ void main() { ) ..setResponse(true); expect( - await launch( - 'http://flutter.dev/', - forceWebView: true, - enableDomStorage: true, - ), + await launch('http://flutter.dev/', forceWebView: true, enableDomStorage: true), isTrue, ); }); @@ -226,46 +211,34 @@ void main() { showTitle: false, ) ..setResponse(true); - expect( - await launch('mailto:gmail-noreply@google.com?subject=Hello'), - isTrue, - ); + expect(await launch('mailto:gmail-noreply@google.com?subject=Hello'), isTrue); }); test('cannot send e-mail with forceSafariVC: true', () async { expect( - () async => launch( - 'mailto:gmail-noreply@google.com?subject=Hello', - forceSafariVC: true, - ), + () async => launch('mailto:gmail-noreply@google.com?subject=Hello', forceSafariVC: true), throwsA(isA()), ); }); test('cannot send e-mail with forceWebView: true', () async { + expect( + () async => launch('mailto:gmail-noreply@google.com?subject=Hello', forceWebView: true), + throwsA(isA()), + ); + }); + + test('cannot send e-mail with forceSafariVC: false and forceWebView: true', () async { expect( () async => launch( 'mailto:gmail-noreply@google.com?subject=Hello', + forceSafariVC: false, forceWebView: true, ), throwsA(isA()), ); }); - test( - 'cannot send e-mail with forceSafariVC: false and forceWebView: true', - () async { - expect( - () async => launch( - 'mailto:gmail-noreply@google.com?subject=Hello', - forceSafariVC: false, - forceWebView: true, - ), - throwsA(isA()), - ); - }, - ); - test('controls system UI when changing statusBarBrightness', () async { mock ..setLaunchExpectations( @@ -281,12 +254,9 @@ void main() { ) ..setResponse(true); - final TestWidgetsFlutterBinding binding = - TestWidgetsFlutterBinding.ensureInitialized(); + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final renderView = RenderView( - view: binding.platformDispatcher.implicitView!, - ); + final renderView = RenderView(view: binding.platformDispatcher.implicitView!); binding.addRenderView(renderView); renderView.automaticSystemUiAdjustment = true; final Future launchResult = launch( @@ -317,12 +287,9 @@ void main() { ) ..setResponse(true); - final TestWidgetsFlutterBinding binding = - TestWidgetsFlutterBinding.ensureInitialized(); + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); debugDefaultTargetPlatformOverride = TargetPlatform.android; - final renderView = RenderView( - view: binding.platformDispatcher.implicitView!, - ); + final renderView = RenderView(view: binding.platformDispatcher.implicitView!); binding.addRenderView(renderView); expect(renderView.automaticSystemUiAdjustment, true); final Future launchResult = launch( @@ -341,8 +308,7 @@ void main() { test('open non-parseable url', () async { mock ..setLaunchExpectations( - url: - 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', + url: 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', useSafariVC: false, useWebView: false, enableJavaScript: false, @@ -354,9 +320,7 @@ void main() { ) ..setResponse(true); expect( - await launch( - 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1', - ), + await launch('rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1'), isTrue, ); }); diff --git a/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart b/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart index 978eef0cb8e6..41dcbe83ef0e 100644 --- a/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart +++ b/packages/url_launcher/url_launcher/test/src/url_launcher_string_test.dart @@ -120,10 +120,7 @@ void main() { showTitle: false, ) ..setResponse(true); - expect( - await launchUrlString(urlString, mode: LaunchMode.inAppWebView), - isTrue, - ); + expect(await launchUrlString(urlString, mode: LaunchMode.inAppWebView), isTrue); }); test('external browser', () async { @@ -140,10 +137,7 @@ void main() { showTitle: false, ) ..setResponse(true); - expect( - await launchUrlString(urlString, mode: LaunchMode.externalApplication), - isTrue, - ); + expect(await launchUrlString(urlString, mode: LaunchMode.externalApplication), isTrue); }); test('in-app browser', () async { @@ -160,10 +154,7 @@ void main() { showTitle: false, ) ..setResponse(true); - expect( - await launchUrlString(urlString, mode: LaunchMode.inAppBrowserView), - isTrue, - ); + expect(await launchUrlString(urlString, mode: LaunchMode.inAppBrowserView), isTrue); }); test('in-app browser with title', () async { @@ -205,10 +196,7 @@ void main() { ) ..setResponse(true); expect( - await launchUrlString( - urlString, - mode: LaunchMode.externalNonBrowserApplication, - ), + await launchUrlString(urlString, mode: LaunchMode.externalNonBrowserApplication), isTrue, ); }); @@ -231,9 +219,7 @@ void main() { await launchUrlString( urlString, mode: LaunchMode.inAppWebView, - webViewConfiguration: const WebViewConfiguration( - enableJavaScript: false, - ), + webViewConfiguration: const WebViewConfiguration(enableJavaScript: false), ), isTrue, ); @@ -257,9 +243,7 @@ void main() { await launchUrlString( urlString, mode: LaunchMode.inAppWebView, - webViewConfiguration: const WebViewConfiguration( - enableDomStorage: false, - ), + webViewConfiguration: const WebViewConfiguration(enableDomStorage: false), ), isTrue, ); @@ -293,8 +277,7 @@ void main() { test('cannot launch a non-web URL in a webview', () async { expect( - () async => - launchUrlString('tel:555-555-5555', mode: LaunchMode.inAppWebView), + () async => launchUrlString('tel:555-555-5555', mode: LaunchMode.inAppWebView), throwsA(isA()), ); }); @@ -318,8 +301,7 @@ void main() { test('allows non-parsable url', () async { // Not a valid Dart [Uri], but a valid URL on at least some platforms. - const urlString = - 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1'; + const urlString = 'rdp://full%20address=s:mypc:3389&audiomode=i:2&disable%20themes=i:1'; mock ..setLaunchExpectations( url: urlString, diff --git a/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart b/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart index c2949a5b9cd7..2d8bd2912af0 100644 --- a/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart +++ b/packages/url_launcher/url_launcher/test/src/url_launcher_uri_test.dart @@ -142,10 +142,7 @@ void main() { showTitle: false, ) ..setResponse(true); - expect( - await launchUrl(url, mode: LaunchMode.externalApplication), - isTrue, - ); + expect(await launchUrl(url, mode: LaunchMode.externalApplication), isTrue); }); test('external non-browser only', () async { @@ -162,10 +159,7 @@ void main() { showTitle: false, ) ..setResponse(true); - expect( - await launchUrl(url, mode: LaunchMode.externalNonBrowserApplication), - isTrue, - ); + expect(await launchUrl(url, mode: LaunchMode.externalNonBrowserApplication), isTrue); }); test('in-app webview without javascript', () async { @@ -186,9 +180,7 @@ void main() { await launchUrl( url, mode: LaunchMode.inAppWebView, - webViewConfiguration: const WebViewConfiguration( - enableJavaScript: false, - ), + webViewConfiguration: const WebViewConfiguration(enableJavaScript: false), ), isTrue, ); @@ -236,9 +228,7 @@ void main() { await launchUrl( url, mode: LaunchMode.inAppWebView, - webViewConfiguration: const WebViewConfiguration( - enableDomStorage: false, - ), + webViewConfiguration: const WebViewConfiguration(enableDomStorage: false), ), isTrue, ); @@ -322,20 +312,14 @@ void main() { test('handles returning true', () async { mock.setResponse(true); - expect( - await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), - true, - ); + expect(await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), true); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); test('handles returning false', () async { mock.setResponse(false); - expect( - await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), - false, - ); + expect(await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView), false); expect(mock.launchMode, PreferredLaunchMode.inAppBrowserView); }); }); diff --git a/packages/url_launcher/url_launcher_android/example/lib/main.dart b/packages/url_launcher/url_launcher_android/example/lib/main.dart index 71c4e5fbfac9..489373baf527 100644 --- a/packages/url_launcher/url_launcher_android/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_android/example/lib/main.dart @@ -51,9 +51,7 @@ class _MyHomePageState extends State { }); }); // Check for Android Custom Tab support. - launcher.supportsMode(PreferredLaunchMode.inAppBrowserView).then(( - bool result, - ) { + launcher.supportsMode(PreferredLaunchMode.inAppBrowserView).then((bool result) { setState(() { _hasCustomTabSupport = result; }); @@ -72,9 +70,7 @@ class _MyHomePageState extends State { Future _launchInNonBrowserExternalApp(String url) async { if (!await launcher.launchUrl( url, - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication, - ), + const LaunchOptions(mode: PreferredLaunchMode.externalNonBrowserApplication), )) { throw Exception('Could not launch $url'); } @@ -117,9 +113,7 @@ class _MyHomePageState extends State { url, const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: InAppWebViewConfiguration( - enableJavaScript: false, - ), + webViewConfiguration: InAppWebViewConfiguration(enableJavaScript: false), ), )) { throw Exception('Could not launch $url'); @@ -131,9 +125,7 @@ class _MyHomePageState extends State { url, const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: InAppWebViewConfiguration( - enableDomStorage: false, - ), + webViewConfiguration: InAppWebViewConfiguration(enableDomStorage: false), ), )) { throw Exception('Could not launch $url'); @@ -171,9 +163,7 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(16.0), child: TextField( onChanged: (String text) => _phone = text, - decoration: const InputDecoration( - hintText: 'Input the phone number to launch', - ), + decoration: const InputDecoration(hintText: 'Input the phone number to launch'), ), ), ElevatedButton( @@ -186,10 +176,7 @@ class _MyHomePageState extends State { ? const Text('Make phone call') : const Text('Calling not supported'), ), - const Padding( - padding: EdgeInsets.all(16.0), - child: Text(toLaunch), - ), + const Padding(padding: EdgeInsets.all(16.0), child: Text(toLaunch)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); diff --git a/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart index 213dc8273f6f..265462271d32 100644 --- a/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_android/lib/src/messages.g.dart @@ -49,9 +49,7 @@ bool _deepEquals(Object? a, Object? b) { } if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { if (a.length != b.length) { @@ -222,13 +220,11 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + UrlLauncherApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -244,9 +240,7 @@ class UrlLauncherApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -258,11 +252,7 @@ class UrlLauncherApi { } /// Opens the URL externally, returning true if successful. - Future launchUrl( - String url, - Map headers, - bool requireNonBrowser, - ) async { + Future launchUrl(String url, Map headers, bool requireNonBrowser) async { final pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_android.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; final pigeonVar_channel = BasicMessageChannel( @@ -270,9 +260,11 @@ class UrlLauncherApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url, headers, requireNonBrowser], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + url, + headers, + requireNonBrowser, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -298,9 +290,12 @@ class UrlLauncherApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url, allowCustomTab, webViewOptions, browserOptions], - ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + url, + allowCustomTab, + webViewOptions, + browserOptions, + ]); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( @@ -342,10 +337,6 @@ class UrlLauncherApi { final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final pigeonVar_replyList = await pigeonVar_sendFuture as List?; - _extractReplyValueOrThrow( - pigeonVar_replyList, - pigeonVar_channelName, - isNullValid: true, - ); + _extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true); } } diff --git a/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart b/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart index dbe301f799f5..8096919533f3 100644 --- a/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart +++ b/packages/url_launcher/url_launcher_android/lib/url_launcher_android.dart @@ -12,8 +12,7 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for Android. class UrlLauncherAndroid extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherAndroid({@visibleForTesting UrlLauncherApi? api}) - : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherAndroid({@visibleForTesting UrlLauncherApi? api}) : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; diff --git a/packages/url_launcher/url_launcher_android/pigeons/messages.dart b/packages/url_launcher/url_launcher_android/pigeons/messages.dart index badef0ab2f16..1e8c6e7d196d 100644 --- a/packages/url_launcher/url_launcher_android/pigeons/messages.dart +++ b/packages/url_launcher/url_launcher_android/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - kotlinOut: - 'android/src/main/kotlin/io/flutter/plugins/urllauncher/Messages.kt', + kotlinOut: 'android/src/main/kotlin/io/flutter/plugins/urllauncher/Messages.kt', kotlinOptions: KotlinOptions(package: 'io.flutter.plugins.urllauncher'), copyrightHeader: 'pigeons/copyright.txt', ), @@ -40,11 +39,7 @@ abstract class UrlLauncherApi { bool canLaunchUrl(String url); /// Opens the URL externally, returning true if successful. - bool launchUrl( - String url, - Map headers, - bool requireNonBrowser, - ); + bool launchUrl(String url, Map headers, bool requireNonBrowser); /// Opens the URL in an in-app Custom Tab or WebView, returning true if it /// opens successfully. diff --git a/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart b/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart index 5a561679a2ef..8a15163fbc83 100644 --- a/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart +++ b/packages/url_launcher/url_launcher_android/test/url_launcher_android_test.dart @@ -180,9 +180,7 @@ void main() { final launcher = UrlLauncherAndroid(api: api); await launcher.launchUrl( 'http://example.com/', - const LaunchOptions( - browserConfiguration: InAppBrowserConfiguration(showTitle: true), - ), + const LaunchOptions(browserConfiguration: InAppBrowserConfiguration(showTitle: true)), ); expect(api.passedBrowserOptions?.showTitle, true); @@ -259,9 +257,7 @@ void main() { final launcher = UrlLauncherAndroid(api: api); final bool launched = await launcher.launchUrl( 'http://example.com/', - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication, - ), + const LaunchOptions(mode: PreferredLaunchMode.externalNonBrowserApplication), ); expect(launched, true); expect(api.usedWebView, false); @@ -312,9 +308,7 @@ void main() { 'http://example.com/', const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: InAppWebViewConfiguration( - enableJavaScript: false, - ), + webViewConfiguration: InAppWebViewConfiguration(enableJavaScript: false), ), ); @@ -327,9 +321,7 @@ void main() { 'http://example.com/', const LaunchOptions( mode: PreferredLaunchMode.inAppWebView, - webViewConfiguration: InAppWebViewConfiguration( - enableDomStorage: false, - ), + webViewConfiguration: InAppWebViewConfiguration(enableDomStorage: false), ), ); @@ -381,10 +373,7 @@ void main() { group('launch with platform default', () { test('uses custom tabs for http', () async { final launcher = UrlLauncherAndroid(api: api); - final bool launched = await launcher.launchUrl( - 'http://example.com/', - const LaunchOptions(), - ); + final bool launched = await launcher.launchUrl('http://example.com/', const LaunchOptions()); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); @@ -392,10 +381,7 @@ void main() { test('uses custom tabs for https', () async { final launcher = UrlLauncherAndroid(api: api); - final bool launched = await launcher.launchUrl( - 'https://example.com/', - const LaunchOptions(), - ); + final bool launched = await launcher.launchUrl('https://example.com/', const LaunchOptions()); expect(launched, true); expect(api.usedWebView, true); expect(api.allowedCustomTab, true); @@ -415,76 +401,46 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final launcher = UrlLauncherAndroid(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final launcher = UrlLauncherAndroid(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns true for in app web view', () async { final launcher = UrlLauncherAndroid(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), true); }); test('returns true for in app browser view when available', () async { final launcher = UrlLauncherAndroid(api: api); api.hasCustomTabSupport = true; - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), true); }); test('returns false for in app browser view when not available', () async { final launcher = UrlLauncherAndroid(api: api); api.hasCustomTabSupport = false; - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); }); }); group('supportsCloseForMode', () { test('returns true for in app web view', () async { final launcher = UrlLauncherAndroid(api: api); - expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), - true, - ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), true); }); test('returns false for other modes', () async { final launcher = UrlLauncherAndroid(api: api); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.externalApplication), false); expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalApplication, - ), - false, - ); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - false, - ); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.inAppBrowserView, - ), + await launcher.supportsCloseForMode(PreferredLaunchMode.externalNonBrowserApplication), false, ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), false); }); }); } @@ -510,11 +466,7 @@ class _FakeUrlLauncherApi implements UrlLauncherApi { } @override - Future launchUrl( - String url, - Map headers, - bool requireNonBrowser, - ) async { + Future launchUrl(String url, Map headers, bool requireNonBrowser) async { passedWebViewOptions = WebViewOptions( enableJavaScript: false, enableDomStorage: false, diff --git a/packages/url_launcher/url_launcher_ios/example/lib/main.dart b/packages/url_launcher/url_launcher_ios/example/lib/main.dart index b7ae99328bc0..3e265800cf37 100644 --- a/packages/url_launcher/url_launcher_ios/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_ios/example/lib/main.dart @@ -78,9 +78,7 @@ class _MyHomePageState extends State { final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance; final bool nativeAppLaunchSucceeded = await launcher.launchUrl( url, - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication, - ), + const LaunchOptions(mode: PreferredLaunchMode.externalNonBrowserApplication), ); if (!nativeAppLaunchSucceeded) { await launcher.launchUrl( @@ -119,9 +117,7 @@ class _MyHomePageState extends State { padding: const EdgeInsets.all(16.0), child: TextField( onChanged: (String text) => _phone = text, - decoration: const InputDecoration( - hintText: 'Input the phone number to launch', - ), + decoration: const InputDecoration(hintText: 'Input the phone number to launch'), ), ), ElevatedButton( @@ -134,10 +130,7 @@ class _MyHomePageState extends State { ? const Text('Make phone call') : const Text('Calling not supported'), ), - const Padding( - padding: EdgeInsets.all(16.0), - child: Text(toLaunch), - ), + const Padding(padding: EdgeInsets.all(16.0), child: Text(toLaunch)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); diff --git a/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart index f668ea34c31d..de2c8fea204e 100644 --- a/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_ios/lib/src/messages.g.dart @@ -85,13 +85,11 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + UrlLauncherApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -102,17 +100,13 @@ class UrlLauncherApi { Future canLaunchUrl(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -135,17 +129,16 @@ class UrlLauncherApi { Future launchUrl(String url, bool universalLinksOnly) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url, universalLinksOnly], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([ + url, + universalLinksOnly, + ]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -169,17 +162,13 @@ class UrlLauncherApi { Future openUrlInSafariViewController(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.openUrlInSafariViewController$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -202,15 +191,13 @@ class UrlLauncherApi { Future closeSafariViewController() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.closeSafariViewController$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart b/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart index db202b398b58..4a4d66d00fab 100644 --- a/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart +++ b/packages/url_launcher/url_launcher_ios/lib/url_launcher_ios.dart @@ -12,8 +12,7 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for iOS. class UrlLauncherIOS extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherIOS({@visibleForTesting UrlLauncherApi? api}) - : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherIOS({@visibleForTesting UrlLauncherApi? api}) : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; @@ -91,10 +90,7 @@ class UrlLauncherIOS extends UrlLauncherPlatform { } if (inApp) { - return _mapInAppLoadResult( - await _hostApi.openUrlInSafariViewController(url), - url: url, - ); + return _mapInAppLoadResult(await _hostApi.openUrlInSafariViewController(url), url: url); } else { return _mapLaunchResult( await _hostApi.launchUrl( @@ -125,8 +121,7 @@ class UrlLauncherIOS extends UrlLauncherPlatform { @override Future supportsCloseForMode(PreferredLaunchMode mode) async { - return mode == PreferredLaunchMode.inAppWebView || - mode == PreferredLaunchMode.inAppBrowserView; + return mode == PreferredLaunchMode.inAppWebView || mode == PreferredLaunchMode.inAppBrowserView; } bool _mapLaunchResult(LaunchResult result) { @@ -162,10 +157,7 @@ class UrlLauncherIOS extends UrlLauncherPlatform { // are a defacto part of the API) is for compatibility with the previous // native implementation. PlatformException _invalidUrlException() { - throw PlatformException( - code: 'argument_error', - message: 'Unable to parse URL', - ); + throw PlatformException(code: 'argument_error', message: 'Unable to parse URL'); } // TODO(stuartmorgan): Remove this as part of standardizing error handling. @@ -175,10 +167,7 @@ class UrlLauncherIOS extends UrlLauncherPlatform { // are a defacto part of the API) is for compatibility with the previous // native implementation. PlatformException _failedSafariViewControllerLoadException(String url) { - throw PlatformException( - code: 'Error', - message: 'Error while launching $url', - ); + throw PlatformException(code: 'Error', message: 'Error while launching $url'); } // TODO(stuartmorgan): Remove this as part of standardizing error handling. @@ -187,9 +176,6 @@ class UrlLauncherIOS extends UrlLauncherPlatform { // This PlatformException is designed to match the pattern of the pre-existing // exceptions above. PlatformException _noUIException() { - throw PlatformException( - code: 'no_ui_available', - message: 'No view controller available', - ); + throw PlatformException(code: 'no_ui_available', message: 'No view controller available'); } } diff --git a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart index a5669f9ff9e3..36b18c277a1f 100644 --- a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart +++ b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.dart @@ -30,25 +30,19 @@ void main() { group('canLaunch', () { test('handles success', () async { - when( - api.canLaunchUrl(_webUrl), - ).thenAnswer((_) async => LaunchResult.success); + when(api.canLaunchUrl(_webUrl)).thenAnswer((_) async => LaunchResult.success); final launcher = UrlLauncherIOS(api: api); expect(await launcher.canLaunch(_webUrl), true); }); test('handles failure', () async { - when( - api.canLaunchUrl(_webUrl), - ).thenAnswer((_) async => LaunchResult.failure); + when(api.canLaunchUrl(_webUrl)).thenAnswer((_) async => LaunchResult.failure); final launcher = UrlLauncherIOS(api: api); expect(await launcher.canLaunch(_webUrl), false); }); test('throws PlatformException for invalid URL', () async { - when( - api.canLaunchUrl(_webUrl), - ).thenAnswer((_) async => LaunchResult.invalidUrl); + when(api.canLaunchUrl(_webUrl)).thenAnswer((_) async => LaunchResult.invalidUrl); final launcher = UrlLauncherIOS(api: api); await expectLater( launcher.canLaunch(_webUrl), @@ -65,9 +59,7 @@ void main() { group('legacy launch', () { test('handles success', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.success); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.success); final launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( @@ -85,9 +77,7 @@ void main() { }); test('handles failure', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.failure); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.failure); final launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( @@ -105,9 +95,7 @@ void main() { }); test('throws PlatformException for invalid URL', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.invalidUrl); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.invalidUrl); final launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launch( @@ -150,9 +138,7 @@ void main() { }); test('universal links only is handled', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.success); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.success); final launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( @@ -170,9 +156,7 @@ void main() { }); test('disallowing SafariVC is handled', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.success); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.success); final launcher = UrlLauncherIOS(api: api); expect( await launcher.launch( @@ -198,9 +182,7 @@ void main() { group('launch without webview', () { test('calls through', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.success); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.success); final launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( _webUrl, @@ -211,9 +193,7 @@ void main() { }); test('throws PlatformException for invalid URL', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.invalidUrl); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.invalidUrl); final launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launchUrl( @@ -264,10 +244,7 @@ void main() { ).thenAnswer((_) async => InAppLoadResult.invalidUrl); final launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launchUrl( - _webUrl, - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), - ), + launcher.launchUrl(_webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), throwsA( isA().having( (PlatformException e) => e.code, @@ -284,10 +261,7 @@ void main() { ).thenAnswer((_) async => InAppLoadResult.noUI); final launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launchUrl( - _webUrl, - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), - ), + launcher.launchUrl(_webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), throwsA( isA().having( (PlatformException e) => e.code, @@ -304,48 +278,31 @@ void main() { ).thenAnswer((_) async => InAppLoadResult.failedToLoad); final launcher = UrlLauncherIOS(api: api); await expectLater( - launcher.launchUrl( - _webUrl, - const LaunchOptions(mode: PreferredLaunchMode.inAppWebView), - ), - throwsA( - isA().having( - (PlatformException e) => e.code, - 'code', - 'Error', - ), - ), + launcher.launchUrl(_webUrl, const LaunchOptions(mode: PreferredLaunchMode.inAppWebView)), + throwsA(isA().having((PlatformException e) => e.code, 'code', 'Error')), ); }); }); group('launch with universal links', () { test('calls through', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.success); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.success); final launcher = UrlLauncherIOS(api: api); final bool launched = await launcher.launchUrl( _webUrl, - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication, - ), + const LaunchOptions(mode: PreferredLaunchMode.externalNonBrowserApplication), ); expect(launched, true); verifyNever(api.openUrlInSafariViewController(any)); }); test('throws PlatformException for invalid URL', () async { - when( - api.launchUrl(_webUrl, any), - ).thenAnswer((_) async => LaunchResult.invalidUrl); + when(api.launchUrl(_webUrl, any)).thenAnswer((_) async => LaunchResult.invalidUrl); final launcher = UrlLauncherIOS(api: api); await expectLater( launcher.launchUrl( _webUrl, - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication, - ), + const LaunchOptions(mode: PreferredLaunchMode.externalNonBrowserApplication), ), throwsA( isA().having( @@ -365,10 +322,7 @@ void main() { api.openUrlInSafariViewController(httpUrl), ).thenAnswer((_) async => InAppLoadResult.success); final launcher = UrlLauncherIOS(api: api); - final bool launched = await launcher.launchUrl( - httpUrl, - const LaunchOptions(), - ); + final bool launched = await launcher.launchUrl(httpUrl, const LaunchOptions()); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); @@ -379,24 +333,16 @@ void main() { api.openUrlInSafariViewController(httpsUrl), ).thenAnswer((_) async => InAppLoadResult.success); final launcher = UrlLauncherIOS(api: api); - final bool launched = await launcher.launchUrl( - httpsUrl, - const LaunchOptions(), - ); + final bool launched = await launcher.launchUrl(httpsUrl, const LaunchOptions()); expect(launched, true); verifyNever(api.launchUrl(any, any)); }); test('uses standard external for other schemes', () async { const nonWebUrl = 'supportedcustomscheme://example.com/'; - when( - api.launchUrl(nonWebUrl, any), - ).thenAnswer((_) async => LaunchResult.success); + when(api.launchUrl(nonWebUrl, any)).thenAnswer((_) async => LaunchResult.success); final launcher = UrlLauncherIOS(api: api); - final bool launched = await launcher.launchUrl( - nonWebUrl, - const LaunchOptions(), - ); + final bool launched = await launcher.launchUrl(nonWebUrl, const LaunchOptions()); expect(launched, true); verifyNever(api.openUrlInSafariViewController(any)); }); @@ -405,78 +351,46 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final launcher = UrlLauncherIOS(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final launcher = UrlLauncherIOS(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns true for external non-browser application', () async { final launcher = UrlLauncherIOS(api: api); - expect( - await launcher.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalNonBrowserApplication), true); }); test('returns true for in app web view', () async { final launcher = UrlLauncherIOS(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), true); }); test('returns true for in app browser view', () async { final launcher = UrlLauncherIOS(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), true); }); }); group('supportsCloseForMode', () { test('returns true for in app web view', () async { final launcher = UrlLauncherIOS(api: api); - expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), - true, - ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), true); }); test('returns true for in app browser view', () async { final launcher = UrlLauncherIOS(api: api); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.inAppBrowserView, - ), - true, - ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), true); }); test('returns false for other modes', () async { final launcher = UrlLauncherIOS(api: api); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.externalApplication), false); expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalApplication, - ), - false, - ); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), + await launcher.supportsCloseForMode(PreferredLaunchMode.externalNonBrowserApplication), false, ); }); diff --git a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart index d3aa97bb6df2..4bd9607f108e 100644 --- a/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart +++ b/packages/url_launcher/url_launcher_ios/test/url_launcher_ios_test.mocks.dart @@ -31,55 +31,34 @@ class MockUrlLauncherApi extends _i1.Mock implements _i2.UrlLauncherApi { } @override - String get pigeonVar_messageChannelSuffix => - (super.noSuchMethod( - Invocation.getter(#pigeonVar_messageChannelSuffix), - returnValue: _i3.dummyValue( - this, - Invocation.getter(#pigeonVar_messageChannelSuffix), - ), - ) - as String); + String get pigeonVar_messageChannelSuffix => (super.noSuchMethod( + Invocation.getter(#pigeonVar_messageChannelSuffix), + returnValue: _i3.dummyValue(this, Invocation.getter(#pigeonVar_messageChannelSuffix)), + ) as String); @override - _i4.Future<_i2.LaunchResult> canLaunchUrl(String? url) => - (super.noSuchMethod( - Invocation.method(#canLaunchUrl, [url]), - returnValue: _i4.Future<_i2.LaunchResult>.value( - _i2.LaunchResult.success, - ), - ) - as _i4.Future<_i2.LaunchResult>); + _i4.Future<_i2.LaunchResult> canLaunchUrl(String? url) => (super.noSuchMethod( + Invocation.method(#canLaunchUrl, [url]), + returnValue: _i4.Future<_i2.LaunchResult>.value(_i2.LaunchResult.success), + ) as _i4.Future<_i2.LaunchResult>); @override - _i4.Future<_i2.LaunchResult> launchUrl( - String? url, - bool? universalLinksOnly, - ) => + _i4.Future<_i2.LaunchResult> launchUrl(String? url, bool? universalLinksOnly) => (super.noSuchMethod( - Invocation.method(#launchUrl, [url, universalLinksOnly]), - returnValue: _i4.Future<_i2.LaunchResult>.value( - _i2.LaunchResult.success, - ), - ) - as _i4.Future<_i2.LaunchResult>); + Invocation.method(#launchUrl, [url, universalLinksOnly]), + returnValue: _i4.Future<_i2.LaunchResult>.value(_i2.LaunchResult.success), + ) as _i4.Future<_i2.LaunchResult>); @override - _i4.Future<_i2.InAppLoadResult> openUrlInSafariViewController(String? url) => - (super.noSuchMethod( - Invocation.method(#openUrlInSafariViewController, [url]), - returnValue: _i4.Future<_i2.InAppLoadResult>.value( - _i2.InAppLoadResult.success, - ), - ) - as _i4.Future<_i2.InAppLoadResult>); + _i4.Future<_i2.InAppLoadResult> openUrlInSafariViewController(String? url) => (super.noSuchMethod( + Invocation.method(#openUrlInSafariViewController, [url]), + returnValue: _i4.Future<_i2.InAppLoadResult>.value(_i2.InAppLoadResult.success), + ) as _i4.Future<_i2.InAppLoadResult>); @override - _i4.Future closeSafariViewController() => - (super.noSuchMethod( - Invocation.method(#closeSafariViewController, []), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) - as _i4.Future); + _i4.Future closeSafariViewController() => (super.noSuchMethod( + Invocation.method(#closeSafariViewController, []), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) as _i4.Future); } diff --git a/packages/url_launcher/url_launcher_linux/example/lib/main.dart b/packages/url_launcher/url_launcher_linux/example/lib/main.dart index 8ca238f3f519..ee9db9266c71 100644 --- a/packages/url_launcher/url_launcher_linux/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_linux/example/lib/main.dart @@ -70,10 +70,7 @@ class _MyHomePageState extends State { Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Padding( - padding: EdgeInsets.all(16.0), - child: Text(toLaunch), - ), + const Padding(padding: EdgeInsets.all(16.0), child: Text(toLaunch)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); diff --git a/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart index 6187ef54deba..772c2b45299a 100644 --- a/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_linux/lib/src/messages.g.dart @@ -43,13 +43,11 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + UrlLauncherApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -60,17 +58,13 @@ class UrlLauncherApi { Future canLaunchUrl(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_linux.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -93,17 +87,13 @@ class UrlLauncherApi { Future launchUrl(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_linux.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart b/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart index 6e7acfa07883..455f8f52f6f3 100644 --- a/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart +++ b/packages/url_launcher/url_launcher_linux/lib/url_launcher_linux.dart @@ -14,8 +14,7 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for Linux. class UrlLauncherLinux extends UrlLauncherPlatform { /// Creates a new URL launcher instance. - UrlLauncherLinux({@visibleForTesting UrlLauncherApi? api}) - : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherLinux({@visibleForTesting UrlLauncherApi? api}) : _hostApi = api ?? UrlLauncherApi(); /// Registers this class as the default instance of [UrlLauncherPlatform]. static void registerWith() { @@ -55,10 +54,7 @@ class UrlLauncherLinux extends UrlLauncherPlatform { // TODO(stuartmorgan): Standardize errors across the entire plugin, // instead of using PlatformException. This preserves the pre-Pigeon // behavior of the C code returning this error response. - throw PlatformException( - code: 'Launch Error', - message: 'Failed to launch URL: $error', - ); + throw PlatformException(code: 'Launch Error', message: 'Failed to launch URL: $error'); } return true; } diff --git a/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart b/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart index 8b6ee6e27280..8f567c3845e5 100644 --- a/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart +++ b/packages/url_launcher/url_launcher_linux/test/url_launcher_linux_test.dart @@ -84,10 +84,7 @@ void main() { final launcher = UrlLauncherLinux(api: api); const url = 'http://example.com/'; - final bool launched = await launcher.launchUrl( - url, - const LaunchOptions(), - ); + final bool launched = await launcher.launchUrl(url, const LaunchOptions()); expect(launched, true); expect(api.argument, url); @@ -115,53 +112,29 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final launcher = UrlLauncherLinux(); - expect( - await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final launcher = UrlLauncherLinux(); - expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns false for other modes', () async { final launcher = UrlLauncherLinux(); expect( - await launcher.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + await launcher.supportsMode(PreferredLaunchMode.externalNonBrowserApplication), false, ); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); }); }); test('supportsCloseForMode returns false', () async { final launcher = UrlLauncherLinux(); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.platformDefault, - ), - false, - ); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalApplication, - ), - false, - ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), false); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.externalApplication), false); }); }); } diff --git a/packages/url_launcher/url_launcher_macos/example/lib/main.dart b/packages/url_launcher/url_launcher_macos/example/lib/main.dart index 8ca238f3f519..ee9db9266c71 100644 --- a/packages/url_launcher/url_launcher_macos/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_macos/example/lib/main.dart @@ -70,10 +70,7 @@ class _MyHomePageState extends State { Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Padding( - padding: EdgeInsets.all(16.0), - child: Text(toLaunch), - ), + const Padding(padding: EdgeInsets.all(16.0), child: Text(toLaunch)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); diff --git a/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart index 8c3a2fdbd421..74a41cc8c692 100644 --- a/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_macos/lib/src/messages.g.dart @@ -21,9 +21,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -60,10 +58,7 @@ class UrlLauncherBoolResult { static UrlLauncherBoolResult decode(Object result) { result as List; - return UrlLauncherBoolResult( - value: result[0]! as bool, - error: result[1] as UrlLauncherError?, - ); + return UrlLauncherBoolResult(value: result[0]! as bool, error: result[1] as UrlLauncherError?); } @override @@ -119,13 +114,11 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + UrlLauncherApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -136,17 +129,13 @@ class UrlLauncherApi { Future canLaunchUrl(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_macos.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -169,17 +158,13 @@ class UrlLauncherApi { Future launchUrl(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_macos.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart b/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart index 68e7eb64196e..0fc1e0a99272 100644 --- a/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart +++ b/packages/url_launcher/url_launcher_macos/lib/url_launcher_macos.dart @@ -12,8 +12,7 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for macOS. class UrlLauncherMacOS extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherMacOS({@visibleForTesting UrlLauncherApi? api}) - : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherMacOS({@visibleForTesting UrlLauncherApi? api}) : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; diff --git a/packages/url_launcher/url_launcher_macos/pigeons/messages.dart b/packages/url_launcher/url_launcher_macos/pigeons/messages.dart index a421f1899cfa..67e601c6cb66 100644 --- a/packages/url_launcher/url_launcher_macos/pigeons/messages.dart +++ b/packages/url_launcher/url_launcher_macos/pigeons/messages.dart @@ -7,8 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - swiftOut: - 'macos/url_launcher_macos/Sources/url_launcher_macos/messages.g.swift', + swiftOut: 'macos/url_launcher_macos/Sources/url_launcher_macos/messages.g.swift', copyrightHeader: 'pigeons/copyright.txt', ), ) diff --git a/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart b/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart index d1fb014975ac..70f3d705f3d3 100644 --- a/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart +++ b/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart @@ -34,10 +34,7 @@ void main() { test('invalid URL returns a PlatformException', () async { final launcher = UrlLauncherMacOS(api: api); - await expectLater( - launcher.canLaunch('invalid://u r l'), - throwsA(isA()), - ); + await expectLater(launcher.canLaunch('invalid://u r l'), throwsA(isA())); }); test('passes unexpected PlatformExceptions through', () async { @@ -118,53 +115,29 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final launcher = UrlLauncherMacOS(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final launcher = UrlLauncherMacOS(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns false for other modes', () async { final launcher = UrlLauncherMacOS(api: api); expect( - await launcher.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), + await launcher.supportsMode(PreferredLaunchMode.externalNonBrowserApplication), false, ); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); }); }); test('supportsCloseForMode returns false', () async { final launcher = UrlLauncherMacOS(api: api); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.platformDefault, - ), - false, - ); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalApplication, - ), - false, - ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), false); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.externalApplication), false); }); }); } @@ -190,10 +163,7 @@ class _FakeUrlLauncherApi implements UrlLauncherApi { case 'https': return UrlLauncherBoolResult(value: true); case 'invalid': - return UrlLauncherBoolResult( - value: false, - error: UrlLauncherError.invalidUrl, - ); + return UrlLauncherBoolResult(value: false, error: UrlLauncherError.invalidUrl); case 'unexpectedthrow': throw PlatformException(code: 'argument_error'); default: diff --git a/packages/url_launcher/url_launcher_platform_interface/lib/link.dart b/packages/url_launcher/url_launcher_platform_interface/lib/link.dart index 028a7b1e7a42..08d5b2e4b4b8 100644 --- a/packages/url_launcher/url_launcher_platform_interface/lib/link.dart +++ b/packages/url_launcher/url_launcher_platform_interface/lib/link.dart @@ -14,8 +14,7 @@ typedef FollowLink = Future Function(); /// Signature for a builder function passed to the [Link] widget to construct /// the widget tree under it. -typedef LinkWidgetBuilder = - Widget Function(BuildContext context, FollowLink? followLink); +typedef LinkWidgetBuilder = Widget Function(BuildContext context, FollowLink? followLink); /// Signature for a delegate function to build the [Link] widget. typedef LinkDelegate = Widget Function(LinkInfo linkWidget); @@ -41,9 +40,7 @@ class LinkTarget { /// /// iOS, on the other hand, defaults to [self] for web URLs, and [blank] for /// non-web URLs. - static const LinkTarget defaultTarget = LinkTarget._( - debugLabel: 'defaultTarget', - ); + static const LinkTarget defaultTarget = LinkTarget._(debugLabel: 'defaultTarget'); /// On the web, this opens the link in the same tab where the flutter app is /// running. @@ -89,10 +86,7 @@ Future pushRouteNameToFramework(Object? _, String routeName) { ui.channelBuffers.push( 'flutter/navigation', _codec.encodeMethodCall( - MethodCall('pushRouteInformation', { - 'location': routeName, - 'state': null, - }), + MethodCall('pushRouteInformation', {'location': routeName, 'state': null}), ), completer.complete, ); diff --git a/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart b/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart index 42e3416b440f..cebcbc88f803 100644 --- a/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart +++ b/packages/url_launcher/url_launcher_platform_interface/lib/src/url_launcher_platform.dart @@ -83,8 +83,7 @@ abstract class UrlLauncherPlatform extends PlatformInterface { useWebView: useWebView, enableJavaScript: options.webViewConfiguration.enableJavaScript, enableDomStorage: options.webViewConfiguration.enableDomStorage, - universalLinksOnly: - options.mode == PreferredLaunchMode.externalNonBrowserApplication, + universalLinksOnly: options.mode == PreferredLaunchMode.externalNonBrowserApplication, headers: options.webViewConfiguration.headers, webOnlyWindowName: options.webOnlyWindowName, ); diff --git a/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart index 76a01d89c1e3..de64e6112b17 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/launch_options_test.dart @@ -6,26 +6,15 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { - test( - 'LaunchOptions have default InAppBrowserConfiguration when not passed', - () { - expect( - const LaunchOptions().browserConfiguration, - const InAppBrowserConfiguration(), - ); - }, - ); + test('LaunchOptions have default InAppBrowserConfiguration when not passed', () { + expect(const LaunchOptions().browserConfiguration, const InAppBrowserConfiguration()); + }); - test( - 'passing non-default InAppBrowserConfiguration to LaunchOptions works', - () { - const browserConfiguration = InAppBrowserConfiguration(showTitle: true); + test('passing non-default InAppBrowserConfiguration to LaunchOptions works', () { + const browserConfiguration = InAppBrowserConfiguration(showTitle: true); - const launchOptions = LaunchOptions( - browserConfiguration: browserConfiguration, - ); + const launchOptions = LaunchOptions(browserConfiguration: browserConfiguration); - expect(launchOptions.browserConfiguration, browserConfiguration); - }, - ); + expect(launchOptions.browserConfiguration, browserConfiguration); + }); } diff --git a/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart index ce0503757ac4..63c366b1a6e6 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/link_test.dart @@ -52,9 +52,7 @@ void main() { class _RouteInformationParser extends RouteInformationParser { @override - Future parseRouteInformation( - RouteInformation routeInformation, - ) { + Future parseRouteInformation(RouteInformation routeInformation) { return SynchronousFuture(routeInformation); } @@ -64,8 +62,7 @@ class _RouteInformationParser extends RouteInformationParser { } } -class _RouteDelegate extends RouterDelegate - with ChangeNotifier { +class _RouteDelegate extends RouterDelegate with ChangeNotifier { final Queue _history = Queue(); @override diff --git a/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart index 05ead0c0f275..5b7234cdca3c 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/method_channel_url_launcher_test.dart @@ -47,14 +47,16 @@ void main() { group('$MethodChannelUrlLauncher', () { const channel = MethodChannel('plugins.flutter.io/url_launcher'); final log = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (MethodCall methodCall) async { - log.add(methodCall); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (MethodCall methodCall) async { + log.add(methodCall); - // Return null explicitly instead of relying on the implicit null - // returned by the method channel if no return statement is specified. - return null; - }); + // Return null explicitly instead of relying on the implicit null + // returned by the method channel if no return statement is specified. + return null; + }, + ); final launcher = MethodChannelUrlLauncher(); @@ -65,10 +67,7 @@ void main() { test('canLaunch', () async { await launcher.canLaunch('http://example.com/'); expect(log, [ - isMethodCall( - 'canLaunch', - arguments: {'url': 'http://example.com/'}, - ), + isMethodCall('canLaunch', arguments: {'url': 'http://example.com/'}), ]); }); @@ -311,8 +310,7 @@ class UrlLauncherPlatformMock extends Mock with MockPlatformInterfaceMixin implements UrlLauncherPlatform {} -class ImplementsUrlLauncherPlatform extends Mock - implements UrlLauncherPlatform {} +class ImplementsUrlLauncherPlatform extends Mock implements UrlLauncherPlatform {} class ExtendsUrlLauncherPlatform extends UrlLauncherPlatform { @override diff --git a/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart b/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart index 9aa4a8bc896b..c59e0851d62b 100644 --- a/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart +++ b/packages/url_launcher/url_launcher_platform_interface/test/url_launcher_platform_test.dart @@ -44,50 +44,42 @@ class CapturingUrlLauncher extends UrlLauncherPlatform { } void main() { - test( - 'launchUrl calls through to launch with default options for web URL', - () async { - final launcher = CapturingUrlLauncher(); - - await launcher.launchUrl('https://flutter.dev', const LaunchOptions()); - - expect(launcher.url, 'https://flutter.dev'); - expect(launcher.useSafariVC, true); - expect(launcher.useWebView, true); - expect(launcher.enableJavaScript, true); - expect(launcher.enableDomStorage, true); - expect(launcher.universalLinksOnly, false); - expect(launcher.headers, isEmpty); - expect(launcher.webOnlyWindowName, null); - }, - ); - - test( - 'launchUrl calls through to launch with default options for non-web URL', - () async { - final launcher = CapturingUrlLauncher(); - - await launcher.launchUrl('tel:123456789', const LaunchOptions()); - - expect(launcher.url, 'tel:123456789'); - expect(launcher.useSafariVC, false); - expect(launcher.useWebView, false); - expect(launcher.enableJavaScript, true); - expect(launcher.enableDomStorage, true); - expect(launcher.universalLinksOnly, false); - expect(launcher.headers, isEmpty); - expect(launcher.webOnlyWindowName, null); - }, - ); + test('launchUrl calls through to launch with default options for web URL', () async { + final launcher = CapturingUrlLauncher(); + + await launcher.launchUrl('https://flutter.dev', const LaunchOptions()); + + expect(launcher.url, 'https://flutter.dev'); + expect(launcher.useSafariVC, true); + expect(launcher.useWebView, true); + expect(launcher.enableJavaScript, true); + expect(launcher.enableDomStorage, true); + expect(launcher.universalLinksOnly, false); + expect(launcher.headers, isEmpty); + expect(launcher.webOnlyWindowName, null); + }); + + test('launchUrl calls through to launch with default options for non-web URL', () async { + final launcher = CapturingUrlLauncher(); + + await launcher.launchUrl('tel:123456789', const LaunchOptions()); + + expect(launcher.url, 'tel:123456789'); + expect(launcher.useSafariVC, false); + expect(launcher.useWebView, false); + expect(launcher.enableJavaScript, true); + expect(launcher.enableDomStorage, true); + expect(launcher.universalLinksOnly, false); + expect(launcher.headers, isEmpty); + expect(launcher.webOnlyWindowName, null); + }); test('launchUrl calls through to launch with universal links', () async { final launcher = CapturingUrlLauncher(); await launcher.launchUrl( 'https://flutter.dev', - const LaunchOptions( - mode: PreferredLaunchMode.externalNonBrowserApplication, - ), + const LaunchOptions(mode: PreferredLaunchMode.externalNonBrowserApplication), ); expect(launcher.url, 'https://flutter.dev'); @@ -100,98 +92,62 @@ void main() { expect(launcher.webOnlyWindowName, null); }); - test( - 'launchUrl calls through to launch with all non-default options', - () async { - final launcher = CapturingUrlLauncher(); - - await launcher.launchUrl( - 'https://flutter.dev', - const LaunchOptions( - mode: PreferredLaunchMode.externalApplication, - webViewConfiguration: InAppWebViewConfiguration( - enableJavaScript: false, - enableDomStorage: false, - headers: {'foo': 'bar'}, - ), - webOnlyWindowName: 'a_name', + test('launchUrl calls through to launch with all non-default options', () async { + final launcher = CapturingUrlLauncher(); + + await launcher.launchUrl( + 'https://flutter.dev', + const LaunchOptions( + mode: PreferredLaunchMode.externalApplication, + webViewConfiguration: InAppWebViewConfiguration( + enableJavaScript: false, + enableDomStorage: false, + headers: {'foo': 'bar'}, ), - ); - - expect(launcher.url, 'https://flutter.dev'); - expect(launcher.useSafariVC, false); - expect(launcher.useWebView, false); - expect(launcher.enableJavaScript, false); - expect(launcher.enableDomStorage, false); - expect(launcher.universalLinksOnly, false); - expect(launcher.headers['foo'], 'bar'); - expect(launcher.webOnlyWindowName, 'a_name'); - }, - ); + webOnlyWindowName: 'a_name', + ), + ); + + expect(launcher.url, 'https://flutter.dev'); + expect(launcher.useSafariVC, false); + expect(launcher.useWebView, false); + expect(launcher.enableJavaScript, false); + expect(launcher.enableDomStorage, false); + expect(launcher.universalLinksOnly, false); + expect(launcher.headers['foo'], 'bar'); + expect(launcher.webOnlyWindowName, 'a_name'); + }); test('supportsMode defaults to true for platform default', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); - expect( - await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('supportsMode defaults to false for all specific values', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); - expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - false, - ); - expect( - await launcher.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), - false, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalApplication), false); + expect(await launcher.supportsMode(PreferredLaunchMode.externalNonBrowserApplication), false); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); }); test('supportsCloseForMode defaults to true for in-app web views', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); - expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), - true, - ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.inAppWebView), true); }); test('supportsCloseForMode defaults to false for all other values', () async { final UrlLauncherPlatform launcher = CapturingUrlLauncher(); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.externalApplication), false); expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalApplication, - ), - false, - ); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - false, - ); - expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), - false, - ); - expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), + await launcher.supportsCloseForMode(PreferredLaunchMode.externalNonBrowserApplication), false, ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.inAppBrowserView), false); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), false); }); } diff --git a/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart b/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart index 80410bcfd12e..69dbc1e3a9c5 100644 --- a/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart +++ b/packages/url_launcher/url_launcher_web/example/integration_test/link_widget_test.dart @@ -38,9 +38,7 @@ void main() { }); group('Link Widget', () { - testWidgets('creates anchor with correct attributes', ( - WidgetTester tester, - ) async { + testWidgets('creates anchor with correct attributes', (WidgetTester tester) async { final Uri uri = Uri.parse('http://foobar/example?q=1'); await tester.pumpWidget( Directionality( @@ -106,10 +104,7 @@ void main() { // Check that internal route properly prepares using the default // [UrlStrategy] - expect( - anchor.getAttribute('href'), - ui_web.urlStrategy?.prepareExternalUrl(uri3.toString()), - ); + expect(anchor.getAttribute('href'), ui_web.urlStrategy?.prepareExternalUrl(uri3.toString())); expect(anchor.getAttribute('target'), '_self'); }); @@ -200,11 +195,7 @@ void main() { await tester.pumpAndSettle(); await tester.pump(); - await tester.scrollUntilVisible( - find.text('#${itemCount - 1}'), - 800, - maxScrolls: 1000, - ); + await tester.scrollUntilVisible(find.text('#${itemCount - 1}'), 800, maxScrolls: 1000); }); testWidgets('MergeSemantics is always present to avoid duplicate nodes', ( @@ -259,9 +250,7 @@ void main() { UrlLauncherPlatform.instance = originalPlugin; }); - testWidgets('click to navigate to internal link', ( - WidgetTester tester, - ) async { + testWidgets('click to navigate to internal link', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -301,9 +290,7 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('keydown to navigate to internal link', ( - WidgetTester tester, - ) async { + testWidgets('keydown to navigate to internal link', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -343,9 +330,7 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('click to navigate to external link', ( - WidgetTester tester, - ) async { + testWidgets('click to navigate to external link', (WidgetTester tester) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; @@ -383,9 +368,7 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('keydown to navigate to external link', ( - WidgetTester tester, - ) async { + testWidgets('keydown to navigate to external link', (WidgetTester tester) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; @@ -431,10 +414,8 @@ void main() { await tester.pumpWidget( MaterialApp( routes: { - '/foobar1': (BuildContext context) => - const Text('Internal route 1'), - '/foobar2': (BuildContext context) => - const Text('Internal route 2'), + '/foobar1': (BuildContext context) => const Text('Internal route 1'), + '/foobar2': (BuildContext context) => const Text('Internal route 2'), }, home: Column( children: [ @@ -469,11 +450,8 @@ void main() { expect(pushedRouteNames, isEmpty); expect(testPlugin.launches, isEmpty); - final [ - html.Element anchor1, - html.Element anchor2, - ...List rest, - ] = _findAllAnchors(); + final [html.Element anchor1, html.Element anchor2, ...List rest] = + _findAllAnchors(); expect(rest, isEmpty); await followLinkCallback2!(); @@ -504,9 +482,7 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('trigger signals are reset after a delay', ( - WidgetTester tester, - ) async { + testWidgets('trigger signals are reset after a delay', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -570,9 +546,7 @@ void main() { expect(event3.defaultPrevented, isTrue); }); - testWidgets('ignores clicks on non-Flutter link', ( - WidgetTester tester, - ) async { + testWidgets('ignores clicks on non-Flutter link', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -652,9 +626,7 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('ignores keydown when it is a modifier key', ( - WidgetTester tester, - ) async { + testWidgets('ignores keydown when it is a modifier key', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -716,9 +688,7 @@ void main() { UrlLauncherPlatform.instance = originalPlugin; }); - testWidgets('click to navigate to internal link', ( - WidgetTester tester, - ) async { + testWidgets('click to navigate to internal link', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -758,9 +728,7 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('keydown to navigate to internal link', ( - WidgetTester tester, - ) async { + testWidgets('keydown to navigate to internal link', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -800,9 +768,7 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('click to navigate to external link', ( - WidgetTester tester, - ) async { + testWidgets('click to navigate to external link', (WidgetTester tester) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; @@ -840,9 +806,7 @@ void main() { expect(event.defaultPrevented, isFalse); }); - testWidgets('keydown to navigate to external link', ( - WidgetTester tester, - ) async { + testWidgets('keydown to navigate to external link', (WidgetTester tester) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; @@ -894,9 +858,7 @@ void main() { UrlLauncherPlatform.instance = originalPlugin; }); - testWidgets('produces the correct semantics tree with a button', ( - WidgetTester tester, - ) async { + testWidgets('produces the correct semantics tree with a button', (WidgetTester tester) async { final SemanticsHandle semanticsHandle = tester.ensureSemantics(); final Key linkKey = UniqueKey(); @@ -910,10 +872,7 @@ void main() { uri: Uri.parse('https://foobar/example?q=1'), target: LinkTarget.blank, builder: (BuildContext context, FollowLink? followLink) { - return ElevatedButton( - onPressed: followLink, - child: const Text('Button Link Text'), - ); + return ElevatedButton(onPressed: followLink, child: const Text('Button Link Text')); }, ), ), @@ -923,10 +882,7 @@ void main() { final Finder linkFinder = find.byKey(linkKey); expect( tester.getSemantics( - find.descendant( - of: linkFinder, - matching: find.byType(Semantics).first, - ), + find.descendant(of: linkFinder, matching: find.byType(Semantics).first), ), matchesSemantics( isLink: true, @@ -945,9 +901,7 @@ void main() { semanticsHandle.dispose(); }); - testWidgets('produces the correct semantics tree with text', ( - WidgetTester tester, - ) async { + testWidgets('produces the correct semantics tree with text', (WidgetTester tester) async { final SemanticsHandle semanticsHandle = tester.ensureSemantics(); final Key linkKey = UniqueKey(); @@ -961,10 +915,7 @@ void main() { uri: Uri.parse('https://foobar/example?q=1'), target: LinkTarget.blank, builder: (BuildContext context, FollowLink? followLink) { - return GestureDetector( - onTap: followLink, - child: const Text('Link Text'), - ); + return GestureDetector(onTap: followLink, child: const Text('Link Text')); }, ), ), @@ -974,9 +925,7 @@ void main() { final Finder linkFinder = find.byKey(linkKey); expect( tester.getSemantics( - find - .descendant(of: linkFinder, matching: find.byType(Semantics)) - .first, + find.descendant(of: linkFinder, matching: find.byType(Semantics)).first, ), matchesSemantics( isLink: true, @@ -990,9 +939,7 @@ void main() { semanticsHandle.dispose(); }); - testWidgets('handles clicks on semantic link with a button', ( - WidgetTester tester, - ) async { + testWidgets('handles clicks on semantic link with a button', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -1008,10 +955,7 @@ void main() { target: LinkTarget.blank, builder: (BuildContext context, FollowLink? followLink) { followLinkCallback = followLink; - return ElevatedButton( - onPressed: () {}, - child: const Text('My Button Link'), - ); + return ElevatedButton(onPressed: () {}, child: const Text('My Button Link')); }, ), ), @@ -1021,9 +965,7 @@ void main() { await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = html.document.createElement( - 'flt-semantics-host', - ); + final html.Element semanticsHost = html.document.createElement('flt-semantics-host'); html.document.body!.append(semanticsHost); final html.Element semanticsAnchor = html.document.createElement('a') ..setAttribute('id', 'flt-semantic-node-99') @@ -1034,10 +976,9 @@ void main() { 'flt-semantics-container', ); semanticsAnchor.append(semanticsContainer); - final html.Element semanticsButton = - html.document.createElement('flt-semantics') - ..setAttribute('role', 'button') - ..textContent = 'My Button Link'; + final html.Element semanticsButton = html.document.createElement('flt-semantics') + ..setAttribute('role', 'button') + ..textContent = 'My Button Link'; semanticsContainer.append(semanticsButton); expect(pushedRouteNames, isEmpty); @@ -1061,9 +1002,7 @@ void main() { expect(event2.defaultPrevented, isTrue); }); - testWidgets('handles clicks on semantic link with text', ( - WidgetTester tester, - ) async { + testWidgets('handles clicks on semantic link with text', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -1079,10 +1018,7 @@ void main() { target: LinkTarget.blank, builder: (BuildContext context, FollowLink? followLink) { followLinkCallback = followLink; - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); + return GestureDetector(onTap: () {}, child: const Text('My Link')); }, ), ), @@ -1092,9 +1028,7 @@ void main() { await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = html.document.createElement( - 'flt-semantics-host', - ); + final html.Element semanticsHost = html.document.createElement('flt-semantics-host'); html.document.body!.append(semanticsHost); final html.Element semanticsAnchor = html.document.createElement('a') ..setAttribute('id', 'flt-semantic-node-99') @@ -1114,9 +1048,7 @@ void main() { expect(event.defaultPrevented, isTrue); }); - testWidgets('handles debounced clicks on semantic link', ( - WidgetTester tester, - ) async { + testWidgets('handles debounced clicks on semantic link', (WidgetTester tester) async { final Uri uri = Uri.parse('https://flutter.dev'); FollowLink? followLinkCallback; @@ -1129,10 +1061,7 @@ void main() { target: LinkTarget.blank, builder: (BuildContext context, FollowLink? followLink) { followLinkCallback = followLink; - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); + return GestureDetector(onTap: () {}, child: const Text('My Link')); }, ), ), @@ -1142,9 +1071,7 @@ void main() { await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = html.document.createElement( - 'flt-semantics-host', - ); + final html.Element semanticsHost = html.document.createElement('flt-semantics-host'); html.document.body!.append(semanticsHost); final html.Element semanticsAnchor = html.document.createElement('a') ..setAttribute('id', 'flt-semantic-node-99') @@ -1185,10 +1112,7 @@ void main() { uri: uri, target: LinkTarget.blank, builder: (BuildContext context, FollowLink? followLink) { - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); + return GestureDetector(onTap: () {}, child: const Text('My Link')); }, ), ), @@ -1198,9 +1122,7 @@ void main() { await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = html.document.createElement( - 'flt-semantics-host', - ); + final html.Element semanticsHost = html.document.createElement('flt-semantics-host'); html.document.body!.append(semanticsHost); final html.Element semanticsAnchor = html.document.createElement('a') ..setAttribute('id', 'flt-semantic-node-99') @@ -1227,9 +1149,7 @@ void main() { // TODO(mdebbar): Remove this test after the engine PR [1] makes it to stable. // [1] https://github.com/flutter/engine/pull/52720 - testWidgets('handles clicks on (old) semantic link with a button', ( - WidgetTester tester, - ) async { + testWidgets('handles clicks on (old) semantic link with a button', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -1254,9 +1174,7 @@ void main() { await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = html.document.createElement( - 'flt-semantics-host', - ); + final html.Element semanticsHost = html.document.createElement('flt-semantics-host'); html.document.body!.append(semanticsHost); final html.Element semanticsAnchor = html.document.createElement('a') ..setAttribute('id', 'flt-semantic-node-99') @@ -1266,10 +1184,9 @@ void main() { 'flt-semantics-container', ); semanticsAnchor.append(semanticsContainer); - final html.Element semanticsButton = - html.document.createElement('flt-semantics') - ..setAttribute('role', 'button') - ..textContent = 'My Button'; + final html.Element semanticsButton = html.document.createElement('flt-semantics') + ..setAttribute('role', 'button') + ..textContent = 'My Button'; semanticsContainer.append(semanticsButton); expect(pushedRouteNames, isEmpty); @@ -1287,9 +1204,7 @@ void main() { // TODO(mdebbar): Remove this test after the engine PR [1] makes it to stable. // [1] https://github.com/flutter/engine/pull/52720 - testWidgets('handles clicks on (old) semantic link with text', ( - WidgetTester tester, - ) async { + testWidgets('handles clicks on (old) semantic link with text', (WidgetTester tester) async { final Uri uri = Uri.parse('/foobar'); FollowLink? followLinkCallback; @@ -1304,10 +1219,7 @@ void main() { target: LinkTarget.blank, builder: (BuildContext context, FollowLink? followLink) { followLinkCallback = followLink; - return GestureDetector( - onTap: () {}, - child: const Text('My Link'), - ); + return GestureDetector(onTap: () {}, child: const Text('My Link')); }, ), ), @@ -1317,9 +1229,7 @@ void main() { await tester.pumpAndSettle(); await tester.pump(); - final html.Element semanticsHost = html.document.createElement( - 'flt-semantics-host', - ); + final html.Element semanticsHost = html.document.createElement('flt-semantics-host'); html.document.body!.append(semanticsHost); final html.Element semanticsAnchor = html.document.createElement('a') ..setAttribute('id', 'flt-semantic-node-99') @@ -1374,10 +1284,7 @@ html.MouseEvent _simulateClick(html.Element target, {bool metaKey = false}) { return mouseEvent; } -html.KeyboardEvent _simulateKeydown( - html.Element target, { - bool metaKey = false, -}) { +html.KeyboardEvent _simulateKeydown(html.Element target, {bool metaKey = false}) { final keydownEvent = html.KeyboardEvent( 'keydown', html.KeyboardEventInit( @@ -1392,11 +1299,7 @@ html.KeyboardEvent _simulateKeydown( } class TestLinkInfo extends LinkInfo { - TestLinkInfo({ - required this.uri, - required this.target, - required this.builder, - }); + TestLinkInfo({required this.uri, required this.target, required this.builder}); @override final LinkWidgetBuilder builder; diff --git a/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart b/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart index 9c1200eb2bcc..95bffb8dc092 100644 --- a/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart +++ b/packages/url_launcher/url_launcher_web/example/integration_test/url_launcher_web_test.dart @@ -41,8 +41,7 @@ void main() { mockNavigator = MockNavigator(); jsMockWindow = createJSInteropWrapper(mockWindow) as html.Window; - final jsMockNavigator = - createJSInteropWrapper(mockNavigator) as html.Navigator; + final jsMockNavigator = createJSInteropWrapper(mockNavigator) as html.Navigator; when(mockWindow.navigator).thenReturn(jsMockNavigator); @@ -66,10 +65,7 @@ void main() { }); testWidgets('"mailto" URLs -> true', (WidgetTester _) async { - expect( - plugin.canLaunch('mailto:name@mydomain.com'), - completion(isTrue), - ); + expect(plugin.canLaunch('mailto:name@mydomain.com'), completion(isTrue)); }); testWidgets('"tel" URLs -> true', (WidgetTester _) async { @@ -77,10 +73,7 @@ void main() { }); testWidgets('"sms" URLs -> true', (WidgetTester _) async { - expect( - plugin.canLaunch('sms:+19725551212?body=hello%20there'), - completion(isTrue), - ); + expect(plugin.canLaunch('sms:+19725551212?body=hello%20there'), completion(isTrue)); }); testWidgets('"javascript" URLs -> false', (WidgetTester _) async { @@ -102,114 +95,61 @@ void main() { }); testWidgets('launching a "sms" returns true', (WidgetTester _) async { - expect( - plugin.launch('sms:+19725551212?body=hello%20there'), - completion(isTrue), - ); + expect(plugin.launch('sms:+19725551212?body=hello%20there'), completion(isTrue)); }); - testWidgets('launching a "javascript" returns false', ( - WidgetTester _, - ) async { + testWidgets('launching a "javascript" returns false', (WidgetTester _) async { expect(plugin.launch('javascript:alert("1")'), completion(isFalse)); }); - testWidgets('launching a unknown sceheme returns true', ( - WidgetTester _, - ) async { + testWidgets('launching a unknown sceheme returns true', (WidgetTester _) async { expect(plugin.launch('foo:bar'), completion(isTrue)); }); }); group('openNewWindow', () { - testWidgets('http urls should be launched in a new window', ( - WidgetTester _, - ) async { + testWidgets('http urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('http://www.google.com'); - verify( - mockWindow.open('http://www.google.com', '', 'noopener,noreferrer'), - ); + verify(mockWindow.open('http://www.google.com', '', 'noopener,noreferrer')); }); - testWidgets('https urls should be launched in a new window', ( - WidgetTester _, - ) async { + testWidgets('https urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('https://www.google.com'); - verify( - mockWindow.open('https://www.google.com', '', 'noopener,noreferrer'), - ); + verify(mockWindow.open('https://www.google.com', '', 'noopener,noreferrer')); }); - testWidgets('mailto urls should be launched on a new window', ( - WidgetTester _, - ) async { + testWidgets('mailto urls should be launched on a new window', (WidgetTester _) async { plugin.openNewWindow('mailto:name@mydomain.com'); - verify( - mockWindow.open( - 'mailto:name@mydomain.com', - '', - 'noopener,noreferrer', - ), - ); + verify(mockWindow.open('mailto:name@mydomain.com', '', 'noopener,noreferrer')); }); - testWidgets('tel urls should be launched on a new window', ( - WidgetTester _, - ) async { + testWidgets('tel urls should be launched on a new window', (WidgetTester _) async { plugin.openNewWindow('tel:5551234567'); verify(mockWindow.open('tel:5551234567', '', 'noopener,noreferrer')); }); - testWidgets('sms urls should be launched on a new window', ( - WidgetTester _, - ) async { + testWidgets('sms urls should be launched on a new window', (WidgetTester _) async { plugin.openNewWindow('sms:+19725551212?body=hello%20there'); - verify( - mockWindow.open( - 'sms:+19725551212?body=hello%20there', - '', - 'noopener,noreferrer', - ), - ); + verify(mockWindow.open('sms:+19725551212?body=hello%20there', '', 'noopener,noreferrer')); + }); + testWidgets('setting webOnlyLinkTarget as _self opens the url in the same tab', ( + WidgetTester _, + ) async { + plugin.openNewWindow('https://www.google.com', webOnlyWindowName: '_self'); + verify(mockWindow.open('https://www.google.com', '_self', 'noopener,noreferrer')); }); - testWidgets( - 'setting webOnlyLinkTarget as _self opens the url in the same tab', - (WidgetTester _) async { - plugin.openNewWindow( - 'https://www.google.com', - webOnlyWindowName: '_self', - ); - verify( - mockWindow.open( - 'https://www.google.com', - '_self', - 'noopener,noreferrer', - ), - ); - }, - ); - testWidgets( - 'setting webOnlyLinkTarget as _blank opens the url in a new tab', - (WidgetTester _) async { - plugin.openNewWindow( - 'https://www.google.com', - webOnlyWindowName: '_blank', - ); - verify( - mockWindow.open( - 'https://www.google.com', - '_blank', - 'noopener,noreferrer', - ), - ); - }, - ); + testWidgets('setting webOnlyLinkTarget as _blank opens the url in a new tab', ( + WidgetTester _, + ) async { + plugin.openNewWindow('https://www.google.com', webOnlyWindowName: '_blank'); + verify(mockWindow.open('https://www.google.com', '_blank', 'noopener,noreferrer')); + }); group('Safari', () { setUp(() { @@ -220,121 +160,64 @@ void main() { plugin = UrlLauncherPlugin(debugWindow: jsMockWindow); }); - testWidgets('http urls should be launched in a new window', ( - WidgetTester _, - ) async { + testWidgets('http urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('http://www.google.com'); - verify( - mockWindow.open('http://www.google.com', '', 'noopener,noreferrer'), - ); + verify(mockWindow.open('http://www.google.com', '', 'noopener,noreferrer')); }); - testWidgets('https urls should be launched in a new window', ( - WidgetTester _, - ) async { + testWidgets('https urls should be launched in a new window', (WidgetTester _) async { plugin.openNewWindow('https://www.google.com'); - verify( - mockWindow.open( - 'https://www.google.com', - '', - 'noopener,noreferrer', - ), - ); + verify(mockWindow.open('https://www.google.com', '', 'noopener,noreferrer')); }); - testWidgets('mailto urls should be launched on the same window', ( - WidgetTester _, - ) async { + testWidgets('mailto urls should be launched on the same window', (WidgetTester _) async { plugin.openNewWindow('mailto:name@mydomain.com'); - verify( - mockWindow.open( - 'mailto:name@mydomain.com', - '_top', - 'noopener,noreferrer', - ), - ); + verify(mockWindow.open('mailto:name@mydomain.com', '_top', 'noopener,noreferrer')); }); - testWidgets('tel urls should be launched on the same window', ( - WidgetTester _, - ) async { + testWidgets('tel urls should be launched on the same window', (WidgetTester _) async { plugin.openNewWindow('tel:5551234567'); - verify( - mockWindow.open('tel:5551234567', '_top', 'noopener,noreferrer'), - ); + verify(mockWindow.open('tel:5551234567', '_top', 'noopener,noreferrer')); }); - testWidgets('sms urls should be launched on the same window', ( - WidgetTester _, - ) async { + testWidgets('sms urls should be launched on the same window', (WidgetTester _) async { plugin.openNewWindow('sms:+19725551212?body=hello%20there'); verify( - mockWindow.open( - 'sms:+19725551212?body=hello%20there', - '_top', - 'noopener,noreferrer', - ), + mockWindow.open('sms:+19725551212?body=hello%20there', '_top', 'noopener,noreferrer'), ); }); - testWidgets( - 'mailto urls should use _blank if webOnlyWindowName is set as _blank', - (WidgetTester _) async { - plugin.openNewWindow( - 'mailto:name@mydomain.com', - webOnlyWindowName: '_blank', - ); - verify( - mockWindow.open( - 'mailto:name@mydomain.com', - '_blank', - 'noopener,noreferrer', - ), - ); - }, - ); + testWidgets('mailto urls should use _blank if webOnlyWindowName is set as _blank', ( + WidgetTester _, + ) async { + plugin.openNewWindow('mailto:name@mydomain.com', webOnlyWindowName: '_blank'); + verify(mockWindow.open('mailto:name@mydomain.com', '_blank', 'noopener,noreferrer')); + }); }); }); group('supportsMode', () { testWidgets('returns true for platformDefault', (WidgetTester _) async { - expect( - plugin.supportsMode(PreferredLaunchMode.platformDefault), - completion(isTrue), - ); + expect(plugin.supportsMode(PreferredLaunchMode.platformDefault), completion(isTrue)); }); testWidgets('returns false for other modes', (WidgetTester _) async { + expect(plugin.supportsMode(PreferredLaunchMode.externalApplication), completion(isFalse)); expect( - plugin.supportsMode(PreferredLaunchMode.externalApplication), - completion(isFalse), - ); - expect( - plugin.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - completion(isFalse), - ); - expect( - plugin.supportsMode(PreferredLaunchMode.inAppBrowserView), - completion(isFalse), - ); - expect( - plugin.supportsMode(PreferredLaunchMode.inAppWebView), + plugin.supportsMode(PreferredLaunchMode.externalNonBrowserApplication), completion(isFalse), ); + expect(plugin.supportsMode(PreferredLaunchMode.inAppBrowserView), completion(isFalse)); + expect(plugin.supportsMode(PreferredLaunchMode.inAppWebView), completion(isFalse)); }); }); testWidgets('supportsCloseForMode returns false', (WidgetTester _) async { - expect( - plugin.supportsCloseForMode(PreferredLaunchMode.platformDefault), - completion(isFalse), - ); + expect(plugin.supportsCloseForMode(PreferredLaunchMode.platformDefault), completion(isFalse)); }); }); } diff --git a/packages/url_launcher/url_launcher_web/lib/src/link.dart b/packages/url_launcher/url_launcher_web/lib/src/link.dart index e4c708456d73..eeb09ead1bc3 100644 --- a/packages/url_launcher/url_launcher_web/lib/src/link.dart +++ b/packages/url_launcher/url_launcher_web/lib/src/link.dart @@ -30,8 +30,8 @@ HtmlViewFactory get linkViewFactory => LinkViewController._viewFactory; /// The function used to push routes to the Flutter framework. @visibleForTesting -Future Function(String) pushRouteToFrameworkFunction = - (String routeName) => pushRouteNameToFramework(null, routeName); +Future Function(String) pushRouteToFrameworkFunction = (String routeName) => + pushRouteNameToFramework(null, routeName); /// The delegate for building the [Link] widget on the web. /// @@ -85,8 +85,7 @@ class WebLinkDelegateState extends State { @override void initState() { super.initState(); - _semanticsIdentifier = - widget.semanticsIdentifier ?? 'link-${_nextSemanticsIdentifier++}'; + _semanticsIdentifier = widget.semanticsIdentifier ?? 'link-${_nextSemanticsIdentifier++}'; } @override @@ -122,10 +121,7 @@ class WebLinkDelegateState extends State { link: true, identifier: _semanticsIdentifier, linkUrl: widget.link.uri, - child: widget.link.builder( - context, - widget.link.isDisabled ? null : _followLink, - ), + child: widget.link.builder(context, widget.link.isDisabled ? null : _followLink), ), ); } @@ -136,23 +132,18 @@ class WebLinkDelegateState extends State { child: PlatformViewLink( viewType: linkViewType, onCreatePlatformView: (PlatformViewCreationParams params) { - _controller = LinkViewController.fromParams( - params, - _semanticsIdentifier, - ); + _controller = LinkViewController.fromParams(params, _semanticsIdentifier); return _controller ..setUri(widget.link.uri) ..setTarget(widget.link.target); }, - surfaceFactory: - (BuildContext context, PlatformViewController controller) { - return PlatformViewSurface( - controller: controller, - gestureRecognizers: - const >{}, - hitTestBehavior: PlatformViewHitTestBehavior.transparent, - ); - }, + surfaceFactory: (BuildContext context, PlatformViewController controller) { + return PlatformViewSurface( + controller: controller, + gestureRecognizers: const >{}, + hitTestBehavior: PlatformViewHitTestBehavior.transparent, + ); + }, ), ), ); @@ -162,8 +153,7 @@ class WebLinkDelegateState extends State { final JSAny _useCapture = {'capture': true}.jsify()!; /// Signature for the function that triggers a link. -typedef TriggerLinkCallback = - void Function(int viewId, html.MouseEvent? mouseEvent); +typedef TriggerLinkCallback = void Function(int viewId, html.MouseEvent? mouseEvent); /// Keeps track of the signals required to trigger a link. /// @@ -253,10 +243,7 @@ class LinkTriggerSignals { /// /// If `mouseEvent` is not null, `viewId` becomes mandatory. If `viewId` is /// not present in this case, a [StateError] is thrown. - void onMouseEvent({ - required int? viewId, - required html.MouseEvent? mouseEvent, - }) { + void onMouseEvent({required int? viewId, required html.MouseEvent? mouseEvent}) { if (mouseEvent != null && viewId == null) { throw StateError('`viewId` must be provided for mouse events'); } @@ -361,8 +348,7 @@ class LinkViewController extends PlatformViewController { return controller; } - static final Map _instancesByViewId = - {}; + static final Map _instancesByViewId = {}; static final Map _instancesBySemanticsIdentifier = {}; @@ -467,14 +453,10 @@ class LinkViewController extends PlatformViewController { /// Global click handler that's called for every click event on the window. @visibleForTesting - static void handleGlobalClick({ - required html.MouseEvent event, - required html.Element? target, - }) { + static void handleGlobalClick({required html.MouseEvent event, required html.Element? target}) { // We only want to handle clicks that land on *our* links. That could be a // platform view link or a semantics link. - final int? viewIdFromTarget = - _getViewIdFromLink(target) ?? _getViewIdFromSemanticsLink(target); + final int? viewIdFromTarget = _getViewIdFromLink(target) ?? _getViewIdFromSemanticsLink(target); if (viewIdFromTarget == null) { // The click target was not one of our links, so we don't want to @@ -543,10 +525,7 @@ class LinkViewController extends PlatformViewController { if (controller._isExternalLink) { if (!_triggerSignals.canBrowserNavigate) { // When the browser can't do the navigation, we have to launch the url manually. - UrlLauncherPlatform.instance.launchUrl( - controller._uri.toString(), - const LaunchOptions(), - ); + UrlLauncherPlatform.instance.launchUrl(controller._uri.toString(), const LaunchOptions()); } // Otherwise, let the browser handle it, so we don't have to do anything. @@ -618,15 +597,12 @@ class LinkViewController extends PlatformViewController { return null; } - final String? semanticsIdentifier = semanticsLink.getAttribute( - 'flt-semantics-identifier', - ); + final String? semanticsIdentifier = semanticsLink.getAttribute('flt-semantics-identifier'); if (semanticsIdentifier == null) { return null; } - final LinkViewController? controller = - _instancesBySemanticsIdentifier[semanticsIdentifier]; + final LinkViewController? controller = _instancesBySemanticsIdentifier[semanticsIdentifier]; if (controller == null) { return null; } diff --git a/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart b/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart index 0043a124e53c..45d49669a635 100644 --- a/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart +++ b/packages/url_launcher/url_launcher_web/lib/url_launcher_web.dart @@ -16,16 +16,14 @@ import 'src/link.dart'; const Set _safariTargetTopSchemes = {'mailto', 'tel', 'sms'}; String? _getUrlScheme(String url) => Uri.tryParse(url)?.scheme; -bool _isSafariTargetTopScheme(String? scheme) => - _safariTargetTopSchemes.contains(scheme); +bool _isSafariTargetTopScheme(String? scheme) => _safariTargetTopSchemes.contains(scheme); // The set of schemes that are explicitly disallowed by the plugin. const Set _disallowedSchemes = {'javascript'}; bool _isDisallowedScheme(String? scheme) => _disallowedSchemes.contains(scheme); bool _navigatorIsSafari(html.Navigator navigator) => - navigator.userAgent.contains('Safari') && - !navigator.userAgent.contains('Chrome'); + navigator.userAgent.contains('Safari') && !navigator.userAgent.contains('Chrome'); /// The web implementation of [UrlLauncherPlatform]. /// @@ -81,8 +79,7 @@ class UrlLauncherPlugin extends UrlLauncherPlatform { // Some schemes need to be opened on the _top window context on Safari. // See https://github.com/flutter/flutter/issues/51461 final String target = - webOnlyWindowName ?? - ((_isSafari && _isSafariTargetTopScheme(scheme)) ? '_top' : ''); + webOnlyWindowName ?? ((_isSafari && _isSafariTargetTopScheme(scheme)) ? '_top' : ''); _window.open(url, target, 'noopener,noreferrer'); diff --git a/packages/url_launcher/url_launcher_windows/example/lib/main.dart b/packages/url_launcher/url_launcher_windows/example/lib/main.dart index 8ca238f3f519..ee9db9266c71 100644 --- a/packages/url_launcher/url_launcher_windows/example/lib/main.dart +++ b/packages/url_launcher/url_launcher_windows/example/lib/main.dart @@ -70,10 +70,7 @@ class _MyHomePageState extends State { Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Padding( - padding: EdgeInsets.all(16.0), - child: Text(toLaunch), - ), + const Padding(padding: EdgeInsets.all(16.0), child: Text(toLaunch)), ElevatedButton( onPressed: () => setState(() { _launched = _launchInBrowser(toLaunch); diff --git a/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart b/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart index 59366e2f0684..8fcb767c09e7 100644 --- a/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart +++ b/packages/url_launcher/url_launcher_windows/lib/src/messages.g.dart @@ -43,13 +43,11 @@ class UrlLauncherApi { /// Constructor for [UrlLauncherApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - UrlLauncherApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + UrlLauncherApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -59,17 +57,13 @@ class UrlLauncherApi { Future canLaunchUrl(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_windows.UrlLauncherApi.canLaunchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -91,17 +85,13 @@ class UrlLauncherApi { Future launchUrl(String url) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.url_launcher_windows.UrlLauncherApi.launchUrl$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [url], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([url]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart b/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart index c776dd1a5960..398e153f158b 100644 --- a/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart +++ b/packages/url_launcher/url_launcher_windows/lib/url_launcher_windows.dart @@ -11,8 +11,7 @@ import 'src/messages.g.dart'; /// An implementation of [UrlLauncherPlatform] for Windows. class UrlLauncherWindows extends UrlLauncherPlatform { /// Creates a new plugin implementation instance. - UrlLauncherWindows({@visibleForTesting UrlLauncherApi? api}) - : _hostApi = api ?? UrlLauncherApi(); + UrlLauncherWindows({@visibleForTesting UrlLauncherApi? api}) : _hostApi = api ?? UrlLauncherApi(); final UrlLauncherApi _hostApi; diff --git a/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart b/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart index 1140cb25214a..9b97f6cd0811 100644 --- a/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart +++ b/packages/url_launcher/url_launcher_windows/test/url_launcher_windows_test.dart @@ -101,51 +101,26 @@ void main() { group('supportsMode', () { test('returns true for platformDefault', () async { final launcher = UrlLauncherWindows(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.platformDefault), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final launcher = UrlLauncherWindows(api: api); - expect( - await launcher.supportsMode(PreferredLaunchMode.externalApplication), - true, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns false for other modes', () async { final launcher = UrlLauncherWindows(api: api); - expect( - await launcher.supportsMode( - PreferredLaunchMode.externalNonBrowserApplication, - ), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), - false, - ); - expect( - await launcher.supportsMode(PreferredLaunchMode.inAppWebView), - false, - ); + expect(await launcher.supportsMode(PreferredLaunchMode.externalNonBrowserApplication), false); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); + expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); }); }); test('supportsCloseForMode returns false', () async { final launcher = UrlLauncherWindows(api: api); - expect( - await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), - false, - ); - expect( - await launcher.supportsCloseForMode( - PreferredLaunchMode.externalApplication, - ), - false, - ); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.platformDefault), false); + expect(await launcher.supportsCloseForMode(PreferredLaunchMode.externalApplication), false); }); } diff --git a/packages/vector_graphics/example/lib/svg_string.dart b/packages/vector_graphics/example/lib/svg_string.dart index 6159727583b3..26459c31e01c 100644 --- a/packages/vector_graphics/example/lib/svg_string.dart +++ b/packages/vector_graphics/example/lib/svg_string.dart @@ -47,9 +47,7 @@ class MyApp extends StatefulWidget { } class _MyAppState extends State { - final TextEditingController _controller = TextEditingController( - text: _flutterLogoString, - ); + final TextEditingController _controller = TextEditingController(text: _flutterLogoString); ByteData? _data; Timer? _debounce; int _svgLength = 0; diff --git a/packages/vector_graphics/lib/src/html_render_vector_graphics.dart b/packages/vector_graphics/lib/src/html_render_vector_graphics.dart index 4de328d28a0c..888b406a5911 100644 --- a/packages/vector_graphics/lib/src/html_render_vector_graphics.dart +++ b/packages/vector_graphics/lib/src/html_render_vector_graphics.dart @@ -15,12 +15,7 @@ import 'listener.dart'; /// for HTML compatibility. class RenderWebVectorGraphic extends RenderBox { /// Create a new [RenderWebVectorGraphic]. - RenderWebVectorGraphic( - this._pictureInfo, - this._assetKey, - this._colorFilter, - this._opacity, - ) { + RenderWebVectorGraphic(this._pictureInfo, this._assetKey, this._colorFilter, this._opacity) { _opacity?.addListener(_updateOpacity); _updateOpacity(); } @@ -122,21 +117,16 @@ class RenderWebVectorGraphic extends RenderBox { super.dispose(); } - final LayerHandle _transformLayer = - LayerHandle(); + final LayerHandle _transformLayer = LayerHandle(); final LayerHandle _opacityHandle = LayerHandle(); - final LayerHandle _filterLayer = - LayerHandle(); + final LayerHandle _filterLayer = LayerHandle(); final Matrix4 _transform = Matrix4.identity(); @override void paint(PaintingContext context, ui.Offset offset) { assert(size == pictureInfo.size); if (kDebugMode && debugSkipRaster) { - context.canvas.drawRect( - offset & size, - Paint()..color = const Color(0xFFFF00FF), - ); + context.canvas.drawRect(offset & size, Paint()..color = const Color(0xFFFF00FF)); return; } @@ -150,24 +140,22 @@ class RenderWebVectorGraphic extends RenderBox { PaintingContext context, Offset offset, ) { - _opacityHandle.layer = context.pushOpacity( - offset, - (_opacityValue * 255).round(), - (PaintingContext context, Offset offset) { - if (colorFilter != null) { - _filterLayer.layer = context.pushColorFilter(offset, colorFilter!, ( - PaintingContext context, - Offset offset, - ) { - context.canvas.drawPicture(pictureInfo.picture); - }, oldLayer: _filterLayer.layer); - } else { - _filterLayer.layer = null; + _opacityHandle.layer = context.pushOpacity(offset, (_opacityValue * 255).round(), ( + PaintingContext context, + Offset offset, + ) { + if (colorFilter != null) { + _filterLayer.layer = context.pushColorFilter(offset, colorFilter!, ( + PaintingContext context, + Offset offset, + ) { context.canvas.drawPicture(pictureInfo.picture); - } - }, - oldLayer: _opacityHandle.layer, - ); + }, oldLayer: _filterLayer.layer); + } else { + _filterLayer.layer = null; + context.canvas.drawPicture(pictureInfo.picture); + } + }, oldLayer: _opacityHandle.layer); }, oldLayer: _transformLayer.layer); } } diff --git a/packages/vector_graphics/lib/src/listener.dart b/packages/vector_graphics/lib/src/listener.dart index cc9e96af8376..ac951773c60d 100644 --- a/packages/vector_graphics/lib/src/listener.dart +++ b/packages/vector_graphics/lib/src/listener.dart @@ -49,8 +49,7 @@ TextDirection? _debugLastTextDirection; @visibleForTesting Iterable> get debugGetPendingDecodeTasks => _pendingDecodes.values.map((Completer e) => e.future); -final Map> _pendingDecodes = - >{}; +final Map> _pendingDecodes = >{}; /// Decode a vector graphics binary asset into a [Picture]. /// @@ -113,18 +112,11 @@ Future decodeVectorGraphics( return Zone.current .fork( specification: ZoneSpecification( - scheduleMicrotask: - (Zone self, ZoneDelegate parent, Zone zone, void Function() f) { - Zone.root.scheduleMicrotask(f); - }, + scheduleMicrotask: (Zone self, ZoneDelegate parent, Zone zone, void Function() f) { + Zone.root.scheduleMicrotask(f); + }, createTimer: - ( - Zone self, - ZoneDelegate parent, - Zone zone, - Duration duration, - void Function() f, - ) { + (Zone self, ZoneDelegate parent, Zone zone, Duration duration, void Function() f) { return Zone.root.createTimer(duration, f); }, createPeriodicTimer: @@ -216,8 +208,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { Locale? locale, TextDirection? textDirection, bool clipViewbox = true, - @visibleForTesting - PictureFactory pictureFactory = const _DefaultPictureFactory(), + @visibleForTesting PictureFactory pictureFactory = const _DefaultPictureFactory(), VectorGraphicsErrorListener? onError, }) { final PictureRecorder recorder = pictureFactory.createPictureRecorder(); @@ -279,14 +270,12 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { static final Paint _emptyPaint = Paint(); static final Paint _grayscaleDstInPaint = Paint() ..blendMode = BlendMode.dstIn - ..colorFilter = const ColorFilter.matrix( - [ - 0, 0, 0, 0, 0, // - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0.2126, 0.7152, 0.0722, 0, 0, - ], - ); //convert to grayscale (https://www.w3.org/Graphics/Color/sRGB) and use them as transparency + ..colorFilter = const ColorFilter.matrix([ + 0, 0, 0, 0, 0, // + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0.2126, 0.7152, 0.0722, 0, 0, + ]); //convert to grayscale (https://www.w3.org/Graphics/Color/sRGB) and use them as transparency /// Convert the vector graphics asset this listener decoded into a [Picture]. /// @@ -331,10 +320,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { } } if (_currentPattern != null) { - _patterns[_currentPattern!._patternId]!.canvas!.drawPath( - path, - paint ?? _emptyPaint, - ); + _patterns[_currentPattern!._patternId]!.canvas!.drawPath(path, paint ?? _emptyPaint); } else { _canvas.drawPath(path, paint ?? _emptyPaint); } @@ -342,11 +328,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { @override void onDrawVertices(Float32List vertices, Uint16List? indices, int? paintId) { - final vertexData = Vertices.raw( - VertexMode.triangles, - vertices, - indices: indices, - ); + final vertexData = Vertices.raw(VertexMode.triangles, vertices, indices: indices); Paint? paint; if (paintId != null) { paint = _paints[paintId]; @@ -402,14 +384,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { } @override - void onPathCubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) { + void onPathCubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { _currentPath!.cubicTo(x1, y1, x2, y2, x3, y3); } @@ -507,10 +482,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { _clipViewbox, ); - patternListener._size = Size( - currentPattern!._width, - currentPattern._height, - ); + patternListener._size = Size(currentPattern!._width, currentPattern._height); final PictureInfo pictureInfo = patternListener.toPicture(); _currentPattern = null; @@ -545,16 +517,8 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { final from = Offset(fromX, fromY); final to = Offset(toX, toY); - final colorValues = [ - for (int i = 0; i < colors.length; i++) Color(colors[i]), - ]; - final gradient = Gradient.linear( - from, - to, - colorValues, - offsets, - TileMode.values[tileMode], - ); + final colorValues = [for (int i = 0; i < colors.length; i++) Color(colors[i])]; + final gradient = Gradient.linear(from, to, colorValues, offsets, TileMode.values[tileMode]); _shaders.add(gradient); } @@ -575,9 +539,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { final center = Offset(centerX, centerY); final Offset? focal = focalX == null ? null : Offset(focalX, focalY!); - final colorValues = [ - for (int i = 0; i < colors.length; i++) Color(colors[i]), - ]; + final colorValues = [for (int i = 0; i < colors.length; i++) Color(colors[i])]; final bool hasFocal = focal != center && focal != null; final gradient = Gradient.radial( center, @@ -665,8 +627,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { } if (position.dx != null) { - _accumulatedTextPositionX = - (_accumulatedTextPositionX ?? 0) + position.dx!; + _accumulatedTextPositionX = (_accumulatedTextPositionX ?? 0) + position.dx!; } if (position.dy != null) { _textPositionY = _textPositionY + position.dy!; @@ -676,12 +637,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { } @override - Future onDrawText( - int textId, - int? fillId, - int? strokeId, - int? patternId, - ) async { + Future onDrawText(int textId, int? fillId, int? strokeId, int? patternId) async { final _TextConfig textConfig = _textConfig[textId]; final double dx = _accumulatedTextPositionX ?? 0; final double dy = _textPositionY; @@ -692,9 +648,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { if (patternId != null) { paint.shader = _patterns[patternId]!.shader; } - final builder = ParagraphBuilder( - ParagraphStyle(textDirection: _textDirection), - ); + final builder = ParagraphBuilder(ParagraphStyle(textDirection: _textDirection)); builder.pushStyle( TextStyle( locale: _locale, @@ -745,25 +699,16 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { } @override - void onImage( - int imageId, - int format, - Uint8List data, { - VectorGraphicsErrorListener? onError, - }) { + void onImage(int imageId, int format, Uint8List data, {VectorGraphicsErrorListener? onError}) { final completer = Completer(); _pendingImages.add(completer.future); final ImageStreamCompleter? cacheCompleter = imageCache.putIfAbsent( _createImageKey(imageId, format), () { return OneFrameImageStreamCompleter( - ImmutableBuffer.fromUint8List(data).then(( - ImmutableBuffer buffer, - ) async { + ImmutableBuffer.fromUint8List(data).then((ImmutableBuffer buffer) async { try { - final ImageDescriptor descriptor = await ImageDescriptor.encoded( - buffer, - ); + final ImageDescriptor descriptor = await ImageDescriptor.encoded(buffer); final Codec codec = await descriptor.instantiateCodec(); final FrameInfo info = await codec.getNextFrame(); final Image image = info.image; @@ -822,10 +767,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { Float64List? transform, ) { final Image? image = _images[imageId]; - assert( - image != null, - 'Invalid imageId: $imageId. Image not found in _images.', - ); + assert(image != null, 'Invalid imageId: $imageId. Image not found in _images.'); if (image == null) { return; } @@ -846,14 +788,7 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener { } class _TextPosition { - const _TextPosition( - this.x, - this.y, - this.dx, - this.dy, - this.reset, - this.transform, - ); + const _TextPosition(this.x, this.y, this.dx, this.dy, this.reset, this.transform); final double? x; final double? y; diff --git a/packages/vector_graphics/lib/src/loader.dart b/packages/vector_graphics/lib/src/loader.dart index 8b49e3aeaf43..d0373ddd9ec8 100644 --- a/packages/vector_graphics/lib/src/loader.dart +++ b/packages/vector_graphics/lib/src/loader.dart @@ -73,9 +73,9 @@ class AssetBytesLoader extends BytesLoader { @override Future loadBytes(BuildContext? context) { - return _resolveBundle(context).load( - packageName == null ? assetName : 'packages/$packageName/$assetName', - ); + return _resolveBundle( + context, + ).load(packageName == null ? assetName : 'packages/$packageName/$assetName'); } @override @@ -91,11 +91,7 @@ class AssetBytesLoader extends BytesLoader { @override Object cacheKey(BuildContext? context) { - return _AssetByteLoaderCacheKey( - assetName, - packageName, - _resolveBundle(context), - ); + return _AssetByteLoaderCacheKey(assetName, packageName, _resolveBundle(context)); } @override @@ -108,11 +104,7 @@ class AssetBytesLoader extends BytesLoader { // value of `DefaultAssetBundle.of(context)`. @immutable class _AssetByteLoaderCacheKey { - const _AssetByteLoaderCacheKey( - this.assetName, - this.packageName, - this.assetBundle, - ); + const _AssetByteLoaderCacheKey(this.assetName, this.packageName, this.assetBundle); final String assetName; final String? packageName; @@ -163,9 +155,7 @@ class NetworkBytesLoader extends BytesLoader { @override bool operator ==(Object other) { - return other is NetworkBytesLoader && - other.headers == headers && - other.url == url; + return other is NetworkBytesLoader && other.headers == headers && other.url == url; } @override diff --git a/packages/vector_graphics/lib/src/render_vector_graphic.dart b/packages/vector_graphics/lib/src/render_vector_graphic.dart index 2c2f3d79344a..3787bf95af84 100644 --- a/packages/vector_graphics/lib/src/render_vector_graphic.dart +++ b/packages/vector_graphics/lib/src/render_vector_graphic.dart @@ -87,8 +87,7 @@ class RenderVectorGraphic extends RenderBox { _updateOpacity(); } - static final Map _liveRasterCache = - {}; + static final Map _liveRasterCache = {}; /// A key that uniquely identifies the [pictureInfo] used for this vg. Object get assetKey => _assetKey; @@ -195,11 +194,7 @@ class RenderVectorGraphic extends RenderBox { return constraints.smallest; } - static RasterData _createRaster( - RasterKey key, - double scaleFactor, - PictureInfo info, - ) { + static RasterData _createRaster(RasterKey key, double scaleFactor, PictureInfo info) { final int scaledWidth = key.width; final int scaledHeight = key.height; // In order to scale a picture, it must be placed in a new picture @@ -214,10 +209,7 @@ class RenderVectorGraphic extends RenderBox { canvas.drawPicture(info.picture); final ui.Picture rasterPicture = recorder.endRecording(); - final ui.Image pending = rasterPicture.toImageSync( - scaledWidth, - scaledHeight, - ); + final ui.Image pending = rasterPicture.toImageSync(scaledWidth, scaledHeight); return RasterData(pending, 0, key); } @@ -236,10 +228,8 @@ class RenderVectorGraphic extends RenderBox { // is sufficiently different. Returns `null` if rasterData has been // updated immediately. void _maybeUpdateRaster() { - final int scaledWidth = (pictureInfo.size.width * devicePixelRatio / scale) - .round(); - final int scaledHeight = - (pictureInfo.size.height * devicePixelRatio / scale).round(); + final int scaledWidth = (pictureInfo.size.width * devicePixelRatio / scale).round(); + final int scaledHeight = (pictureInfo.size.height * devicePixelRatio / scale).round(); final key = RasterKey(assetKey, scaledWidth, scaledHeight); // First check if the raster is available synchronously. This also handles @@ -253,11 +243,7 @@ class RenderVectorGraphic extends RenderBox { _rasterData = data; return; } - final RasterData data = _createRaster( - key, - devicePixelRatio / scale, - pictureInfo, - ); + final RasterData data = _createRaster(key, devicePixelRatio / scale, pictureInfo); data.count += 1; assert(!_liveRasterCache.containsKey(key)); @@ -295,10 +281,7 @@ class RenderVectorGraphic extends RenderBox { void paint(PaintingContext context, ui.Offset offset) { assert(size == pictureInfo.size); if (kDebugMode && debugSkipRaster) { - context.canvas.drawRect( - offset & size, - Paint()..color = const Color(0xFFFF00FF), - ); + context.canvas.drawRect(offset & size, Paint()..color = const Color(0xFFFF00FF)); return; } @@ -333,11 +316,7 @@ class RenderVectorGraphic extends RenderBox { /// A render object which draws a vector graphic instance as a picture. class RenderPictureVectorGraphic extends RenderBox { /// Create a new [RenderPictureVectorGraphic]. - RenderPictureVectorGraphic( - this._pictureInfo, - this._colorFilter, - this._opacity, - ) { + RenderPictureVectorGraphic(this._pictureInfo, this._colorFilter, this._opacity) { _opacity?.addListener(_updateOpacity); _updateOpacity(); } diff --git a/packages/vector_graphics/lib/src/vector_graphics.dart b/packages/vector_graphics/lib/src/vector_graphics.dart index f909d59f1025..4a325465ea5a 100644 --- a/packages/vector_graphics/lib/src/vector_graphics.dart +++ b/packages/vector_graphics/lib/src/vector_graphics.dart @@ -44,13 +44,15 @@ enum RenderingStrategy { } /// The signature that [VectorGraphic.errorBuilder] uses to report exceptions. -typedef VectorGraphicsErrorWidget = - Widget Function(BuildContext context, Object error, StackTrace stackTrace); +typedef VectorGraphicsErrorWidget = Widget Function( + BuildContext context, + Object error, + StackTrace stackTrace, +); /// The signature that [VectorGraphic.imageBuilder] uses to wrap the /// successfully loaded vector graphic widget. -typedef VectorGraphicsImageWidget = - Widget Function(BuildContext context, Widget child); +typedef VectorGraphicsImageWidget = Widget Function(BuildContext context, Widget child); /// A vector graphic/flutter_svg compatibility shim. VectorGraphic createCompatVectorGraphic({ @@ -300,12 +302,7 @@ class _PictureData { @immutable class _PictureKey { - const _PictureKey( - this.cacheKey, - this.locale, - this.textDirection, - this.clipViewbox, - ); + const _PictureKey(this.cacheKey, this.locale, this.textDirection, this.clipViewbox); final Object cacheKey; final Locale? locale; @@ -331,8 +328,7 @@ class _VectorGraphicWidgetState extends State { Locale? locale; TextDirection? textDirection; - static final Map<_PictureKey, _PictureData> _livePictureCache = - <_PictureKey, _PictureData>{}; + static final Map<_PictureKey, _PictureData> _livePictureCache = <_PictureKey, _PictureData>{}; static final Map<_PictureKey, Future<_PictureData>> _pendingPictures = <_PictureKey, Future<_PictureData>>{}; @@ -370,11 +366,7 @@ class _VectorGraphicWidgetState extends State { } } - Future<_PictureData> _loadPicture( - BuildContext context, - _PictureKey key, - BytesLoader loader, - ) { + Future<_PictureData> _loadPicture(BuildContext context, _PictureKey key, BytesLoader loader) { if (_pendingPictures.containsKey(key)) { return _pendingPictures[key]!; } @@ -413,12 +405,7 @@ class _VectorGraphicWidgetState extends State { Future _loadAssetBytes() async { // First check if we have an avilable picture and use this immediately. final Object loaderKey = widget.loader.cacheKey(context); - final key = _PictureKey( - loaderKey, - locale, - textDirection, - widget.clipViewbox, - ); + final key = _PictureKey(loaderKey, locale, textDirection, widget.clipViewbox); final _PictureData? data = _livePictureCache[key]; if (data != null) { data.count += 1; @@ -478,10 +465,7 @@ class _VectorGraphicWidgetState extends State { var scale = 1.0; if (width != null && height != null) { - scale = math.min( - pictureInfo.size.width / width, - pictureInfo.size.height / height, - ); + scale = math.min(pictureInfo.size.width / width, pictureInfo.size.height / height); } if (_webRenderObject) { @@ -535,11 +519,7 @@ class _VectorGraphicWidgetState extends State { child = widget.imageBuilder!(context, child); } } else if (_error != null && widget.errorBuilder != null) { - child = widget.errorBuilder!( - context, - _error!, - _stackTrace ?? StackTrace.empty, - ); + child = widget.errorBuilder!(context, _error!, _stackTrace ?? StackTrace.empty); } else { child = widget.placeholderBuilder?.call(context) ?? @@ -596,10 +576,7 @@ class _RawVectorGraphicWidget extends SingleChildRenderObjectWidget { } @override - void updateRenderObject( - BuildContext context, - covariant RenderVectorGraphic renderObject, - ) { + void updateRenderObject(BuildContext context, covariant RenderVectorGraphic renderObject) { renderObject ..pictureInfo = pictureInfo ..assetKey = assetKey @@ -629,10 +606,7 @@ class _RawWebVectorGraphicWidget extends SingleChildRenderObjectWidget { } @override - void updateRenderObject( - BuildContext context, - covariant RenderWebVectorGraphic renderObject, - ) { + void updateRenderObject(BuildContext context, covariant RenderWebVectorGraphic renderObject) { renderObject ..pictureInfo = pictureInfo ..assetKey = assetKey @@ -660,10 +634,7 @@ class _RawPictureVectorGraphicWidget extends SingleChildRenderObjectWidget { } @override - void updateRenderObject( - BuildContext context, - covariant RenderPictureVectorGraphic renderObject, - ) { + void updateRenderObject(BuildContext context, covariant RenderPictureVectorGraphic renderObject) { renderObject ..pictureInfo = pictureInfo ..colorFilter = colorFilter @@ -700,9 +671,7 @@ class VectorGraphicUtilities { // ignore: invalid_use_of_visible_for_testing_member return Future.wait(debugGetPendingDecodeTasks); } - throw UnsupportedError( - 'This method is only for use in tests in debug mode for tests.', - ); + throw UnsupportedError('This method is only for use in tests in debug mode for tests.'); } /// Load the [PictureInfo] from a given [loader]. diff --git a/packages/vector_graphics/test/caching_test.dart b/packages/vector_graphics/test/caching_test.dart index 33b0a8af4187..0ed58e0e6f95 100644 --- a/packages/vector_graphics/test/caching_test.dart +++ b/packages/vector_graphics/test/caching_test.dart @@ -18,43 +18,34 @@ void main() { imageCache.clearLiveImages(); }); - testWidgets( - 'Does not reload identical bytes when forced to re-create state object', - (WidgetTester tester) async { - final testBundle = TestAssetBundle(); - final GlobalKey key = GlobalKey(); - - await tester.pumpWidget( - DefaultAssetBundle( - key: UniqueKey(), - bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), - ), - ); + testWidgets('Does not reload identical bytes when forced to re-create state object', ( + WidgetTester tester, + ) async { + final testBundle = TestAssetBundle(); + final GlobalKey key = GlobalKey(); - expect(testBundle.loadKeys.single, 'foo.svg'); + await tester.pumpWidget( + DefaultAssetBundle( + key: UniqueKey(), + bundle: testBundle, + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), + ), + ); - await tester.pumpWidget( - DefaultAssetBundle( - key: UniqueKey(), - bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), - ), - ); + expect(testBundle.loadKeys.single, 'foo.svg'); - expect(testBundle.loadKeys, ['foo.svg']); - }, - ); + await tester.pumpWidget( + DefaultAssetBundle( + key: UniqueKey(), + bundle: testBundle, + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), + ), + ); - testWidgets('Only loads bytes once for a repeated vg', ( - WidgetTester tester, - ) async { + expect(testBundle.loadKeys, ['foo.svg']); + }); + + testWidgets('Only loads bytes once for a repeated vg', (WidgetTester tester) async { final testBundle = TestAssetBundle(); await tester.pumpWidget( @@ -63,18 +54,9 @@ void main() { bundle: testBundle, child: Column( children: [ - VectorGraphic( - key: GlobalKey(), - loader: const AssetBytesLoader('foo.svg'), - ), - VectorGraphic( - key: GlobalKey(), - loader: const AssetBytesLoader('foo.svg'), - ), - VectorGraphic( - key: GlobalKey(), - loader: const AssetBytesLoader('foo.svg'), - ), + VectorGraphic(key: GlobalKey(), loader: const AssetBytesLoader('foo.svg')), + VectorGraphic(key: GlobalKey(), loader: const AssetBytesLoader('foo.svg')), + VectorGraphic(key: GlobalKey(), loader: const AssetBytesLoader('foo.svg')), ], ), ), @@ -90,18 +72,9 @@ void main() { bundle: testBundle, child: Column( children: [ - VectorGraphic( - key: GlobalKey(), - loader: const AssetBytesLoader('foo.svg'), - ), - VectorGraphic( - key: GlobalKey(), - loader: const AssetBytesLoader('foo.svg'), - ), - VectorGraphic( - key: GlobalKey(), - loader: const AssetBytesLoader('foo.svg'), - ), + VectorGraphic(key: GlobalKey(), loader: const AssetBytesLoader('foo.svg')), + VectorGraphic(key: GlobalKey(), loader: const AssetBytesLoader('foo.svg')), + VectorGraphic(key: GlobalKey(), loader: const AssetBytesLoader('foo.svg')), ], ), ), @@ -121,10 +94,7 @@ void main() { DefaultAssetBundle( key: UniqueKey(), bundle: testBundleA, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ); @@ -135,10 +105,7 @@ void main() { DefaultAssetBundle( key: UniqueKey(), bundle: testBundleB, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ); @@ -152,16 +119,11 @@ void main() { await tester.pumpWidget( Localizations( - delegates: >[ - TestLocalizationsDelegate(), - ], + delegates: >[TestLocalizationsDelegate()], locale: const Locale('fr', 'CH'), child: DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ), ); @@ -172,16 +134,11 @@ void main() { await tester.pumpWidget( Localizations( - delegates: >[ - TestLocalizationsDelegate(), - ], + delegates: >[TestLocalizationsDelegate()], locale: const Locale('ab', 'cd'), child: DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ), ); @@ -191,9 +148,7 @@ void main() { expect(testBundle.loadKeys, ['foo.svg', 'foo.svg']); }); - testWidgets('reload bytes when text direction changes', ( - WidgetTester tester, - ) async { + testWidgets('reload bytes when text direction changes', (WidgetTester tester) async { final testBundle = TestAssetBundle(); final GlobalKey key = GlobalKey(); @@ -202,10 +157,7 @@ void main() { textDirection: TextDirection.ltr, child: DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ), ); @@ -217,10 +169,7 @@ void main() { textDirection: TextDirection.rtl, child: DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ), ); @@ -228,40 +177,33 @@ void main() { expect(testBundle.loadKeys, ['foo.svg', 'foo.svg']); }); - testWidgets( - 'Cache is purged immediately after last VectorGraphic removed from tree', - (WidgetTester tester) async { - final testBundle = TestAssetBundle(); - final GlobalKey key = GlobalKey(); + testWidgets('Cache is purged immediately after last VectorGraphic removed from tree', ( + WidgetTester tester, + ) async { + final testBundle = TestAssetBundle(); + final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - DefaultAssetBundle( - bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), - ), - ); + await tester.pumpWidget( + DefaultAssetBundle( + bundle: testBundle, + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), + ), + ); - expect(testBundle.loadKeys.single, 'foo.svg'); + expect(testBundle.loadKeys.single, 'foo.svg'); - // Force VectorGraphic removed from tree. - await tester.pumpWidget(const SizedBox()); + // Force VectorGraphic removed from tree. + await tester.pumpWidget(const SizedBox()); - await tester.pumpWidget( - DefaultAssetBundle( - bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), - ), - ); + await tester.pumpWidget( + DefaultAssetBundle( + bundle: testBundle, + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), + ), + ); - expect(testBundle.loadKeys, ['foo.svg', 'foo.svg']); - }, - ); + expect(testBundle.loadKeys, ['foo.svg', 'foo.svg']); + }); // For this test we evaluate an edge case where asset loading starts, but then a new // asset is requested before the first can load. We want to ensure that first asset does @@ -285,10 +227,7 @@ void main() { await tester.pumpWidget( DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('bar.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('bar.svg')), ), ); @@ -304,10 +243,7 @@ void main() { await tester.pumpWidget( DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ); @@ -339,8 +275,7 @@ class ControlledAssetBytesLoader extends AssetBytesLoader { } } -class TestLocalizationsDelegate - extends LocalizationsDelegate { +class TestLocalizationsDelegate extends LocalizationsDelegate { @override bool isSupported(Locale locale) { return true; diff --git a/packages/vector_graphics/test/listener_test.dart b/packages/vector_graphics/test/listener_test.dart index 72330c7dd002..f33e775188aa 100644 --- a/packages/vector_graphics/test/listener_test.dart +++ b/packages/vector_graphics/test/listener_test.dart @@ -51,8 +51,7 @@ void main() { loader: const AssetBytesLoader('test'), ); final ui.Image image = info.picture.toImageSync(15, 15); - final Uint32List imageBytes = (await image.toByteData())!.buffer - .asUint32List(); + final Uint32List imageBytes = (await image.toByteData())!.buffer.asUint32List(); expect(imageBytes.first, 0xFF000000); expect(imageBytes.last, 0x00000000); }, skip: kIsWeb); @@ -66,8 +65,7 @@ void main() { loader: const AssetBytesLoader('test'), ); final ui.Image image = info.picture.toImageSync(15, 15); - final Uint32List imageBytes = (await image.toByteData())!.buffer - .asUint32List(); + final Uint32List imageBytes = (await image.toByteData())!.buffer.asUint32List(); expect(imageBytes.first, 0xFF000000); expect(imageBytes.last, 0xFF000000); }, skip: kIsWeb); @@ -82,10 +80,7 @@ void main() { expect(drawRect.isMethod, true); expect(drawRect.memberName, #drawImageRect); expect(drawRect.positionalArguments[1], const ui.Rect.fromLTRB(0, 0, 1, 1)); - expect( - drawRect.positionalArguments[2], - const ui.Rect.fromLTRB(10, 10, 40, 40), - ); + expect(drawRect.positionalArguments[2], const ui.Rect.fromLTRB(10, 10, 40, 40)); }); test('Pattern start clips the new canvas', () async { @@ -95,10 +90,7 @@ void main() { final Invocation clipRect = factory.fakeCanvases.last.invocations.single; expect(clipRect.isMethod, true); expect(clipRect.memberName, #clipRect); - expect( - clipRect.positionalArguments.single, - const ui.Rect.fromLTRB(0, 0, 100, 100), - ); + expect(clipRect.positionalArguments.single, const ui.Rect.fromLTRB(0, 0, 100, 100)); }); test('Text position is respected', () async { @@ -138,10 +130,7 @@ void main() { final listener = FlutterVectorGraphicsListener(pictureFactory: factory); listener.onImage(0, 0, base64.decode(bluePngPixel)); await listener.waitForImageDecode(); - expect( - () => listener.onDrawImage(2, 10, 10, 100, 100, null), - throwsAssertionError, - ); + expect(() => listener.onDrawImage(2, 10, 10, 100, 100, null), throwsAssertionError); }); } diff --git a/packages/vector_graphics/test/render_vector_graphics_test.dart b/packages/vector_graphics/test/render_vector_graphics_test.dart index 2523f2a7641e..a816d39afa70 100644 --- a/packages/vector_graphics/test/render_vector_graphics_test.dart +++ b/packages/vector_graphics/test/render_vector_graphics_test.dart @@ -40,14 +40,7 @@ void main() { }); test('Rasterizes a picture to a draw image call', () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakePaintingContext(); renderVectorGraphic.paint(context, Offset.zero); @@ -61,22 +54,8 @@ void main() { }); test('Multiple render objects with the same scale share a raster', () async { - final renderVectorGraphicA = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); - final renderVectorGraphicB = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); + final renderVectorGraphicA = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); + final renderVectorGraphicB = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); renderVectorGraphicA.layout(BoxConstraints.tight(const Size(50, 50))); renderVectorGraphicB.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakeHistoryPaintingContext(); @@ -90,22 +69,8 @@ void main() { }); test('disposing render object release raster', () async { - final renderVectorGraphicA = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); - final renderVectorGraphicB = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); + final renderVectorGraphicA = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); + final renderVectorGraphicB = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); renderVectorGraphicA.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakeHistoryPaintingContext(); @@ -118,31 +83,14 @@ void main() { renderVectorGraphicB.paint(context, Offset.zero); expect(context.canvas.images, hasLength(2)); - expect( - identical(context.canvas.images[0], context.canvas.images[1]), - false, - ); + expect(identical(context.canvas.images[0], context.canvas.images[1]), false); }); test( 'Multiple render objects with the same scale share a raster, different load order', () async { - final renderVectorGraphicA = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); - final renderVectorGraphicB = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); + final renderVectorGraphicA = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); + final renderVectorGraphicB = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); renderVectorGraphicA.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakeHistoryPaintingContext(); @@ -155,32 +103,19 @@ void main() { renderVectorGraphicB.paint(context, Offset.zero); expect(context.canvas.images, hasLength(2)); - expect( - identical(context.canvas.images[0], context.canvas.images[1]), - true, - ); + expect(identical(context.canvas.images[0], context.canvas.images[1]), true); }, ); test('Changing color filter does not re-rasterize', () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakePaintingContext(); renderVectorGraphic.paint(context, Offset.zero); final ui.Image firstImage = context.canvas.lastImage!; - renderVectorGraphic.colorFilter = const ui.ColorFilter.mode( - Colors.red, - ui.BlendMode.colorBurn, - ); + renderVectorGraphic.colorFilter = const ui.ColorFilter.mode(Colors.red, ui.BlendMode.colorBurn); renderVectorGraphic.paint(context, Offset.zero); expect(firstImage.debugDisposed, false); @@ -190,43 +125,26 @@ void main() { expect(context.canvas.lastImage, equals(firstImage)); }); - test( - 'Changing device pixel ratio does re-rasterize and dispose old raster', - () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); - renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); - final context = FakePaintingContext(); - renderVectorGraphic.paint(context, Offset.zero); + test('Changing device pixel ratio does re-rasterize and dispose old raster', () async { + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); + renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); + final context = FakePaintingContext(); + renderVectorGraphic.paint(context, Offset.zero); - final ui.Image firstImage = context.canvas.lastImage!; + final ui.Image firstImage = context.canvas.lastImage!; - renderVectorGraphic.devicePixelRatio = 2.0; - renderVectorGraphic.paint(context, Offset.zero); + renderVectorGraphic.devicePixelRatio = 2.0; + renderVectorGraphic.paint(context, Offset.zero); - expect(firstImage.debugDisposed, true); + expect(firstImage.debugDisposed, true); - renderVectorGraphic.paint(context, Offset.zero); + renderVectorGraphic.paint(context, Offset.zero); - expect(context.canvas.lastImage!.debugDisposed, false); - }, - ); + expect(context.canvas.lastImage!.debugDisposed, false); + }); test('Changing scale does re-rasterize and dispose old raster', () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakePaintingContext(); renderVectorGraphic.paint(context, Offset.zero); @@ -258,21 +176,11 @@ void main() { // Dst rect is always size of RO. expect(context.canvas.lastDst, const Rect.fromLTWH(0, 0, 50, 50)); - expect( - context.canvas.lastSrc, - const Rect.fromLTWH(0, 0, 50 / 0.5, 50 / 0.5), - ); + expect(context.canvas.lastSrc, const Rect.fromLTWH(0, 0, 50 / 0.5, 50 / 0.5)); }); test('The raster size is increased by the device pixel ratio', () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 2.0, - null, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 2.0, null, 1.0); renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakePaintingContext(); renderVectorGraphic.paint(context, Offset.zero); @@ -282,62 +190,32 @@ void main() { expect(context.canvas.lastSrc, const Rect.fromLTWH(0, 0, 100, 100)); }); - test( - 'The raster size is increased by the device pixel ratio and ratio', - () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 2.0, - null, - 0.5, - ); - renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); - final context = FakePaintingContext(); - renderVectorGraphic.paint(context, Offset.zero); - - // Dst rect is always size of RO. - expect(context.canvas.lastDst, const Rect.fromLTWH(0, 0, 50, 50)); - expect(context.canvas.lastSrc, const Rect.fromLTWH(0, 0, 200, 200)); - }, - ); + test('The raster size is increased by the device pixel ratio and ratio', () async { + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 2.0, null, 0.5); + renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); + final context = FakePaintingContext(); + renderVectorGraphic.paint(context, Offset.zero); - test( - 'Changing size asserts if it is different from the picture size', - () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); - renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); - final context = FakePaintingContext(); - renderVectorGraphic.paint(context, Offset.zero); - - // change size. - renderVectorGraphic.layout(BoxConstraints.tight(const Size(1000, 1000))); - - expect( - () => renderVectorGraphic.paint(context, Offset.zero), - throwsAssertionError, - ); - }, - ); + // Dst rect is always size of RO. + expect(context.canvas.lastDst, const Rect.fromLTWH(0, 0, 50, 50)); + expect(context.canvas.lastSrc, const Rect.fromLTWH(0, 0, 200, 200)); + }); + + test('Changing size asserts if it is different from the picture size', () async { + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); + renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); + final context = FakePaintingContext(); + renderVectorGraphic.paint(context, Offset.zero); + + // change size. + renderVectorGraphic.layout(BoxConstraints.tight(const Size(1000, 1000))); + + expect(() => renderVectorGraphic.paint(context, Offset.zero), throwsAssertionError); + }); test('Does not rasterize a picture when fully transparent', () async { final opacity = FixedOpacityAnimation(0.0); - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - opacity, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, opacity, 1.0); renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakePaintingContext(); renderVectorGraphic.paint(context, Offset.zero); @@ -356,14 +234,7 @@ void main() { test('paints partially opaque picture', () async { final opacity = FixedOpacityAnimation(0.5); - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - opacity, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, opacity, 1.0); renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakePaintingContext(); renderVectorGraphic.paint(context, Offset.zero); @@ -372,14 +243,7 @@ void main() { }); test('Disposing render object disposes picture', () async { - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - null, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, null, 1.0); renderVectorGraphic.layout(BoxConstraints.tight(const Size(50, 50))); final context = FakePaintingContext(); renderVectorGraphic.paint(context, Offset.zero); @@ -393,14 +257,7 @@ void main() { test('Removes listeners on detach, dispose, adds then on attach', () async { final opacity = FixedOpacityAnimation(0.5); - final renderVectorGraphic = RenderVectorGraphic( - pictureInfo, - 'test', - null, - 1.0, - opacity, - 1.0, - ); + final renderVectorGraphic = RenderVectorGraphic(pictureInfo, 'test', null, 1.0, opacity, 1.0); final pipelineOwner = PipelineOwner(); expect(opacity._listeners, hasLength(1)); @@ -438,10 +295,7 @@ void main() { final context = FakePaintingContext(); render.paint(context, Offset.zero); - expect( - context.canvas.lastClipRect, - equals(const ui.Rect.fromLTRB(0, 0, 50, 50)), - ); + expect(context.canvas.lastClipRect, equals(const ui.Rect.fromLTRB(0, 0, 50, 50))); expect(context.canvas.saveCount, 0); expect(context.canvas.totalSaves, 1); expect(context.canvas.totalSaveLayers, 1); @@ -497,11 +351,7 @@ class FakeCanvas extends Fake implements Canvas { } @override - void clipRect( - ui.Rect rect, { - ui.ClipOp clipOp = ui.ClipOp.intersect, - bool doAntiAlias = true, - }) { + void clipRect(ui.Rect rect, {ui.ClipOp clipOp = ui.ClipOp.intersect, bool doAntiAlias = true}) { lastClipRect = rect; } } diff --git a/packages/vector_graphics/test/vector_graphics_test.dart b/packages/vector_graphics/test/vector_graphics_test.dart index a3dc559258bc..155134589312 100644 --- a/packages/vector_graphics/test/vector_graphics_test.dart +++ b/packages/vector_graphics/test/vector_graphics_test.dart @@ -65,76 +65,58 @@ void main() { expect(listener.toPicture, throwsAssertionError); }); - testWidgets( - 'Creates layout widgets when VectorGraphic is sized (0x0 graphic)', - (WidgetTester tester) async { - final buffer = VectorGraphicsBuffer(); - await tester.pumpWidget( - VectorGraphic( - loader: TestBytesLoader(buffer.done()), - width: 100, - height: 100, - ), - ); - await tester.pumpAndSettle(); + testWidgets('Creates layout widgets when VectorGraphic is sized (0x0 graphic)', ( + WidgetTester tester, + ) async { + final buffer = VectorGraphicsBuffer(); + await tester.pumpWidget( + VectorGraphic(loader: TestBytesLoader(buffer.done()), width: 100, height: 100), + ); + await tester.pumpAndSettle(); - expect(find.byType(SizedBox), findsNWidgets(2)); + expect(find.byType(SizedBox), findsNWidgets(2)); - final sizedBox = - find.byType(SizedBox).evaluate().first.widget as SizedBox; + final sizedBox = find.byType(SizedBox).evaluate().first.widget as SizedBox; - expect(sizedBox.width, 100); - expect(sizedBox.height, 100); - }, - ); + expect(sizedBox.width, 100); + expect(sizedBox.height, 100); + }); - testWidgets( - 'Creates layout widgets when VectorGraphic is sized (1:1 ratio)', - (WidgetTester tester) async { - final buffer = VectorGraphicsBuffer(); - const VectorGraphicsCodec().writeSize(buffer, 50, 50); - await tester.pumpWidget( - VectorGraphic( - loader: TestBytesLoader(buffer.done()), - width: 100, - height: 100, - ), - ); - await tester.pumpAndSettle(); + testWidgets('Creates layout widgets when VectorGraphic is sized (1:1 ratio)', ( + WidgetTester tester, + ) async { + final buffer = VectorGraphicsBuffer(); + const VectorGraphicsCodec().writeSize(buffer, 50, 50); + await tester.pumpWidget( + VectorGraphic(loader: TestBytesLoader(buffer.done()), width: 100, height: 100), + ); + await tester.pumpAndSettle(); - expect(find.byType(SizedBox), findsNWidgets(2)); + expect(find.byType(SizedBox), findsNWidgets(2)); - final sizedBox = - find.byType(SizedBox).evaluate().first.widget as SizedBox; + final sizedBox = find.byType(SizedBox).evaluate().first.widget as SizedBox; - expect(sizedBox.width, 100); - expect(sizedBox.height, 100); - }, - ); + expect(sizedBox.width, 100); + expect(sizedBox.height, 100); + }); - testWidgets( - 'Creates layout widgets when VectorGraphic is sized (3:5 ratio)', - (WidgetTester tester) async { - final buffer = VectorGraphicsBuffer(); - const VectorGraphicsCodec().writeSize(buffer, 30, 50); - await tester.pumpWidget( - VectorGraphic( - loader: TestBytesLoader(buffer.done()), - width: 100, - height: 100, - ), - ); - await tester.pumpAndSettle(); + testWidgets('Creates layout widgets when VectorGraphic is sized (3:5 ratio)', ( + WidgetTester tester, + ) async { + final buffer = VectorGraphicsBuffer(); + const VectorGraphicsCodec().writeSize(buffer, 30, 50); + await tester.pumpWidget( + VectorGraphic(loader: TestBytesLoader(buffer.done()), width: 100, height: 100), + ); + await tester.pumpAndSettle(); - expect(find.byType(SizedBox), findsNWidgets(2)); + expect(find.byType(SizedBox), findsNWidgets(2)); - final sizedBox = - find.byType(SizedBox).evaluate().first.widget as SizedBox; + final sizedBox = find.byType(SizedBox).evaluate().first.widget as SizedBox; - expect(sizedBox.width, 60); - expect(sizedBox.height, 100); - }, - ); + expect(sizedBox.width, 60); + expect(sizedBox.height, 100); + }); testWidgets('Creates alignment widgets when VectorGraphic is aligned', ( WidgetTester tester, @@ -151,8 +133,7 @@ void main() { expect(find.byType(FittedBox), findsOneWidget); - final fittedBox = - find.byType(FittedBox).evaluate().first.widget as FittedBox; + final fittedBox = find.byType(FittedBox).evaluate().first.widget as FittedBox; expect(fittedBox.fit, BoxFit.fitHeight); expect(fittedBox.alignment, Alignment.centerLeft); @@ -173,58 +154,50 @@ void main() { child: SizedBox( width: 200, height: 200, - child: VectorGraphic( - fit: fit, - loader: TestBytesLoader(buffer.done()), - ), + child: VectorGraphic(fit: fit, loader: TestBytesLoader(buffer.done())), ), ), ), ); await tester.pumpAndSettle(); - final RenderProxyBox outsideBox = tester.renderObject( - find.byType(VectorGraphic), - ); + final RenderProxyBox outsideBox = tester.renderObject(find.byType(VectorGraphic)); expect(outsideBox.size, const Size(200, 200)); - final RenderBox insideBox = tester.renderObject( - find.byType(SizedBox).last, - ); + final RenderBox insideBox = tester.renderObject(find.byType(SizedBox).last); expect(insideBox.size, const Size(100, 50)); return (outsideBox, insideBox); } - testWidgets( - 'Scale on BoxFit.contain without constraints, but with viewbox', - (WidgetTester tester) async { - final (RenderBox outsideBox, RenderBox insideBox) = - await setupBoxFitVectorGraphic(tester, fit: BoxFit.contain); - - // Top left point as offset in child space - final Offset insidePoint = insideBox.localToGlobal(Offset.zero); - // Top left point as offset in parent space - final Offset outsidePoint = outsideBox.localToGlobal( - const Offset(0, 50), - ); - - expect(insidePoint, equals(outsidePoint)); - }, - ); + testWidgets('Scale on BoxFit.contain without constraints, but with viewbox', ( + WidgetTester tester, + ) async { + final (RenderBox outsideBox, RenderBox insideBox) = await setupBoxFitVectorGraphic( + tester, + fit: BoxFit.contain, + ); + + // Top left point as offset in child space + final Offset insidePoint = insideBox.localToGlobal(Offset.zero); + // Top left point as offset in parent space + final Offset outsidePoint = outsideBox.localToGlobal(const Offset(0, 50)); + + expect(insidePoint, equals(outsidePoint)); + }); testWidgets('Scale on BoxFit.cover without constraints, but with viewbox', ( WidgetTester tester, ) async { - final (RenderBox outsideBox, RenderBox insideBox) = - await setupBoxFitVectorGraphic(tester, fit: BoxFit.cover); + final (RenderBox outsideBox, RenderBox insideBox) = await setupBoxFitVectorGraphic( + tester, + fit: BoxFit.cover, + ); // Top left point as offset in child space final Offset insidePoint = insideBox.localToGlobal(Offset.zero); // Top left point as offset in parent space - final Offset outsidePoint = outsideBox.localToGlobal( - const Offset(-100, 0), - ); + final Offset outsidePoint = outsideBox.localToGlobal(const Offset(-100, 0)); expect(insidePoint, equals(outsidePoint)); }); @@ -232,8 +205,10 @@ void main() { testWidgets('Scale on BoxFit.fill without constraints, but with viewbox', ( WidgetTester tester, ) async { - final (RenderBox outsideBox, RenderBox insideBox) = - await setupBoxFitVectorGraphic(tester, fit: BoxFit.fill); + final (RenderBox outsideBox, RenderBox insideBox) = await setupBoxFitVectorGraphic( + tester, + fit: BoxFit.fill, + ); // Top left point as offset in child space final Offset insidePoint = insideBox.localToGlobal(Offset.zero); @@ -245,39 +220,28 @@ void main() { }); group('ClipBehavior', () { - testWidgets('Sets clipBehavior to hardEdge if not provided', ( - WidgetTester tester, - ) async { + testWidgets('Sets clipBehavior to hardEdge if not provided', (WidgetTester tester) async { final buffer = VectorGraphicsBuffer(); - await tester.pumpWidget( - VectorGraphic(loader: TestBytesLoader(buffer.done())), - ); + await tester.pumpWidget(VectorGraphic(loader: TestBytesLoader(buffer.done()))); await tester.pumpAndSettle(); expect(find.byType(FittedBox), findsOneWidget); - final fittedBox = - find.byType(FittedBox).evaluate().first.widget as FittedBox; + final fittedBox = find.byType(FittedBox).evaluate().first.widget as FittedBox; expect(fittedBox.clipBehavior, Clip.hardEdge); }); - testWidgets('Passes clipBehavior to FittedBox if provided', ( - WidgetTester tester, - ) async { + testWidgets('Passes clipBehavior to FittedBox if provided', (WidgetTester tester) async { final buffer = VectorGraphicsBuffer(); await tester.pumpWidget( - VectorGraphic( - loader: TestBytesLoader(buffer.done()), - clipBehavior: Clip.none, - ), + VectorGraphic(loader: TestBytesLoader(buffer.done()), clipBehavior: Clip.none), ); await tester.pumpAndSettle(); expect(find.byType(FittedBox), findsOneWidget); - final fittedBox = - find.byType(FittedBox).evaluate().first.widget as FittedBox; + final fittedBox = find.byType(FittedBox).evaluate().first.widget as FittedBox; expect(fittedBox.clipBehavior, Clip.none); }); @@ -289,9 +253,7 @@ void main() { final buffer = VectorGraphicsBuffer(); codec.writeSize(buffer, 100, 200); - await tester.pumpWidget( - VectorGraphic(loader: TestBytesLoader(buffer.done())), - ); + await tester.pumpWidget(VectorGraphic(loader: TestBytesLoader(buffer.done()))); await tester.pumpAndSettle(); expect(find.byType(SizedBox), findsNWidgets(1)); @@ -302,19 +264,14 @@ void main() { expect(sizedBox.height, 200); }); - testWidgets('Reloads bytes when configuration changes', ( - WidgetTester tester, - ) async { + testWidgets('Reloads bytes when configuration changes', (WidgetTester tester) async { final testBundle = TestAssetBundle(); final GlobalKey key = GlobalKey(); await tester.pumpWidget( DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('foo.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('foo.svg')), ), ); @@ -323,10 +280,7 @@ void main() { await tester.pumpWidget( DefaultAssetBundle( bundle: testBundle, - child: VectorGraphic( - key: key, - loader: const AssetBytesLoader('bar.svg'), - ), + child: VectorGraphic(key: key, loader: const AssetBytesLoader('bar.svg')), ), ); @@ -361,9 +315,7 @@ void main() { final testBundle = TestAssetBundle(); await tester.pumpWidget( Localizations( - delegates: const >[ - DefaultWidgetsLocalizations.delegate, - ], + delegates: const >[DefaultWidgetsLocalizations.delegate], locale: const Locale('fr', 'CH'), child: Directionality( textDirection: TextDirection.rtl, @@ -381,9 +333,7 @@ void main() { await tester.pumpWidget( Localizations( - delegates: const >[ - DefaultWidgetsLocalizations.delegate, - ], + delegates: const >[DefaultWidgetsLocalizations.delegate], locale: const Locale('ab', 'AB'), child: Directionality( textDirection: TextDirection.ltr, @@ -400,9 +350,7 @@ void main() { expect(debugLastTextDirection, TextDirection.ltr); }); - testWidgets('Test animated switch between placeholder and image', ( - WidgetTester tester, - ) async { + testWidgets('Test animated switch between placeholder and image', (WidgetTester tester) async { final testBundle = TestAssetBundle(); const placeholderWidget = Text('Placeholder'); @@ -455,10 +403,7 @@ void main() { bundle: testBundle, child: const Directionality( textDirection: TextDirection.ltr, - child: VectorGraphic( - loader: AssetBytesLoader('foo.svg'), - semanticsLabel: 'Foo', - ), + child: VectorGraphic(loader: AssetBytesLoader('foo.svg'), semanticsLabel: 'Foo'), ), ), ); @@ -478,10 +423,7 @@ void main() { bundle: testBundle, child: const Directionality( textDirection: TextDirection.ltr, - child: VectorGraphic( - loader: AssetBytesLoader('foo.svg'), - semanticsLabel: 'Foo', - ), + child: VectorGraphic(loader: AssetBytesLoader('foo.svg'), semanticsLabel: 'Foo'), ), ), ); @@ -511,9 +453,7 @@ void main() { expect(find.byKey(const ValueKey(23)), findsOneWidget); }); - testWidgets('Does not call setState after unmounting', ( - WidgetTester tester, - ) async { + testWidgets('Does not call setState after unmounting', (WidgetTester tester) async { final buffer = VectorGraphicsBuffer(); codec.writeSize(buffer, 100, 200); final completer = Completer(); @@ -533,9 +473,7 @@ void main() { final completer = Completer(); await tester.pumpWidget( Localizations( - delegates: const >[ - DefaultWidgetsLocalizations.delegate, - ], + delegates: const >[DefaultWidgetsLocalizations.delegate], locale: const Locale('fr', 'CH'), child: Directionality( textDirection: TextDirection.rtl, @@ -543,9 +481,7 @@ void main() { bundle: testBundle, child: Builder( builder: (BuildContext context) { - vg - .loadPicture(const AssetBytesLoader('foo.svg'), context) - .then(completer.complete); + vg.loadPicture(const AssetBytesLoader('foo.svg'), context).then(completer.complete); return const Center(); }, ), @@ -567,9 +503,7 @@ void main() { final completer = Completer(); await tester.pumpWidget( Localizations( - delegates: const >[ - DefaultWidgetsLocalizations.delegate, - ], + delegates: const >[DefaultWidgetsLocalizations.delegate], locale: const Locale('fr', 'CH'), child: Directionality( textDirection: TextDirection.rtl, @@ -578,10 +512,7 @@ void main() { child: Builder( builder: (BuildContext context) { vg - .loadPicture( - AssetBytesLoader('foo.svg', assetBundle: testBundle), - null, - ) + .loadPicture(AssetBytesLoader('foo.svg', assetBundle: testBundle), null) .then(completer.complete); return const Center(); }, @@ -597,14 +528,9 @@ void main() { expect(debugLastTextDirection, TextDirection.ltr); }); - testWidgets('Throws a helpful exception if decoding fails', ( - WidgetTester tester, - ) async { + testWidgets('Throws a helpful exception if decoding fails', (WidgetTester tester) async { final data = Uint8List(256); - final loader = TestBytesLoader( - data.buffer.asByteData(), - '/foo/bar/whatever.vec', - ); + final loader = TestBytesLoader(data.buffer.asByteData(), '/foo/bar/whatever.vec'); final GlobalKey key = GlobalKey(); await tester.pumpWidget(Placeholder(key: key)); @@ -684,10 +610,7 @@ void main() { expect(imageCache.statusForKey(imageKey).pending, true); // A blank image, because the image hasn't loaded yet. - await expectLater( - find.byKey(key), - matchesGoldenFile('goldens/vg_with_image_blank.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('goldens/vg_with_image_blank.png')); expect(imageCache.currentSize, 1); expect(imageCache.statusForKey(imageKey).live, false); @@ -701,10 +624,7 @@ void main() { expect(imageCache.statusForKey(imageKey).keepAlive, true); // A blue square, because the image is available now. - await expectLater( - find.byKey(key), - matchesGoldenFile('goldens/vg_with_image_blue.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('goldens/vg_with_image_blue.png')); }, skip: kIsWeb); test('AssetBytesLoader respects packages', () async { @@ -713,11 +633,7 @@ void main() { 'packages/packageName/foo': Uint8List(1).buffer.asByteData(), }); final loader = AssetBytesLoader('foo', assetBundle: bundle); - final packageLoader = AssetBytesLoader( - 'foo', - assetBundle: bundle, - packageName: 'packageName', - ); + final packageLoader = AssetBytesLoader('foo', assetBundle: bundle, packageName: 'packageName'); expect((await loader.loadBytes(null)).lengthInBytes, 0); expect((await packageLoader.loadBytes(null)).lengthInBytes, 1); }); @@ -743,21 +659,14 @@ void main() { textDirection: TextDirection.rtl, child: DefaultAssetBundle( bundle: testBundle, - child: const VectorGraphic( - loader: AssetBytesLoader('foo.svg'), - matchTextDirection: true, - ), + child: const VectorGraphic(loader: AssetBytesLoader('foo.svg'), matchTextDirection: true), ), ), ); await tester.pumpAndSettle(); final matrix = Matrix4.identity(); - final RenderObject transformObject = find - .byType(Transform) - .evaluate() - .first - .renderObject!; + final RenderObject transformObject = find.byType(Transform).evaluate().first.renderObject!; var visited = false; transformObject.visitChildren((RenderObject child) { if (!visited) { @@ -766,18 +675,13 @@ void main() { visited = true; }); expect(visited, true); - expect( - matrix.getTranslation().x, - 100, - ); // Width specified in the TestAssetBundle. + expect(matrix.getTranslation().x, 100); // Width specified in the TestAssetBundle. expect(matrix.getTranslation().y, 0); expect(matrix.row0.x, -1); expect(matrix.row1.y, 1); }); - testWidgets('imageBuilder wraps the loaded vector graphic', ( - WidgetTester tester, - ) async { + testWidgets('imageBuilder wraps the loaded vector graphic', (WidgetTester tester) async { final buffer = VectorGraphicsBuffer(); codec.writeSize(buffer, 100, 200); final ByteData data = buffer.done(); @@ -788,10 +692,7 @@ void main() { child: VectorGraphic( loader: TestBytesLoader(data), imageBuilder: (BuildContext context, Widget child) { - return Container( - key: const ValueKey('image-builder'), - child: child, - ); + return Container(key: const ValueKey('image-builder'), child: child); }, ), ), @@ -801,9 +702,7 @@ void main() { expect(find.byKey(const ValueKey('image-builder')), findsOneWidget); }); - testWidgets('imageBuilder is not called during placeholder state', ( - WidgetTester tester, - ) async { + testWidgets('imageBuilder is not called during placeholder state', (WidgetTester tester) async { final completer = Completer(); await tester.pumpWidget( @@ -812,10 +711,7 @@ void main() { child: VectorGraphic( loader: DelayedBytesLoader(completer.future), imageBuilder: (BuildContext context, Widget child) { - return Container( - key: const ValueKey('image-builder'), - child: child, - ); + return Container(key: const ValueKey('image-builder'), child: child); }, placeholderBuilder: (BuildContext context) { return Container(key: const ValueKey('placeholder')); @@ -847,13 +743,12 @@ void main() { loader: const ThrowingBytesLoader(), width: 100, height: 100, - errorBuilder: - (BuildContext context, Object error, StackTrace stackTrace) { - return const Directionality( - textDirection: TextDirection.ltr, - child: Text('Error is handled'), - ); - }, + errorBuilder: (BuildContext context, Object error, StackTrace stackTrace) { + return const Directionality( + textDirection: TextDirection.ltr, + child: Text('Error is handled'), + ); + }, ), ); await tester.pumpAndSettle(); diff --git a/packages/vector_graphics_codec/lib/src/fp16.dart b/packages/vector_graphics_codec/lib/src/fp16.dart index 6b5aa98c9031..8e2d9e3ebfe8 100644 --- a/packages/vector_graphics_codec/lib/src/fp16.dart +++ b/packages/vector_graphics_codec/lib/src/fp16.dart @@ -28,8 +28,7 @@ const int SHIFTED_EXPONENT_MASK = 0x1f; const int SIGNIFICAND_MASK = 0x3ff; // ignore: non_constant_identifier_names -final ByteData FP32_DENORMAL_FLOAT = ByteData(4) - ..setUint32(0, FP32_DENORMAL_MAGIC); +final ByteData FP32_DENORMAL_FLOAT = ByteData(4)..setUint32(0, FP32_DENORMAL_MAGIC); /// Convert the single precision floating point value stored in [byteData] into a half-precision floating point value. /// diff --git a/packages/vector_graphics_codec/lib/vector_graphics_codec.dart b/packages/vector_graphics_codec/lib/vector_graphics_codec.dart index 2f491a783403..4b06b710984e 100644 --- a/packages/vector_graphics_codec/lib/vector_graphics_codec.dart +++ b/packages/vector_graphics_codec/lib/vector_graphics_codec.dart @@ -39,8 +39,7 @@ const int kLineThroughMask = 0x4; /// decoding. /// /// See [VectorGraphicsCodecListener.onImage]. -typedef VectorGraphicsErrorListener = - void Function(Object error, StackTrace? stackTrace); +typedef VectorGraphicsErrorListener = void Function(Object error, StackTrace? stackTrace); /// Enumeration of the types of image data accepted by [VectorGraphicsCodec.writeImage]. /// @@ -147,21 +146,15 @@ class VectorGraphicsCodec { if (response == null) { buffer = _ReadBuffer(data); if (data.lengthInBytes < 5) { - throw StateError( - 'The provided data was not a vector_graphics binary asset.', - ); + throw StateError('The provided data was not a vector_graphics binary asset.'); } final int magicNumber = buffer.getUint32(); if (magicNumber != _magicNumber) { - throw StateError( - 'The provided data was not a vector_graphics binary asset.', - ); + throw StateError('The provided data was not a vector_graphics binary asset.'); } final int version = buffer.getUint8(); if (version != _version) { - throw StateError( - 'The provided data does not match the currently supported version.', - ); + throw StateError('The provided data does not match the currently supported version.'); } } else { buffer = response._buffer!; @@ -260,12 +253,7 @@ class VectorGraphicsCodec { /// Encode a draw path command in the current buffer. /// /// Requires that [pathId] and [paintId] to already be encoded. - void writeDrawPath( - VectorGraphicsBuffer buffer, - int pathId, - int paintId, - int? patternId, - ) { + void writeDrawPath(VectorGraphicsBuffer buffer, int pathId, int paintId, int? patternId) { buffer._checkPhase(_CurrentSection.commands); buffer._addCommandsTag(); @@ -315,12 +303,7 @@ class VectorGraphicsCodec { /// /// This method is only used to write the paint used for fill commands. /// To write a paint used for a stroke command, see [writeStroke]. - int writeFill( - VectorGraphicsBuffer buffer, - int color, - int blendMode, [ - int? shaderId, - ]) { + int writeFill(VectorGraphicsBuffer buffer, int color, int blendMode, [int? shaderId]) { buffer._checkPhase(_CurrentSection.paints); final int paintId = buffer._nextPaintId++; @@ -381,9 +364,7 @@ class VectorGraphicsCodec { required Float64List? transform, required int tileMode, }) { - assert( - (focalX == null && focalY == null) || (focalX != null && focalY != null), - ); + assert((focalX == null && focalY == null) || (focalX != null && focalY != null)); assert(transform == null || transform.length == 16); buffer._checkPhase(_CurrentSection.shaders); @@ -449,10 +430,7 @@ class VectorGraphicsCodec { return paintId; } - void _readLinearGradient( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readLinearGradient(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int id = buffer.getUint16(); final double fromX = buffer.getFloat32(); final double fromY = buffer.getFloat32(); @@ -463,22 +441,10 @@ class VectorGraphicsCodec { final int offsetLength = buffer.getUint16(); final Float32List offsets = buffer.getFloat32List(offsetLength); final int tileMode = buffer.getUint8(); - listener?.onLinearGradient( - fromX, - fromY, - toX, - toY, - colors, - offsets, - tileMode, - id, - ); + listener?.onLinearGradient(fromX, fromY, toX, toY, colors, offsets, tileMode, id); } - void _readRadialGradient( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readRadialGradient(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int id = buffer.getUint16(); final double centerX = buffer.getFloat32(); final double centerY = buffer.getFloat32(); @@ -510,10 +476,7 @@ class VectorGraphicsCodec { ); } - void _readFillPaint( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readFillPaint(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int color = buffer.getUint32(); final int blendMode = buffer.getUint8(); final int id = buffer.getUint16(); @@ -532,10 +495,7 @@ class VectorGraphicsCodec { ); } - void _readStrokePaint( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readStrokePaint(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int color = buffer.getUint32(); final int strokeCap = buffer.getUint8(); final int strokeJoin = buffer.getUint8(); @@ -672,10 +632,7 @@ class VectorGraphicsCodec { buffer._writeTransform(transform); } - void writeUpdateTextPosition( - VectorGraphicsBuffer buffer, - int textPositionId, - ) { + void writeUpdateTextPosition(VectorGraphicsBuffer buffer, int textPositionId) { buffer._checkPhase(_CurrentSection.commands); buffer._addCommandsTag(); buffer._putUint8(_updateTextPositionTag); @@ -819,11 +776,7 @@ class VectorGraphicsCodec { buffer._writeTransform(transform); } - void _readPath( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, { - required bool half, - }) { + void _readPath(_ReadBuffer buffer, VectorGraphicsCodecListener? listener, {required bool half}) { final int fillType = buffer.getUint8(); final int id = buffer.getUint16(); final int tagLength = buffer.getUint32(); @@ -867,10 +820,7 @@ class VectorGraphicsCodec { listener?.onPathFinished(); } - void _readDrawPath( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readDrawPath(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int pathId = buffer.getUint16(); final int paintId = buffer.getUint16(); int? patternId = buffer.getUint16(); @@ -880,10 +830,7 @@ class VectorGraphicsCodec { listener?.onDrawPath(pathId, paintId, patternId); } - void _readDrawVertices( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readDrawVertices(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int paintId = buffer.getUint16(); final int verticesLength = buffer.getUint16(); final Float32List vertices = buffer.getFloat32List(verticesLength); @@ -892,25 +839,15 @@ class VectorGraphicsCodec { if (indexLength != 0) { indices = buffer.getUint16List(indexLength); } - listener?.onDrawVertices( - vertices, - indices, - paintId != kMaxId ? paintId : null, - ); + listener?.onDrawVertices(vertices, indices, paintId != kMaxId ? paintId : null); } - void _readSaveLayer( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readSaveLayer(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int paintId = buffer.getUint16(); listener?.onSaveLayer(paintId); } - void _readClipPath( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readClipPath(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int pathId = buffer.getUint16(); listener?.onClipPath(pathId); } @@ -921,10 +858,7 @@ class VectorGraphicsCodec { listener?.onSize(width, height); } - void _readTextPosition( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readTextPosition(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int id = buffer.getUint16(); final double x = buffer.getFloat32(); final double y = buffer.getFloat32(); @@ -945,18 +879,12 @@ class VectorGraphicsCodec { ); } - void _readUpdateTextPosition( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readUpdateTextPosition(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int textPositionId = buffer.getUint16(); listener?.onUpdateTextPosition(textPositionId); } - void _readTextConfig( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readTextConfig(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int id = buffer.getUint16(); final double xAnchorMultiplier = buffer.getFloat32(); final double fontSize = buffer.getFloat32(); @@ -985,10 +913,7 @@ class VectorGraphicsCodec { ); } - void _readDrawText( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readDrawText(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int textId = buffer.getUint16(); int? fillId = buffer.getUint16(); if (fillId == kMaxId) { @@ -1006,10 +931,7 @@ class VectorGraphicsCodec { listener?.onDrawText(textId, fillId, strokeId, patternId); } - void _readImageConfig( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readImageConfig(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int id = buffer.getUint16(); final int format = buffer.getUint8(); final int dataLength = buffer.getUint32(); @@ -1017,10 +939,7 @@ class VectorGraphicsCodec { listener?.onImage(id, format, data); } - void _readDrawImage( - _ReadBuffer buffer, - VectorGraphicsCodecListener? listener, - ) { + void _readDrawImage(_ReadBuffer buffer, VectorGraphicsCodecListener? listener) { final int id = buffer.getUint16(); final double x = buffer.getFloat32(); final double y = buffer.getFloat32(); @@ -1078,14 +997,7 @@ abstract class VectorGraphicsCodecListener { /// A path object will draw a cubic to (x1, y1), with control point 1 as /// (x2, y2) and control point 2 as (x3, y3). - void onPathCubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ); + void onPathCubicTo(double x1, double y1, double x2, double y2, double x3, double y3); /// The current path has been closed. void onPathClose(); @@ -1166,12 +1078,7 @@ abstract class VectorGraphicsCodecListener { /// /// If the [onError] callback is not null, it must be called if an error /// occurs while attempting to decode the image [data]. - void onImage( - int imageId, - int format, - Uint8List data, { - VectorGraphicsErrorListener? onError, - }); + void onImage(int imageId, int format, Uint8List data, {VectorGraphicsErrorListener? onError}); /// An image should be drawn at the provided location. void onDrawImage( @@ -1211,16 +1118,7 @@ abstract class VectorGraphicsCodecListener { void onUpdateTextPosition(int textPositionId); } -enum _CurrentSection { - size, - images, - shaders, - paints, - paths, - textPositions, - text, - commands, -} +enum _CurrentSection { size, images, shaders, paints, paths, textPositions, text, commands } /// Write-only buffer for incrementally building a [ByteData] instance. /// @@ -1230,10 +1128,7 @@ enum _CurrentSection { /// The byte order used is [Endian.little] throughout. class VectorGraphicsBuffer { /// Creates an interface for incrementally building a [ByteData] instance. - VectorGraphicsBuffer() - : _buffer = [], - _isDone = false, - _eightBytes = ByteData(8) { + VectorGraphicsBuffer() : _buffer = [], _isDone = false, _eightBytes = ByteData(8) { _eightBytesAsList = _eightBytes.buffer.asUint8List(); // Begin message with the magic number and current version. _putUint32(VectorGraphicsCodec._magicNumber); @@ -1327,9 +1222,7 @@ class VectorGraphicsBuffer { void _putInt32List(Int32List list) { assert(!_isDone); _alignTo(4); - _buffer.addAll( - list.buffer.asUint8List(list.offsetInBytes, 4 * list.length), - ); + _buffer.addAll(list.buffer.asUint8List(list.offsetInBytes, 4 * list.length)); } /// Write an Float32 into the buffer. @@ -1347,26 +1240,20 @@ class VectorGraphicsBuffer { void _putUint16List(Uint16List list) { assert(!_isDone); _alignTo(2); - _buffer.addAll( - list.buffer.asUint8List(list.offsetInBytes, 2 * list.length), - ); + _buffer.addAll(list.buffer.asUint8List(list.offsetInBytes, 2 * list.length)); } /// Write all the values from a [Float32List] into the buffer. void _putFloat32List(Float32List list) { assert(!_isDone); _alignTo(4); - _buffer.addAll( - list.buffer.asUint8List(list.offsetInBytes, 4 * list.length), - ); + _buffer.addAll(list.buffer.asUint8List(list.offsetInBytes, 4 * list.length)); } void _putFloat64List(Float64List list) { assert(!_isDone); _alignTo(8); - _buffer.addAll( - list.buffer.asUint8List(list.offsetInBytes, 8 * list.length), - ); + _buffer.addAll(list.buffer.asUint8List(list.offsetInBytes, 8 * list.length)); } void _alignTo(int alignment) { @@ -1457,20 +1344,14 @@ class _ReadBuffer { /// Reads the given number of Uint8s from the buffer. Uint8List getUint8List(int length) { - final Uint8List list = data.buffer.asUint8List( - data.offsetInBytes + _position, - length, - ); + final Uint8List list = data.buffer.asUint8List(data.offsetInBytes + _position, length); _position += length; return list; } Uint16List getUint16List(int length) { _alignTo(2); - final Uint16List list = data.buffer.asUint16List( - data.offsetInBytes + _position, - length, - ); + final Uint16List list = data.buffer.asUint16List(data.offsetInBytes + _position, length); _position += 2 * length; return list; } @@ -1478,10 +1359,7 @@ class _ReadBuffer { /// Reads the given number of Int32s from the buffer. Int32List getInt32List(int length) { _alignTo(4); - final Int32List list = data.buffer.asInt32List( - data.offsetInBytes + _position, - length, - ); + final Int32List list = data.buffer.asInt32List(data.offsetInBytes + _position, length); _position += 4 * length; return list; } @@ -1489,10 +1367,7 @@ class _ReadBuffer { /// Reads the given number of Int64s from the buffer. Int64List getInt64List(int length) { _alignTo(8); - final Int64List list = data.buffer.asInt64List( - data.offsetInBytes + _position, - length, - ); + final Int64List list = data.buffer.asInt64List(data.offsetInBytes + _position, length); _position += 8 * length; return list; } @@ -1500,10 +1375,7 @@ class _ReadBuffer { /// Reads the given number of Float32s from the buffer Float32List getFloat32List(int length) { _alignTo(4); - final Float32List list = data.buffer.asFloat32List( - data.offsetInBytes + _position, - length, - ); + final Float32List list = data.buffer.asFloat32List(data.offsetInBytes + _position, length); _position += 4 * length; return list; } @@ -1511,10 +1383,7 @@ class _ReadBuffer { /// Reads the given number of Float64s from the buffer. Float64List getFloat64List(int length) { _alignTo(8); - final Float64List list = data.buffer.asFloat64List( - data.offsetInBytes + _position, - length, - ); + final Float64List list = data.buffer.asFloat64List(data.offsetInBytes + _position, length); _position += 8 * length; return list; } diff --git a/packages/vector_graphics_codec/test/fp16_test.dart b/packages/vector_graphics_codec/test/fp16_test.dart index 75db15da14d5..a057fcd1ad50 100644 --- a/packages/vector_graphics_codec/test/fp16_test.dart +++ b/packages/vector_graphics_codec/test/fp16_test.dart @@ -19,11 +19,7 @@ void main() { final missed = >[]; /// Validate that all numbers between [min] and [max] can be converted within [tolerance]. - void checkRange({ - required double min, - required double max, - required double tolerance, - }) { + void checkRange({required double min, required double max, required double tolerance}) { final byteData = ByteData(8); for (var i = min; i < max; i += 1) { byteData.setFloat32(0, i); diff --git a/packages/vector_graphics_codec/test/vector_graphics_codec_test.dart b/packages/vector_graphics_codec/test/vector_graphics_codec_test.dart index 613ed1a0d8fb..be4ef2de29e7 100644 --- a/packages/vector_graphics_codec/test/vector_graphics_codec_test.dart +++ b/packages/vector_graphics_codec/test/vector_graphics_codec_test.dart @@ -80,9 +80,7 @@ void main() { isA().having( (StateError se) => se.message, 'message', - contains( - 'he provided data does not match the currently supported version.', - ), + contains('he provided data does not match the currently supported version.'), ), ), ); @@ -141,16 +139,7 @@ void main() { tileMode: 1, ); final int fillId = codec.writeFill(buffer, 23, 0, shaderId); - final int strokeId = codec.writeStroke( - buffer, - 44, - 1, - 2, - 3, - 4.0, - 6.0, - shaderId, - ); + final int strokeId = codec.writeStroke(buffer, 44, 1, 2, 3, 4.0, 6.0, shaderId); final int pathId = codec.writePath( buffer, Uint8List.fromList([ @@ -234,11 +223,7 @@ void main() { id: paintId, shaderId: null, ), - OnDrawVertices( - const [0.0, 2.0, 3.0, 4.0, 2.0, 4.0], - null, - paintId, - ), + OnDrawVertices(const [0.0, 2.0, 3.0, 4.0, 2.0, 4.0], null, paintId), ]); }); @@ -575,15 +560,7 @@ void main() { codec.decode(buffer.done(), listener); expect(listener.commands, [ - OnTextPosition( - id: 0, - x: 1, - y: 2, - dx: 3, - dy: 4, - reset: true, - transform: mat4, - ), + OnTextPosition(id: 0, x: 1, y: 2, dx: 3, dy: 4, reset: true, transform: mat4), ]); }); @@ -591,11 +568,7 @@ void main() { final buffer = VectorGraphicsBuffer(); final listener = TestListener(); - final int id = codec.writeImage( - buffer, - 0, - Uint8List.fromList([0, 1, 3, 4, 5]), - ); + final int id = codec.writeImage(buffer, 0, Uint8List.fromList([0, 1, 3, 4, 5])); codec.writeDrawImage(buffer, id, 1, 2, 100, 100, null); final ByteData data = buffer.done(); final DecodeResponse response = codec.decode(data, listener); @@ -605,11 +578,7 @@ void main() { OnImage(id, 0, const [0, 1, 3, 4, 5]), ]); - final DecodeResponse nextResponse = codec.decode( - data, - listener, - response: response, - ); + final DecodeResponse nextResponse = codec.decode(data, listener, response: response); expect(nextResponse.complete, true); expect(listener.commands, [ @@ -622,11 +591,7 @@ void main() { final buffer = VectorGraphicsBuffer(); final listener = TestListener(); - final int id = codec.writeImage( - buffer, - 0, - Uint8List.fromList([0, 1, 3, 4, 5]), - ); + final int id = codec.writeImage(buffer, 0, Uint8List.fromList([0, 1, 3, 4, 5])); codec.writeDrawImage(buffer, id, 1, 2, 100, 100, mat4); final ByteData data = buffer.done(); final DecodeResponse response = codec.decode(data, listener); @@ -636,11 +601,7 @@ void main() { OnImage(id, 0, const [0, 1, 3, 4, 5]), ]); - final DecodeResponse nextResponse = codec.decode( - data, - listener, - response: response, - ); + final DecodeResponse nextResponse = codec.decode(data, listener, response: response); expect(nextResponse.complete, true); expect(listener.commands, [ @@ -654,11 +615,7 @@ void main() { for (final int format in ImageFormatTypes.values) { expect( - codec.writeImage( - buffer, - format, - Uint8List.fromList([0, 1, 3, 4, 5]), - ), + codec.writeImage(buffer, format, Uint8List.fromList([0, 1, 3, 4, 5])), greaterThan(-1), ); } @@ -668,11 +625,7 @@ void main() { final buffer = VectorGraphicsBuffer(); final listener = TestListener(); - final int imageId = codec.writeImage( - buffer, - 0, - Uint8List.fromList([0, 1, 3, 4, 5]), - ); + final int imageId = codec.writeImage(buffer, 0, Uint8List.fromList([0, 1, 3, 4, 5])); final int shaderId = codec.writeLinearGradient( buffer, fromX: 0, @@ -684,16 +637,7 @@ void main() { tileMode: 1, ); final int fillId = codec.writeFill(buffer, 23, 0, shaderId); - final int strokeId = codec.writeStroke( - buffer, - 44, - 1, - 2, - 3, - 4.0, - 6.0, - shaderId, - ); + final int strokeId = codec.writeStroke(buffer, 44, 1, 2, 3, 4.0, 6.0, shaderId); final int pathId = codec.writePath( buffer, Uint8List.fromList([ @@ -937,14 +881,7 @@ class TestListener extends VectorGraphicsCodecListener { } @override - void onPathCubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) { + void onPathCubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { commands.add(OnPathCubicTo(x1, y1, x2, y2, x3, y3)); } @@ -1080,12 +1017,7 @@ class TestListener extends VectorGraphicsCodecListener { } @override - void onImage( - int imageId, - int format, - Uint8List data, { - VectorGraphicsErrorListener? onError, - }) { + void onImage(int imageId, int format, Uint8List data, {VectorGraphicsErrorListener? onError}) { commands.add(OnImage(imageId, format, data, onError: onError)); } @@ -1136,15 +1068,8 @@ class OnTextPosition { final Float64List? transform; @override - int get hashCode => Object.hash( - id, - x, - y, - dx, - dy, - reset, - Object.hashAll(transform ?? []), - ); + int get hashCode => + Object.hash(id, x, y, dx, dy, reset, Object.hashAll(transform ?? [])); @override bool operator ==(Object other) { @@ -1343,11 +1268,8 @@ class OnDrawVertices { final int? paintId; @override - int get hashCode => Object.hash( - Object.hashAll(vertices), - Object.hashAll(indices ?? []), - paintId, - ); + int get hashCode => + Object.hash(Object.hashAll(vertices), Object.hashAll(indices ?? []), paintId); @override bool operator ==(Object other) => @@ -1484,8 +1406,7 @@ class OnPathLineTo { int get hashCode => Object.hash(x, y); @override - bool operator ==(Object other) => - other is OnPathLineTo && other.x == x && other.y == y; + bool operator ==(Object other) => other is OnPathLineTo && other.x == x && other.y == y; @override String toString() => 'OnPathLineTo($x, $y)'; @@ -1502,8 +1423,7 @@ class OnPathMoveTo { int get hashCode => Object.hash(x, y); @override - bool operator ==(Object other) => - other is OnPathMoveTo && other.x == x && other.y == y; + bool operator ==(Object other) => other is OnPathMoveTo && other.x == x && other.y == y; @override String toString() => 'OnPathMoveTo($x, $y)'; @@ -1650,14 +1570,7 @@ class OnImage { @immutable class OnDrawImage { - const OnDrawImage( - this.id, - this.x, - this.y, - this.width, - this.height, - this.transform, - ); + const OnDrawImage(this.id, this.x, this.y, this.width, this.height, this.transform); final int id; final double x; @@ -1667,14 +1580,8 @@ class OnDrawImage { final Float64List? transform; @override - int get hashCode => Object.hash( - id, - x, - y, - width, - height, - Object.hashAll(transform ?? const []), - ); + int get hashCode => + Object.hash(id, x, y, width, height, Object.hashAll(transform ?? const [])); @override bool operator ==(Object other) { @@ -1693,14 +1600,7 @@ class OnDrawImage { @immutable class OnPatternStart { - const OnPatternStart( - this.patternId, - this.x, - this.y, - this.width, - this.height, - this.transform, - ); + const OnPatternStart(this.patternId, this.x, this.y, this.width, this.height, this.transform); final int patternId; final double x; @@ -1710,8 +1610,7 @@ class OnPatternStart { final Float64List transform; @override - int get hashCode => - Object.hash(patternId, x, y, width, height, Object.hashAll(transform)); + int get hashCode => Object.hash(patternId, x, y, width, height, Object.hashAll(transform)); @override bool operator ==(Object other) => @@ -1724,8 +1623,7 @@ class OnPatternStart { _listEquals(other.transform, transform); @override - String toString() => - 'OnPatternStart($patternId, $x, $y, $width, $height, $transform)'; + String toString() => 'OnPatternStart($patternId, $x, $y, $width, $height, $transform)'; } bool _listEquals(List? left, List? right) { @@ -1756,6 +1654,5 @@ class OnUpdateTextPosition { int get hashCode => id; @override - bool operator ==(Object other) => - other is OnUpdateTextPosition && other.id == id; + bool operator ==(Object other) => other is OnUpdateTextPosition && other.id == id; } diff --git a/packages/vector_graphics_compiler/bin/util/isolate_processor.dart b/packages/vector_graphics_compiler/bin/util/isolate_processor.dart index 78a6f4511d87..7ef364514fa3 100644 --- a/packages/vector_graphics_compiler/bin/util/isolate_processor.dart +++ b/packages/vector_graphics_compiler/bin/util/isolate_processor.dart @@ -99,9 +99,7 @@ class IsolateProcessor { try { resource = await _pool.request(); await Isolate.run(() { - if (maskingOptimizerEnabled || - clippingOptimizerEnabled || - overdrawOptimizerEnabled) { + if (maskingOptimizerEnabled || clippingOptimizerEnabled || overdrawOptimizerEnabled) { _loadPathOps(libpathops); } if (tessellate) { diff --git a/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart b/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart index b971aa2c73ce..266b0be21e2d 100644 --- a/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart +++ b/packages/vector_graphics_compiler/bin/vector_graphics_compiler.dart @@ -81,11 +81,7 @@ final ArgParser argParser = ArgParser() 'The output directory path ' 'use it with --input-dir to specific the output dirictory', ) - ..addOption( - 'input', - abbr: 'i', - help: 'The path to a file containing a single SVG', - ) + ..addOption('input', abbr: 'i', help: 'The path to a file containing a single SVG') ..addOption( 'concurrency', abbr: 'k', @@ -115,9 +111,7 @@ final ArgParser argParser = ArgParser() void validateOptions(ArgResults results) { if (results.wasParsed('input-dir') && (results.wasParsed('input') || results.wasParsed('output'))) { - print( - '--input-dir cannot be combined with --input and/or --output options.', - ); + print('--input-dir cannot be combined with --input and/or --output options.'); exit(1); } if (!results.wasParsed('input') && !results.wasParsed('input-dir')) { @@ -135,9 +129,7 @@ SvgTheme _parseTheme(ArgResults results) { return SvgTheme( currentColor: currentColor, fontSize: double.tryParse(results['font-size'] as String) ?? 14, - xHeight: results.wasParsed('x-height') - ? double.tryParse(results['x-height'] as String) - : null, + xHeight: results.wasParsed('x-height') ? double.tryParse(results['x-height'] as String) : null, ); } @@ -159,8 +151,7 @@ Future main(List args) async { print('input-dir ${directory.path} does not exist.'); exit(1); } - for (final File file - in directory.listSync(recursive: true).whereType()) { + for (final File file in directory.listSync(recursive: true).whereType()) { if (!file.path.endsWith('.svg')) { continue; } @@ -181,8 +172,7 @@ Future main(List args) async { } } else { final inputFilePath = results['input'] as String; - final String outputFilePath = - results['output'] as String? ?? '$inputFilePath.vec'; + final String outputFilePath = results['output'] as String? ?? '$inputFilePath.vec'; pairs.add(Pair(inputFilePath, outputFilePath)); } @@ -191,8 +181,7 @@ Future main(List args) async { final overdrawOptimizerEnabled = results['optimize-overdraw'] == true; final tessellate = results['tessellate'] == true; final dumpDebug = results['dump-debug'] == true; - final useHalfPrecisionControlPoints = - results['use-half-precision-control-points'] == true; + final useHalfPrecisionControlPoints = results['use-half-precision-control-points'] == true; final int concurrency; if (results.wasParsed('concurrency')) { concurrency = int.parse(results['concurrency'] as String); diff --git a/packages/vector_graphics_compiler/lib/src/_initialize_tessellator_io.dart b/packages/vector_graphics_compiler/lib/src/_initialize_tessellator_io.dart index 735f633687da..fb76426994f3 100644 --- a/packages/vector_graphics_compiler/lib/src/_initialize_tessellator_io.dart +++ b/packages/vector_graphics_compiler/lib/src/_initialize_tessellator_io.dart @@ -34,8 +34,7 @@ bool initializeTessellatorFromFlutterCache() { print('Tesselation not supported on ${Platform.localeName}'); return false; } - final tessellator = - '${cacheRoot.path}/artifacts/engine/$platform/$executable'; + final tessellator = '${cacheRoot.path}/artifacts/engine/$platform/$executable'; if (!File(tessellator).existsSync()) { print('Could not locate libtessellator at $tessellator.'); print('Ensure you are on a supported version of flutter and then run '); diff --git a/packages/vector_graphics_compiler/lib/src/debug_format.dart b/packages/vector_graphics_compiler/lib/src/debug_format.dart index ae3bdb338cbe..8ba070c041a7 100644 --- a/packages/vector_graphics_compiler/lib/src/debug_format.dart +++ b/packages/vector_graphics_compiler/lib/src/debug_format.dart @@ -14,10 +14,7 @@ import 'paint.dart'; Uint8List dumpToDebugFormat(Uint8List bytes) { const codec = VectorGraphicsCodec(); final listener = _DebugVectorGraphicsListener(); - final DecodeResponse response = codec.decode( - bytes.buffer.asByteData(), - listener, - ); + final DecodeResponse response = codec.decode(bytes.buffer.asByteData(), listener); if (!response.complete) { codec.decode(bytes.buffer.asByteData(), listener, response: response); } @@ -60,9 +57,7 @@ class _DebugVectorGraphicsListener extends VectorGraphicsCodecListener { @override void onDrawText(int textId, int? fillId, int? strokeId, int? patternId) { - buffer.writeln( - 'DrawText: id:$textId (fill: $fillId, stroke: $strokeId, pattern: $patternId)', - ); + buffer.writeln('DrawText: id:$textId (fill: $fillId, stroke: $strokeId, pattern: $patternId)'); } @override @@ -71,15 +66,8 @@ class _DebugVectorGraphicsListener extends VectorGraphicsCodecListener { } @override - void onImage( - int imageId, - int format, - Uint8List data, { - VectorGraphicsErrorListener? onError, - }) { - buffer.writeln( - 'StoreImage: id:$imageId (format:$format, byteLength:${data.lengthInBytes}', - ); + void onImage(int imageId, int format, Uint8List data, {VectorGraphicsErrorListener? onError}) { + buffer.writeln('StoreImage: id:$imageId (format:$format, byteLength:${data.lengthInBytes}'); } @override @@ -139,14 +127,7 @@ class _DebugVectorGraphicsListener extends VectorGraphicsCodecListener { } @override - void onPathCubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) { + void onPathCubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { buffer.writeln(' cubicTo(($x1, $y1), ($x2, $y2), ($x3, $y3)'); } @@ -167,9 +148,7 @@ class _DebugVectorGraphicsListener extends VectorGraphicsCodecListener { @override void onPathStart(int id, int fillType) { - buffer.writeln( - 'PathStart: id:$id ${fillType == 0 ? 'nonZero' : 'evenOdd'}', - ); + buffer.writeln('PathStart: id:$id ${fillType == 0 ? 'nonZero' : 'evenOdd'}'); } @override diff --git a/packages/vector_graphics_compiler/lib/src/draw_command_builder.dart b/packages/vector_graphics_compiler/lib/src/draw_command_builder.dart index 203897dce318..e5042ff361f7 100644 --- a/packages/vector_graphics_compiler/lib/src/draw_command_builder.dart +++ b/packages/vector_graphics_compiler/lib/src/draw_command_builder.dart @@ -24,20 +24,13 @@ class DrawCommandBuilder { final Map _patternData = {}; final Map _textPositions = {}; - int _getOrGenerateId(T object, Map map) => - map.putIfAbsent(object, () => map.length); + int _getOrGenerateId(T object, Map map) => map.putIfAbsent(object, () => map.length); /// Add a vertices to the command stack. void addVertices(IndexedVertices vertices, Paint paint) { final int paintId = _getOrGenerateId(paint, _paints); final int verticesId = _getOrGenerateId(vertices, _vertices); - _commands.add( - DrawCommand( - DrawCommandType.vertices, - paintId: paintId, - objectId: verticesId, - ), - ); + _commands.add(DrawCommand(DrawCommandType.vertices, paintId: paintId, objectId: verticesId)); } /// Add a save layer to the command stack. @@ -77,20 +70,14 @@ class DrawCommandBuilder { _patternData, ); _commands.add( - DrawCommand( - DrawCommandType.pattern, - objectId: patternId, - patternDataId: patternDataId, - ), + DrawCommand(DrawCommandType.pattern, objectId: patternId, patternDataId: patternDataId), ); } /// Updates the current text position to [position]. void updateTextPosition(TextPosition position) { final int positionId = _getOrGenerateId(position, _textPositions); - _commands.add( - DrawCommand(DrawCommandType.textPosition, objectId: positionId), - ); + _commands.add(DrawCommand(DrawCommandType.textPosition, objectId: positionId)); } /// Add a path to the current draw command stack @@ -113,12 +100,7 @@ class DrawCommandBuilder { } /// Adds a text to the current draw command stack. - void addText( - TextConfig textConfig, - Paint paint, - String? debugString, - Object? patternId, - ) { + void addText(TextConfig textConfig, Paint paint, String? debugString, Object? patternId) { final int paintId = _getOrGenerateId(paint, _paints); final int styleId = _getOrGenerateId(textConfig, _text); _commands.add( @@ -141,11 +123,7 @@ class DrawCommandBuilder { final int drawImageId = _getOrGenerateId(drawImageData, _drawImages); _commands.add( - DrawCommand( - DrawCommandType.image, - objectId: drawImageId, - debugString: debugString, - ), + DrawCommand(DrawCommandType.image, objectId: drawImageId, debugString: debugString), ); } diff --git a/packages/vector_graphics_compiler/lib/src/geometry/basic_types.dart b/packages/vector_graphics_compiler/lib/src/geometry/basic_types.dart index 9e80ba6630f0..784c613198b1 100644 --- a/packages/vector_graphics_compiler/lib/src/geometry/basic_types.dart +++ b/packages/vector_graphics_compiler/lib/src/geometry/basic_types.dart @@ -91,8 +91,7 @@ class Rect { /// Creates a rectangle representing a circle with centerpoint `x,`y` and /// radius `r`. - const Rect.fromCircle(double x, double y, double r) - : this.fromLTRB(x - r, y - r, x + r, y + r); + const Rect.fromCircle(double x, double y, double r) : this.fromLTRB(x - r, y - r, x + r, y + r); /// A rectangle covering the entire coordinate space, equal to dart:ui's /// definition. diff --git a/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart b/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart index 02e5e7bf2df3..1214facb32b8 100644 --- a/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart +++ b/packages/vector_graphics_compiler/lib/src/geometry/matrix.dart @@ -16,15 +16,8 @@ import 'basic_types.dart'; class AffineMatrix { /// Creates an immutable affine matrix. To work with the identity matrix, use /// the [identity] property. - const AffineMatrix( - this.a, - this.b, - this.c, - this.d, - this.e, - this.f, [ - double? m4_10, - ]) : _m4_10 = m4_10 ?? (1.0 * a); + const AffineMatrix(this.a, this.b, this.c, this.d, this.e, this.f, [double? m4_10]) + : _m4_10 = m4_10 ?? (1.0 * a); /// The identity affine matrix. static const AffineMatrix identity = AffineMatrix(1, 0, 0, 1, 0, 0); @@ -104,15 +97,7 @@ class AffineMatrix { /// Creates a new affine matrix, translated along the x and y axis. AffineMatrix translated(double x, double y) { - return AffineMatrix( - a, - b, - c, - d, - (a * x) + (c * y) + e, - (b * x) + (d * y) + f, - _m4_10, - ); + return AffineMatrix(a, b, c, d, (a * x) + (c * y) + e, (b * x) + (d * y) + f, _m4_10); } /// Creates a new affine matrix, skewed along the x axis. @@ -160,10 +145,7 @@ class AffineMatrix { /// Maps `point` using the values of this matrix. Point transformPoint(Point point) { - return Point( - (a * point.x) + (c * point.y) + e, - (b * point.x) + (d * point.y) + f, - ); + return Point((a * point.x) + (c * point.y) + e, (b * point.x) + (d * point.y) + f); } /// Maps `rect` using the values of this matrix. diff --git a/packages/vector_graphics_compiler/lib/src/geometry/path.dart b/packages/vector_graphics_compiler/lib/src/geometry/path.dart index 51f7ffe0a4cd..37b548f63334 100644 --- a/packages/vector_graphics_compiler/lib/src/geometry/path.dart +++ b/packages/vector_graphics_compiler/lib/src/geometry/path.dart @@ -205,13 +205,7 @@ class CubicToCommand extends PathCommand { /// The returned list describes two cubics, where elements `0, 1, 2, 3` are /// the start, cp1, cp2, and end points of the first cubic and `3, 4, 5, 6` /// are the start, cp1, cp2, and end points of the second cubic. - static List subdivide( - Point start, - Point control1, - Point control2, - Point end, - double t, - ) { + static List subdivide(Point start, Point control1, Point control2, Point end, double t) { final Point ab = Point.lerp(start, control1, t); final Point bc = Point.lerp(control1, control2, t); final Point cd = Point.lerp(control2, end, t); @@ -236,20 +230,8 @@ class CubicToCommand extends PathCommand { if (Point.distance(cp1, Point.lerp(p1, p2, 1 / 3)) > tolerance || Point.distance(cp2, Point.lerp(p1, p2, 2 / 3)) > tolerance) { final List points = subdivide(p1, cp1, cp2, p2, .5); - distance = compute( - points[0], - points[1], - points[2], - points[3], - distance, - ); - distance = compute( - points[3], - points[4], - points[5], - points[6], - distance, - ); + distance = compute(points[0], points[1], points[2], points[3], distance); + distance = compute(points[3], points[4], points[5], points[6], distance); } else { // It's collinear enough to just treat as a line. distance += Point.distance(p1, p2); @@ -319,8 +301,7 @@ class PathBuilder implements PathProxy { /// Creates a new path builder for paths of the specified fill type. /// /// By default, will create non-zero filled paths. - PathBuilder([PathFillType? fillType]) - : fillType = fillType ?? PathFillType.nonZero; + PathBuilder([PathFillType? fillType]) : fillType = fillType ?? PathFillType.nonZero; /// Creates a new mutable path builder object from an existing [Path]. PathBuilder.fromPath(Path path) { @@ -337,14 +318,7 @@ class PathBuilder implements PathProxy { } @override - PathBuilder cubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) { + PathBuilder cubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { _commands.add(CubicToCommand(x1, y1, x2, y2, x3, y3)); return this; } @@ -370,14 +344,8 @@ class PathBuilder implements PathProxy { /// Adds an oval command to new path. PathBuilder addOval(Rect oval) { final r = Point(oval.width * 0.5, oval.height * 0.5); - final c = Point( - oval.left + (oval.width * 0.5), - oval.top + (oval.height * 0.5), - ); - final m = Point( - _kArcApproximationMagic * r.x, - _kArcApproximationMagic * r.y, - ); + final c = Point(oval.left + (oval.width * 0.5), oval.top + (oval.height * 0.5)); + final m = Point(_kArcApproximationMagic * r.x, _kArcApproximationMagic * r.y); moveTo(c.x, c.y - r.y); @@ -496,10 +464,7 @@ class PathBuilder implements PathProxy { @immutable class Path { /// Creates a new immutable collection of [PathCommand]s. - Path({ - List commands = const [], - this.fillType = PathFillType.nonZero, - }) { + Path({List commands = const [], this.fillType = PathFillType.nonZero}) { _commands.addAll(commands); } @@ -536,9 +501,7 @@ class Path { @override bool operator ==(Object other) { - return other is Path && - listEquals(_commands, other._commands) && - other.fillType == fillType; + return other is Path && listEquals(_commands, other._commands) && other.fillType == fillType; } /// Creates a dashed version of this path. @@ -715,9 +678,7 @@ class _PathDasher { ); currentPoint = dividedPoints[3]; if (draw) { - _dashedCommands.add( - CubicToCommand._fromIterablePoints(dividedPoints.skip(1).take(3)), - ); + _dashedCommands.add(CubicToCommand._fromIterablePoints(dividedPoints.skip(1).take(3))); } else { _dashedCommands.add(MoveToCommand(currentPoint.x, currentPoint.y)); } diff --git a/packages/vector_graphics_compiler/lib/src/geometry/vertices.dart b/packages/vector_graphics_compiler/lib/src/geometry/vertices.dart index 1cd478e8ed30..f3858814100a 100644 --- a/packages/vector_graphics_compiler/lib/src/geometry/vertices.dart +++ b/packages/vector_graphics_compiler/lib/src/geometry/vertices.dart @@ -15,10 +15,7 @@ class Vertices { /// [Float32List], interpreted as x,y pairs. factory Vertices.fromFloat32List(Float32List vertices) { if (vertices.length.isOdd) { - throw ArgumentError( - 'must be an even number of vertex points', - 'vertices', - ); + throw ArgumentError('must be an even number of vertex points', 'vertices'); } final vertexPoints = []; for (var index = 0; index < vertices.length; index += 2) { @@ -53,15 +50,11 @@ class Vertices { } final List compressedPoints = pointMap.keys.toList(); - if (compressedPoints.length * 2 + indices.length > - vertexPoints.length * 2) { + if (compressedPoints.length * 2 + indices.length > vertexPoints.length * 2) { return IndexedVertices(pointsToFloat32List(vertexPoints), null); } - return IndexedVertices( - pointsToFloat32List(compressedPoints), - Uint16List.fromList(indices), - ); + return IndexedVertices(pointsToFloat32List(compressedPoints), Uint16List.fromList(indices)); } } diff --git a/packages/vector_graphics_compiler/lib/src/image/image_info.dart b/packages/vector_graphics_compiler/lib/src/image/image_info.dart index 24e425cdb94b..6cf8cf0ab8ed 100644 --- a/packages/vector_graphics_compiler/lib/src/image/image_info.dart +++ b/packages/vector_graphics_compiler/lib/src/image/image_info.dart @@ -28,12 +28,9 @@ enum ImageFormat { /// of an image. abstract class ImageSizeData { /// Allows subclasses to be const. - const ImageSizeData({ - required this.format, - required this.width, - required this.height, - }) : assert(width >= 0), - assert(height >= 0); + const ImageSizeData({required this.format, required this.width, required this.height}) + : assert(width >= 0), + assert(height >= 0); /// Creates an appropriate [ImageSizeData] for the source `bytes`, if possible. /// @@ -89,11 +86,7 @@ abstract class ImageSizeData { /// The [ImageSizeData] for a PNG image. class PngImageSizeData extends ImageSizeData { PngImageSizeData._(ByteData data) - : super( - format: ImageFormat.png, - width: data.getUint32(16), - height: data.getUint32(20), - ); + : super(format: ImageFormat.png, width: data.getUint32(16), height: data.getUint32(20)); /// Returns true if `bytes` starts with the expected header for a PNG image. static bool matches(Uint8List bytes) { @@ -161,10 +154,7 @@ class JpegImageSizeData extends ImageSizeData { /// Returns true if `bytes` starts with the expected header for a JPEG image. static bool matches(Uint8List bytes) { - return bytes.lengthInBytes > 12 && - bytes[0] == 0xFF && - bytes[1] == 0xD8 && - bytes[2] == 0xFF; + return bytes.lengthInBytes > 12 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF; } } diff --git a/packages/vector_graphics_compiler/lib/src/paint.dart b/packages/vector_graphics_compiler/lib/src/paint.dart index 9b17473f49ea..6b27e5646831 100644 --- a/packages/vector_graphics_compiler/lib/src/paint.dart +++ b/packages/vector_graphics_compiler/lib/src/paint.dart @@ -37,10 +37,7 @@ class Color { /// Each part is represented by an integer from 0..255. const Color.fromARGB(int a, int r, int g, int b) : value = - (((a & 0xff) << 24) | - ((r & 0xff) << 16) | - ((g & 0xff) << 8) | - ((b & 0xff) << 0)) & + (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | ((b & 0xff) << 0)) & 0xFFFFFFFF; /// Fully opaque black. @@ -470,14 +467,8 @@ class Paint { @immutable class Stroke { /// Creates a new collection of stroking properties. - const Stroke({ - Color? color, - this.shader, - this.cap, - this.join, - this.miterLimit, - this.width, - }) : color = color ?? Color.opaqueBlack; + const Stroke({Color? color, this.shader, this.cap, this.join, this.miterLimit, this.width}) + : color = color ?? Color.opaqueBlack; /// The color to use for this stroke. /// @@ -507,15 +498,8 @@ class Stroke { final double? width; @override - int get hashCode => Object.hash( - PaintingStyle.stroke, - color, - shader, - cap, - join, - miterLimit, - width, - ); + int get hashCode => + Object.hash(PaintingStyle.stroke, color, shader, cap, join, miterLimit, width); @override bool operator ==(Object other) { @@ -1233,14 +1217,7 @@ enum TileMode { @immutable class TextPosition { /// See [TextPosition]. - const TextPosition({ - this.x, - this.y, - this.dx, - this.dy, - this.reset = false, - this.transform, - }); + const TextPosition({this.x, this.y, this.dx, this.dy, this.reset = false, this.transform}); /// The horizontal axis coordinate for the current text position. /// diff --git a/packages/vector_graphics_compiler/lib/src/svg/_path_ops_ffi.dart b/packages/vector_graphics_compiler/lib/src/svg/_path_ops_ffi.dart index 05bc0bfa83b9..e78acb6c6f8f 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/_path_ops_ffi.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/_path_ops_ffi.dart @@ -22,8 +22,7 @@ late final String _dylibPath; /// [dispose] has been called, this class must not be used again. class Path implements PathProxy { /// Creates an empty path object with the specified fill type. - Path([FillType fillType = FillType.nonZero]) - : _path = _createPathFn(fillType.index); + Path([FillType fillType = FillType.nonZero]) : _path = _createPathFn(fillType.index); /// Creates a copy of this path. factory Path.from(Path other) { @@ -147,14 +146,7 @@ class Path implements PathProxy { } @override - void cubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) { + void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { assert(_path != null); _resetPathData(); _cubicToFn(_path!, x1, y1, x2, y2, x3, y3); @@ -221,87 +213,72 @@ base class _PathData extends ffi.Struct { typedef _CreatePathType = ffi.Pointer<_SkPath> Function(int); typedef _create_path_type = ffi.Pointer<_SkPath> Function(ffi.Int); -final _CreatePathType _createPathFn = _dylib - .lookupFunction<_create_path_type, _CreatePathType>('CreatePath'); +final _CreatePathType _createPathFn = _dylib.lookupFunction<_create_path_type, _CreatePathType>( + 'CreatePath', +); typedef _MoveToType = void Function(ffi.Pointer<_SkPath>, double, double); -typedef _move_to_type = - ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Float, ffi.Float); +typedef _move_to_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Float, ffi.Float); -final _MoveToType _moveToFn = _dylib.lookupFunction<_move_to_type, _MoveToType>( - 'MoveTo', -); +final _MoveToType _moveToFn = _dylib.lookupFunction<_move_to_type, _MoveToType>('MoveTo'); typedef _LineToType = void Function(ffi.Pointer<_SkPath>, double, double); -typedef _line_to_type = - ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Float, ffi.Float); - -final _LineToType _lineToFn = _dylib.lookupFunction<_line_to_type, _LineToType>( - 'LineTo', +typedef _line_to_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Float, ffi.Float); + +final _LineToType _lineToFn = _dylib.lookupFunction<_line_to_type, _LineToType>('LineTo'); + +typedef _CubicToType = void Function( + ffi.Pointer<_SkPath>, + double, + double, + double, + double, + double, + double, +); +typedef _cubic_to_type = ffi.Void Function( + ffi.Pointer<_SkPath>, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, ); -typedef _CubicToType = - void Function( - ffi.Pointer<_SkPath>, - double, - double, - double, - double, - double, - double, - ); -typedef _cubic_to_type = - ffi.Void Function( - ffi.Pointer<_SkPath>, - ffi.Float, - ffi.Float, - ffi.Float, - ffi.Float, - ffi.Float, - ffi.Float, - ); - -final _CubicToType _cubicToFn = _dylib - .lookupFunction<_cubic_to_type, _CubicToType>('CubicTo'); +final _CubicToType _cubicToFn = _dylib.lookupFunction<_cubic_to_type, _CubicToType>('CubicTo'); typedef _CloseType = void Function(ffi.Pointer<_SkPath>, bool); typedef _close_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Bool); -final _CloseType _closeFn = _dylib.lookupFunction<_close_type, _CloseType>( - 'Close', -); +final _CloseType _closeFn = _dylib.lookupFunction<_close_type, _CloseType>('Close'); typedef _ResetType = void Function(ffi.Pointer<_SkPath>); typedef _reset_type = ffi.Void Function(ffi.Pointer<_SkPath>); -final _ResetType _resetFn = _dylib.lookupFunction<_reset_type, _ResetType>( - 'Reset', -); +final _ResetType _resetFn = _dylib.lookupFunction<_reset_type, _ResetType>('Reset'); typedef _DestroyType = void Function(ffi.Pointer<_SkPath>); typedef _destroy_type = ffi.Void Function(ffi.Pointer<_SkPath>); -final _DestroyType _destroyFn = _dylib - .lookupFunction<_destroy_type, _DestroyType>('DestroyPath'); +final _DestroyType _destroyFn = _dylib.lookupFunction<_destroy_type, _DestroyType>('DestroyPath'); -typedef _OpType = - void Function(ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, int); -typedef _op_type = - ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, ffi.Int); +typedef _OpType = void Function(ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, int); +typedef _op_type = ffi.Void Function(ffi.Pointer<_SkPath>, ffi.Pointer<_SkPath>, ffi.Int); final _OpType _opFn = _dylib.lookupFunction<_op_type, _OpType>('Op'); typedef _PathDataType = ffi.Pointer<_PathData> Function(ffi.Pointer<_SkPath>); typedef _path_data_type = ffi.Pointer<_PathData> Function(ffi.Pointer<_SkPath>); -final _PathDataType _dataFn = _dylib - .lookupFunction<_path_data_type, _PathDataType>('Data'); +final _PathDataType _dataFn = _dylib.lookupFunction<_path_data_type, _PathDataType>('Data'); typedef _DestroyDataType = void Function(ffi.Pointer<_PathData>); typedef _destroy_data_type = ffi.Void Function(ffi.Pointer<_PathData>); -final _DestroyDataType _destroyDataFn = _dylib - .lookupFunction<_destroy_data_type, _DestroyDataType>('DestroyData'); +final _DestroyDataType _destroyDataFn = _dylib.lookupFunction<_destroy_data_type, _DestroyDataType>( + 'DestroyData', +); typedef _GetFillTypeType = int Function(ffi.Pointer<_SkPath>); typedef _get_fill_type_type = ffi.Int32 Function(ffi.Pointer<_SkPath>); diff --git a/packages/vector_graphics_compiler/lib/src/svg/_path_ops_unsupported.dart b/packages/vector_graphics_compiler/lib/src/svg/_path_ops_unsupported.dart index d9abca5e53fc..f7aa6187c68f 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/_path_ops_unsupported.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/_path_ops_unsupported.dart @@ -41,14 +41,7 @@ class Path implements PathProxy { } @override - void cubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) { + void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { throw UnsupportedError('PathOps not supported on the web'); } diff --git a/packages/vector_graphics_compiler/lib/src/svg/_tessellator_ffi.dart b/packages/vector_graphics_compiler/lib/src/svg/_tessellator_ffi.dart index 2d76ec4f14e6..81fcf8a3f366 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/_tessellator_ffi.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/_tessellator_ffi.dart @@ -46,18 +46,13 @@ class Tessellator extends Visitor Node visitParentNode(ParentNode parentNode, void data) { return ParentNode( SvgAttributes.empty, - children: [ - for (final Node child in parentNode.children) child.accept(this, data), - ], + children: [for (final Node child in parentNode.children) child.accept(this, data)], ); } @override Node visitResolvedClipNode(ResolvedClipNode clipNode, void data) { - return ResolvedClipNode( - clips: clipNode.clips, - child: clipNode.child.accept(this, data), - ); + return ResolvedClipNode(clips: clipNode.clips, child: clipNode.child.accept(this, data)); } @override @@ -70,13 +65,9 @@ class Tessellator extends Visitor } @override - Node visitResolvedTextPositionNode( - ResolvedTextPositionNode textPositionNode, - void data, - ) { + Node visitResolvedTextPositionNode(ResolvedTextPositionNode textPositionNode, void data) { return ResolvedTextPositionNode(textPositionNode.textPosition, [ - for (final Node child in textPositionNode.children) - child.accept(this, data), + for (final Node child in textPositionNode.children) child.accept(this, data), ]); } @@ -101,21 +92,12 @@ class Tessellator extends Visitor builder.lineTo(line.x, line.y); case PathCommandType.cubic: final cubic = command as CubicToCommand; - builder.cubicTo( - cubic.x1, - cubic.y1, - cubic.x2, - cubic.y2, - cubic.x3, - cubic.y3, - ); + builder.cubicTo(cubic.x1, cubic.y1, cubic.x2, cubic.y2, cubic.x3, cubic.y3); case PathCommandType.close: builder.close(); } } - final Float32List rawVertices = builder.tessellate( - fillType: pathNode.path.fillType, - ); + final Float32List rawVertices = builder.tessellate(fillType: pathNode.path.fillType); if (rawVertices.isNotEmpty) { final vertices = Vertices.fromFloat32List(rawVertices); final IndexedVertices indexedVertices = vertices.createIndex(); @@ -156,9 +138,7 @@ class Tessellator extends Visitor return SaveLayerNode( SvgAttributes.empty, paint: layerNode.paint, - children: [ - for (final Node child in layerNode.children) child.accept(this, data), - ], + children: [for (final Node child in layerNode.children) child.accept(this, data)], ); } @@ -169,10 +149,7 @@ class Tessellator extends Visitor width: viewportNode.width, height: viewportNode.height, transform: viewportNode.transform, - children: [ - for (final Node child in viewportNode.children) - child.accept(this, data), - ], + children: [for (final Node child in viewportNode.children) child.accept(this, data)], ); } @@ -222,14 +199,7 @@ class VerticesBuilder { /// Adds a cubic Bezier curve with x1,y1 as the first control point, x2,y2 as /// the second control point, and end point x3,y3. - void cubicTo( - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - ) { + void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3) { assert(_builder != null); _cubicToFn(_builder!, x1, y1, x2, y2, x3, y3); } @@ -284,87 +254,72 @@ typedef _CreatePathBuilderType = ffi.Pointer<_PathBuilder> Function(); typedef _create_path_builder_type = ffi.Pointer<_PathBuilder> Function(); final _CreatePathBuilderType _createPathFn = _dylib - .lookupFunction<_create_path_builder_type, _CreatePathBuilderType>( - 'CreatePathBuilder', - ); + .lookupFunction<_create_path_builder_type, _CreatePathBuilderType>('CreatePathBuilder'); typedef _MoveToType = void Function(ffi.Pointer<_PathBuilder>, double, double); -typedef _move_to_type = - ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Float, ffi.Float); +typedef _move_to_type = ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Float, ffi.Float); -final _MoveToType _moveToFn = _dylib.lookupFunction<_move_to_type, _MoveToType>( - 'MoveTo', -); +final _MoveToType _moveToFn = _dylib.lookupFunction<_move_to_type, _MoveToType>('MoveTo'); typedef _LineToType = void Function(ffi.Pointer<_PathBuilder>, double, double); -typedef _line_to_type = - ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Float, ffi.Float); - -final _LineToType _lineToFn = _dylib.lookupFunction<_line_to_type, _LineToType>( - 'LineTo', +typedef _line_to_type = ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Float, ffi.Float); + +final _LineToType _lineToFn = _dylib.lookupFunction<_line_to_type, _LineToType>('LineTo'); + +typedef _CubicToType = void Function( + ffi.Pointer<_PathBuilder>, + double, + double, + double, + double, + double, + double, +); +typedef _cubic_to_type = ffi.Void Function( + ffi.Pointer<_PathBuilder>, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, + ffi.Float, ); -typedef _CubicToType = - void Function( - ffi.Pointer<_PathBuilder>, - double, - double, - double, - double, - double, - double, - ); -typedef _cubic_to_type = - ffi.Void Function( - ffi.Pointer<_PathBuilder>, - ffi.Float, - ffi.Float, - ffi.Float, - ffi.Float, - ffi.Float, - ffi.Float, - ); - -final _CubicToType _cubicToFn = _dylib - .lookupFunction<_cubic_to_type, _CubicToType>('CubicTo'); +final _CubicToType _cubicToFn = _dylib.lookupFunction<_cubic_to_type, _CubicToType>('CubicTo'); typedef _CloseType = void Function(ffi.Pointer<_PathBuilder>, bool); typedef _close_type = ffi.Void Function(ffi.Pointer<_PathBuilder>, ffi.Bool); -final _CloseType _closeFn = _dylib.lookupFunction<_close_type, _CloseType>( - 'Close', -); +final _CloseType _closeFn = _dylib.lookupFunction<_close_type, _CloseType>('Close'); -typedef _TessellateType = - ffi.Pointer<_Vertices> Function( - ffi.Pointer<_PathBuilder>, - int, - double, - double, - double, - ); -typedef _tessellate_type = - ffi.Pointer<_Vertices> Function( - ffi.Pointer<_PathBuilder>, - ffi.Int, - ffi.Float, - ffi.Float, - ffi.Float, - ); +typedef _TessellateType = ffi.Pointer<_Vertices> Function( + ffi.Pointer<_PathBuilder>, + int, + double, + double, + double, +); +typedef _tessellate_type = ffi.Pointer<_Vertices> Function( + ffi.Pointer<_PathBuilder>, + ffi.Int, + ffi.Float, + ffi.Float, + ffi.Float, +); -final _TessellateType _tessellateFn = _dylib - .lookupFunction<_tessellate_type, _TessellateType>('Tessellate'); +final _TessellateType _tessellateFn = _dylib.lookupFunction<_tessellate_type, _TessellateType>( + 'Tessellate', +); typedef _DestroyType = void Function(ffi.Pointer<_PathBuilder>); typedef _destroy_type = ffi.Void Function(ffi.Pointer<_PathBuilder>); -final _DestroyType _destroyFn = _dylib - .lookupFunction<_destroy_type, _DestroyType>('DestroyPathBuilder'); +final _DestroyType _destroyFn = _dylib.lookupFunction<_destroy_type, _DestroyType>( + 'DestroyPathBuilder', +); typedef _DestroyVerticesType = void Function(ffi.Pointer<_Vertices>); typedef _destroy_vertices_type = ffi.Void Function(ffi.Pointer<_Vertices>); final _DestroyVerticesType _destroyVerticesFn = _dylib - .lookupFunction<_destroy_vertices_type, _DestroyVerticesType>( - 'DestroyVertices', - ); + .lookupFunction<_destroy_vertices_type, _DestroyVerticesType>('DestroyVertices'); diff --git a/packages/vector_graphics_compiler/lib/src/svg/_tessellator_unsupported.dart b/packages/vector_graphics_compiler/lib/src/svg/_tessellator_unsupported.dart index 9dc9e857df69..7289709c3ade 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/_tessellator_unsupported.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/_tessellator_unsupported.dart @@ -76,10 +76,7 @@ class Tessellator extends Visitor } @override - Node visitResolvedTextPositionNode( - ResolvedTextPositionNode textPositionNode, - void data, - ) { + Node visitResolvedTextPositionNode(ResolvedTextPositionNode textPositionNode, void data) { return textPositionNode; } } diff --git a/packages/vector_graphics_compiler/lib/src/svg/clipping_optimizer.dart b/packages/vector_graphics_compiler/lib/src/svg/clipping_optimizer.dart index 0da96b033d52..907f5a7e8204 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/clipping_optimizer.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/clipping_optimizer.dart @@ -23,8 +23,7 @@ class _Result { /// there are multiple path nodes in ResolvedClipNode.clips /// or cases where the intersection of the clip and the path /// results in Path.commands being empty. -class ClippingOptimizer extends Visitor<_Result, Node> - with ErrorOnUnResolvedNode<_Result, Node> { +class ClippingOptimizer extends Visitor<_Result, Node> with ErrorOnUnResolvedNode<_Result, Node> { ///List of clips to apply. final List clipsToApply = []; @@ -147,18 +146,12 @@ class ClippingOptimizer extends Visitor<_Result, Node> if (childResult.deleteClipNode) { result = _Result(childResult.node); } else { - final newClipNode = ResolvedClipNode( - child: childResult.node, - clips: clipNode.clips, - ); + final newClipNode = ResolvedClipNode(child: childResult.node, clips: clipNode.clips); result = _Result(newClipNode); } } else { final _Result childResult = clipNode.child.accept(this, clipNode); - final newClipNode = ResolvedClipNode( - child: childResult.node, - clips: clipNode.clips, - ); + final newClipNode = ResolvedClipNode(child: childResult.node, clips: clipNode.clips); result = _Result(newClipNode); } return result; @@ -204,10 +197,7 @@ class ClippingOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedVerticesNode( - ResolvedVerticesNode verticesNode, - Node data, - ) { + _Result visitResolvedVerticesNode(ResolvedVerticesNode verticesNode, Node data) { final result = _Result(verticesNode); return result; } @@ -257,10 +247,7 @@ class ClippingOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedImageNode( - ResolvedImageNode resolvedImageNode, - Node data, - ) { + _Result visitResolvedImageNode(ResolvedImageNode resolvedImageNode, Node data) { final result = _Result(resolvedImageNode); result.deleteClipNode = false; return result; @@ -274,14 +261,10 @@ class ClippingOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedTextPositionNode( - ResolvedTextPositionNode textPositionNode, - void data, - ) { + _Result visitResolvedTextPositionNode(ResolvedTextPositionNode textPositionNode, void data) { return _Result( ResolvedTextPositionNode(textPositionNode.textPosition, [ - for (final Node child in textPositionNode.children) - child.accept(this, data).node, + for (final Node child in textPositionNode.children) child.accept(this, data).node, ]), ); } diff --git a/packages/vector_graphics_compiler/lib/src/svg/color_mapper.dart b/packages/vector_graphics_compiler/lib/src/svg/color_mapper.dart index 3ef0e5ddaaf9..570a6c2c9d77 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/color_mapper.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/color_mapper.dart @@ -9,10 +9,5 @@ abstract class ColorMapper { /// Returns a new color to use in place of [color] during SVG parsing. /// /// The SVG parser will call this method every time it parses a color - Color substitute( - String? id, - String elementName, - String attributeName, - Color color, - ); + Color substitute(String? id, String elementName, String attributeName, Color color); } diff --git a/packages/vector_graphics_compiler/lib/src/svg/colors.dart b/packages/vector_graphics_compiler/lib/src/svg/colors.dart index 1d1d0fadf9cc..0c38e2b90b67 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/colors.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/colors.dart @@ -241,14 +241,10 @@ CssRgbRecord? parseCssRgb(String input) { if (match == null) { return null; } - final String? r = - match.namedGroup('commaRed') ?? match.namedGroup('spaceRed'); - final String? g = - match.namedGroup('commaGreen') ?? match.namedGroup('spaceGreen'); - final String? b = - match.namedGroup('commaBlue') ?? match.namedGroup('spaceBlue'); - final String a = - match.namedGroup('commaAlpha') ?? match.namedGroup('spaceAlpha') ?? '1'; + final String? r = match.namedGroup('commaRed') ?? match.namedGroup('spaceRed'); + final String? g = match.namedGroup('commaGreen') ?? match.namedGroup('spaceGreen'); + final String? b = match.namedGroup('commaBlue') ?? match.namedGroup('spaceBlue'); + final String a = match.namedGroup('commaAlpha') ?? match.namedGroup('spaceAlpha') ?? '1'; return (r: r!, g: g!, b: b!, a: a); } @@ -267,17 +263,10 @@ CssHslRecord? parseCssHsl(String input) { if (match == null) { return null; } - final String? h = - match.namedGroup('commaHue') ?? match.namedGroup('spaceHue'); - final String? s = - match.namedGroup('commaSaturation') ?? - match.namedGroup('spaceSaturation'); - final String? l = - match.namedGroup('commaLightness') ?? match.namedGroup('spaceLightness'); - final String a = - match.namedGroup('commaHslAlpha') ?? - match.namedGroup('spaceHslAlpha') ?? - '1'; + final String? h = match.namedGroup('commaHue') ?? match.namedGroup('spaceHue'); + final String? s = match.namedGroup('commaSaturation') ?? match.namedGroup('spaceSaturation'); + final String? l = match.namedGroup('commaLightness') ?? match.namedGroup('spaceLightness'); + final String a = match.namedGroup('commaHslAlpha') ?? match.namedGroup('spaceHslAlpha') ?? '1'; return (h: h!, s: s!, l: l!, a: a); } @@ -297,11 +286,7 @@ CssHslRecord? parseCssHsl(String input) { Color parseRgbFunction(String colorString) { final CssRgbRecord? parsed = parseCssRgb(colorString); if (parsed == null) { - throw ArgumentError.value( - colorString, - 'colorString', - 'Invalid CSS rgb/rgba color syntax', - ); + throw ArgumentError.value(colorString, 'colorString', 'Invalid CSS rgb/rgba color syntax'); } return _cssRgbRecordToColor(parsed); } @@ -321,11 +306,7 @@ Color parseRgbFunction(String colorString) { Color parseHslFunction(String colorString) { final CssHslRecord? parsed = parseCssHsl(colorString); if (parsed == null) { - throw ArgumentError.value( - colorString, - 'colorString', - 'Invalid CSS hsl/hsla color syntax', - ); + throw ArgumentError.value(colorString, 'colorString', 'Invalid CSS hsl/hsla color syntax'); } return _cssHslRecordToColor(parsed); } diff --git a/packages/vector_graphics_compiler/lib/src/svg/masking_optimizer.dart b/packages/vector_graphics_compiler/lib/src/svg/masking_optimizer.dart index 755f8799a4f0..9aa694f2efe9 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/masking_optimizer.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/masking_optimizer.dart @@ -85,9 +85,7 @@ Path toVectorGraphicsPath(path_ops.Path path) { case path_ops.PathVerb.quadTo: final double cpX = points[index++]; final double cpY = points[index++]; - newCommands.add( - CubicToCommand(cpX, cpY, cpX, cpY, points[index++], points[index++]), - ); + newCommands.add(CubicToCommand(cpX, cpY, cpX, cpY, points[index++], points[index++])); case path_ops.PathVerb.cubicTo: newCommands.add( CubicToCommand( @@ -104,10 +102,7 @@ Path toVectorGraphicsPath(path_ops.Path path) { } } - final newPath = Path( - commands: newCommands, - fillType: toVectorGraphicsFillType(path.fillType), - ); + final newPath = Path(commands: newCommands, fillType: toVectorGraphicsFillType(path.fillType)); return newPath; } @@ -128,8 +123,7 @@ ResolvedPathNode? getSingleChild(Node node) { /// there are multiple path nodes in a mask or cases where /// the intersection of the mask and the path results in /// Path.commands being empty. -class MaskingOptimizer extends Visitor<_Result, Node> - with ErrorOnUnResolvedNode<_Result, Node> { +class MaskingOptimizer extends Visitor<_Result, Node> with ErrorOnUnResolvedNode<_Result, Node> { /// List of masks to add. final List masksToApply = []; @@ -140,10 +134,7 @@ class MaskingOptimizer extends Visitor<_Result, Node> } /// Applies mask to a path node, and returns resulting path node. - ResolvedPathNode applyMask( - ResolvedPathNode pathNode, - ResolvedPathNode maskPathNode, - ) { + ResolvedPathNode applyMask(ResolvedPathNode pathNode, ResolvedPathNode maskPathNode) { final path_ops.Path maskPathOpsPath = toPathOpsPath(maskPathNode.path); final path_ops.Path pathPathOpsPath = toPathOpsPath(pathNode.path); final path_ops.Path intersection = pathPathOpsPath.applyOp( @@ -257,10 +248,7 @@ class MaskingOptimizer extends Visitor<_Result, Node> // ignore: library_private_types_in_public_api _Result visitResolvedClipNode(ResolvedClipNode clipNode, Node data) { final _Result childResult = clipNode.child.accept(this, clipNode); - final newClipNode = ResolvedClipNode( - clips: clipNode.clips, - child: childResult.node, - ); + final newClipNode = ResolvedClipNode(clips: clipNode.clips, child: childResult.node); final result = _Result(newClipNode); result.children.add(childResult.node); @@ -279,10 +267,7 @@ class MaskingOptimizer extends Visitor<_Result, Node> if (masksToApply.isNotEmpty) { var newPathNode = pathNode; for (final ResolvedPathNode maskPathNode in masksToApply) { - final ResolvedPathNode intersection = applyMask( - newPathNode, - maskPathNode, - ); + final ResolvedPathNode intersection = applyMask(newPathNode, maskPathNode); if (intersection.path.commands.isNotEmpty) { newPathNode = intersection; } else { @@ -304,10 +289,7 @@ class MaskingOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedVerticesNode( - ResolvedVerticesNode verticesNode, - Node data, - ) { + _Result visitResolvedVerticesNode(ResolvedVerticesNode verticesNode, Node data) { final result = _Result(verticesNode); return result; } @@ -355,10 +337,7 @@ class MaskingOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedImageNode( - ResolvedImageNode resolvedImageNode, - Node data, - ) { + _Result visitResolvedImageNode(ResolvedImageNode resolvedImageNode, Node data) { final result = _Result(resolvedImageNode, deleteMaskNode: false); return result; @@ -372,14 +351,10 @@ class MaskingOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedTextPositionNode( - ResolvedTextPositionNode textPositionNode, - void data, - ) { + _Result visitResolvedTextPositionNode(ResolvedTextPositionNode textPositionNode, void data) { return _Result( ResolvedTextPositionNode(textPositionNode.textPosition, [ - for (final Node child in textPositionNode.children) - child.accept(this, data).node, + for (final Node child in textPositionNode.children) child.accept(this, data).node, ]), ); } diff --git a/packages/vector_graphics_compiler/lib/src/svg/node.dart b/packages/vector_graphics_compiler/lib/src/svg/node.dart index 3a03413790b4..c6565cfae88d 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/node.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/node.dart @@ -54,8 +54,7 @@ abstract class Node { /// the [newAttributes] are from the parent. /// /// By default, returns this. - Node applyAttributes(SvgAttributes newAttributes, {bool replace = false}) => - this; + Node applyAttributes(SvgAttributes newAttributes, {bool replace = false}) => this; } class _EmptyNode extends Node { @@ -140,11 +139,8 @@ typedef NodeCallback = void Function(Node child); /// A node that contains children, transformed by [transform]. class ParentNode extends AttributedNode { /// Creates a new [ParentNode]. - ParentNode( - super.attributes, { - super.precalculatedTransform, - List? children, - }) : _children = children ?? []; + ParentNode(super.attributes, {super.precalculatedTransform, List? children}) + : _children = children ?? []; /// The child nodes of this node. final List _children; @@ -200,14 +196,9 @@ class ParentNode extends AttributedNode { } @override - AttributedNode applyAttributes( - SvgAttributes newAttributes, { - bool replace = false, - }) { - return ParentNode( - attributes.applyParent(newAttributes), - precalculatedTransform: transform, - ).._children.addAll(_children); + AttributedNode applyAttributes(SvgAttributes newAttributes, {bool replace = false}) { + return ParentNode(attributes.applyParent(newAttributes), precalculatedTransform: transform) + .._children.addAll(_children); } /// Create the paint required to draw a save layer, or `null` if none is @@ -291,10 +282,7 @@ class TextPositionNode extends ParentNode { } @override - AttributedNode applyAttributes( - SvgAttributes newAttributes, { - bool replace = false, - }) { + AttributedNode applyAttributes(SvgAttributes newAttributes, {bool replace = false}) { return TextPositionNode(attributes.applyParent(newAttributes), reset: reset) .._children.addAll(_children); } @@ -419,11 +407,7 @@ class PathNode extends AttributedNode { /// Compute the paint used by this Path. Paint? computePaint(Rect bounds, AffineMatrix transform) { final Stroke? stroke = attributes.stroke?.toStroke(bounds, transform); - final Fill? fill = attributes.fill?.toFill( - bounds, - transform, - defaultColor: Color.opaqueBlack, - ); + final Fill? fill = attributes.fill?.toFill(bounds, transform, defaultColor: Color.opaqueBlack); if (fill == null && stroke == null) { return null; } @@ -431,10 +415,7 @@ class PathNode extends AttributedNode { } @override - AttributedNode applyAttributes( - SvgAttributes newAttributes, { - bool replace = false, - }) { + AttributedNode applyAttributes(SvgAttributes newAttributes, {bool replace = false}) { return PathNode( path, replace @@ -467,10 +448,7 @@ class DeferredNode extends AttributedNode { final Resolver resolver; @override - AttributedNode applyAttributes( - SvgAttributes newAttributes, { - bool replace = false, - }) { + AttributedNode applyAttributes(SvgAttributes newAttributes, {bool replace = false}) { return DeferredNode( replace ? newAttributes.applyParent(attributes, transformOverride: transform) @@ -502,11 +480,7 @@ class TextNode extends AttributedNode { /// Compute the [Paint] that this text node uses. Paint? computePaint(Rect bounds, AffineMatrix transform) { - final Fill? fill = attributes.fill?.toFill( - bounds, - transform, - defaultColor: Color.opaqueBlack, - ); + final Fill? fill = attributes.fill?.toFill(bounds, transform, defaultColor: Color.opaqueBlack); final Stroke? stroke = attributes.stroke?.toStroke(bounds, transform); if (fill == null && stroke == null) { return null; @@ -531,10 +505,7 @@ class TextNode extends AttributedNode { } @override - AttributedNode applyAttributes( - SvgAttributes newAttributes, { - bool replace = false, - }) { + AttributedNode applyAttributes(SvgAttributes newAttributes, {bool replace = false}) { final SvgAttributes resolvedAttributes = replace ? newAttributes.applyParent(attributes, transformOverride: transform) : attributes.applyParent(newAttributes); @@ -565,10 +536,7 @@ class ImageNode extends AttributedNode { final ImageFormat format; @override - AttributedNode applyAttributes( - SvgAttributes newAttributes, { - bool replace = false, - }) { + AttributedNode applyAttributes(SvgAttributes newAttributes, {bool replace = false}) { return ImageNode( data, format, diff --git a/packages/vector_graphics_compiler/lib/src/svg/overdraw_optimizer.dart b/packages/vector_graphics_compiler/lib/src/svg/overdraw_optimizer.dart index 492d038401da..15ae46389ad5 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/overdraw_optimizer.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/overdraw_optimizer.dart @@ -18,8 +18,7 @@ class _Result { } /// Removes unnecessary overlappping. -class OverdrawOptimizer extends Visitor<_Result, Node> - with ErrorOnUnResolvedNode<_Result, Node> { +class OverdrawOptimizer extends Visitor<_Result, Node> with ErrorOnUnResolvedNode<_Result, Node> { /// Applies visitor to given node. Node apply(Node node) { final Node newNode = node.accept(this, null).node; @@ -27,10 +26,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> } /// Removes overlap between top and bottom path from bottom. - ResolvedPathNode removeOverlap( - ResolvedPathNode bottomPathNode, - ResolvedPathNode topPathNode, - ) { + ResolvedPathNode removeOverlap(ResolvedPathNode bottomPathNode, ResolvedPathNode topPathNode) { final path_ops.Path topPathOpsPath = toPathOpsPath(topPathNode.path); final path_ops.Path bottomPathOpsPath = toPathOpsPath(bottomPathNode.path); final path_ops.Path intersection = bottomPathOpsPath.applyOp( @@ -73,12 +69,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> final double g = ((1 - a0) * a1 * g1 + a0 * g0) / a; final double b = ((1 - a0) * a1 * b1 + a0 * b0) / a; - final overlapColor = Color.fromARGB( - (a * 255).round(), - r.round(), - g.round(), - b.round(), - ); + final overlapColor = Color.fromARGB((a * 255).round(), r.round(), g.round(), b.round()); return overlapColor; } @@ -93,9 +84,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> if (bottomColor != null && topColor != null) { final Color overlapColor = calculateOverlapColor(bottomColor, topColor); final path_ops.Path topPathOpsPath = toPathOpsPath(topPathNode.path); - final path_ops.Path bottomPathOpsPath = toPathOpsPath( - bottomPathNode.path, - ); + final path_ops.Path bottomPathOpsPath = toPathOpsPath(bottomPathNode.path); final path_ops.Path intersection = bottomPathOpsPath.applyOp( topPathOpsPath, path_ops.PathOp.intersect, @@ -127,10 +116,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> paint: Paint( blendMode: bottomPathNode.paint.blendMode, stroke: bottomPathNode.paint.stroke, - fill: Fill( - color: overlapColor, - shader: bottomPathNode.paint.fill?.shader, - ), + fill: Fill(color: overlapColor, shader: bottomPathNode.paint.fill?.shader), ), bounds: bottomPathNode.bounds, path: newOverlapVGPath, @@ -141,11 +127,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> intersection.dispose(); newBottomPath.dispose(); - return [ - newBottomPathNode, - newTopPathNode, - newOverlapPathNode, - ]; + return [newBottomPathNode, newTopPathNode, newOverlapPathNode]; } return [bottomPathNode, topPathNode]; } @@ -213,9 +195,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> /// the "top" path, is opaque, the removeOverlap function /// will be used. if (child.paint.fill?.color.a == 255) { - newChildList[lastPathNodeIndex] = [ - removeOverlap(lastPathNode, child), - ]; + newChildList[lastPathNodeIndex] = [removeOverlap(lastPathNode, child)]; lastPathNode = child; lastPathNodeIndex = index; } else { @@ -306,10 +286,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> // ignore: library_private_types_in_public_api _Result visitResolvedClipNode(ResolvedClipNode clipNode, Node data) { final _Result childResult = clipNode.child.accept(this, clipNode); - final newClipNode = ResolvedClipNode( - clips: clipNode.clips, - child: childResult.node, - ); + final newClipNode = ResolvedClipNode(clips: clipNode.clips, child: childResult.node); final result = _Result(newClipNode); result.children.add(childResult.node); @@ -330,10 +307,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedVerticesNode( - ResolvedVerticesNode verticesNode, - Node data, - ) { + _Result visitResolvedVerticesNode(ResolvedVerticesNode verticesNode, Node data) { return _Result(verticesNode); } @@ -358,10 +332,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedImageNode( - ResolvedImageNode resolvedImageNode, - Node data, - ) { + _Result visitResolvedImageNode(ResolvedImageNode resolvedImageNode, Node data) { return _Result(resolvedImageNode); } @@ -370,10 +341,7 @@ class OverdrawOptimizer extends Visitor<_Result, Node> _Result visitViewportNode(ViewportNode viewportNode, void data) { final children = []; - final parentNode = ParentNode( - SvgAttributes.empty, - children: viewportNode.children.toList(), - ); + final parentNode = ParentNode(SvgAttributes.empty, children: viewportNode.children.toList()); final _Result childResult = parentNode.accept(this, viewportNode); children.addAll((childResult.node as ParentNode).children); @@ -399,14 +367,10 @@ class OverdrawOptimizer extends Visitor<_Result, Node> @override // ignore: library_private_types_in_public_api - _Result visitResolvedTextPositionNode( - ResolvedTextPositionNode textPositionNode, - void data, - ) { + _Result visitResolvedTextPositionNode(ResolvedTextPositionNode textPositionNode, void data) { return _Result( ResolvedTextPositionNode(textPositionNode.textPosition, [ - for (final Node child in textPositionNode.children) - child.accept(this, data).node, + for (final Node child in textPositionNode.children) child.accept(this, data).node, ]), ); } diff --git a/packages/vector_graphics_compiler/lib/src/svg/parser.dart b/packages/vector_graphics_compiler/lib/src/svg/parser.dart index a7f9b61f6419..0d86ca86e045 100644 --- a/packages/vector_graphics_compiler/lib/src/svg/parser.dart +++ b/packages/vector_graphics_compiler/lib/src/svg/parser.dart @@ -35,8 +35,7 @@ import 'visitor.dart'; final Set _unhandledElements = {'title', 'desc'}; -typedef _ParseFunc = - void Function(SvgParser parserState, bool warningsAsErrors); +typedef _ParseFunc = void Function(SvgParser parserState, bool warningsAsErrors); typedef _PathFunc = Path? Function(SvgParser parserState); final RegExp _whitespacePattern = RegExp(r'\s'); @@ -158,11 +157,7 @@ class _Elements { final String rawWidth = parserState.attribute('width') ?? ''; final String rawHeight = parserState.attribute('height') ?? ''; - double? patternWidth = parsePatternUnitToDouble( - rawWidth, - 'width', - viewBox: parserState._root, - ); + double? patternWidth = parsePatternUnitToDouble(rawWidth, 'width', viewBox: parserState._root); double? patternHeight = parsePatternUnitToDouble( rawHeight, 'height', @@ -213,18 +208,16 @@ class _Elements { } final AffineMatrix transform = - (parseTransform(parserState.attribute('transform')) ?? - AffineMatrix.identity) - .translated( - parserState.parseDoubleWithUnits( - parserState.attribute('x', def: '0'), - percentageRef: parserState.viewportWidth, - )!, - parserState.parseDoubleWithUnits( - parserState.attribute('y', def: '0'), - percentageRef: parserState.viewportHeight, - )!, - ); + (parseTransform(parserState.attribute('transform')) ?? AffineMatrix.identity).translated( + parserState.parseDoubleWithUnits( + parserState.attribute('x', def: '0'), + percentageRef: parserState.viewportWidth, + )!, + parserState.parseDoubleWithUnits( + parserState.attribute('y', def: '0'), + percentageRef: parserState.viewportHeight, + )!, + ); final group = ParentNode( // parserState._currentAttributes, @@ -257,20 +250,13 @@ class _Elements { return; } - static void parseStops( - SvgParser parserState, - List colors, - List offsets, - ) { + static void parseStops(SvgParser parserState, List colors, List offsets) { for (final XmlEvent event in parserState._readSubtree()) { if (event is XmlEndElementEvent) { continue; } if (event is XmlStartElementEvent) { - final String rawOpacity = parserState.attribute( - 'stop-opacity', - def: '1', - )!; + final String rawOpacity = parserState.attribute('stop-opacity', def: '1')!; final Color stopColor = parserState.parseColor( parserState.attribute('stop-color'), @@ -355,14 +341,8 @@ class _Elements { parseStops(parserState, colors, offsets); } - final fromPoint = Point( - parseDecimalOrPercentage(x1), - parseDecimalOrPercentage(y1), - ); - final toPoint = Point( - parseDecimalOrPercentage(x2), - parseDecimalOrPercentage(y2), - ); + final fromPoint = Point(parseDecimalOrPercentage(x1), parseDecimalOrPercentage(y1)); + final toPoint = Point(parseDecimalOrPercentage(x2), parseDecimalOrPercentage(y2)); parserState._definitions.addGradient( LinearGradient( @@ -400,9 +380,7 @@ class _Elements { PathNode( Path( commands: sourcePath.commands.toList(), - fillType: - parserState._currentAttributes.clipRule ?? - PathFillType.nonZero, + fillType: parserState._currentAttributes.clipRule ?? PathFillType.nonZero, ), parserState._currentAttributes, ), @@ -453,9 +431,7 @@ class _Elements { final ImageFormat? format = supportedMimeTypes[mimeType]; if (format == null) { if (warningsAsErrors) { - throw UnimplementedError( - 'Image data format not supported: $mimeType', - ); + throw UnimplementedError('Image data format not supported: $mimeType'); } else { print('Warning: Unsupported image format $mimeType'); } @@ -507,9 +483,7 @@ class _Paths { percentageRef: diagRef, )!; final oval = Rect.fromCircle(cx, cy, r); - return PathBuilder( - parserState._currentAttributes.fillRule, - ).addOval(oval).toPath(); + return PathBuilder(parserState._currentAttributes.fillRule).addOval(oval).toPath(); } static Path path(SvgParser parserState) { @@ -542,14 +516,8 @@ class _Paths { ryRaw ??= rxRaw; if (rxRaw != null && rxRaw != '') { - final double rx = parserState.parseDoubleWithUnits( - rxRaw, - percentageRef: vw, - )!; - final double ry = parserState.parseDoubleWithUnits( - ryRaw, - percentageRef: vh, - )!; + final double rx = parserState.parseDoubleWithUnits(rxRaw, percentageRef: vw)!; + final double ry = parserState.parseDoubleWithUnits(ryRaw, percentageRef: vh)!; return PathBuilder( parserState._currentAttributes.fillRule, ).addRRect(Rect.fromLTWH(x, y, w, h), rx, ry).toPath(); @@ -599,9 +567,7 @@ class _Paths { )!; final r = Rect.fromLTWH(cx - rx, cy - ry, rx * 2, ry * 2); - return PathBuilder( - parserState._currentAttributes.fillRule, - ).addOval(r).toPath(); + return PathBuilder(parserState._currentAttributes.fillRule).addOval(r).toPath(); } static Path line(SvgParser parserState) { @@ -640,26 +606,15 @@ class _SvgGroupTuple { /// Parse an SVG to the initial Node tree. @visibleForTesting Node parseToNodeTree(String source) { - return SvgParser( - source, - const SvgTheme(), - null, - true, - null, - )._parseToNodeTree(); + return SvgParser(source, const SvgTheme(), null, true, null)._parseToNodeTree(); } /// Reads an SVG XML string and via the [parse] method creates a set of /// [VectorInstructions]. class SvgParser { /// Creates a new [SvgParser]. - SvgParser( - String xml, - this.theme, - this._key, - this._warningsAsErrors, - this._colorMapper, - ) : _eventIterator = parseEvents(xml).iterator; + SvgParser(String xml, this.theme, this._key, this._warningsAsErrors, this._colorMapper) + : _eventIterator = parseEvents(xml).iterator; /// The theme used when parsing SVG elements. final SvgTheme theme; @@ -717,9 +672,7 @@ class SvgParser { final XmlEvent event = _eventIterator.current; var isSelfClosing = false; if (event is XmlStartElementEvent) { - final Map attributeMap = _createAttributeMap( - event.attributes, - ); + final Map attributeMap = _createAttributeMap(event.attributes); if (!_isVisible(attributeMap)) { if (!event.isSelfClosing) { depth += 1; @@ -765,13 +718,11 @@ class SvgParser { // a space. final bool prependSpace = _currentAttributes.x == null && - (_lastEndElementEvent?.localName == 'tspan' && - textHasNonWhitespace) || + (_lastEndElementEvent?.localName == 'tspan' && textHasNonWhitespace) || _lastTextEndedWithSpace; _lastTextEndedWithSpace = - textHasNonWhitespace && - text.startsWith(_whitespacePattern, text.length - 1); + textHasNonWhitespace && text.startsWith(_whitespacePattern, text.length - 1); // From the spec: // First, it will remove all newline characters. @@ -800,8 +751,7 @@ class SvgParser { bool get _inTextOrTSpan => _parentDrawables.isNotEmpty && - (_parentDrawables.last.name == 'text' || - _parentDrawables.last.name == 'tspan'); + (_parentDrawables.last.name == 'text' || _parentDrawables.last.name == 'tspan'); void _parseTree() { for (final XmlEvent event in _readSubtree()) { @@ -893,8 +843,7 @@ class SvgParser { } /// Gets the attribute for the current position of the parser. - String? attribute(String name, {String? def}) => - _currentAttributes.raw[name] ?? def; + String? attribute(String name, {String? def}) => _currentAttributes.raw[name] ?? def; /// The current group, if any, in the [Drawable] heirarchy. ParentNode? get currentGroup { @@ -965,8 +914,7 @@ class SvgParser { /// Handles the end of an XML element. void endElement(XmlEndElementEvent event) { - while (event.name == _parentDrawables.last.name && - _parentDrawables.last.drawable is ClipNode) { + while (event.name == _parentDrawables.last.name && _parentDrawables.last.drawable is ClipNode) { _parentDrawables.removeLast(); } if (event.name == _parentDrawables.last.name) { @@ -984,8 +932,7 @@ class SvgParser { /// Will only print an error once for unhandled/unexpected elements, except for /// `